mirror of
https://github.com/got-feedBack/feedBack.git
synced 2026-09-11 16:24:30 +00:00
Compare commits
34
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fd5c46ed72 | ||
|
|
beefd7bc09 | ||
|
|
a7ea719652 | ||
|
|
1e2d5a6162 | ||
|
|
744c848636 | ||
|
|
41cdfd576a | ||
|
|
23df6767a7 | ||
|
|
f4b59e67d6 | ||
|
|
110b47f2ae | ||
|
|
96a84996a2 | ||
|
|
2910a3c8cb | ||
|
|
115c96a3f0 | ||
|
|
48f435408f | ||
|
|
7173007412 | ||
|
|
df4e17bc99 | ||
|
|
6aed8510d7 | ||
|
|
6b0e37aa35 | ||
|
|
6bfd92aa06 | ||
|
|
bc4d2a3592 | ||
|
|
7713ca92f4 | ||
|
|
7e977b9572 | ||
|
|
095d718b85 | ||
|
|
c4bb58233d | ||
|
|
1434eb6342 | ||
|
|
24d24ef2cf | ||
|
|
58047e6ad6 | ||
|
|
817db6382b | ||
|
|
9f914770c6 | ||
|
|
5ef163e9f9 | ||
|
|
64b95d6f34 | ||
|
|
491039a12d | ||
|
|
6c42d83c31 | ||
|
|
9f0d48cb1f | ||
|
|
b0338849f8 |
@@ -52,7 +52,7 @@ jobs:
|
||||
run: pytest
|
||||
|
||||
- name: Run JS plugin-API tests
|
||||
run: node --test tests/js/*.test.js 'tests/plugins/*/js/*.test.js'
|
||||
run: node --test tests/js/*.test.js 'tests/plugins/*/js/*.test.js' 'plugins/*/tests/*.test.js'
|
||||
|
||||
tailwind-fresh:
|
||||
# Guard that the committed static/tailwind.min.css is in sync with source.
|
||||
|
||||
@@ -44,6 +44,12 @@ plugins/minigames/__pycache__/
|
||||
plugins/tuner/__pycache__/
|
||||
!plugins/input_setup/
|
||||
!plugins/input_setup/**
|
||||
!plugins/drum_highway_3d/
|
||||
!plugins/drum_highway_3d/**
|
||||
plugins/drum_highway_3d/__pycache__/
|
||||
!plugins/keys_highway_3d/
|
||||
!plugins/keys_highway_3d/**
|
||||
plugins/keys_highway_3d/__pycache__/
|
||||
node_modules/
|
||||
test-results/
|
||||
playwright-report/
|
||||
|
||||
@@ -8,6 +8,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- **3D Drum Highway: bloom glow + adaptive-resolution support — the first slice of visual parity with the guitar highway.** The drum highway now renders through the same post-processing path as `highway_3d`: an `UnrealBloomPass` (strength 0.65, radius 0.5, threshold 0.82 — high, so only emissive/bright surfaces bleed) on a multisampled HalfFloat target with ACES filmic tone mapping, so the white hit-line bar and proximity-lit notes get a real glow instead of a flat emissive tint. **On by default**, with a new **Graphics → "Glow (bloom)"** toggle in the plugin settings (`drum_h3d_bg_bloom`, applies live, no reload); if the vendored postprocessing addons can't load (older self-hosted core), the plugin silently falls back to the direct render path. The plugin also now honors the host's **adaptive render scale** (`bundle.renderScale` — the Quality/"Min res" controls that the guitar highway already respected), multiplying it into the device pixel ratio, and caps DPR at 1.25 when more than one viz instance is live (splitscreen) so two panels don't double the GPU fill cost. Groundwork for the rest of the parity series: an FX-settings scaffold (`FX_DEFAULTS`/`readFxSettings`/`window.drumH3dSetFx`, `drum_h3d_bg_*` localStorage keys) that the sparks/themes/backgrounds PRs extend, plus a first node test suite for the plugin (`plugins/drum_highway_3d/tests/data_layer.test.js` — vm-loaded like the keys plugin's, covering the hit-variant precedence, the Auto-mode steal-guard predicate, and FX defaults; 8 tests, runs in CI via the `plugins/*/tests/*.test.js` glob).
|
||||
- **3D Keys Highway: sharp HiDPI rendering, bloom glow, a live combo HUD, and a graphics settings panel — the first slice of visual parity with the guitar highway.** The biggest single fix is resolution: the plugin never called `setPixelRatio`, so on HiDPI/retina displays (and Windows display scaling) it rendered at CSS resolution and was upscaled — soft and aliased. It now multiplies the device pixel ratio (capped at 2, or 1.25 when two viz panels are live in splitscreen) with the host's **adaptive render scale** (`bundle.renderScale`, the Quality/"Min res" controls), exactly like `highway_3d`. On top of that: the same **bloom** post-processing path as the guitar highway (UnrealBloomPass 0.65/0.5/0.82 on a multisampled HalfFloat target + ACES tone mapping — the cyan hit-line, hit flames and the sustain "consume" glow finally bleed light instead of reading flat), **on by default** with a graceful direct-render fallback when the vendored addons can't load. The plugin gains its first **settings panel** (`settings.html`, Settings → graphics category, `"settings"` block in plugin.json) with a live-applying "Glow (bloom)" toggle (`keys3d_bg_bloom`), plus the FX scaffold (`FX_DEFAULTS`/`readFxSettings`/`window.keys3dSetFx`, `keys3d_bg_*` keys) the later parity PRs extend. And the score state the plugin was already tracking is finally visible: a **combo / accuracy / best-streak HUD** overlay (drum-highway pattern), shown only while a MIDI keyboard session is wired so it never renders a frozen 0× combo. Tests: `plugins/keys_highway_3d/tests/fx_settings.test.js` (defaults, localStorage overrides + type coercion, setter persist/dispatch/unknown-key guard; 3 tests alongside the existing 20).
|
||||
- **The 3D Drum Highway and 3D Keys Highway are now bundled core plugins** (`plugins/drum_highway_3d/`, `plugins/keys_highway_3d/`), imported from their former standalone repos (`feedBack-plugin-drum-highway-3d`, `feedBack-plugin-keys-highway-3d`, now archived) via `git subtree` so their history is preserved. They join the other in-tree plugins-as-plugins: the loader treats them identically to user-installed ones, both are marked `"bundled": true` in their manifests, and `.gitignore` gains the matching `!plugins/<id>/` exceptions. This puts all three 3D highways (guitar, drums, keys) in one repo ahead of a visual-parity pass that ports the guitar highway's polish (bloom, sparks, themes, reactive backgrounds) to the other two — shared helper code and theme tables can now be reviewed and kept in sync in a single place. The keys plugin's existing node test suite is wired into CI (the JS test step gains a `plugins/*/tests/*.test.js` glob, +20 tests), and `static/tailwind.min.css` is regenerated since the core Tailwind build scans `plugins/**`. One deliberate behavior change ships with the bundling: the drum highway's Auto-mode predicate is **narrowed** (it used to claim any pack with `has_drum_tab` — a pack-level flag — which, now that the plugin ships to everyone and sorts before `highway_3d` in first-match-wins Auto order, would have stolen full-band packs from the guitar highway even on Lead/Bass arrangements; it now claims only drum arrangements, or packs nothing more specific can render). Picking the drum highway manually from the viz picker is unchanged.
|
||||
- **The tuner now tracks what tuning your instrument is *actually* in, so it prompts you to retune in BOTH directions — down to a song's tuning, and back up when the next song needs it.** The coverage check used to compare each song against your fixed instrument-profile tuning, so it only ever prompted you *away* from "home" (e.g. E → Drop C#) and stayed silent coming back (Drop C# → E), even though you'd physically retuned. It now reads the host's live **per-instrument working tuning** (`window.feedBack.workingTuning`) — what your selected instrument is currently in — so coverage is measured against your *actual* tuning and fires both ways. When you clear an auto-opened tuner, the tuner publishes that song's tuning as your instrument's live working tuning (`assumed` — an explicit "I tuned / Skip" refines it in a later PR), so the next song is judged against where you now are. **Per-instrument** — your guitar's and bass's tunings are tracked separately (keyed like the selector), so switching instruments uses the right one. Feature-detected: on a host without the working-tuning capability it falls back to the static `/api/settings` tuning (today's behavior). `plugins/tuner/screen.js` (`_playerTuning` reads `workingTuning` keyed by the selected instrument; `_publishWorkingTuning` writes on clear). Builds on the host `workingTuning` foundation (PR 1 of the series) + the instrument→chart routing (PR 2). Tests: `tests/js/tuner_auto_open.test.js` (both-directions coverage via a live Drop-D working tuning; publish-on-clear targets the right instrument slot) — 29 pass.
|
||||
- **`.jsonc` support for feedpak data files** (feedpak-spec §8, FEP #3 / PR #13). Hand-edited packs may now use the `.jsonc` extension (JSON with C-style `//` line and `/* */` block comments) for any data file the manifest points at — arrangements, notation sidecars, `drum_tab`, `song_timeline`, `lyrics`, and `keys`. New shared `lib/jsonc.py` provides `parse_jsonc(text)` + `load_json(path)` (auto-detects `.jsonc` by suffix, string-aware so comment-like text inside JSON string values is preserved) and is now used by every reader in `lib/sloppak.py` (six side-file sites) and `scripts/lift_keys_notation.py` (three arrangement / song_timeline read sites). The strip regex mirrors the reference validator in `feedpak-spec/tools/validate.py`. This is an additive (MINOR) change: `.jsonc` is opt-in, so any pack that keeps its data files as `.json` is unaffected and needs no regeneration. Note that a `.jsonc` file containing real comments only loads on a reader that implements §8 — a pre-this-change reader calls bare `json.loads` and fails on the comments rather than ignoring them, so don't hand out `.jsonc` packs to older hosts. Tests: `tests/test_sloppak_jsonc_load.py` (covers all six side-file types, the lift helper, and the string-boundary preservation rule end-to-end).
|
||||
- **The highway now loads the part that matches your selected instrument — a bass player gets the Bass arrangement, not the default Lead/guitar chart.** When you open a song without an explicit arrangement, the WebSocket handler (`server.py` `highway_ws`) reads your selected `instrument` from `config.json` (the same file it already reads for your default-arrangement preference) and routes to the matching part: **bass → the Bass arrangement**; guitar — and any unknown/future instrument (drums, keys) — falls through to the existing preference/most-notes default, which already lands on a guitar part. Previously the instrument selector only fed the tuner, so a bass player was handed a guitar chart (and a tune/coverage check then compared a 4-string bass against a 6-string part). An **explicit arrangement request always wins** (a manual arrangement switch is untouched), and a bass player's saved default-arrangement preference is still honored **within** the bass parts (so a preferred `Bass 2` / `Alt. Bass` wins over the canonical Bass), so this only changes the *default* part chosen on load. Server-only — every launch path already flows through the WS, so there's no client change. This is the instrument↔chart-routing piece the working-tuning series leans on (otherwise coverage compares across instruments). Tests: `tests/test_highway_ws_instrument_routing.py` (bass→Bass, bass-honors-pref, bass-no-bass-part→guitar, guitar→default, explicit-wins).
|
||||
- **Host "working tuning" — a live, app-wide record of what tuning your instrument is *actually* in right now (foundation; no behavior change yet).** Introduces `window.feedBack.workingTuning`, a host-owned, session-lived state distinct from any one song's tuning and from a soft opt-in default: the offsets + string-count + reference pitch the player's instrument is currently in, plus an `assumed`/`verified` provenance flag. It's **per-instrument** — your guitar's current tuning and your bass's are kept *separately* (keyed like the instrument selector, e.g. `guitar-6` / `bass-4`), so switching instruments surfaces that instrument's own remembered tuning and you only ever deal with the one you've selected. It exists so a retune — or an instrument swap mid-session — is reflected **everywhere** (the highway, the library/song-picker, and plugins like the tuner, Virtuoso, and the minigames) instead of being re-derived per surface or wrongly assumed from a fixed profile. Modeled on the shipped `tuning` capability + the `feedBack.theme` read-API: a **synchronous `get(instrument?)`** (returns the selected instrument's state, defaulting to the seed until known), a `set(state, {provenance, instrument})` mutator (the tuner becomes the sole writer in the next change), `setCurrentInstrument()` for the selector, `resetToDefault()`, and a `working-tuning-changed` event that fires on every change **and once on hydration** (carrying which instrument changed) so a late-mounting consumer is never stuck on stale state. State is **in-memory, seeded from `/api/settings` on boot and reset on restart** — a stale "you're in drop-A" assumption is worse than re-asking. Registered as a separate `working-tuning` **exclusive-owner** capability (tuner = writer, the rest = requesters). This is the foundation (plumbing only — nothing writes to it yet) of the working-tuning series, which fixes the tuner gate only ever prompting *away from* a fixed "home" tuning (never back) and makes the current tuning a first-class signal the whole app shares. Offsets use the same per-string semitone vocabulary as song tunings, so fully custom/extended tunings (e.g. a drop-A 8-string) are first-class. Frontend-only: new `static/capabilities/working-tuning.js`, loaded from `static/index.html` + `static/v3/index.html`.
|
||||
- **The v3 Songs grid is now DOM-virtualized — card-node count stays bounded no matter how big the library is or how far you scroll.** The grid used to append every scrolled page and never let go, so a 2000-song library grew the DOM from 24 → 624 → 2001 card nodes as you scrolled (layout/memory cost scaling with depth). It now renders only the **visible window** of cards (± a small overscan); a sizer element sized to the whole library (`ceil(total/cols) × rowH`) gives the scrollbar its full geometry while the grid is absolutely positioned to the first visible row. `state.songs` is a sparse, absolutely-indexed store fetched a page at a time on demand — using the stage-1 **keyset cursor** for contiguous forward scroll (O(page)) and falling back to `OFFSET page=` for jumps/restore/non-keyset providers (collections, remote). Verified bounded (~60 nodes for a 2001-song library while the count still reads "2001 songs"). The **A–Z rail now seeks directly**: `sort_letters` gives a letter's first-row index (cumulative of prior buckets), converted to a scrollTop in O(1) — no more paging through every intervening row (a bounded forward scan covers the rare legacy provider without `sort_letters`). Select-mode selections, accuracy badges, the ⋮ card menu, plugin card actions, scroll-restore (now scrollTop-based, since geometry is stable), and the tree/folder views all survive cards leaving and re-entering the DOM. Plugins that decorate cards get a stable `window.v3Songs.visibleCards()` accessor + a `v3:library-window-rendered` event instead of assuming every card is present (the highway-stutter lesson). Stage 2 of the virtualized-grid project (got-feedback/feedBack#636 item 3), building on the stage-1 keyset data layer below. Frontend-only: `static/v3/songs.js`, `static/v3/v3.css`. Tests: `tests/browser/v3-grid-virtualization.spec.ts` (bounded-DOM invariant across a 2001-song scroll + direct rail jump), updated `tests/js/v3_az_rail.test.js` + `tests/js/v3_songs_scroll.test.js`.
|
||||
- **Keyset (cursor) pagination for the library grid — the data layer for an upcoming virtualized grid, and a latent paging bug fixed along the way.** Every library sort now carries a unique `filename` tiebreak, making the order **total** — which fixes a latent bug where rows sharing a sort key (e.g. two songs by the same artist) could be skipped or duplicated across `OFFSET` pages. `GET /api/library` gains an opaque `after` cursor + a `next_cursor` in the response: passing the cursor back fetches the next page with a **WHERE-seek** instead of `OFFSET`, so deep paging is O(page) regardless of depth. The seek is NULL-aware and exactly `OFFSET`-equivalent (verified across artist/title/recent, ascending + descending, including the legacy `dir=desc` shape and NULL sort keys); unknown/compound sorts and bad cursors fall back to `OFFSET`, and only the local provider is handed a cursor (collections/remote page by `OFFSET`). New composite `(artist NOCASE, filename)` / `(title NOCASE, filename)` / `(mtime, filename)` indexes cover the order. This is stage 1 of the virtualized-grid project (got-feedback/feedBack#636 item 3); the DOM-recycling render window builds on it next. Tests: `tests/test_library_keyset.py` (keyset==OFFSET parity, stable tiebreak, dir=desc, NULL keys, cursor fallback).
|
||||
- **Smart collections — save a set of library filters as a live, auto-updating source.** A collection is a saved `/api/library` query (e.g. "Drop-D tunings", "sloppak only", "recently added") that stays live: it's registered as a **library provider**, so it shows up in the v3 Songs source picker and inherits the whole grid UI — paging, stats, the A–Z rail, art — for free, with **no new screen**. Storage reuses the playlist subsystem (a `playlists.rules` JSON blob = a smart collection; membership is the live filter result, not stored songs, and collections are excluded from the manual-playlist list + read-only to playlist mutations). New `GET`/`POST`/`PUT`/`DELETE /api/collections`; a per-collection `SmartCollectionProvider` delegates `query_page`/`query_stats`/`query_artists` to the local DB with the stored rules applied; providers are re-registered from a boot scan so collections survive a restart. Rules mirror the raw `/api/library` query params (unknown keys dropped, never 500). Frontend: a "+ Save as collection" action in the v3 filter drawer (shown when filters are active) names the current filter set and switches to it. The charrette's "the homelab primitive FeedBack was missing" pick (got-feedback/feedBack#636 item 2); richer rule fields (accuracy, genre, difficulty) follow as the metadata work lands. Tests: `tests/test_collections_api.py`, `tests/js/v3_collections.test.js`.
|
||||
@@ -47,6 +54,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
- **v3 library: exact artist/album filters + scroll/page-depth restore** (feedBack#857). The v3 Songs toolbar gains Artist and Album dropdowns (Album populates from the selected artist and stays disabled until one is chosen), backed by new exact, case-insensitive (`COLLATE NOCASE`) `artist` / `album` query params threaded through `MetadataDB._build_where` → `query_page` / `query_artists` / `query_stats` and the `/api/library`, `/api/library/artists`, `/api/library/stats` endpoints (the free-text `q` search stays fuzzy and composes with the exact filters). The artist/album catalog is fetched independently of the active artist/album selection so the dropdowns always list the full set for the current provider/search. The toolbar is now sticky so filter controls stay reachable when browsing deep libraries, and returning from the player restores the previous scroll position **and** the loaded infinite-scroll page depth via a `sessionStorage` snapshot keyed by a filter/sort/view state hash (invalidated whenever those change, so a filter change still resets to the top). Tests: `tests/test_library_filters.py` (backend artist/album filters), `tests/js/v3_songs_scroll.test.js` (state-hash + snapshot helpers).
|
||||
|
||||
### Fixed
|
||||
- **Tuner auto-open is now opt-in and persists instead of flashing open-then-shut.** When you entered a song (or switched arrangement) whose tuning differed from the last, the tuner auto-opened and — for some testers — vanished ~1s later (reported macOS+Windows, 0.3.0). Root cause: the tuner closes itself on `song:play` (`plugins/tuner/utils/ui.js` — you don't tune while playing), so a **song switch** fired autoplay → `song:play` → the just-auto-opened tuner closed; an **arrangement switch** (which never arms autoplay) had no `song:play`, so it stayed open — exactly why two testers saw opposite behaviour (it wasn't the mic). Now: (1) the feature is a **new opt-in setting** ("Auto-open on tuning change", in the tuner's Settings panel, persisted as `autoOpenOnTuningChange`, **default OFF**); (2) an **auto**-opened tuner *persists* — it ignores the autoplay `song:play`, stray outside-clicks, and same-screen re-emits, closing only via the new in-panel **`×`** / **"Skip"** buttons or when you leave the song. A *manually* opened tuner keeps its classic click-away / play-to-close behaviour. The panel previously had no in-box close at all; this adds one (`×` + contextual Skip). All in the tuner plugin (`routes.py` config, `screen.js` gate + persist, `utils/ui.js` buttons + `song:play` guard, `settings.html` toggle) — **no core `app.js` changes**. Tests: `tests/js/tuner_auto_open.test.js` (opt-in gate, `{ auto: true }` persist mode, play/click-proofing). **Default (opt-in vs opt-out) is teed up for Byron to decide — flip one boolean.**
|
||||
- **Tuner auto-open is now tuning-coverage-aware — extended-range players aren't nagged for songs their instrument already covers.** With the opt-in auto-open on, it now prompts only when your **current physical tuning** (from your instrument selection in Settings) doesn't already cover the song. FeedBack is tune-to-song — the highway draws tab in the song's tuning — so the check aligns the song's open-string tuning string-for-string against your instrument: an **8-string F♯-standard** player gets **no** prompt for a 6- or 7-string standard song (its top strings already match those tunings), while a song needing an open string you don't have (e.g. a **Drop-A 7-string**, whose low A isn't an open string on an F♯ 8-string) **still** prompts. A whole-instrument reference difference also prompts — A440 vs A432, or an octave-down `centOffset` (which the auto-open now accounts for; it was previously ignored). The player's instrument is read from core **`/api/settings`** (the v3 instrument selector — a stable physical reference, not the tuner's song-tracking selection); when nothing's declared or the lookup is unavailable it falls back to a conservative prompt, so a real retune is never silently skipped. **v3-only** (the instrument selector is v3). All in the tuner plugin (`plugins/tuner/screen.js`) — **no core changes**. Tests: `tests/js/tuner_auto_open.test.js` (covered vs uncovered, the Drop-A case, reference-pitch mismatch, contiguous alignment). _Follow-up (E1.6): a passive "different tuning" badge cue that names the string(s) to retune, plus the splitscreen / no-usable-input guards._
|
||||
- **The tuner badge now passively flags when a song needs a different tuning — and names the retune.** Building on the coverage check: when you enter a song your current instrument doesn't cover, the topbar tuner badge gets an amber ring and a tooltip that **names the change** — e.g. *"retune B→A"* for a Drop-A song on an F♯ 8-string, or *"the reference pitch"* for an A440-vs-A432 mismatch. It's purely **advisory** (it never auto-opens the panel — tap the badge to tune), recomputed on `song:ready` and cleared when a new song loads or you leave the player. The retune diff comes from the tuner plugin's coverage report (`window._tunerAutoOpen.coverageReport` → `{ covered, retune: [{ from, to }], reference, cantCover }`); the cue is CSS-free (an inline ring + native tooltip — no Tailwind rebuild) and no-ops when the tuner plugin isn't installed. **v3-only.** Touches `static/v3/badges.js` (the cue) + `plugins/tuner/screen.js` (the report). Tests: `tests/js/tuner_auto_open.test.js` (the report names the strings; reference mismatch; the badge wiring). _(The splitscreen-suppress and no-usable-input guards move to the playback-gate stage, where they matter for its no-trap rule.)_
|
||||
- **Tuner auto-open can now gate playback until you've tuned — the "tune before you play" model — via a new core `holdAutoplay()` hook.** With the opt-in auto-open on, when a song needs a retune the tuner opens and **playback waits** for your choice — **Skip** (you've tuned → play, and record the song's tuning as your instrument's current working tuning), **Back to library** / **Esc** (leave the song; a gated retune is never a one-way trap), or press **Play** (always wins). For an auto-open the in-panel **×** is dropped — Skip / Back to library / Esc are its dismiss surface. Previously the song played with the tuner overlaid; now it holds — which also definitively kills the original flash, since autoplay's `song:play` can't fire while playback is held. Implemented as a small **core hook** `window.feedBack.holdAutoplay()` (mirrors the existing `holdAutoExit()`): a plugin claims it **synchronously on `song:loading`** (so it beats the `song:ready` autostart), and `release()` — or a **12-second fail-open backstop** — runs the deferred start. **Generation-guarded** (a new song invalidates a stale hold) and **fail-open** (a wedged or crashed plugin can never permanently strand a song); **manual Play always wins** (it doesn't flow through the autostart path). The tuner claims the gate only when the feature is on, and **releases it the instant** it decides not to open (song already covered / tuning unchanged) or when you Skip. Touches core `static/app.js` (the hook + an autostart refactor) and the tuner plugin (`plugins/tuner/screen.js` — the claim/release; `plugins/tuner/utils/ui.js` — the Skip / Back-to-library buttons, × dropped on auto-open); the hook is generic and shell-agnostic (a test asserts `app.js` still doesn't reference the tuner's internals). Tests: `tests/js/tuner_auto_open.test.js` (claim on `song:loading`, release on dismiss, feature-off no-claim, the core hook + fail-open backstop, the Skip / Back-to-library / Esc escape-hatch) + a `speed_reset.test.js` stub. ⚠️ **Needs a manual smoke-test before shipping** — this is a core playback change; verify on desktop that the tuner mic doesn't contend with note_detect's scoring input (ASIO/exclusive mode), per the design charrette.
|
||||
- **v3 player: opening another rail popover now closes the Section Practice popover (no more two stacked popovers).** Opening the **Practice** pill's popover and then clicking a different player-rail icon (e.g. **Plugins**) left the Practice popover open underneath the new one — looked broken (reported on macOS, 0.3.0 / 2026-06-28). The rail icons call `e.stopPropagation()` in their click handler (`static/v3/player-chrome.js`), which killed bubbling before it reached the Practice popover's outside-click dismiss bound on `document`. The dismiss (`_installSectionPracticeDismiss` in `static/app.js`) now binds in the **capture phase**, which runs before the target's handler so a descendant's `stopPropagation()` can't swallow it — mirroring how the audio-mixer popover already dismisses. Esc handling stays bubble-phase (the player's Escape-to-exit ordering is unchanged). v2 shares `app.js` and is only hardened (no rail `stopPropagation` there). Tests: `tests/js/section_practice_dismiss.test.js`.
|
||||
- **v3 UI no longer lets you accidentally text-select the chrome.** Dragging or double-clicking across the interface used to marquee-highlight buttons, labels, the sidebar, the transport, and the note-highway HUD — which looks broken (reported on Mac + Windows). The v3 shell now defaults to `user-select: none` on `html` (`static/v3/v3.css`), then opts *content* back in — so chrome is non-selectable but the text you actually copy still works. Decided by a 4-lens panel (UX / accessibility / dev-ops / plugin-ecosystem); the guardrails are deliberate: **form fields are always re-enabled** (never break the caret / IME — no `* { user-select:none }`, which trips a WebKit input bug); **plugin screens (`.screen[id^="plugin-"]`) stay selectable by default** so a plugin's copyable text (lyrics, chord names, results) — including community plugins that don't know about this — isn't silently locked; and **core read-only content opts back in by container** via a new hand-authored **`.fb-selectable`** class — applied to the whole **Settings** panel (paths, device names, version, diagnostics, About — answering "is settings still copyable?": yes), the **now-playing song metadata** (with `pointer-events` re-enabled so the HUD text is actually reachable), and the focused **modals / dialogs / toasts / scan banner** that carry copyable errors, IDs, paths, and file names. It's cosmetic only (it protects nothing) and never used to lock copy-worthy text — errors, IDs, paths, versions, and metadata stay selectable per WCAG 2.2 (copy-paste as a permitted mechanism). Dense card lists (library grid, dashboard, profile) stay non-selectable by design — making them selectable would reintroduce the marquee-mess across cards. **v3-only** (v2 unchanged); plain CSS, no Tailwind rebuild; no desktop changes (standard OS-framed window). Plugin authors: `.fb-selectable` is documented in `CLAUDE.md` for re-enabling copyable content rendered outside a plugin screen. Tests: `tests/js/v3_user_select_policy.test.js`.
|
||||
- **Input-setup wizard no longer collapses an audio device's driver-type variants into one entry.** On Windows the desktop engine enumerates the same interface once per host API (ASIO / Windows Audio / DirectSound), and the wizard's audio picker (`plugins/input_setup/screen.js`) de-duped the source list by display **label** — so the variants (which share a name) collapsed to a single choice, silently keeping whichever sorted first (often *not* the low-latency ASIO one the player wants). The audio-input capability already collapses true duplicates by `logicalSourceKey` (`_visibleInputSources` in `static/capabilities/audio-session.js`), and the variants each have a **distinct** key, so the wizard's extra label-collapse was redundant for real dupes and destructive for these — it also could drop the variant that was actually `selected`. Removed it; the picker now lists every selectable input. Pairs with feedBack-desktop's change to label each source with its driver type (e.g. "Focusrite (ASIO)") so the now-distinct entries are legible.
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
# Working-tuning — on-device test checklist
|
||||
|
||||
The working-tuning series (PRs 1–9) ships with headless unit tests for every state
|
||||
machine (`tests/js/working_tuning*.test.js`, `tests/js/tuner_auto_open.test.js`). The
|
||||
items below are the parts that **cannot** be covered headlessly — they need a real mic,
|
||||
a real instrument, and (for the ASIO item) a specific audio backend. Run these on a
|
||||
build before shipping the feature to users.
|
||||
|
||||
Prereq: enable the opt-in in **Tuner → settings → "Auto-open on tuning change"** (it's
|
||||
off by default). Have a guitar (and a bass, for the per-instrument checks) on hand.
|
||||
|
||||
## 1. Auto-open + gate ("tune before you play")
|
||||
- [ ] Load a song whose tuning differs from your instrument's current tuning → the tuner
|
||||
**auto-opens** and playback **waits** (does not start underneath it).
|
||||
- [ ] Load a song already covered by your tuning → **no** auto-open, playback starts.
|
||||
- [ ] **Skip** ("I've tuned") → playback starts, and the tuner badge stops flagging this
|
||||
song's tuning (a working tuning was recorded).
|
||||
- [ ] **Back to library** / **Esc** → leaves the song, records **nothing** (re-enter the
|
||||
same song → it still prompts).
|
||||
- [ ] Take **longer than 12 s** to tune with the panel open → playback does **not** start
|
||||
underneath you (the fail-open backstop was settled once the panel opened).
|
||||
- [ ] Hit **Play** manually while the panel is open → Play wins; no double-start.
|
||||
|
||||
## 2. Both-directions retune prompt
|
||||
- [ ] From standard, load a Drop-C# song → prompted **down** (E→C#). Tune down, Skip.
|
||||
- [ ] Now load a standard song → prompted **back up** (C#→E). (Pre-series, this direction
|
||||
was silent.)
|
||||
- [ ] Switch guitar↔bass in the instrument card → each instrument remembers its **own**
|
||||
working tuning; the card label follows the selection (dim = home, amber = retuned).
|
||||
|
||||
## 3. Mic-verify (assumed → verified)
|
||||
- [ ] With a selected (non-free) tuning, tap **Verify tuning** and play each string in tune.
|
||||
Each string needs ~8 stable in-tune frames (±6 ¢); the per-string progress advances.
|
||||
- [ ] Play a string **out of tune** → it never completes; drifting out mid-streak resets it.
|
||||
- [ ] Complete all strings → the instrument card's provenance glyph flips to the **filled**
|
||||
(verified) diamond, and the recorded working tuning carries the tuning you verified
|
||||
(not a stale one).
|
||||
- [ ] Load the **next** song → the verified state **decays to assumed** (per-session only).
|
||||
- [ ] Verify against a **manually-selected** tuning (tuner opened off a song) → the stamped
|
||||
offsets match that tuning, not the last song's.
|
||||
|
||||
## 4. Mic contention with note-detection (the ASIO / exclusive-mode risk)
|
||||
This is the item flagged in the design charrette: the tuner's mic capture must not starve
|
||||
note_detect's scoring input.
|
||||
- [ ] Desktop, **ASIO / WASAPI-exclusive** device: auto-open the tuner mid-song, tune, Skip
|
||||
→ scoring resumes cleanly; no dropped input, no device-in-use error, no crash.
|
||||
- [ ] Shared/`auto` device: same flow → both the tuner and scoring read the mic without a
|
||||
stall.
|
||||
- [ ] Leave the tuner's background badge audio running + start a scored song → note_detect
|
||||
still scores (the badge auto-start doesn't hold the device exclusively).
|
||||
|
||||
Log the build hash and OS/audio backend with results; file any failure against the
|
||||
working-tuning series.
|
||||
@@ -0,0 +1,56 @@
|
||||
"""JSONC support — JSON with C-style comments.
|
||||
|
||||
Per feedpak-spec §8: when a manifest pointer resolves to a ``.jsonc`` file, a
|
||||
Reader MUST strip ``//`` line comments and ``/* */`` block comments before
|
||||
parsing the JSON content. This module implements that stripping in a single
|
||||
shared place so every sloppak/feedpak reader in this repo parses ``.jsonc``
|
||||
the same way (string-aware so comment-like text inside JSON strings survives).
|
||||
|
||||
The regex mirrors the reference implementation in ``feedpak-spec/tools/validate.py``.
|
||||
``load_json(path)`` auto-detects ``.jsonc`` by suffix; plain ``.json`` (and any
|
||||
other extension) goes straight through ``json.loads``. Use it as a drop-in
|
||||
replacement for ``json.loads(path.read_text(encoding="utf-8"))``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
# Match JSON string literals (preserved), // line comments, and /* block */
|
||||
# comments. A single combined alternation processed by `sub` with a callback
|
||||
# that keeps strings and replaces comments with the empty string — so
|
||||
# comment-like text inside a string literal is never stripped.
|
||||
_JSONC_STRIP_RE = re.compile(
|
||||
r'"(?:[^"\\]|\\.)*"|' # string literal — keep as-is
|
||||
r'//.*|' # // line comment — strip
|
||||
r'/\*[\s\S]*?\*/', # /* block comment */ — strip
|
||||
)
|
||||
|
||||
|
||||
def parse_jsonc(text: str) -> object:
|
||||
"""Parse a JSONC string, stripping C-style comments before JSON parsing.
|
||||
|
||||
Handles ``//`` line comments and ``/* */`` block comments, respecting
|
||||
string boundaries so that comment-like text inside strings is preserved.
|
||||
Raises ``json.JSONDecodeError`` on malformed JSON (after stripping).
|
||||
"""
|
||||
stripped = _JSONC_STRIP_RE.sub(
|
||||
lambda m: m.group(0) if m.group(0).startswith('"') else '',
|
||||
text,
|
||||
)
|
||||
return json.loads(stripped)
|
||||
|
||||
|
||||
def load_json(path: Path) -> object:
|
||||
"""Read and parse a JSON/JSONC file by path.
|
||||
|
||||
Files ending in ``.jsonc`` are stripped of comments via :func:`parse_jsonc`;
|
||||
all other files are parsed as plain JSON. UTF-8 encoded, matching every
|
||||
other reader in this repo.
|
||||
"""
|
||||
raw = path.read_text(encoding="utf-8")
|
||||
if path.name.lower().endswith(".jsonc"):
|
||||
return parse_jsonc(raw)
|
||||
return json.loads(raw)
|
||||
+7
-7
@@ -13,7 +13,6 @@ See the format spec in the project's sloppak plan for the full layout.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import shutil
|
||||
@@ -37,6 +36,7 @@ SONG_EXTS = (FEEDPAK_EXT, SLOPPAK_EXT) # accepted on read/discovery
|
||||
|
||||
import yaml
|
||||
|
||||
from jsonc import load_json
|
||||
from safepath import safe_join
|
||||
from song import (
|
||||
Song,
|
||||
@@ -423,7 +423,7 @@ def load_song(
|
||||
if not arr_path.exists():
|
||||
continue
|
||||
try:
|
||||
data = json.loads(arr_path.read_text(encoding="utf-8"))
|
||||
data = load_json(arr_path)
|
||||
except Exception as e:
|
||||
log.debug("sloppak: failed to parse arrangement %r: %s", rel, e)
|
||||
continue
|
||||
@@ -489,7 +489,7 @@ def load_song(
|
||||
raw_nt = None
|
||||
if nt_path is not None and nt_path.exists():
|
||||
try:
|
||||
raw_nt = json.loads(nt_path.read_text(encoding="utf-8"))
|
||||
raw_nt = load_json(nt_path)
|
||||
except Exception as e:
|
||||
log.warning("sloppak: failed to parse notation %r: %s", notation_rel, e)
|
||||
if raw_nt is not None:
|
||||
@@ -528,7 +528,7 @@ def load_song(
|
||||
dt_path = None
|
||||
if dt_path is not None and dt_path.exists():
|
||||
try:
|
||||
raw = json.loads(dt_path.read_text(encoding="utf-8"))
|
||||
raw = load_json(dt_path)
|
||||
except Exception as e:
|
||||
log.warning("sloppak: failed to parse drum_tab %r: %s", drum_tab_rel, e)
|
||||
raw = None
|
||||
@@ -588,7 +588,7 @@ def load_song(
|
||||
st_path = None
|
||||
if st_path is not None and st_path.exists():
|
||||
try:
|
||||
raw = json.loads(st_path.read_text(encoding="utf-8"))
|
||||
raw = load_json(st_path)
|
||||
except Exception as e:
|
||||
log.warning("sloppak: failed to parse song_timeline %r: %s", song_timeline_rel, e)
|
||||
raw = None
|
||||
@@ -686,7 +686,7 @@ def load_song(
|
||||
lyr_path = None
|
||||
if lyr_path is not None and lyr_path.exists():
|
||||
try:
|
||||
raw = json.loads(lyr_path.read_text(encoding="utf-8"))
|
||||
raw = load_json(lyr_path)
|
||||
except Exception as e:
|
||||
log.debug("sloppak: failed to parse lyrics %r: %s", lyrics_rel, e)
|
||||
raw = None
|
||||
@@ -773,7 +773,7 @@ def load_song(
|
||||
k_path = None
|
||||
if k_path is not None and k_path.exists():
|
||||
try:
|
||||
raw = json.loads(k_path.read_text(encoding="utf-8"))
|
||||
raw = load_json(k_path)
|
||||
except Exception as e:
|
||||
log.warning("sloppak: failed to parse keys %r: %s", keys_rel, e)
|
||||
raw = None
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
*.swp
|
||||
.vscode/
|
||||
.idea/
|
||||
@@ -0,0 +1,661 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
@@ -0,0 +1,82 @@
|
||||
# 3D Drum Highway — Mockup
|
||||
|
||||

|
||||
|
||||
An exploratory **pure-visual** sibling of `highway_3d`. Renders an 8-lane
|
||||
drum highway (7 lanes for hand pieces + a full-width kick bar) populated
|
||||
from a hardcoded demo pattern that loops indefinitely. Not yet wired to
|
||||
song data, hit detection, audio, or note_detect — this is here to play
|
||||
with the look-and-feel.
|
||||
|
||||
To see it, load any song in the player, then pick **3D Drum Highway**
|
||||
from the viz picker. The mockup animates regardless of what song is
|
||||
playing.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
[HH] [SNR] [TM1] [TM2] [FT] [CR] [RD] <- 7 lanes, left to right
|
||||
| | | | | | |
|
||||
v v v v v v v
|
||||
----- hit line -----------------------------
|
||||
▓▓▓▓▓▓▓▓▓▓▓▓▓ KICK BAR ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ <- full-width kick lane
|
||||
```
|
||||
|
||||
- **Drums** (snare, toms, floor tom): flat disc geometry (`CylinderGeometry`),
|
||||
palette-tinted, with subtle emissive pulse on approach. Snare gets a
|
||||
thin white "wires" stripe.
|
||||
- **Cymbals** (hi-hat, crash, ride): faceted gem geometry (truncated
|
||||
`CylinderGeometry`), metallic material, slightly translucent.
|
||||
- **Kick**: full-width amber bar across the base, brighter on approach.
|
||||
|
||||
## Variants visible in the demo
|
||||
|
||||
| Variant | How it reads |
|
||||
|---|---|
|
||||
| `accent` | Bigger note + white halo ring |
|
||||
| `ghost` | Hollow ring (~65% size) instead of a solid disc |
|
||||
| `flam` | Main note + a small grace disc offset slightly before |
|
||||
| `bell` | Ride only — adds a bright dot in the center of the gem |
|
||||
|
||||
The **Fill showcase** demo pattern fires every variant at least once in
|
||||
a few bars, plus a tom roll down the kit. Best read of what's possible.
|
||||
|
||||
## Settings (Settings → Plugins → 3D Drum Highway)
|
||||
|
||||
- **Palette** — shared 3 palettes with `highway_3d` (default / neon / pastel).
|
||||
- **Demo pattern** — rock backbeat / jazz swing / fill showcase.
|
||||
- **Camera angle** — 0 (down the lanes) to 1 (top-down). Default 0.35.
|
||||
|
||||
All settings persist in `localStorage` under the `drum_h3d_*` prefix.
|
||||
|
||||
## What this plugin is *not* doing yet
|
||||
|
||||
(Historical note: this started as a pure-visual mockup; it now reads
|
||||
`bundle.drumTab` + `bundle.currentTime` and scores MIDI hits against the
|
||||
chart, so the old "no song-data wiring" caveats are gone.)
|
||||
|
||||
- Sustain trails (drums don't sustain meaningfully)
|
||||
- Sticking labels, double kick, rolls — see the TODOs in `screen.js`
|
||||
for the variant backlog
|
||||
|
||||
## Ported helpers (keep in sync with highway_3d)
|
||||
|
||||
Visual-parity code copied from `plugins/highway_3d/screen.js` — same
|
||||
function names, signatures, and constants on purpose, marked with
|
||||
`PORTED FROM highway_3d` comments at each site. If the guitar highway
|
||||
tunes one of these, mirror the change here (and in `keys_highway_3d`):
|
||||
|
||||
- `_bloomEnsure()` / `_bloomDispose()` — EffectComposer + UnrealBloomPass
|
||||
(0.65/0.5/0.82) on a multisampled HalfFloat target, ACES↔None tone-
|
||||
mapping switch in `draw()`; addons dynamic-imported from
|
||||
`/static/vendor/three/addons/` (no CDN fallback — direct render is the
|
||||
graceful degrade)
|
||||
|
||||
## Why a separate plugin (vs. drum mode inside highway_3d)?
|
||||
|
||||
Cleaner iteration. The drum highway is its own geometry, its own
|
||||
gameplay assumptions (lanes ≠ strings, no frets, no chord shapes,
|
||||
no sustains), and likely its own chart format. Forking the visuals
|
||||
in a sibling plugin lets the mockup move fast without risking
|
||||
regressions in the guitar viz that ships today. If the drum highway
|
||||
eventually matures, we can decide whether to merge or keep separate.
|
||||
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 256 256" role="img" aria-label="3D Drum Highway placeholder thumbnail">
|
||||
<rect width="256" height="256" rx="36" fill="#0f172a"/>
|
||||
<rect x="18" y="18" width="220" height="220" rx="28" fill="#1e293b" stroke="#334155" stroke-width="3"/>
|
||||
<text x="128" y="150" font-family="Rubik, Arial, sans-serif" font-size="104" font-weight="800" fill="#38bdf8" text-anchor="middle">3D</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 464 B |
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"id": "drum_highway_3d",
|
||||
"name": "3D Drum Highway",
|
||||
"version": "0.3.0",
|
||||
"type": "visualization",
|
||||
"bundled": true,
|
||||
"script": "screen.js",
|
||||
"settings": {
|
||||
"html": "settings.html",
|
||||
"category": "graphics"
|
||||
},
|
||||
"standards": [
|
||||
"capability-pipelines.v1",
|
||||
"plugin-runtime-idempotent.v1"
|
||||
],
|
||||
"capabilities": {
|
||||
"midi-input": {
|
||||
"roles": [
|
||||
"requester"
|
||||
],
|
||||
"requests": [
|
||||
"discover",
|
||||
"list-sources",
|
||||
"select-source",
|
||||
"open-source",
|
||||
"close-source"
|
||||
],
|
||||
"mode": "active",
|
||||
"compatibility": "degrade-noop",
|
||||
"ownership": "requester-only",
|
||||
"safety": "sensitive",
|
||||
"description": "Reads the e-kit/MIDI-pad input through the core midi-input domain (Web-MIDI provider ships built-in with the domain). Absent domain \u2192 no MIDI devices, fail-soft.",
|
||||
"version": 1
|
||||
}
|
||||
},
|
||||
"category": "practice",
|
||||
"description": "3D note highway for drum charts.",
|
||||
"icon": "assets/thumb.svg"
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
After Width: | Height: | Size: 44 KiB |
@@ -0,0 +1,456 @@
|
||||
<div role="group" aria-labelledby="drumh3d-heading">
|
||||
<h3 id="drumh3d-heading" class="text-sm font-medium text-gray-400 mb-2">3D Drum Highway</h3>
|
||||
<p class="text-xs text-gray-500 mb-3">
|
||||
Pick a song with a drum tab (sloppak-spec §5.3), choose <em>3D
|
||||
Drum Highway</em> from the viz picker. The plugin auto-attaches
|
||||
to your MIDI controller and routes chart pieces through the kit
|
||||
you configure below.
|
||||
</p>
|
||||
|
||||
<!-- Palette -->
|
||||
<div class="mt-3">
|
||||
<label for="drumh3d-palette" class="text-xs font-medium text-gray-400 mb-1 block">Palette</label>
|
||||
<select id="drumh3d-palette"
|
||||
onchange="window.drumH3dSetPalette && window.drumH3dSetPalette(this.value); (window._drumH3dRenderPaletteSwatches || function(){})(this.value)"
|
||||
class="w-full bg-dark-700 border border-gray-800 rounded-lg px-3 py-2 text-xs text-gray-300 outline-none">
|
||||
<option value="default">Default (Classic)</option>
|
||||
<option value="neon">Neon (saturated, electric)</option>
|
||||
<option value="pastel">Pastel (soft, low contrast)</option>
|
||||
</select>
|
||||
<div class="mt-2 flex items-center gap-1" aria-hidden="true">
|
||||
<span id="drumh3d-swatch-0" class="inline-block h-6 w-5 rounded border border-gray-700/60"></span>
|
||||
<span id="drumh3d-swatch-1" class="inline-block h-6 w-5 rounded border border-gray-700/60"></span>
|
||||
<span id="drumh3d-swatch-2" class="inline-block h-6 w-5 rounded border border-gray-700/60"></span>
|
||||
<span id="drumh3d-swatch-3" class="inline-block h-6 w-5 rounded border border-gray-700/60"></span>
|
||||
<span id="drumh3d-swatch-4" class="inline-block h-6 w-5 rounded border border-gray-700/60"></span>
|
||||
<span id="drumh3d-swatch-5" class="inline-block h-6 w-5 rounded border border-gray-700/60"></span>
|
||||
<span id="drumh3d-swatch-6" class="inline-block h-6 w-5 rounded border border-gray-700/60"></span>
|
||||
<span id="drumh3d-swatch-7" class="inline-block h-6 w-5 rounded border border-gray-700/60"
|
||||
style="background:#ffa030"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Camera angle -->
|
||||
<div class="mt-4">
|
||||
<label for="drumh3d-camera" class="text-xs font-medium text-gray-400 mb-1 block">
|
||||
Camera angle <span id="drumh3d-camera-val" class="text-gray-500 font-mono">0.35</span>
|
||||
</label>
|
||||
<input type="range" id="drumh3d-camera"
|
||||
min="0" max="1" step="0.05" value="0.35"
|
||||
oninput="window.drumH3dSetCameraAngle && window.drumH3dSetCameraAngle(this.value); document.getElementById('drumh3d-camera-val').textContent = parseFloat(this.value).toFixed(2)"
|
||||
class="w-full">
|
||||
<p class="text-xs text-gray-500 mt-1">0 = down the lanes · 1 = top-down</p>
|
||||
</div>
|
||||
|
||||
<!-- Graphics -->
|
||||
<div class="mt-6 border-t border-gray-800 pt-4">
|
||||
<h4 class="text-xs font-medium text-gray-300 mb-2">Graphics</h4>
|
||||
<label for="drumh3d-fx-bloom" class="flex items-center gap-2 text-xs text-gray-300 cursor-pointer">
|
||||
<input type="checkbox" id="drumh3d-fx-bloom" checked
|
||||
onchange="window.drumH3dSetFx && window.drumH3dSetFx('bloom', this.checked)">
|
||||
Glow (bloom)
|
||||
</label>
|
||||
<p class="text-xs text-gray-500 mt-1">
|
||||
Soft light-bleed around the hit line and bright notes. Applies
|
||||
live; turn off to reclaim GPU headroom on weak machines.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- MIDI input -->
|
||||
<div class="mt-6 border-t border-gray-800 pt-4">
|
||||
<h4 class="text-xs font-medium text-gray-300 mb-2">MIDI input</h4>
|
||||
<label for="drumh3d-midi-input" class="text-xs font-medium text-gray-400 mb-1 block">Device</label>
|
||||
<select id="drumh3d-midi-input"
|
||||
onchange="window.drumH3dSetMidiInput && window.drumH3dSetMidiInput(this.value)"
|
||||
class="w-full bg-dark-700 border border-gray-800 rounded-lg px-3 py-1.5 text-xs text-gray-300 outline-none">
|
||||
<option value="">— none —</option>
|
||||
</select>
|
||||
<p class="text-xs text-gray-500 mt-1">
|
||||
Auto-picks the first non-passthrough input on load. Pick "none" to pause hit and miss tracking.
|
||||
</p>
|
||||
|
||||
<label for="drumh3d-synth-vol" class="text-xs font-medium text-gray-400 mb-1 mt-3 block">
|
||||
Kit volume <span id="drumh3d-synth-vol-val" class="text-gray-500 font-mono">0.70</span>
|
||||
</label>
|
||||
<input type="range" id="drumh3d-synth-vol"
|
||||
min="0" max="1" step="0.01" value="0.7"
|
||||
oninput="window.drumH3dSetSynthVolume && window.drumH3dSetSynthVolume(this.value); document.getElementById('drumh3d-synth-vol-val').textContent = parseFloat(this.value).toFixed(2)"
|
||||
class="w-full">
|
||||
</div>
|
||||
|
||||
<!-- Kit configuration -->
|
||||
<div class="mt-6 border-t border-gray-800 pt-4">
|
||||
<h4 class="text-xs font-medium text-gray-300 mb-2">My kit</h4>
|
||||
<p class="text-xs text-gray-500 mb-3">
|
||||
Add the pieces you actually have, in the order you want them
|
||||
on the highway (left → right). The default fallback routing
|
||||
covers most common kit setups; use the fallbacks panel below
|
||||
to reroute any chart piece to a different lane on your kit,
|
||||
or set it to "—" to silently drop it.
|
||||
</p>
|
||||
|
||||
<label class="text-xs font-medium text-gray-400 mb-1 block">Kit name</label>
|
||||
<input type="text" id="drumh3d-kit-name" maxlength="80"
|
||||
class="w-full bg-dark-700 border border-gray-800 rounded-lg px-3 py-1.5 text-xs text-gray-300 outline-none mb-3"
|
||||
oninput="window._drumH3dKit && window._drumH3dKit.onNameInput(this.value)">
|
||||
|
||||
<label class="text-xs font-medium text-gray-400 mb-1 block">Lanes (left → right on the highway; kick is always a full-width bar)</label>
|
||||
<div id="drumh3d-kit-lanes" class="space-y-1 mb-2"></div>
|
||||
|
||||
<div class="mt-2 mb-3">
|
||||
<label class="text-xs font-medium text-gray-400 mb-1 block">Add a piece</label>
|
||||
<select id="drumh3d-kit-add"
|
||||
onchange="window._drumH3dKit && window._drumH3dKit.onAddPiece(this.value); this.value=''"
|
||||
class="w-full bg-dark-700 border border-gray-800 rounded-lg px-3 py-1.5 text-xs text-gray-300 outline-none">
|
||||
<option value="">— pick a piece to add —</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<details class="mt-2 mb-3">
|
||||
<summary class="text-xs text-gray-400 cursor-pointer">Chart fallbacks for pieces I don't have</summary>
|
||||
<p class="text-xs text-gray-500 mt-2 mb-2">
|
||||
When a song uses a piece that isn't on your kit, route it
|
||||
to one of your lanes. Set "—" to silently drop that piece.
|
||||
</p>
|
||||
<div id="drumh3d-kit-fallbacks" class="space-y-1"></div>
|
||||
</details>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-2 mt-3">
|
||||
<button type="button"
|
||||
onclick="window._drumH3dKit && window._drumH3dKit.copyToClipboard()"
|
||||
class="px-3 py-1.5 bg-dark-600 hover:bg-dark-500 rounded-lg text-xs">📋 Copy kit</button>
|
||||
<button type="button"
|
||||
onclick="document.getElementById('drumh3d-kit-import-row').classList.toggle('hidden')"
|
||||
class="px-3 py-1.5 bg-dark-600 hover:bg-dark-500 rounded-lg text-xs">📥 Import kit…</button>
|
||||
<button type="button"
|
||||
onclick="window._drumH3dKit && window._drumH3dKit.resetDefault()"
|
||||
class="px-3 py-1.5 bg-dark-600 hover:bg-dark-500 rounded-lg text-xs">Reset</button>
|
||||
<span id="drumh3d-kit-status" class="text-xs text-gray-500 ml-auto"></span>
|
||||
</div>
|
||||
|
||||
<div id="drumh3d-kit-import-row" class="hidden mt-3">
|
||||
<label class="text-xs font-medium text-gray-400 mb-1 block">Paste a shared kit</label>
|
||||
<textarea id="drumh3d-kit-import-text" rows="3"
|
||||
placeholder="Paste a base64 kit string here…"
|
||||
class="w-full bg-dark-700 border border-gray-800 rounded-lg px-3 py-2 text-[10px] font-mono text-gray-300 outline-none"></textarea>
|
||||
<button type="button"
|
||||
onclick="window._drumH3dKit && window._drumH3dKit.importFromTextarea()"
|
||||
class="mt-2 px-3 py-1.5 bg-emerald-700 hover:bg-emerald-600 rounded-lg text-xs">Apply imported kit</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
// Mirror of PALETTES in screen.js — kept in sync for swatch previews.
|
||||
const PALETTES = {
|
||||
default: [0xff2828, 0xffd400, 0x2080ff, 0xff8020, 0x30d040, 0xa040ff, 0xff6bd5, 0x6bffe6],
|
||||
neon: [0xff0030, 0xffe800, 0x0080ff, 0xff8030, 0x40ff50, 0xb050ff, 0xff40d0, 0x40ffd0],
|
||||
pastel: [0xe89aa0, 0xefdf90, 0x9adfee, 0xefb898, 0xa6e0a8, 0xc4a6e0, 0xe0a6c8, 0xa6e0d8],
|
||||
};
|
||||
|
||||
function toHex(n) { return '#' + n.toString(16).padStart(6, '0'); }
|
||||
|
||||
// Palette swatch preview: read the FIRST 8 pieces of the active
|
||||
// kit's lanes (or pad to 8) for colour reference.
|
||||
window._drumH3dRenderPaletteSwatches = function (id) {
|
||||
const pal = PALETTES[id] || PALETTES.default;
|
||||
const kit = (window.drumH3dGetKit && window.drumH3dGetKit()) || null;
|
||||
const lanes = (kit && kit.lanes) || [];
|
||||
// The kick always shows amber — same as the renderer. Other
|
||||
// lanes follow the piece's palette index from screen.js,
|
||||
// retrieved via drumH3dGetPiecePaletteIdx() so settings.html
|
||||
// stays in sync when pieces are added without any copy-paste.
|
||||
const PALETTE_IDX = (window.drumH3dGetPiecePaletteIdx && window.drumH3dGetPiecePaletteIdx()) || {
|
||||
kick: -1, // sentinel — render amber
|
||||
snare: 0, snare_xstick: 0,
|
||||
hh_closed: 7, hh_open: 7, hh_pedal: 7,
|
||||
tom_hi: 4, tom_mid: 2, tom_low: 5, tom_floor: 5,
|
||||
crash_l: 1, crash_r: 1, splash: 1, china: 1,
|
||||
ride: 3, ride_bell: 3,
|
||||
};
|
||||
for (let i = 0; i < 8; i++) {
|
||||
const el = document.getElementById('drumh3d-swatch-' + i);
|
||||
if (!el) continue;
|
||||
const ln = lanes[i];
|
||||
if (!ln) { el.style.background = '#000'; el.style.opacity = '0.3'; continue; }
|
||||
el.style.opacity = '1';
|
||||
const idx = PALETTE_IDX[ln.piece];
|
||||
if (idx === -1) { el.style.background = '#ffa030'; continue; }
|
||||
el.style.background = toHex(pal[idx ?? 0]);
|
||||
}
|
||||
};
|
||||
|
||||
// Read fresh inside renderKit() — they're set by screen.js's IIFE,
|
||||
// which may not have finished evaluating when this inline script
|
||||
// first runs if the user opens Settings before the player ever loaded.
|
||||
|
||||
// Friendly piece labels — self-contained so renderKit's callbacks
|
||||
// (which run after our local PIECE_LABELS scope has cleared)
|
||||
// still work.
|
||||
const FRIENDLY = {
|
||||
kick: 'Kick',
|
||||
snare: 'Snare', snare_xstick: 'Snare (cross-stick)',
|
||||
hh_closed: 'Hi-hat (closed)', hh_open: 'Hi-hat (open)', hh_pedal: 'Hi-hat (pedal)',
|
||||
tom_hi: 'Tom — high', tom_mid: 'Tom — mid', tom_low: 'Tom — low', tom_floor: 'Floor tom',
|
||||
crash_l: 'Crash (left)', crash_r: 'Crash (right)', splash: 'Splash', china: 'China',
|
||||
ride: 'Ride', ride_bell: 'Ride bell',
|
||||
};
|
||||
function friendly(p) { return FRIENDLY[p] || p; }
|
||||
|
||||
// Render the current kit's lane list with reorder + remove buttons.
|
||||
function renderKit() {
|
||||
const kit = window.drumH3dGetKit ? window.drumH3dGetKit() : null;
|
||||
if (!kit) {
|
||||
// screen.js hasn't published its API yet — defer one tick.
|
||||
// Happens when the settings panel opens before the player
|
||||
// has loaded a song.
|
||||
setTimeout(renderKit, 100);
|
||||
return;
|
||||
}
|
||||
const PIECE_CATEGORY = window.drumH3dGetPieceCategory ? window.drumH3dGetPieceCategory() : {};
|
||||
const ALL_PIECES = window.drumH3dGetAllPieces ? window.drumH3dGetAllPieces() : [];
|
||||
document.getElementById('drumh3d-kit-name').value = kit.name || '';
|
||||
|
||||
// Lanes panel — order matters: up/down buttons reorder, x
|
||||
// removes (also clears any fallback that pointed at the
|
||||
// removed piece on the way out).
|
||||
const lanesEl = document.getElementById('drumh3d-kit-lanes');
|
||||
lanesEl.innerHTML = '';
|
||||
const taken = new Set(kit.lanes.map(l => l.piece));
|
||||
kit.lanes.forEach((ln, i) => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'flex items-center gap-2 px-2 py-1 bg-dark-700/60 rounded';
|
||||
// Screen readers should hear the user-facing label
|
||||
// ("Hi-hat (closed)") not the internal piece id ("hh_closed").
|
||||
const pieceName = friendly(ln.piece);
|
||||
row.innerHTML =
|
||||
`<span class="font-mono text-[10px] text-gray-500 w-6 text-center">${i}</span>` +
|
||||
`<span class="flex-1 text-xs text-gray-300">${pieceName}</span>` +
|
||||
`<button type="button" data-act="up" data-i="${i}" class="px-1.5 py-0.5 text-xs text-gray-400 hover:text-white" ${i === 0 ? 'disabled' : ''} title="Move up" aria-label="Move ${pieceName} up">▲</button>` +
|
||||
`<button type="button" data-act="down" data-i="${i}" class="px-1.5 py-0.5 text-xs text-gray-400 hover:text-white" ${i === kit.lanes.length - 1 ? 'disabled' : ''} title="Move down" aria-label="Move ${pieceName} down">▼</button>` +
|
||||
`<button type="button" data-act="rm" data-i="${i}" class="px-1.5 py-0.5 text-xs text-red-400 hover:text-red-300" title="Remove from kit" aria-label="Remove ${pieceName} from kit">✗</button>`;
|
||||
lanesEl.appendChild(row);
|
||||
});
|
||||
lanesEl.querySelectorAll('button').forEach(btn => {
|
||||
btn.onclick = () => {
|
||||
const i = parseInt(btn.dataset.i, 10);
|
||||
const act = btn.dataset.act;
|
||||
const next = JSON.parse(JSON.stringify(kit));
|
||||
if (act === 'up' && i > 0) {
|
||||
[next.lanes[i - 1], next.lanes[i]] = [next.lanes[i], next.lanes[i - 1]];
|
||||
} else if (act === 'down' && i < next.lanes.length - 1) {
|
||||
[next.lanes[i + 1], next.lanes[i]] = [next.lanes[i], next.lanes[i + 1]];
|
||||
} else if (act === 'rm') {
|
||||
const removed = next.lanes[i].piece;
|
||||
next.lanes.splice(i, 1);
|
||||
// Drop any fallback that targeted the removed piece
|
||||
// — it's no longer a valid target.
|
||||
for (const k of Object.keys(next.fallbacks || {})) {
|
||||
if (next.fallbacks[k] === removed) delete next.fallbacks[k];
|
||||
}
|
||||
} else { return; }
|
||||
// Guard: drumH3dSetKit returns false when validation
|
||||
// rejects the kit (e.g. empty lanes[] after last removal).
|
||||
if (!window.drumH3dSetKit(next)) {
|
||||
setStatus('Kit must have at least one lane', 'err');
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
// Add-a-piece dropdown — pieces NOT already in lanes, grouped
|
||||
// by category (kick / drums / cymbals).
|
||||
const addSel = document.getElementById('drumh3d-kit-add');
|
||||
addSel.innerHTML = '<option value="">— pick a piece to add —</option>';
|
||||
const groups = { kick: [], drum: [], cymbal: [] };
|
||||
for (const p of ALL_PIECES) {
|
||||
if (taken.has(p)) continue;
|
||||
const cat = PIECE_CATEGORY[p] || 'drum';
|
||||
if (groups[cat]) groups[cat].push(p);
|
||||
}
|
||||
for (const [cat, label] of [['kick', 'Kick'], ['drum', 'Drums'], ['cymbal', 'Cymbals']]) {
|
||||
if (!groups[cat].length) continue;
|
||||
const og = document.createElement('optgroup');
|
||||
og.label = label;
|
||||
for (const p of groups[cat]) {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = p;
|
||||
opt.textContent = friendly(p);
|
||||
og.appendChild(opt);
|
||||
}
|
||||
addSel.appendChild(og);
|
||||
}
|
||||
|
||||
// Fallback list — every piece NOT in lanes gets a dropdown
|
||||
// mapping it to one of the user's pieces (or "—" to drop).
|
||||
const fbEl = document.getElementById('drumh3d-kit-fallbacks');
|
||||
fbEl.innerHTML = '';
|
||||
for (const p of ALL_PIECES) {
|
||||
if (taken.has(p)) continue;
|
||||
const row = document.createElement('div');
|
||||
row.className = 'flex items-center gap-2 px-2 py-1';
|
||||
const labelTxt = friendly(p);
|
||||
const current = (kit.fallbacks && kit.fallbacks[p]) || '';
|
||||
let optsHtml = '<option value="">— drop —</option>';
|
||||
for (const ln of kit.lanes) {
|
||||
const sel = ln.piece === current ? ' selected' : '';
|
||||
optsHtml += `<option value="${ln.piece}"${sel}>${friendly(ln.piece)}</option>`;
|
||||
}
|
||||
row.innerHTML =
|
||||
`<span class="flex-1 text-xs text-gray-400">${labelTxt}</span>` +
|
||||
`<span class="text-xs text-gray-600">→</span>` +
|
||||
`<select data-from="${p}" class="bg-dark-700 border border-gray-800 rounded px-2 py-1 text-xs text-gray-300 outline-none">${optsHtml}</select>`;
|
||||
fbEl.appendChild(row);
|
||||
}
|
||||
fbEl.querySelectorAll('select').forEach(s => {
|
||||
s.onchange = () => {
|
||||
const next = JSON.parse(JSON.stringify(kit));
|
||||
next.fallbacks = next.fallbacks || {};
|
||||
if (s.value) next.fallbacks[s.dataset.from] = s.value;
|
||||
else delete next.fallbacks[s.dataset.from];
|
||||
window.drumH3dSetKit(next); // event-driven renderKit() via drum_h3d:kit
|
||||
};
|
||||
});
|
||||
|
||||
// Refresh palette swatches so they reflect the new lane order.
|
||||
if (window._drumH3dRenderPaletteSwatches) {
|
||||
const pSel = document.getElementById('drumh3d-palette');
|
||||
window._drumH3dRenderPaletteSwatches(pSel ? pSel.value : 'default');
|
||||
}
|
||||
}
|
||||
|
||||
function setStatus(msg, kind) {
|
||||
const el = document.getElementById('drumh3d-kit-status');
|
||||
if (!el) return;
|
||||
el.textContent = msg;
|
||||
el.className = 'text-xs ml-auto ' + (kind === 'err' ? 'text-red-400' : kind === 'ok' ? 'text-emerald-400' : 'text-gray-500');
|
||||
setTimeout(() => { if (el.textContent === msg) el.textContent = ''; }, 3000);
|
||||
}
|
||||
|
||||
// Expose the kit interaction surface to the inline onclick / onchange
|
||||
// attributes used by the markup above.
|
||||
window._drumH3dKit = {
|
||||
onNameInput(name) {
|
||||
// Use the name-only setter to avoid triggering 'drum_h3d:kit'
|
||||
// on every keystroke — that event causes a full WebGL scene
|
||||
// teardown/reinit which produces visible stutter while typing.
|
||||
window.drumH3dSetKitName && window.drumH3dSetKitName(name);
|
||||
},
|
||||
onAddPiece(piece) {
|
||||
if (!piece) return;
|
||||
const kit = window.drumH3dGetKit();
|
||||
kit.lanes.push({ piece });
|
||||
window.drumH3dSetKit(kit); // event-driven renderKit() via drum_h3d:kit
|
||||
},
|
||||
copyToClipboard() {
|
||||
const b64 = window.drumH3dExportKit && window.drumH3dExportKit();
|
||||
if (!b64) return setStatus('export failed', 'err');
|
||||
const _showImportFallback = (str) => {
|
||||
// Clipboard unavailable — reveal the import row so the user can
|
||||
// copy the string from the textarea manually.
|
||||
document.getElementById('drumh3d-kit-import-row').classList.remove('hidden');
|
||||
const ta = document.getElementById('drumh3d-kit-import-text');
|
||||
ta.value = str;
|
||||
ta.focus();
|
||||
ta.select();
|
||||
setStatus('clipboard blocked — copy from the textarea below', 'err');
|
||||
};
|
||||
if (!navigator.clipboard) {
|
||||
_showImportFallback(b64);
|
||||
return;
|
||||
}
|
||||
navigator.clipboard.writeText(b64).then(
|
||||
() => setStatus('✓ kit copied', 'ok'),
|
||||
() => _showImportFallback(b64),
|
||||
);
|
||||
},
|
||||
importFromTextarea() {
|
||||
const txt = document.getElementById('drumh3d-kit-import-text').value;
|
||||
if (!txt.trim()) return setStatus('paste a kit string first', 'err');
|
||||
const ok = window.drumH3dImportKit && window.drumH3dImportKit(txt);
|
||||
// drumH3dImportKit calls drumH3dSetKit which dispatches drum_h3d:kit;
|
||||
// the event listener re-renders the panel, so no explicit renderKit().
|
||||
if (ok) { setStatus('✓ kit imported', 'ok'); }
|
||||
else setStatus('invalid kit string', 'err');
|
||||
},
|
||||
resetDefault() {
|
||||
window.drumH3dResetKit && window.drumH3dResetKit();
|
||||
// drumH3dResetKit calls drumH3dSetKit → dispatches drum_h3d:kit
|
||||
// → event listener re-renders. No explicit renderKit() needed.
|
||||
setStatus('✓ reset to default', 'ok');
|
||||
},
|
||||
};
|
||||
|
||||
// Re-render the kit list whenever the kit changes (covers external
|
||||
// changes from setKit() / importKit() not initiated by this panel).
|
||||
window.addEventListener('drum_h3d:kit', () => renderKit());
|
||||
|
||||
// ─── MIDI device picker ───────────────────────────────
|
||||
function renderMidiPicker() {
|
||||
const sel = document.getElementById('drumh3d-midi-input');
|
||||
if (!sel) return;
|
||||
const inputs = window.drumH3dListMidiInputs ? window.drumH3dListMidiInputs() : [];
|
||||
const current = window.drumH3dGetMidiInputId ? window.drumH3dGetMidiInputId() : '';
|
||||
sel.innerHTML = '<option value="">— none —</option>';
|
||||
for (const inp of inputs) {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = inp.id;
|
||||
opt.textContent = inp.name;
|
||||
if (inp.id === current) opt.selected = true;
|
||||
sel.appendChild(opt);
|
||||
}
|
||||
// Sync volume slider with the actual persisted value (default
|
||||
// 0.7 if storage was empty or never written).
|
||||
const vol = window.drumH3dGetSynthVolume ? window.drumH3dGetSynthVolume() : 0.7;
|
||||
const volSlider = document.getElementById('drumh3d-synth-vol');
|
||||
const volLabel = document.getElementById('drumh3d-synth-vol-val');
|
||||
if (volSlider) volSlider.value = String(vol);
|
||||
if (volLabel) volLabel.textContent = parseFloat(vol).toFixed(2);
|
||||
}
|
||||
window.addEventListener('drum_h3d:midi_devices', renderMidiPicker);
|
||||
// Kick off MIDI initialisation if the player viz never ran (user
|
||||
// opened Settings → 3D Drum Highway directly). _midiInit is
|
||||
// idempotent so this is safe even when the viz is also active.
|
||||
// Re-render the picker when the access promise settles.
|
||||
(function pollMidi() {
|
||||
if (window.drumH3dEnsureMidiInit) {
|
||||
Promise.resolve(window.drumH3dEnsureMidiInit()).then(renderMidiPicker);
|
||||
renderMidiPicker(); // first paint with whatever's cached
|
||||
} else {
|
||||
setTimeout(pollMidi, 100);
|
||||
}
|
||||
})();
|
||||
|
||||
// Hydrate controls from stored config on first paint.
|
||||
// Narrow the try/catch to just localStorage reads — renderKit() and
|
||||
// swatches must always run even when storage is blocked/disabled.
|
||||
const pSel = document.getElementById('drumh3d-palette');
|
||||
const cam = document.getElementById('drumh3d-camera');
|
||||
const camVal = document.getElementById('drumh3d-camera-val');
|
||||
try {
|
||||
const storedPal = localStorage.getItem('drum_h3d_palette');
|
||||
if (storedPal && PALETTES[storedPal]) pSel.value = storedPal;
|
||||
|
||||
const storedCam = parseFloat(localStorage.getItem('drum_h3d_camera_angle'));
|
||||
if (Number.isFinite(storedCam)) {
|
||||
const c = Math.min(1, Math.max(0, storedCam));
|
||||
cam.value = String(c);
|
||||
camVal.textContent = c.toFixed(2);
|
||||
}
|
||||
|
||||
// FX toggles (drum_h3d_bg_* — guitar-parity graphics controls).
|
||||
// Only explicit values override; absent/corrupt keys keep the
|
||||
// default (ON), matching screen.js readFxSettings.
|
||||
const storedBloom = localStorage.getItem('drum_h3d_bg_bloom');
|
||||
if (storedBloom === '1' || storedBloom === 'true') {
|
||||
document.getElementById('drumh3d-fx-bloom').checked = true;
|
||||
} else if (storedBloom === '0' || storedBloom === 'false') {
|
||||
document.getElementById('drumh3d-fx-bloom').checked = false;
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('[Drum-Hwy3D settings] hydration failed:', e);
|
||||
}
|
||||
renderKit();
|
||||
window._drumH3dRenderPaletteSwatches(pSel.value);
|
||||
})();
|
||||
</script>
|
||||
</div>
|
||||
@@ -0,0 +1,94 @@
|
||||
// Pure data-layer tests: load screen.js in a bare vm window and exercise the
|
||||
// __test exports (no DOM, no WebGL, no network). Doubles as a lint that no
|
||||
// module-scope code touches document/localStorage outside a try/catch —
|
||||
// the vm window deliberately provides neither.
|
||||
const { test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
|
||||
function load() {
|
||||
const window = {
|
||||
console,
|
||||
location: { protocol: 'http:', host: 'localhost' },
|
||||
slopsmith: {},
|
||||
};
|
||||
window.window = window;
|
||||
window.globalThis = window;
|
||||
const context = vm.createContext(window);
|
||||
const src = fs.readFileSync(path.join(__dirname, '..', 'screen.js'), 'utf8');
|
||||
vm.runInContext(src, context, { filename: 'screen.js' });
|
||||
return window.slopsmithViz_drum_highway_3d;
|
||||
}
|
||||
|
||||
test('module loads in a bare vm (no DOM / localStorage at module scope)', () => {
|
||||
const factory = load();
|
||||
assert.equal(typeof factory, 'function');
|
||||
assert.equal(factory.contextType, 'webgl2');
|
||||
});
|
||||
|
||||
test('_variantForHit: ghost > flam > bell > accent > normal precedence', () => {
|
||||
const { _variantForHit } = load().__test;
|
||||
assert.equal(_variantForHit({ g: true, f: true, v: 120 }), 'ghost');
|
||||
assert.equal(_variantForHit({ f: true, v: 120 }), 'flam');
|
||||
assert.equal(_variantForHit({ p: 'ride_bell' }), 'bell');
|
||||
assert.equal(_variantForHit({ v: 100 }), 'accent');
|
||||
assert.equal(_variantForHit({ v: 127 }), 'accent');
|
||||
assert.equal(_variantForHit({ v: 99 }), 'normal');
|
||||
// Missing velocity defaults to 100 → accent.
|
||||
assert.equal(_variantForHit({}), 'accent');
|
||||
});
|
||||
|
||||
test('matchesArrangement: claims drum arrangements', () => {
|
||||
const matches = load().matchesArrangement;
|
||||
assert.equal(matches({ has_drum_tab: true, arrangement: 'Drums' }), true);
|
||||
assert.equal(matches({ has_drum_tab: true, arrangement: 'Drum Kit' }), true);
|
||||
assert.equal(matches({ has_drum_tab: true, arrangement: 'Percussion' }), true);
|
||||
});
|
||||
|
||||
test('matchesArrangement: never claims without a drum tab', () => {
|
||||
const matches = load().matchesArrangement;
|
||||
assert.equal(matches(null), false);
|
||||
assert.equal(matches({}), false);
|
||||
assert.equal(matches({ arrangement: 'Drums' }), false);
|
||||
});
|
||||
|
||||
test('matchesArrangement: steal-guard — guitar arrangements stay with highway_3d', () => {
|
||||
const matches = load().matchesArrangement;
|
||||
// Full-band pack (drum_tab present) playing a guitar-family part:
|
||||
// first-match-wins Auto order must not hand these to the drum highway.
|
||||
for (const arr of ['Lead', 'Rhythm', 'Bass', 'Combo', 'Guitar 22', 'Alt. Lead']) {
|
||||
assert.equal(matches({ has_drum_tab: true, arrangement: arr }), false, arr);
|
||||
}
|
||||
// Keys notation present → the keys/staff viz take it.
|
||||
assert.equal(matches({ has_drum_tab: true, has_notation: true, arrangement: 'Piano' }), false);
|
||||
});
|
||||
|
||||
test('matchesArrangement: claims packs nothing more specific can render', () => {
|
||||
const matches = load().matchesArrangement;
|
||||
// Drum tab + nondescript arrangement, no notation → drummable, claim it.
|
||||
assert.equal(matches({ has_drum_tab: true, arrangement: '' }), true);
|
||||
assert.equal(matches({ has_drum_tab: true }), true);
|
||||
// Word-boundary check: "BasslineKeys"-style names don't contain a
|
||||
// guitar-family word as a whole word.
|
||||
assert.equal(matches({ has_drum_tab: true, arrangement: 'Bassline' }), true);
|
||||
});
|
||||
|
||||
test('readFxSettings: defaults survive a localStorage-less environment', () => {
|
||||
const { readFxSettings, FX_DEFAULTS } = load().__test;
|
||||
// The vm window has no localStorage — the try/catch must eat the
|
||||
// ReferenceError and hand back pure defaults (everything ON).
|
||||
assert.deepEqual(readFxSettings(), FX_DEFAULTS);
|
||||
assert.equal(FX_DEFAULTS.bloom, true);
|
||||
});
|
||||
|
||||
test('MIDI map: open hi-hat is a first-class piece (46 → hh_open)', () => {
|
||||
const { MIDI_TO_PIECE, HIT_TOLERANCE_S } = load().__test;
|
||||
assert.equal(MIDI_TO_PIECE[46], 'hh_open');
|
||||
assert.equal(MIDI_TO_PIECE[42], 'hh_closed');
|
||||
assert.equal(MIDI_TO_PIECE[35], 'kick');
|
||||
assert.equal(MIDI_TO_PIECE[36], 'kick');
|
||||
// ±50 ms window matches the 2D drums plugin.
|
||||
assert.equal(HIT_TOLERANCE_S, 0.05);
|
||||
});
|
||||
+314
-76
@@ -1607,37 +1607,32 @@
|
||||
ss.isCanvasFocused(highwayCanvas));
|
||||
}
|
||||
|
||||
// A/B toggle for the wide-pane horizontal-FOV-hold. Flips
|
||||
// window.__h3dAspectTune.enabled so the running app can switch between the
|
||||
// current framing (off, the baseline) and the Hor+ framing (on) with one
|
||||
// keypress, across all panes at once. Registered once per session via a
|
||||
// module-level guard (it toggles a shared global, so per-instance
|
||||
// registration would stack duplicate handlers and cancel itself out); it's
|
||||
// a harmless debug control, so it is never unregistered. No-ops where the
|
||||
// core shortcut API isn't present (older core / borrowed contexts).
|
||||
let _abShortcutRegistered = false;
|
||||
function _registerAspectAbShortcut() {
|
||||
if (_abShortcutRegistered) return;
|
||||
// Shortcut for the wide-pane framing tuner. Opens/closes the floating panel
|
||||
// (the A/B on/off and the per-pane target live inside it now). Registered
|
||||
// once per session via a module-level guard (it drives shared module state,
|
||||
// so per-instance registration would stack duplicate handlers and cancel
|
||||
// itself out); it's a harmless debug control, so it is never unregistered.
|
||||
// No-ops where the core shortcut API isn't present (older core / borrowed
|
||||
// contexts).
|
||||
let _tunerShortcutRegistered = false;
|
||||
function _registerTunerShortcut() {
|
||||
if (_tunerShortcutRegistered) return;
|
||||
if (typeof window.registerShortcut !== 'function') return;
|
||||
_abShortcutRegistered = true;
|
||||
_tunerShortcutRegistered = true;
|
||||
try {
|
||||
window.registerShortcut({
|
||||
key: 'A', // uppercase e.key → produced with Shift held (Shift+A)
|
||||
description: '3D Highway: toggle wide-pane framing A/B (Shift+A)',
|
||||
description: '3D Highway: open/close wide-pane framing tuner (Shift+A)',
|
||||
scope: 'player',
|
||||
handler: () => {
|
||||
const t = _aspectTune();
|
||||
t.enabled = !t.enabled;
|
||||
try { console.log('[h3d] wide-pane framing', t.enabled ? 'ON' : 'OFF'); } catch (e) {}
|
||||
// Surface the live tuner panel whenever the feature is on,
|
||||
// hide it when off. Built lazily on first use.
|
||||
_ensureAspectPanel();
|
||||
_setAspectPanelVisible(t.enabled);
|
||||
_syncAspectPanel();
|
||||
// Open/close the live tuner panel. The A/B on/off and the
|
||||
// per-pane target now live in the panel itself, so the
|
||||
// shortcut is just a dismiss/reveal.
|
||||
_toggleAspectPanel();
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
_abShortcutRegistered = false; // allow a later retry if it threw
|
||||
_tunerShortcutRegistered = false; // allow a later retry if it threw
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1685,8 +1680,42 @@
|
||||
let _aspectPanelEl = null; // the floating panel root (built once)
|
||||
let _aspectPanelRO = null; // readout <div>
|
||||
let _aspectPanelRAF = 0; // readout poll handle
|
||||
let _aspectTargetSel = null; // the "Target" <select>
|
||||
let _aspectTgtRow = null; // the Target row (hidden when only one pane)
|
||||
let _aspectHfovCb = null; // hfov-override checkbox (synced explicitly)
|
||||
let _aspectHfovSl = null; // hfov-override slider
|
||||
// Which pane the panel edits. '' = all panes (writes the shared base object);
|
||||
// a pane key ('arr:<name>' or the fallback 'pane:<uid>') writes that pane's
|
||||
// sparse override, so one split pane can be framed independently.
|
||||
let _aspectEditTarget = '';
|
||||
// Bumped when the SET of live panes changes (add/prune) so the panel rebuilds
|
||||
// the Target dropdown — never on a per-frame label re-report, which would
|
||||
// flicker the <select>.
|
||||
let _aspectPanesDirty = true;
|
||||
// Monotonic counter for the per-instance fallback key (when a pane has no
|
||||
// arrangement name to key by).
|
||||
let _aspectPaneCounter = 0;
|
||||
function _aspectNowMs() {
|
||||
try { if (performance && performance.now) return performance.now(); } catch (e) {}
|
||||
try { return Date.now(); } catch (e) { return 0; } // keep pruning functional
|
||||
}
|
||||
// Pane key: prefer the arrangement name ('arr:Bass') so a pane's framing is
|
||||
// stable across songs AND distinct between split panes, with no dependency on
|
||||
// the external splitscreen panel index (which isn't always available). Fall
|
||||
// back to a per-instance id ('pane:3') when there's no arrangement.
|
||||
function _aspectPaneKey(arrangement, uid) {
|
||||
const a = (typeof arrangement === 'string') ? arrangement.trim() : '';
|
||||
return a ? ('arr:' + a) : ('pane:' + uid);
|
||||
}
|
||||
// Human label derived from the key.
|
||||
function _aspectPaneLabel(paneKey) {
|
||||
if (paneKey.slice(0, 4) === 'arr:') return paneKey.slice(4);
|
||||
if (paneKey.slice(0, 5) === 'pane:') return 'Pane ' + paneKey.slice(5);
|
||||
return paneKey;
|
||||
}
|
||||
|
||||
// Get-or-create the live bridge object, seeded from defaults + localStorage.
|
||||
// Get-or-create the shared bridge object, seeded from defaults + localStorage.
|
||||
// May carry a sparse `__panels` map of per-pane overrides.
|
||||
function _aspectTune() {
|
||||
let t = window.__h3dAspectTune;
|
||||
if (!t || typeof t !== 'object') {
|
||||
@@ -1699,48 +1728,196 @@
|
||||
}
|
||||
return t;
|
||||
}
|
||||
// Bumped on every tune mutation (all writes funnel through _aspectPersist) so
|
||||
// the per-pane resolve cache below can invalidate cheaply.
|
||||
let _aspectRev = 0;
|
||||
function _aspectPersist() {
|
||||
_aspectRev++;
|
||||
try {
|
||||
const t = _aspectTune(), out = {};
|
||||
Object.keys(_ASPECT_DEFAULTS).forEach((k) => { out[k] = t[k]; });
|
||||
// Persist per-pane overrides keyed by arrangement ('arr:*') only, so a
|
||||
// pane's framing carries across songs. Instance-id fallback keys
|
||||
// ('pane:*') are session-only — persisting them would leak a new key
|
||||
// every reload.
|
||||
if (t.__panels) {
|
||||
const p = {}; let any = false;
|
||||
Object.keys(t.__panels).forEach((k) => {
|
||||
if (k.slice(0, 4) === 'arr:') { p[k] = t.__panels[k]; any = true; }
|
||||
});
|
||||
if (any) out.__panels = p;
|
||||
}
|
||||
localStorage.setItem(_ASPECT_LS, JSON.stringify(out));
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
// Resolve the effective tune for a pane: the shared base, with that pane's
|
||||
// override keys (if any) laid on top. Called every frame per renderer, so the
|
||||
// merged object is memoized per pane and only rebuilt when the tune mutates
|
||||
// (_aspectRev changes). Panes with no override return the base directly (no
|
||||
// allocation).
|
||||
const _aspectResolveCache = new Map(); // paneKey -> { rev, obj }
|
||||
function _resolveTuneFor(paneKey) {
|
||||
const base = _aspectTune();
|
||||
const ov = base.__panels && base.__panels[paneKey];
|
||||
if (!ov) return base;
|
||||
const c = _aspectResolveCache.get(paneKey);
|
||||
if (c && c.rev === _aspectRev) return c.obj;
|
||||
const out = {};
|
||||
Object.keys(_ASPECT_DEFAULTS).forEach((k) => { out[k] = (k in ov) ? ov[k] : base[k]; });
|
||||
_aspectResolveCache.set(paneKey, { rev: _aspectRev, obj: out });
|
||||
return out;
|
||||
}
|
||||
// Record a live pane so the Target dropdown can list it. Called every frame
|
||||
// by each renderer with its pane key. `seen` is refreshed each call for
|
||||
// pruning; the dropdown is only marked dirty when a pane is newly added — not
|
||||
// on every re-report, which would flicker the <select>.
|
||||
function _aspectRegisterPane(paneKey) {
|
||||
const reg = window.__h3dAspectPanes || (window.__h3dAspectPanes = {});
|
||||
const label = _aspectPaneLabel(paneKey);
|
||||
let e = reg[paneKey];
|
||||
if (!e) { e = reg[paneKey] = { label, seen: 0 }; _aspectPanesDirty = true; }
|
||||
else if (e.label !== label) { e.label = label; _aspectPanesDirty = true; }
|
||||
e.seen = _aspectNowMs();
|
||||
}
|
||||
// Drop panes not reported recently (song change, split teardown, pane close).
|
||||
function _aspectPrunePanes() {
|
||||
const reg = window.__h3dAspectPanes;
|
||||
if (!reg) return;
|
||||
const now = _aspectNowMs();
|
||||
const ro = window.__h3dAspectReadout;
|
||||
Object.keys(reg).forEach((k) => {
|
||||
if (now - (reg[k].seen || 0) > 1500) {
|
||||
delete reg[k];
|
||||
// Prune the matching readout slot so it can't grow unbounded as
|
||||
// songs/arrangements churn, and drop a dangling __last pointer.
|
||||
if (ro) { delete ro[k]; if (ro.__last === k) delete ro.__last; }
|
||||
_aspectPanesDirty = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// True while _syncAspectPanel is programmatically refreshing controls, so the
|
||||
// synthetic 'input' events it dispatches to update labels don't write back
|
||||
// into the tune (which would populate a full override for every field and
|
||||
// spam localStorage). Real user input runs with this false.
|
||||
let _aspectSyncing = false;
|
||||
// Read/write against the current edit target ('' → base, else pane override).
|
||||
function _aspectReadVal(k) {
|
||||
const base = _aspectTune();
|
||||
if (!_aspectEditTarget) return base[k];
|
||||
const ov = base.__panels && base.__panels[_aspectEditTarget];
|
||||
return (ov && (k in ov)) ? ov[k] : base[k];
|
||||
}
|
||||
function _aspectWriteVal(k, v) {
|
||||
const base = _aspectTune();
|
||||
if (!_aspectEditTarget) { base[k] = v; }
|
||||
else {
|
||||
const m = base.__panels || (base.__panels = {});
|
||||
(m[_aspectEditTarget] || (m[_aspectEditTarget] = {}))[k] = v;
|
||||
}
|
||||
_aspectPersist();
|
||||
}
|
||||
// Clear a field: for the base target set the explicit auto value (null); for a
|
||||
// pane target delete the override key so the pane re-inherits the base value
|
||||
// (and drop the pane's override object once it's empty).
|
||||
function _aspectClearVal(k) {
|
||||
const base = _aspectTune();
|
||||
if (!_aspectEditTarget) { base[k] = null; }
|
||||
else {
|
||||
const m = base.__panels, ov = m && m[_aspectEditTarget];
|
||||
if (ov) { delete ov[k]; if (!Object.keys(ov).length) delete m[_aspectEditTarget]; }
|
||||
}
|
||||
_aspectPersist();
|
||||
}
|
||||
|
||||
// (Re)build the Target dropdown from the live pane registry, preserving the
|
||||
// current selection when it's still valid.
|
||||
function _aspectBuildTargets() {
|
||||
if (!_aspectTargetSel) return;
|
||||
// Don't yank a dropdown the user is actively interacting with — leave it
|
||||
// dirty and rebuild on a later tick once it's no longer focused.
|
||||
if (document.activeElement === _aspectTargetSel) return;
|
||||
const reg = window.__h3dAspectPanes || {};
|
||||
const keys = Object.keys(reg).sort();
|
||||
_aspectTargetSel.innerHTML = '';
|
||||
const all = document.createElement('option');
|
||||
all.value = ''; all.textContent = keys.length > 1 ? 'All panes' : 'All';
|
||||
_aspectTargetSel.appendChild(all);
|
||||
keys.forEach((pk) => {
|
||||
const o = document.createElement('option');
|
||||
o.value = pk; o.textContent = reg[pk].label;
|
||||
_aspectTargetSel.appendChild(o);
|
||||
});
|
||||
// Force the edit target back to "All" when the Target row is hidden
|
||||
// (single pane) or the selected pane is gone — otherwise a stale pane
|
||||
// target would silently route edits into a hidden (and persistent
|
||||
// arr:*) override in single-player.
|
||||
if (keys.length <= 1 || (_aspectEditTarget && !reg[_aspectEditTarget])) {
|
||||
_aspectEditTarget = '';
|
||||
}
|
||||
_aspectTargetSel.value = _aspectEditTarget;
|
||||
// The Target row only matters with more than one pane (a split). With a
|
||||
// single pane there's nothing to disambiguate, so hide it.
|
||||
if (_aspectTgtRow) _aspectTgtRow.style.display = keys.length > 1 ? '' : 'none';
|
||||
_aspectPanesDirty = false;
|
||||
}
|
||||
|
||||
function _ensureAspectPanel() {
|
||||
if (_aspectPanelEl || typeof document === 'undefined') return;
|
||||
const t = _aspectTune();
|
||||
const wrap = document.createElement('div');
|
||||
wrap.id = 'h3d-aspect-tuner';
|
||||
wrap.style.cssText = [
|
||||
'position:fixed', 'top:64px', 'right:12px', 'z-index:99999',
|
||||
'width:230px', 'padding:10px 12px', 'border-radius:8px',
|
||||
'width:236px', 'padding:10px 12px', 'border-radius:8px',
|
||||
'background:rgba(12,18,28,0.92)', 'border:1px solid rgba(120,150,200,0.35)',
|
||||
'box-shadow:0 6px 24px rgba(0,0,0,0.5)', 'color:#cfe0f5',
|
||||
'font:11px/1.35 system-ui,sans-serif', 'user-select:none',
|
||||
'pointer-events:auto',
|
||||
].join(';');
|
||||
|
||||
// Header: title + close (×). Close hides the panel; the feature keeps
|
||||
// whatever enabled state it had — this is a dismiss, not an A/B toggle.
|
||||
const hdr = document.createElement('div');
|
||||
hdr.style.cssText = 'display:flex;align-items:center;justify-content:space-between;margin-bottom:6px;';
|
||||
const title = document.createElement('div');
|
||||
title.textContent = 'Wide-pane framing (A/B)';
|
||||
title.style.cssText = 'font-weight:700;margin-bottom:6px;color:#e8c040;';
|
||||
wrap.appendChild(title);
|
||||
title.textContent = 'Wide-pane framing';
|
||||
title.style.cssText = 'font-weight:700;color:#e8c040;';
|
||||
const close = document.createElement('button');
|
||||
close.type = 'button'; // never submit if nested in a <form>
|
||||
close.textContent = '×';
|
||||
close.title = 'Close (Shift+A)';
|
||||
close.setAttribute('aria-label', 'Close');
|
||||
close.style.cssText = 'border:none;background:transparent;color:#cfe0f5;font-size:17px;line-height:1;cursor:pointer;padding:0 2px;';
|
||||
close.addEventListener('click', () => _setAspectPanelVisible(false));
|
||||
hdr.appendChild(title); hdr.appendChild(close); wrap.appendChild(hdr);
|
||||
|
||||
// enabled + splitOnly checkboxes
|
||||
[['enabled', 'Enabled (Shift+A)'], ['splitOnly', 'Split panes only']].forEach(([k, lbl]) => {
|
||||
// Target selector — which pane the controls below edit.
|
||||
const tgtRow = document.createElement('div'); tgtRow.style.cssText = 'margin:2px 0 7px;';
|
||||
_aspectTgtRow = tgtRow;
|
||||
const tgtLab = document.createElement('div');
|
||||
tgtLab.textContent = 'Target'; tgtLab.style.cssText = 'color:#9fb0c8;margin-bottom:2px;';
|
||||
_aspectTargetSel = document.createElement('select');
|
||||
_aspectTargetSel.setAttribute('aria-label', 'Target pane');
|
||||
_aspectTargetSel.style.cssText = 'width:100%;background:rgba(30,44,66,0.9);color:#cfe0f5;border:1px solid rgba(120,150,200,0.4);border-radius:4px;padding:3px;';
|
||||
_aspectTargetSel.addEventListener('change', () => {
|
||||
_aspectEditTarget = _aspectTargetSel.value; _syncAspectPanel();
|
||||
});
|
||||
tgtRow.appendChild(tgtLab); tgtRow.appendChild(_aspectTargetSel); wrap.appendChild(tgtRow);
|
||||
_aspectBuildTargets();
|
||||
|
||||
// enabled + splitOnly checkboxes (per-target)
|
||||
[['enabled', 'Enabled'], ['splitOnly', 'Split panes only']].forEach(([k, lbl]) => {
|
||||
const row = document.createElement('label');
|
||||
row.style.cssText = 'display:flex;align-items:center;gap:6px;margin:2px 0;cursor:pointer;';
|
||||
const cb = document.createElement('input');
|
||||
cb.type = 'checkbox'; cb.checked = !!t[k]; cb.dataset.k = k;
|
||||
cb.addEventListener('change', () => {
|
||||
_aspectTune()[k] = cb.checked; _aspectPersist();
|
||||
if (k === 'enabled') _setAspectPanelVisible(cb.checked);
|
||||
});
|
||||
cb.type = 'checkbox'; cb.checked = !!_aspectReadVal(k); cb.dataset.k = k;
|
||||
cb.addEventListener('change', () => { _aspectWriteVal(k, cb.checked); });
|
||||
const span = document.createElement('span'); span.textContent = lbl;
|
||||
row.appendChild(cb); row.appendChild(span); wrap.appendChild(row);
|
||||
});
|
||||
|
||||
// numeric sliders
|
||||
// numeric sliders (per-target)
|
||||
_ASPECT_FIELDS.forEach((f) => {
|
||||
const row = document.createElement('div');
|
||||
row.style.cssText = 'margin:5px 0;';
|
||||
@@ -1752,13 +1929,15 @@
|
||||
head.appendChild(lab); head.appendChild(val); row.appendChild(head);
|
||||
const sl = document.createElement('input');
|
||||
sl.type = 'range'; sl.min = f.min; sl.max = f.max; sl.step = f.step;
|
||||
sl.value = Number.isFinite(t[f.k]) ? t[f.k] : _ASPECT_DEFAULTS[f.k];
|
||||
const rv = _aspectReadVal(f.k);
|
||||
sl.value = Number.isFinite(rv) ? rv : _ASPECT_DEFAULTS[f.k];
|
||||
sl.dataset.k = f.k;
|
||||
sl.style.cssText = 'width:100%;';
|
||||
const show = () => { val.textContent = (+sl.value).toFixed(f.step < 1 ? 2 : 0); };
|
||||
show();
|
||||
sl.addEventListener('input', () => {
|
||||
_aspectTune()[f.k] = parseFloat(sl.value); show(); _aspectPersist();
|
||||
show(); // label always refreshes
|
||||
if (!_aspectSyncing) _aspectWriteVal(f.k, parseFloat(sl.value));
|
||||
});
|
||||
row.appendChild(sl); wrap.appendChild(row);
|
||||
});
|
||||
@@ -1769,23 +1948,26 @@
|
||||
const head = document.createElement('label');
|
||||
head.style.cssText = 'display:flex;align-items:center;gap:6px;cursor:pointer;';
|
||||
const cb = document.createElement('input');
|
||||
cb.type = 'checkbox'; cb.checked = Number.isFinite(t.hfovDeg);
|
||||
cb.type = 'checkbox'; cb.checked = Number.isFinite(_aspectReadVal('hfovDeg'));
|
||||
const lbl = document.createElement('span'); lbl.textContent = 'Override held hFOV°';
|
||||
head.appendChild(cb); head.appendChild(lbl); row.appendChild(head);
|
||||
const sl = document.createElement('input');
|
||||
sl.type = 'range'; sl.min = 40; sl.max = 160; sl.step = 1;
|
||||
sl.value = Number.isFinite(t.hfovDeg) ? t.hfovDeg : 102;
|
||||
const hv = _aspectReadVal('hfovDeg');
|
||||
sl.value = Number.isFinite(hv) ? hv : 102;
|
||||
sl.disabled = !cb.checked;
|
||||
sl.style.cssText = 'width:100%;';
|
||||
cb.addEventListener('change', () => {
|
||||
if (_aspectSyncing) return;
|
||||
sl.disabled = !cb.checked;
|
||||
_aspectTune().hfovDeg = cb.checked ? parseFloat(sl.value) : null;
|
||||
_aspectPersist();
|
||||
if (cb.checked) _aspectWriteVal('hfovDeg', parseFloat(sl.value));
|
||||
else _aspectClearVal('hfovDeg'); // base → auto (null); pane → re-inherit base
|
||||
});
|
||||
sl.addEventListener('input', () => {
|
||||
if (cb.checked) { _aspectTune().hfovDeg = parseFloat(sl.value); _aspectPersist(); }
|
||||
if (!_aspectSyncing && cb.checked) _aspectWriteVal('hfovDeg', parseFloat(sl.value));
|
||||
});
|
||||
row.appendChild(sl); wrap.appendChild(row);
|
||||
_aspectHfovCb = cb; _aspectHfovSl = sl;
|
||||
}
|
||||
|
||||
// live readout
|
||||
@@ -1799,22 +1981,31 @@
|
||||
btnRow.style.cssText = 'display:flex;gap:6px;margin-top:8px;';
|
||||
const mkBtn = (txt, fn) => {
|
||||
const b = document.createElement('button');
|
||||
b.type = 'button'; // never submit if nested in a <form>
|
||||
b.textContent = txt;
|
||||
b.style.cssText = 'flex:1;padding:4px 0;border-radius:5px;border:1px solid rgba(120,150,200,0.4);background:rgba(40,60,90,0.6);color:#cfe0f5;cursor:pointer;font:11px system-ui;';
|
||||
b.addEventListener('click', fn);
|
||||
return b;
|
||||
};
|
||||
// Reset: for "All" restores the shared defaults exactly; for a pane
|
||||
// clears that pane's override so it inherits the shared base again. Panel
|
||||
// visibility is independent (Shift+A / ×), so Reset doesn't force it open.
|
||||
btnRow.appendChild(mkBtn('Reset', () => {
|
||||
const t2 = _aspectTune();
|
||||
Object.keys(_ASPECT_DEFAULTS).forEach((k) => { t2[k] = _ASPECT_DEFAULTS[k]; });
|
||||
t2.enabled = true; // keep panel up after reset
|
||||
const base = _aspectTune();
|
||||
if (!_aspectEditTarget) {
|
||||
Object.keys(_ASPECT_DEFAULTS).forEach((k) => { base[k] = _ASPECT_DEFAULTS[k]; });
|
||||
} else if (base.__panels) {
|
||||
delete base.__panels[_aspectEditTarget];
|
||||
}
|
||||
_aspectPersist(); _syncAspectPanel();
|
||||
}));
|
||||
// Copy: the resolved values for the current target, as JSON.
|
||||
btnRow.appendChild(mkBtn('Copy', () => {
|
||||
const t2 = _aspectTune(), out = {};
|
||||
Object.keys(_ASPECT_DEFAULTS).forEach((k) => { out[k] = t2[k]; });
|
||||
const r = _aspectEditTarget ? _resolveTuneFor(_aspectEditTarget) : _aspectTune();
|
||||
const out = {};
|
||||
Object.keys(_ASPECT_DEFAULTS).forEach((k) => { out[k] = r[k]; });
|
||||
const json = JSON.stringify(out, null, 2);
|
||||
try { console.log('[h3d] wide-pane framing values:\n' + json); } catch (e) {}
|
||||
try { console.log('[h3d] wide-pane framing values (' + (_aspectEditTarget || 'all') + '):\n' + json); } catch (e) {}
|
||||
try { if (navigator.clipboard) navigator.clipboard.writeText(json); } catch (e) {}
|
||||
}));
|
||||
wrap.appendChild(btnRow);
|
||||
@@ -1824,19 +2015,33 @@
|
||||
_aspectPanelEl.style.display = 'none';
|
||||
}
|
||||
|
||||
// Push current bridge values back into the panel controls (after Reset or an
|
||||
// external edit). Cheap; only runs on demand.
|
||||
// Push the current target's values back into the panel controls (after Reset,
|
||||
// a target switch, or an external edit). Cheap; only runs on demand.
|
||||
function _syncAspectPanel() {
|
||||
if (!_aspectPanelEl) return;
|
||||
const t = _aspectTune();
|
||||
_aspectPanelEl.querySelectorAll('input[type=checkbox][data-k]').forEach((cb) => {
|
||||
cb.checked = !!t[cb.dataset.k];
|
||||
});
|
||||
_aspectPanelEl.querySelectorAll('input[type=range][data-k]').forEach((sl) => {
|
||||
const k = sl.dataset.k;
|
||||
if (Number.isFinite(t[k])) sl.value = t[k];
|
||||
sl.dispatchEvent(new Event('input')); // refresh the value label
|
||||
});
|
||||
_aspectBuildTargets();
|
||||
// Guard so the synthetic 'input' events below only refresh labels and
|
||||
// don't write the read-back values into the target (which would turn a
|
||||
// sparse pane override into a full one and spam localStorage).
|
||||
_aspectSyncing = true;
|
||||
try {
|
||||
_aspectPanelEl.querySelectorAll('input[type=checkbox][data-k]').forEach((cb) => {
|
||||
cb.checked = !!_aspectReadVal(cb.dataset.k);
|
||||
});
|
||||
_aspectPanelEl.querySelectorAll('input[type=range][data-k]').forEach((sl) => {
|
||||
const v = _aspectReadVal(sl.dataset.k);
|
||||
if (Number.isFinite(v)) sl.value = v;
|
||||
sl.dispatchEvent(new Event('input')); // refresh the value label only
|
||||
});
|
||||
if (_aspectHfovCb) {
|
||||
const hv = _aspectReadVal('hfovDeg');
|
||||
_aspectHfovCb.checked = Number.isFinite(hv);
|
||||
_aspectHfovSl.disabled = !_aspectHfovCb.checked;
|
||||
if (Number.isFinite(hv)) _aspectHfovSl.value = hv;
|
||||
}
|
||||
} finally {
|
||||
_aspectSyncing = false;
|
||||
}
|
||||
}
|
||||
|
||||
function _setAspectPanelVisible(on) {
|
||||
@@ -1844,19 +2049,35 @@
|
||||
if (!_aspectPanelEl) return;
|
||||
_aspectPanelEl.style.display = on ? 'block' : 'none';
|
||||
window.__h3dAspectPanelOpen = !!on; // gates the per-frame readout publish
|
||||
// Prune before the first build so panes from a prior song/split don't
|
||||
// flash in the dropdown until the first RAF tick.
|
||||
if (on) { _aspectPrunePanes(); _aspectBuildTargets(); }
|
||||
if (on && !_aspectPanelRAF) {
|
||||
const tick = () => {
|
||||
if (!window.__h3dAspectPanelOpen) { _aspectPanelRAF = 0; return; }
|
||||
_aspectPrunePanes();
|
||||
if (_aspectPanesDirty) _aspectBuildTargets();
|
||||
const ro = window.__h3dAspectReadout;
|
||||
if (_aspectPanelRO && ro && Number.isFinite(ro.aspect)) {
|
||||
_aspectPanelRO.textContent =
|
||||
'aspect ' + ro.aspect.toFixed(2) + ' · vFOV ' + ro.vfov.toFixed(1) + '°';
|
||||
if (_aspectPanelRO && ro) {
|
||||
const key = _aspectEditTarget || ro.__last;
|
||||
const e = key && ro[key];
|
||||
if (e && Number.isFinite(e.aspect)) {
|
||||
_aspectPanelRO.textContent =
|
||||
'aspect ' + e.aspect.toFixed(2) + ' · vFOV ' + e.vfov.toFixed(1) + '°';
|
||||
}
|
||||
}
|
||||
_aspectPanelRAF = requestAnimationFrame(tick);
|
||||
};
|
||||
_aspectPanelRAF = requestAnimationFrame(tick);
|
||||
}
|
||||
}
|
||||
// Toggle the panel open/closed (the Shift+A dismiss/reveal).
|
||||
function _toggleAspectPanel() {
|
||||
_ensureAspectPanel();
|
||||
const open = !(_aspectPanelEl && _aspectPanelEl.style.display !== 'none');
|
||||
_setAspectPanelVisible(open);
|
||||
if (open) _syncAspectPanel();
|
||||
}
|
||||
|
||||
/* ======================================================================
|
||||
* Background animations (issue #13)
|
||||
@@ -3770,6 +3991,11 @@
|
||||
// __h3dAspectTune edits) without waiting for a resize. 0 until first
|
||||
// applySize().
|
||||
let _paneAspect = 0;
|
||||
// Per-instance fallback id for the wide-pane tuner's pane key, used only
|
||||
// when this pane has no arrangement name to key by. Assigned once in
|
||||
// init(); overrides keyed off arrangement persist across songs, this
|
||||
// fallback is session-only.
|
||||
let _paneUid = 0;
|
||||
// True once applySize() has pinned the .h3d-wrap overlay to the
|
||||
// highway canvas's offset box. Stays false while the canvas has no
|
||||
// layout yet (init() can run before #highway has a real box, where
|
||||
@@ -14222,14 +14448,23 @@
|
||||
|
||||
// ── Horizontal-FOV-hold + optional wide-pane pose nudges ──
|
||||
// Driven by window.__h3dAspectTune (default off → exact no-op).
|
||||
// _aspectTune() returns the live bridge object, seeded from defaults
|
||||
// + localStorage on first read so a persisted tuning session applies
|
||||
// on load without opening the panel. Every field is finite-coerced.
|
||||
// When disabled (or splitOnly and not in a split) the tune is treated
|
||||
// as null, so effectiveVfov returns the base vertical fov and cam.fov
|
||||
// is restored to it. The fov write is guarded on an actual change so
|
||||
// a steady pane costs nothing.
|
||||
const _aspTune = _aspectTune();
|
||||
// _resolveTuneFor(paneKey) returns the shared base with THIS pane's
|
||||
// overrides (if any) laid on top, so a single split pane can be framed
|
||||
// independently. The base is seeded from defaults + localStorage on
|
||||
// first read, so a persisted tuning session applies on load without
|
||||
// opening the panel. Every field is finite-coerced. When disabled (or
|
||||
// splitOnly and not in a split) the tune is treated as null, so
|
||||
// effectiveVfov returns the base vertical fov and cam.fov is restored
|
||||
// to it. The fov write is guarded on an actual change so a steady pane
|
||||
// costs nothing.
|
||||
const _paneKey = _aspectPaneKey(
|
||||
bundle && bundle.songInfo && bundle.songInfo.arrangement, _paneUid);
|
||||
// Only feed the Target-picker registry while the tuner is open (same
|
||||
// gate as the readout). Closed → nothing is registered, so the registry
|
||||
// can't grow for users who never open the panel; the key is still
|
||||
// resolved below so any saved overrides keep applying.
|
||||
if (window.__h3dAspectPanelOpen) _aspectRegisterPane(_paneKey);
|
||||
const _aspTune = _resolveTuneFor(_paneKey);
|
||||
const _aspActive = !!(_aspTune && _aspTune.enabled
|
||||
&& !(_aspTune.splitOnly && !_ssActive()));
|
||||
const _tune = _aspActive ? _aspTune : null;
|
||||
@@ -14238,12 +14473,14 @@
|
||||
cam.fov = _vfov;
|
||||
cam.updateProjectionMatrix();
|
||||
}
|
||||
// Publish a live readout for the tuner panel (only while it's open,
|
||||
// so the steady path stays allocation-free). Last pane to render wins
|
||||
// the slot — fine, all panes share the same aspect in a split layout.
|
||||
// Publish a per-pane live readout for the tuner panel (only while it's
|
||||
// open, so the steady path stays allocation-free). Keyed by pane so
|
||||
// the panel can show the reading for whichever target is selected.
|
||||
if (window.__h3dAspectPanelOpen) {
|
||||
const _ro = window.__h3dAspectReadout || (window.__h3dAspectReadout = {});
|
||||
_ro.aspect = _paneAspect; _ro.vfov = _vfov;
|
||||
const _slot = _ro[_paneKey] || (_ro[_paneKey] = {});
|
||||
_slot.aspect = _paneAspect; _slot.vfov = _vfov;
|
||||
_ro.__last = _paneKey;
|
||||
}
|
||||
// Optional pose nudges (height / dolly / pitch) to chase a low-flat
|
||||
// wide-pane look if fov alone isn't enough. Gated to wide panes and
|
||||
@@ -14678,7 +14915,8 @@
|
||||
}
|
||||
_destroyed = _isReady = false;
|
||||
_isFocused = true;
|
||||
_registerAspectAbShortcut(); // session-global A/B toggle (self-guarded)
|
||||
if (!_paneUid) _paneUid = ++_aspectPaneCounter; // fallback pane id (no-arrangement panes)
|
||||
_registerTunerShortcut(); // session-global tuner shortcut (self-guarded)
|
||||
const myToken = ++_initToken;
|
||||
highwayCanvas = canvas;
|
||||
_invertedCached = !!(bundle && bundle.inverted);
|
||||
|
||||
@@ -0,0 +1,661 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
@@ -0,0 +1,37 @@
|
||||
# Keys Highway 3D
|
||||
|
||||
RS+-style falling-note 3D piano highway for [Slopsmith](https://github.com/got-feedback/feedback), fed by the **Sloppak Notation Format** (sloppak-spec §5.3) — part of the piano/keys first-class epic (slopsmith#828, plugin workstream slopsmith#824).
|
||||
|
||||
- Consumes the `notation_info` / `notation_measures` highway-WS stream over a private per-instance socket and flattens measure → staff → voice → beat → note into `{midi, t, durSec, hand}` (durations derived from written `dur`/`dot`/`tu` at the running tempo; ties extend; overlap-clamped).
|
||||
- 3D perspective highway to a vanishing point with a real white/black-key keyboard; per-key **pitch-class colours** (Synthesia convention — C red, D yellow, E blue, …) with hand (rh/lh) as a secondary brightness cue.
|
||||
- Full RS+ visual treatment: key **letter glyphs** printed on the active-range key tops (cached CanvasTextures), **bevelled gem-style note blocks** (ExtrudeGeometry, geometry/material caches keyed by size and pitch-class×hand), **floating bar numbers** scrolling with the notes, **active-range lane dimming** so the playable span pops, and a **glowing pulsing hit-line** (layered additive gradient planes — no postprocessing).
|
||||
- Performance discipline: no per-frame allocations or DOM queries in `draw()`. Chart-scoped resources — note geometries/materials, bar-number and glow textures — are cached and disposed on chart teardown; the key-letter glyph `CanvasTexture`s live in a shared module-level cache that survives teardown and is reused across instances.
|
||||
- Auto-selected for arrangements with notation via `matchesArrangement(songInfo.has_notation)`; capability-native `visualization` provider declaration.
|
||||
- **Web MIDI input scoring**: module-level MIDI singleton (one access per tab, focused-instance routing) with device auto-connect by saved id+name, loopback blocklist, channel filter, transpose and CC64 sustain (`keys3d_` localStorage prefix; `window.keysH3d*` settings API). Hit detection matches played MIDI against the flattened chart notes within ±0.10 s with per-note dedupe and a missed-note sweep (only while a device is connected — never retroactive across a mid-song connect).
|
||||
- **Live hit feedback on the MIDI path** (not the chart): key depress (~4° back-edge pivot, ~120 ms spring; the key letter rides along), wrong-note red key flash, and a vertical flame flare on hits (pooled additive sprites, white-hot base fading into the pitch-class colour, ~400 ms).
|
||||
- **End-of-run stats**: POSTs `/api/stats` `{filename, arrangement, score, accuracy}` exactly once per run with the same formula as the guitar notedetect path (`accuracy = hits / max(1, hits+misses)`, `score = round(hits·100·accuracy)`), then notifies the progression core when present.
|
||||
- **Capability wiring** (all guarded for servers without the hosts): registers as a note-detection `midi` provider (`keys-midi`, `verify.target`), opens a per-song binding scoped to the chart's keys range, reports hit/miss observability events, and exposes Web MIDI inputs to the audio-input domain with pseudonymized labels (`midi-input-1`, …) via `source.enumerate/describe/open/close`.
|
||||
- Headless test hook: `window.__keysHwTest = { injectNoteOn(midi, when), getScore() }`.
|
||||
|
||||
## Tests
|
||||
|
||||
```
|
||||
node --test tests/*.test.js
|
||||
```
|
||||
|
||||
## Ported helpers (keep in sync with highway_3d)
|
||||
|
||||
Visual-parity code copied from `plugins/highway_3d/screen.js` — same
|
||||
function names, signatures, and constants on purpose, marked with
|
||||
`PORTED FROM highway_3d` comments at each site. If the guitar highway
|
||||
tunes one of these, mirror the change here (and in `drum_highway_3d`):
|
||||
|
||||
- `_bloomEnsure()` / `_bloomDispose()` — EffectComposer + UnrealBloomPass
|
||||
(0.65/0.5/0.82) on a multisampled HalfFloat target, ACES↔None tone-
|
||||
mapping switch in `draw()`; addons dynamic-imported from
|
||||
`/static/vendor/three/addons/` (no CDN fallback — direct render is the
|
||||
graceful degrade)
|
||||
|
||||
## License
|
||||
|
||||
AGPL-3.0.
|
||||
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 256 256" role="img" aria-label="Keys Highway 3D placeholder thumbnail">
|
||||
<rect width="256" height="256" rx="36" fill="#0f172a"/>
|
||||
<rect x="18" y="18" width="220" height="220" rx="28" fill="#1e293b" stroke="#334155" stroke-width="3"/>
|
||||
<text x="128" y="150" font-family="Rubik, Arial, sans-serif" font-size="104" font-weight="800" fill="#38bdf8" text-anchor="middle">KH</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 464 B |
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"id": "keys_highway_3d",
|
||||
"name": "Keys Highway 3D",
|
||||
"version": "0.1.0",
|
||||
"description": "RS+-style 3D falling-note piano highway fed by the Sloppak Notation Format, with Web MIDI input scoring.",
|
||||
"type": "visualization",
|
||||
"bundled": true,
|
||||
"script": "screen.js",
|
||||
"settings": {
|
||||
"html": "settings.html",
|
||||
"category": "graphics"
|
||||
},
|
||||
"standards": [
|
||||
"capability-pipelines.v1",
|
||||
"plugin-runtime-idempotent.v1"
|
||||
],
|
||||
"capabilities": {
|
||||
"visualization": {
|
||||
"roles": [
|
||||
"provider"
|
||||
],
|
||||
"operations": [
|
||||
"renderer.create",
|
||||
"renderer.destroy"
|
||||
],
|
||||
"emits": [
|
||||
"renderer-ready",
|
||||
"renderer-failed"
|
||||
],
|
||||
"mode": "active",
|
||||
"safety": "safe"
|
||||
},
|
||||
"note-detection": {
|
||||
"roles": [
|
||||
"provider"
|
||||
],
|
||||
"operations": [
|
||||
"verify.target"
|
||||
],
|
||||
"emits": [
|
||||
"hit",
|
||||
"miss"
|
||||
],
|
||||
"mode": "active",
|
||||
"safety": "sensitive"
|
||||
},
|
||||
"midi-input": {
|
||||
"roles": [
|
||||
"requester"
|
||||
],
|
||||
"requests": [
|
||||
"discover",
|
||||
"list-sources",
|
||||
"select-source",
|
||||
"open-source",
|
||||
"close-source"
|
||||
],
|
||||
"mode": "active",
|
||||
"compatibility": "degrade-noop",
|
||||
"ownership": "requester-only",
|
||||
"safety": "sensitive",
|
||||
"description": "Reads the MIDI keyboard input through the core midi-input domain (Web-MIDI provider ships built-in with the domain). Absent domain \u2192 no MIDI devices, fail-soft.",
|
||||
"version": 1
|
||||
}
|
||||
},
|
||||
"category": "practice",
|
||||
"icon": "assets/thumb.svg"
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,47 @@
|
||||
<div role="group" aria-labelledby="keysh3d-heading">
|
||||
<h3 id="keysh3d-heading" class="text-sm font-medium text-gray-400 mb-2">3D Keys Highway</h3>
|
||||
<p class="text-xs text-gray-500 mb-3">
|
||||
Pick a song with keys notation (sloppak-spec §5.3) and choose
|
||||
<em>Keys Highway 3D</em> from the viz picker (Auto selects it for
|
||||
notation charts). The plugin auto-attaches to your MIDI keyboard;
|
||||
device, channel and transpose are configured from the player for
|
||||
now — this panel holds the graphics controls.
|
||||
</p>
|
||||
|
||||
<!-- Graphics -->
|
||||
<div class="mt-3">
|
||||
<h4 class="text-xs font-medium text-gray-300 mb-2">Graphics</h4>
|
||||
<label for="keysh3d-fx-bloom" class="flex items-center gap-2 text-xs text-gray-300 cursor-pointer">
|
||||
<input type="checkbox" id="keysh3d-fx-bloom" checked
|
||||
onchange="window.keys3dSetFx && window.keys3dSetFx('bloom', this.checked)">
|
||||
Glow (bloom)
|
||||
</label>
|
||||
<p class="text-xs text-gray-500 mt-1">
|
||||
Soft light-bleed around the hit line, hit flames and consumed
|
||||
sustains. Applies live; turn off to reclaim GPU headroom on
|
||||
weak machines.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
'use strict';
|
||||
// Hydrate controls from stored config on first paint. Narrow the
|
||||
// try/catch to just the localStorage reads (drum_highway_3d
|
||||
// settings-hydration convention).
|
||||
try {
|
||||
// FX toggles (keys3d_bg_* — guitar-parity graphics controls).
|
||||
// Only explicit values override; absent/corrupt keys keep the
|
||||
// default (ON), matching screen.js readFxSettings.
|
||||
const storedBloom = localStorage.getItem('keys3d_bg_bloom');
|
||||
if (storedBloom === '1' || storedBloom === 'true') {
|
||||
document.getElementById('keysh3d-fx-bloom').checked = true;
|
||||
} else if (storedBloom === '0' || storedBloom === 'false') {
|
||||
document.getElementById('keysh3d-fx-bloom').checked = false;
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('[Keys-Hwy3D settings] hydration failed:', e);
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
</div>
|
||||
@@ -0,0 +1,190 @@
|
||||
// Pure data-layer tests: load screen.js in a bare vm window and exercise the
|
||||
// __test exports (no DOM, no WebGL, no network).
|
||||
const { test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
|
||||
function load() {
|
||||
const window = {
|
||||
console,
|
||||
location: { protocol: 'http:', host: 'localhost' },
|
||||
slopsmith: {},
|
||||
};
|
||||
window.window = window;
|
||||
window.globalThis = window;
|
||||
const context = vm.createContext(window);
|
||||
const src = fs.readFileSync(path.join(__dirname, '..', 'screen.js'), 'utf8');
|
||||
vm.runInContext(src, context, { filename: 'screen.js' });
|
||||
return window.slopsmithViz_keys_highway_3d.__test;
|
||||
}
|
||||
|
||||
test('beatDurSec: base, dotted, double-dotted, tuplet', () => {
|
||||
const { beatDurSec } = load();
|
||||
// 120 BPM → quarter = 0.5s
|
||||
assert.equal(beatDurSec({ dur: 4 }, 120), 0.5);
|
||||
assert.equal(beatDurSec({ dur: 2 }, 120), 1.0);
|
||||
assert.equal(beatDurSec({ dur: 8 }, 120), 0.25);
|
||||
// dotted quarter = 0.75s; double-dotted = 0.875s
|
||||
assert.equal(beatDurSec({ dur: 4, dot: 1 }, 120), 0.75);
|
||||
assert.equal(beatDurSec({ dur: 4, dot: 2 }, 120), 0.875);
|
||||
// triplet eighth: 0.25 * 2/3
|
||||
assert.ok(Math.abs(beatDurSec({ dur: 8, tu: [3, 2] }, 120) - 0.25 * 2 / 3) < 1e-9);
|
||||
// invalid → null
|
||||
assert.equal(beatDurSec({ dur: 0 }, 120), null);
|
||||
assert.equal(beatDurSec({ dur: 4 }, null), null);
|
||||
});
|
||||
|
||||
function measure(idx, t, opts = {}) {
|
||||
return { idx, t, ...opts };
|
||||
}
|
||||
|
||||
test('flattenNotation: basic two-hand flatten, sorted, durSec from tempo', () => {
|
||||
const { flattenNotation } = load();
|
||||
const notes = flattenNotation([
|
||||
{
|
||||
idx: 1, t: 0, tempo: 120,
|
||||
staves: {
|
||||
rh: { voices: [{ v: 1, beats: [
|
||||
{ t: 0.5, dur: 4, notes: [{ midi: 64 }] },
|
||||
{ t: 1.0, dur: 8, notes: [{ midi: 67 }] },
|
||||
] }] },
|
||||
lh: { voices: [{ v: 1, beats: [
|
||||
{ t: 0.0, dur: 2, notes: [{ midi: 48 }] },
|
||||
] }] },
|
||||
},
|
||||
},
|
||||
]);
|
||||
assert.equal(notes.length, 3);
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(notes.map(n => n.midi))), [48, 64, 67]); // time-sorted
|
||||
assert.equal(notes[0].hand, 'lh');
|
||||
assert.equal(notes[0].durSec, 1.0); // half at 120
|
||||
assert.equal(notes[1].durSec, 0.5); // quarter
|
||||
assert.equal(notes[2].durSec, 0.25); // eighth
|
||||
assert.equal(notes[1].measureIdx, 1);
|
||||
});
|
||||
|
||||
test('flattenNotation: tempo state carries across measures and changes apply', () => {
|
||||
const { flattenNotation } = load();
|
||||
const notes = flattenNotation([
|
||||
measure(1, 0, { tempo: 120, staves: { rh: { voices: [{ v: 1, beats: [{ t: 0, dur: 4, notes: [{ midi: 60 }] }] }] } } }),
|
||||
measure(2, 2, { staves: { rh: { voices: [{ v: 1, beats: [{ t: 2, dur: 4, notes: [{ midi: 62 }] }] }] } } }),
|
||||
measure(3, 4, { tempo: 60, staves: { rh: { voices: [{ v: 1, beats: [{ t: 4, dur: 4, notes: [{ midi: 64 }] }] }] } } }),
|
||||
]);
|
||||
assert.equal(notes[0].durSec, 0.5); // 120 BPM
|
||||
assert.equal(notes[1].durSec, 0.5); // tempo carried
|
||||
assert.equal(notes[2].durSec, 1.0); // 60 BPM
|
||||
});
|
||||
|
||||
test('flattenNotation: tied notes extend instead of emitting a new block', () => {
|
||||
const { flattenNotation } = load();
|
||||
const notes = flattenNotation([
|
||||
{
|
||||
idx: 1, t: 0, tempo: 120,
|
||||
staves: { rh: { voices: [{ v: 1, beats: [
|
||||
{ t: 0.0, dur: 2, notes: [{ midi: 60 }] },
|
||||
{ t: 1.0, dur: 2, notes: [{ midi: 60, tied: true }] },
|
||||
] }] } },
|
||||
},
|
||||
]);
|
||||
assert.equal(notes.length, 1);
|
||||
assert.equal(notes[0].durSec, 2.0); // half + tied half
|
||||
});
|
||||
|
||||
test('flattenNotation: no tempo anywhere falls back to next-onset gap', () => {
|
||||
const { flattenNotation } = load();
|
||||
const notes = flattenNotation([
|
||||
{
|
||||
idx: 1, t: 0,
|
||||
staves: { rh: { voices: [{ v: 1, beats: [
|
||||
{ t: 0.0, dur: 4, notes: [{ midi: 60 }] },
|
||||
{ t: 0.8, dur: 4, notes: [{ midi: 62 }] },
|
||||
] }] } },
|
||||
},
|
||||
]);
|
||||
assert.ok(Math.abs(notes[0].durSec - 0.8) < 1e-9);
|
||||
assert.equal(notes[1].durSec, 2.0); // final-beat fallback
|
||||
});
|
||||
|
||||
test('flattenNotation: overlap clamp against next same-hand same-midi onset', () => {
|
||||
const { flattenNotation } = load();
|
||||
const notes = flattenNotation([
|
||||
{
|
||||
idx: 1, t: 0, tempo: 30, // whole note = 8s — way past the next onset
|
||||
staves: { rh: { voices: [{ v: 1, beats: [
|
||||
{ t: 0.0, dur: 1, notes: [{ midi: 60 }] },
|
||||
{ t: 1.0, dur: 1, notes: [{ midi: 60 }] },
|
||||
] }] } },
|
||||
},
|
||||
]);
|
||||
assert.equal(notes[0].durSec, 1.0); // clamped to next onset
|
||||
});
|
||||
|
||||
test('flattenNotation: rests, malformed beats, and out-of-range midi are skipped', () => {
|
||||
const { flattenNotation } = load();
|
||||
const notes = flattenNotation([
|
||||
{
|
||||
idx: 1, t: 0, tempo: 120,
|
||||
staves: { rh: { voices: [{ v: 1, beats: [
|
||||
{ t: 0.0, dur: 4, rest: true },
|
||||
{ t: 0.5, dur: 4, notes: [{ midi: 200 }] },
|
||||
null,
|
||||
{ t: 1.0, dur: 4, notes: [{ midi: 64 }] },
|
||||
] }] } },
|
||||
},
|
||||
]);
|
||||
assert.equal(notes.length, 1);
|
||||
assert.equal(notes[0].midi, 64);
|
||||
});
|
||||
|
||||
test('keyRange pads and clamps to the 88-key piano, keeps active span explicit', () => {
|
||||
const { keyRange } = load();
|
||||
assert.deepEqual(
|
||||
JSON.parse(JSON.stringify(keyRange([{ midi: 60 }, { midi: 72 }]))),
|
||||
{ low: 58, high: 74, activeLow: 60, activeHigh: 72 },
|
||||
);
|
||||
// At the clamp edges the active span still reflects the chart extremes
|
||||
// (not low+pad — that would mark A0/C8 inactive when actually played).
|
||||
assert.deepEqual(
|
||||
JSON.parse(JSON.stringify(keyRange([{ midi: 21 }, { midi: 108 }]))),
|
||||
{ low: 21, high: 108, activeLow: 21, activeHigh: 108 },
|
||||
);
|
||||
const empty = keyRange([]);
|
||||
assert.ok(empty.low < 60 && empty.high > 60);
|
||||
assert.ok(empty.activeLow > empty.activeHigh, 'empty chart has an empty active span');
|
||||
});
|
||||
|
||||
test('noteLetter maps midi to pitch-class letters', () => {
|
||||
const { noteLetter } = load();
|
||||
assert.equal(noteLetter(60), 'C');
|
||||
assert.equal(noteLetter(61), 'C#');
|
||||
assert.equal(noteLetter(69), 'A');
|
||||
assert.equal(noteLetter(71), 'B');
|
||||
assert.equal(noteLetter(72), 'C'); // octave wraps
|
||||
assert.equal(noteLetter(21), 'A'); // A0
|
||||
});
|
||||
|
||||
test('scrollZ: events sit at hitZ exactly at their time and approach from -Z', () => {
|
||||
const { scrollZ } = load();
|
||||
const hitZ = -0.5, speed = 2.0;
|
||||
// At now === eventT the event is exactly on the hit-line.
|
||||
assert.equal(scrollZ(10, 10, hitZ, speed), hitZ);
|
||||
// 1s before its time it is `speed` units further away (towards -Z).
|
||||
assert.equal(scrollZ(10, 9, hitZ, speed), hitZ - speed);
|
||||
// After its time it has moved past the hit-line (towards +Z).
|
||||
assert.equal(scrollZ(10, 11, hitZ, speed), hitZ + speed);
|
||||
// Marker and note-front-edge maths agree by construction: a note of
|
||||
// length L positioned at scrollZ(t) - L/2 has its front edge at
|
||||
// scrollZ(t).
|
||||
const len = 0.8;
|
||||
assert.equal(scrollZ(10, 10, hitZ, speed) - len / 2 + len / 2, hitZ);
|
||||
});
|
||||
|
||||
test('measureMarkers extracts idx/t pairs', () => {
|
||||
const { measureMarkers } = load();
|
||||
assert.deepEqual(
|
||||
JSON.parse(JSON.stringify(measureMarkers([{ idx: 1, t: 0 }, { idx: 2, t: 2.5 }, { bogus: true }]))),
|
||||
[{ idx: 1, t: 0 }, { idx: 2, t: 2.5 }],
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
// FX-settings scaffold tests (guitar-highway parity controls). Same bare-vm
|
||||
// harness as data_layer.test.js — no DOM, no localStorage — which doubles as
|
||||
// a lint that the new module-scope FX code stays side-effect safe.
|
||||
const { test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
|
||||
function load(extraWindow) {
|
||||
const window = {
|
||||
console,
|
||||
location: { protocol: 'http:', host: 'localhost' },
|
||||
slopsmith: {},
|
||||
...extraWindow,
|
||||
};
|
||||
window.window = window;
|
||||
window.globalThis = window;
|
||||
const context = vm.createContext(window);
|
||||
const src = fs.readFileSync(path.join(__dirname, '..', 'screen.js'), 'utf8');
|
||||
vm.runInContext(src, context, { filename: 'screen.js' });
|
||||
return window;
|
||||
}
|
||||
|
||||
test('readFxSettings: defaults survive a localStorage-less environment', () => {
|
||||
const { readFxSettings, FX_DEFAULTS } = load().slopsmithViz_keys_highway_3d.__test;
|
||||
assert.deepEqual(readFxSettings(), FX_DEFAULTS);
|
||||
assert.equal(FX_DEFAULTS.bloom, true); // effects on by default
|
||||
});
|
||||
|
||||
test('readFxSettings: reads keys3d_bg_* overrides and coerces types', () => {
|
||||
const store = { keys3d_bg_bloom: '0' };
|
||||
const win = load({
|
||||
localStorage: {
|
||||
getItem: (k) => (k in store ? store[k] : null),
|
||||
setItem: (k, v) => { store[k] = v; },
|
||||
},
|
||||
});
|
||||
const { readFxSettings } = win.slopsmithViz_keys_highway_3d.__test;
|
||||
assert.equal(readFxSettings().bloom, false);
|
||||
store.keys3d_bg_bloom = 'true';
|
||||
assert.equal(readFxSettings().bloom, true);
|
||||
store.keys3d_bg_bloom = 'false';
|
||||
assert.equal(readFxSettings().bloom, false);
|
||||
// Corrupt/foreign value → keep the default rather than silently
|
||||
// disabling the effect.
|
||||
store.keys3d_bg_bloom = 'banana';
|
||||
assert.equal(readFxSettings().bloom, true);
|
||||
});
|
||||
|
||||
test('keys3dSetFx: persists, coerces, and ignores unknown keys', () => {
|
||||
const store = {};
|
||||
const events = [];
|
||||
const win = load({
|
||||
localStorage: {
|
||||
getItem: (k) => (k in store ? store[k] : null),
|
||||
setItem: (k, v) => { store[k] = v; },
|
||||
},
|
||||
dispatchEvent: (ev) => { events.push(ev); return true; },
|
||||
CustomEvent: class CustomEvent {
|
||||
constructor(type, opts) { this.type = type; this.detail = opts && opts.detail; }
|
||||
},
|
||||
});
|
||||
win.keys3dSetFx('bloom', false);
|
||||
assert.equal(store.keys3d_bg_bloom, '0');
|
||||
// String forms round-trip like the reader's accepted representations.
|
||||
win.keys3dSetFx('bloom', 'false');
|
||||
assert.equal(store.keys3d_bg_bloom, '0');
|
||||
win.keys3dSetFx('bloom', 'true');
|
||||
assert.equal(store.keys3d_bg_bloom, '1');
|
||||
win.keys3dSetFx('bloom', false);
|
||||
assert.equal(events.length, 4);
|
||||
assert.equal(events[0].type, 'keys3d:settings');
|
||||
// Field-wise (the detail object was built inside the vm realm, so a
|
||||
// deep-strict compare would trip on its foreign Object.prototype).
|
||||
assert.equal(events[0].detail.fx.bloom, false);
|
||||
assert.deepEqual(Object.keys(events[0].detail.fx), ['bloom']);
|
||||
// Unknown key: no write, no event.
|
||||
win.keys3dSetFx('nonsense', 1);
|
||||
assert.equal(events.length, 4);
|
||||
assert.ok(!('keys3d_bg_nonsense' in store));
|
||||
});
|
||||
@@ -0,0 +1,154 @@
|
||||
// Pure MIDI-scoring tests: load screen.js in a bare vm window and exercise
|
||||
// the __test exports (no DOM, no WebGL, no MIDI device, no network).
|
||||
const { test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
|
||||
function load() {
|
||||
const window = {
|
||||
console,
|
||||
location: { protocol: 'http:', host: 'localhost' },
|
||||
slopsmith: {},
|
||||
};
|
||||
window.window = window;
|
||||
window.globalThis = window;
|
||||
const context = vm.createContext(window);
|
||||
const src = fs.readFileSync(path.join(__dirname, '..', 'screen.js'), 'utf8');
|
||||
vm.runInContext(src, context, { filename: 'screen.js' });
|
||||
return window.slopsmithViz_keys_highway_3d.__test;
|
||||
}
|
||||
|
||||
const TOL = 0.10;
|
||||
|
||||
test('accuracyOf/scoreOf mirror the notedetect stats formula', () => {
|
||||
const { accuracyOf, scoreOf } = load();
|
||||
// accuracy = hits / max(1, hits + misses)
|
||||
assert.equal(accuracyOf(0, 0), 0);
|
||||
assert.equal(accuracyOf(10, 0), 1);
|
||||
assert.equal(accuracyOf(3, 1), 0.75);
|
||||
// score = round(hits * 100 * accuracy)
|
||||
assert.equal(scoreOf(0, 0), 0);
|
||||
assert.equal(scoreOf(10, 0), 1000);
|
||||
assert.equal(scoreOf(3, 1), Math.round(3 * 100 * 0.75));
|
||||
// Monotonic in accuracy at fixed hits.
|
||||
assert.ok(scoreOf(5, 0) > scoreOf(5, 5));
|
||||
});
|
||||
|
||||
test('judgeHit: exact note inside ±0.10 s window hits; outside misses', () => {
|
||||
const { judgeHit } = load();
|
||||
const notes = [
|
||||
{ midi: 60, t: 1.0 },
|
||||
{ midi: 64, t: 1.0 },
|
||||
{ midi: 62, t: 2.0 },
|
||||
];
|
||||
const hitKeys = new Set();
|
||||
// On time.
|
||||
assert.equal(judgeHit(notes, 60, 1.0, hitKeys, TOL), '1.000|60');
|
||||
// Near the edge of the window (the exact ±0.10 boundary is float-
|
||||
// representation dependent, same as the piano plugin).
|
||||
assert.equal(judgeHit(notes, 62, 2.099, hitKeys, TOL), '2.000|62');
|
||||
assert.equal(judgeHit(notes, 64, 0.901, hitKeys, TOL), '1.000|64');
|
||||
// Just outside the window.
|
||||
assert.equal(judgeHit(notes, 60, 1.11, hitKeys, TOL), null);
|
||||
// Wrong note — nothing at that midi anywhere near.
|
||||
assert.equal(judgeHit(notes, 65, 1.0, hitKeys, TOL), null);
|
||||
});
|
||||
|
||||
test('judgeHit: dedupes by t|midi — a chart note can only be hit once', () => {
|
||||
const { judgeHit } = load();
|
||||
const notes = [{ midi: 60, t: 1.0 }, { midi: 60, t: 1.15 }];
|
||||
const hitKeys = new Set();
|
||||
const first = judgeHit(notes, 60, 1.02, hitKeys, TOL);
|
||||
assert.equal(first, '1.000|60');
|
||||
hitKeys.add(first);
|
||||
// Second strike near the same time falls through to the NEXT un-hit
|
||||
// chart note at the same midi (double-stop repeats).
|
||||
const second = judgeHit(notes, 60, 1.06, hitKeys, TOL);
|
||||
assert.equal(second, '1.150|60');
|
||||
hitKeys.add(second);
|
||||
// Third strike: both consumed → wrong note.
|
||||
assert.equal(judgeHit(notes, 60, 1.1, hitKeys, TOL), null);
|
||||
});
|
||||
|
||||
test('judgeHit: empty/absent chart never judges', () => {
|
||||
const { judgeHit } = load();
|
||||
assert.equal(judgeHit([], 60, 1.0, new Set(), TOL), null);
|
||||
assert.equal(judgeHit(null, 60, 1.0, new Set(), TOL), null);
|
||||
});
|
||||
|
||||
test('sweepMissed: marks elapsed unhit notes once, respects hit + floor', () => {
|
||||
const { sweepMissed, noteKey } = load();
|
||||
const notes = [
|
||||
{ midi: 60, t: 1.0 },
|
||||
{ midi: 62, t: 1.5 },
|
||||
{ midi: 64, t: 5.0 },
|
||||
];
|
||||
const hitKeys = new Set([noteKey(1.0, 60)]); // 60@1.0 was hit
|
||||
const missedKeys = new Set();
|
||||
const missed = [];
|
||||
// At t=2.0 the windows for 1.0 and 1.5 have elapsed; 5.0 is pending.
|
||||
const n1 = sweepMissed(notes, 2.0, hitKeys, missedKeys, TOL, null, n => missed.push(n.midi));
|
||||
assert.equal(n1, 1);
|
||||
assert.deepEqual(missed, [62]);
|
||||
assert.ok(missedKeys.has(noteKey(1.5, 62)));
|
||||
// Sweeping again counts nothing new (idempotent per note).
|
||||
assert.equal(sweepMissed(notes, 2.1, hitKeys, missedKeys, TOL, null), 0);
|
||||
// Floor: a device connected at t=6 must not retro-miss the 5.0 note.
|
||||
const hk2 = new Set(), mk2 = new Set();
|
||||
assert.equal(sweepMissed(notes, 6.0, hk2, mk2, TOL, 6.0), 0);
|
||||
});
|
||||
|
||||
test('sweepMissed: a note exactly at the connect floor is not retro-missed', () => {
|
||||
// Off-by-one guard: floor is the connect instant; a note whose onset
|
||||
// equals it (device connected exactly as the onset passed) must be
|
||||
// excluded, not swept. Floor comparison is `<=`, not `<`.
|
||||
const { sweepMissed } = load();
|
||||
const notes = [{ midi: 60, t: 5.0 }, { midi: 62, t: 6.0 }];
|
||||
const missedKeys = new Set();
|
||||
const missed = [];
|
||||
const n = sweepMissed(notes, 7.0, new Set(), missedKeys, TOL, 5.0,
|
||||
m => missed.push(m.midi));
|
||||
assert.equal(n, 1);
|
||||
assert.deepEqual(missed, [62]);
|
||||
});
|
||||
|
||||
test('sweepMissed: a long frame stall cannot let elapsed notes slip past', () => {
|
||||
const { sweepMissed } = load();
|
||||
const notes = [{ midi: 60, t: 1.0 }, { midi: 62, t: 3.0 }];
|
||||
const missedKeys = new Set();
|
||||
// The previous sweep ran at t≈0; the next runs 10 s later (backgrounded
|
||||
// tab / render hitch). Both elapsed notes must still be counted.
|
||||
assert.equal(sweepMissed(notes, 10.0, new Set(), missedKeys, TOL, null), 2);
|
||||
});
|
||||
|
||||
test('sweepMissed: cursor advances monotonically and never recounts', () => {
|
||||
const { sweepMissed } = load();
|
||||
const notes = [
|
||||
{ midi: 60, t: 1.0 },
|
||||
{ midi: 62, t: 2.0 },
|
||||
{ midi: 64, t: 9.0 },
|
||||
];
|
||||
const hitKeys = new Set(), missedKeys = new Set();
|
||||
const cursor = { idx: 0 };
|
||||
assert.equal(sweepMissed(notes, 1.5, hitKeys, missedKeys, TOL, null, null, cursor), 1);
|
||||
assert.equal(cursor.idx, 1);
|
||||
// Stall to t=8: the 2.0 note is counted exactly once from the cursor.
|
||||
assert.equal(sweepMissed(notes, 8.0, hitKeys, missedKeys, TOL, null, null, cursor), 1);
|
||||
assert.equal(cursor.idx, 2);
|
||||
// Seek BACKWARDS: the cursor does not rewind, nothing is recounted.
|
||||
assert.equal(sweepMissed(notes, 1.5, hitKeys, missedKeys, TOL, null, null, cursor), 0);
|
||||
// The cursor still advances past pre-floor notes without counting them.
|
||||
const c2 = { idx: 0 };
|
||||
const mk2 = new Set();
|
||||
assert.equal(sweepMissed(notes, 8.0, new Set(), mk2, TOL, 5.0, null, c2), 0);
|
||||
assert.equal(c2.idx, 2);
|
||||
});
|
||||
|
||||
test('noteKey quantises time to ms so float drift cannot double-count', () => {
|
||||
const { noteKey } = load();
|
||||
assert.equal(noteKey(1.0004, 60), noteKey(1.0001, 60));
|
||||
assert.notEqual(noteKey(1.002, 60), noteKey(1.0001, 60));
|
||||
assert.notEqual(noteKey(1.0, 60), noteKey(1.0, 61));
|
||||
});
|
||||
@@ -37,6 +37,7 @@ def setup(app: FastAPI, context: dict):
|
||||
"showFloatingButton": True,
|
||||
"visualizationMode": "default",
|
||||
"audioInputMode": "auto",
|
||||
"autoOpenOnTuningChange": False,
|
||||
}
|
||||
if not config_file.exists():
|
||||
return defaults
|
||||
@@ -55,6 +56,11 @@ def setup(app: FastAPI, context: dict):
|
||||
res["visualizationMode"] = str(data.get("visualizationMode", "default"))
|
||||
raw_mode = str(data.get("audioInputMode", "auto"))
|
||||
res["audioInputMode"] = raw_mode if raw_mode in ("auto", "browser") else "auto"
|
||||
# Fail closed: only a real JSON boolean enables the opt-in. A hand-edited /
|
||||
# migrated / bad-client value (e.g. the string "false" or "0") must NOT be
|
||||
# coerced to True by bool().
|
||||
_auto_open = data.get("autoOpenOnTuningChange", False)
|
||||
res["autoOpenOnTuningChange"] = _auto_open if isinstance(_auto_open, bool) else False
|
||||
|
||||
if not isinstance(res["customTunings"], dict):
|
||||
res["customTunings"] = {}
|
||||
|
||||
+442
-10
@@ -13,8 +13,17 @@
|
||||
let _lastAutoOpenSessionKey = null;
|
||||
let _autoOpenDismissedSessionKey = null;
|
||||
let _autoOpenGeneration = 0;
|
||||
// Bumped on every enable()/disable() so an in-flight open (which awaits audio start
|
||||
// with the panel already visible) can detect it was dismissed mid-open and NOT flip
|
||||
// _state.enabled on afterwards — avoiding a zombie enabled-but-hidden tuner.
|
||||
let _openGen = 0;
|
||||
let _onAutoOpenSongLoading = null;
|
||||
let _onAutoOpenSongReady = null;
|
||||
// Autoplay gate (E2): when the feature is on, hold playback on song:loading and
|
||||
// release it once we know we won't open (covered / unchanged) or the tuner is
|
||||
// dismissed — so playback waits behind a genuinely-needed retune.
|
||||
let _autoplayRelease = null;
|
||||
let _gateClaimed = false;
|
||||
|
||||
// ── Shared mutable state (read/written by screen.js; UI reads via closure) ──
|
||||
const _state = {
|
||||
@@ -133,15 +142,259 @@
|
||||
return filename + '::' + arr;
|
||||
}
|
||||
|
||||
// ── §4 instrument-coverage ────────────────────────────────────────────────
|
||||
// FeedBack is tune-to-song: the highway draws tab in the SONG's tuning, so the
|
||||
// player tunes their instrument to match. We therefore only auto-open when the
|
||||
// player's CURRENT physical tuning doesn't already cover the song — i.e. the
|
||||
// song's open-string tuning isn't an exact contiguous run inside the player's
|
||||
// strings, OR the global reference differs. So an 8-string F# player isn't
|
||||
// nagged for a 6-/7-string standard song (its top strings already match), but a
|
||||
// Drop-A song whose dropped open string the player lacks still prompts.
|
||||
function _openMidisFromFreqs(freqs) {
|
||||
const u = window._tunerUtils;
|
||||
if (!u || !Array.isArray(freqs)) return null;
|
||||
return freqs.map((f) => Math.round(u.freqToMidi(f)));
|
||||
}
|
||||
|
||||
// The song's open-string MIDI (at A440; centOffset handled separately as a
|
||||
// global). Mirrors _tuningIdentityKey's isBass / string-count derivation.
|
||||
function _songOpenMidis(songInfo) {
|
||||
const u = window._tunerUtils;
|
||||
if (!u || !songInfo || !Array.isArray(songInfo.tuning) || !songInfo.tuning.length) return null;
|
||||
const ctx = (typeof window.feedBack?.songTuningContext === 'function')
|
||||
? window.feedBack.songTuningContext(songInfo)
|
||||
: { stringCount: songInfo.stringCount, arrangement: songInfo.arrangement, arrangement_smart_name: songInfo.arrangement_smart_name };
|
||||
const isBass = (typeof window.feedBack?.isBassArrangement === 'function')
|
||||
? window.feedBack.isBassArrangement(ctx)
|
||||
: (songInfo.arrangement || '').toLowerCase().includes('bass');
|
||||
const sc = (typeof window.feedBack?.effectiveStringCount === 'function')
|
||||
? window.feedBack.effectiveStringCount(songInfo.tuning, ctx)
|
||||
: (songInfo.stringCount || songInfo.tuning.length);
|
||||
if (!sc || sc <= 0) return null;
|
||||
const offsets = songInfo.tuning.slice(0, sc);
|
||||
if (!offsets.length) return null;
|
||||
return _openMidisFromFreqs(u.offsetsToFreqs(offsets, isBass));
|
||||
}
|
||||
|
||||
// The player's CURRENT physical tuning. Prefer the host-owned live working
|
||||
// tuning (window.feedBack.workingTuning) — what the instrument is *actually* in
|
||||
// right now, which advances as the player retunes — so coverage prompts fire in
|
||||
// BOTH directions (E→C# and back), not only away from a fixed profile. Feature-
|
||||
// detected: on a host without the working-tuning capability, or before it's been
|
||||
// set, we fall back to the static /api/settings instrument tuning (today's
|
||||
// behavior). Returns { midis, refCents } or null.
|
||||
// The SELECTED physical instrument's working-tuning slot identity, from /api/settings.
|
||||
// The read (_playerTuning) and the write (_publishWorkingTuning) MUST agree on this
|
||||
// key — the working tuning is a property of the player's selected instrument, not of
|
||||
// any one song — or a published tuning lands in a slot coverage never reads back.
|
||||
// Returns { isBass, sc, key }.
|
||||
function _selectedInstrument(s) {
|
||||
const isBass = !!(s && s.instrument === 'bass');
|
||||
const sc = (s && Number(s.string_count)) || (isBass ? 4 : 6);
|
||||
return { isBass, sc, key: (isBass ? 'bass' : 'guitar') + '-' + sc };
|
||||
}
|
||||
|
||||
// Memoize the player's tuning: it depends only on /api/settings + the working
|
||||
// tuning, which change on instrument:changed / working-tuning-changed (NOT per song).
|
||||
// Without this, a consumer that evaluates coverage for many items at once — the
|
||||
// library's per-song tuning-match chips — would fire one /api/settings fetch PER item
|
||||
// per paint. Cache the promise so they all share one read; invalidate on the events
|
||||
// that change the answer, AND expire after a short TTL so a settings write that
|
||||
// doesn't emit an event (e.g. the input-setup flow) still heals within seconds.
|
||||
let _playerTuningPromise = null;
|
||||
let _playerTuningAt = 0;
|
||||
const _PLAYER_TUNING_TTL_MS = 3000;
|
||||
function _playerTuning() {
|
||||
const now = (typeof Date !== 'undefined' && Date.now) ? Date.now() : 0;
|
||||
if (!_playerTuningPromise || (now - _playerTuningAt) > _PLAYER_TUNING_TTL_MS) {
|
||||
_playerTuningAt = now;
|
||||
const p = _computePlayerTuning();
|
||||
_playerTuningPromise = p;
|
||||
// Never pin a transient failure: if the read yields null (or rejects), drop
|
||||
// the cache so the next call retries. A real result stays until invalidation/TTL.
|
||||
p.then((r) => { if (r == null && _playerTuningPromise === p) _playerTuningPromise = null; },
|
||||
() => { if (_playerTuningPromise === p) _playerTuningPromise = null; });
|
||||
}
|
||||
return _playerTuningPromise;
|
||||
}
|
||||
function _invalidatePlayerTuning() { _playerTuningPromise = null; }
|
||||
|
||||
async function _computePlayerTuning() {
|
||||
const u = window._tunerUtils;
|
||||
if (!u) return null;
|
||||
// Instrument IDENTITY (which instrument is selected) + the static fallback
|
||||
// tuning, from /api/settings.
|
||||
let s = null;
|
||||
try { s = await fetch('/api/settings').then((r) => (r && r.ok ? r.json() : null)); }
|
||||
catch (_) { s = null; }
|
||||
const { isBass, sc, key } = _selectedInstrument(s);
|
||||
// Cache the resolved selection so the (synchronous) publish-on-clear writes to
|
||||
// the EXACT slot this read path uses — no second /api/settings fetch that could
|
||||
// race an instrument switch. Only cache when settings were actually read: on a
|
||||
// fetch failure we keep the last confident selection (or none → publish skips)
|
||||
// rather than recording a bogus default-instrument slot to publish into later.
|
||||
// Coverage runs before any auto-open, so this is set by the time a clear can publish.
|
||||
if (s) {
|
||||
_state._playerSelected = { isBass, sc, key, refPitch: Number(s.reference_pitch) || 440 };
|
||||
}
|
||||
// The LIVE per-instrument working tuning (advances as the player retunes) —
|
||||
// this is what makes coverage prompt in BOTH directions, not only away from a
|
||||
// fixed profile. Feature-detected; falls back to the static settings tuning
|
||||
// when unset / no host capability.
|
||||
const wt = (window.feedBack && window.feedBack.workingTuning
|
||||
&& typeof window.feedBack.workingTuning.get === 'function')
|
||||
? window.feedBack.workingTuning.get(key) : null;
|
||||
const wtHasOffsets = !!(wt && Array.isArray(wt.offsets) && wt.offsets.length);
|
||||
let freqs = null;
|
||||
if (wtHasOffsets) {
|
||||
freqs = u.offsetsToFreqs(wt.offsets.slice(0, sc), isBass);
|
||||
} else if (s && Array.isArray(s.tuning)) {
|
||||
freqs = u.offsetsToFreqs(s.tuning.slice(0, sc), isBass);
|
||||
} else if (s && typeof s.tuning === 'string') {
|
||||
const named = _state._allTunings && _state._allTunings[key];
|
||||
if (named && Array.isArray(named[s.tuning])) freqs = named[s.tuning];
|
||||
}
|
||||
if (!freqs) {
|
||||
// No confident instrument identity — settings absent, OR present but carrying
|
||||
// no instrument/string_count/tuning (a fresh profile: /api/settings omits them)
|
||||
// — and no live working tuning. We can't tell the player's tuning, so fail
|
||||
// toward prompting (null → not-covered) rather than silently assuming standard
|
||||
// and suppressing a genuinely-needed prompt.
|
||||
const hasIdentity = !!(s && (s.instrument || s.string_count || s.tuning));
|
||||
if (!hasIdentity && !wtHasOffsets) return null;
|
||||
freqs = u.offsetsToFreqs(new Array(sc).fill(0), isBass); // standard fallback
|
||||
}
|
||||
const midis = _openMidisFromFreqs(freqs);
|
||||
if (!midis) return null;
|
||||
const refPitch = (wt && Number(wt.referencePitch)) || (s && Number(s.reference_pitch)) || 440;
|
||||
return { midis, refCents: 1200 * Math.log2(refPitch / 440) };
|
||||
}
|
||||
|
||||
// PR: host workingTuning — when the player clears an AUTO-OPENED tuner we assume
|
||||
// they tuned their (selected) instrument to the song, so publish the song's tuning
|
||||
// as the live working tuning for that instrument ('assumed' — PR 4's explicit
|
||||
// "I tuned / Skip" will replace this heuristic). After the instrument->chart routing
|
||||
// PR the loaded arrangement matches the selected instrument, so the song's tuning IS
|
||||
// the player's instrument's new tuning.
|
||||
//
|
||||
// We write to the SELECTED instrument's slot (the exact key _playerTuning reads),
|
||||
// NOT a song-derived one, so the publish can't be stranded in a slot coverage never
|
||||
// looks at. If the cleared song is a chart for the OTHER instrument (a manual switch
|
||||
// to e.g. the bass part while guitar is selected), we skip — that isn't evidence the
|
||||
// selected instrument was retuned, and writing it would pollute the wrong slot.
|
||||
//
|
||||
// Synchronous, off the selection _playerTuning last resolved (`_state._playerSelected`)
|
||||
// — an auto-open always runs a coverage check first, so it's populated by the time a
|
||||
// clear can publish. Reusing it (rather than re-fetching /api/settings here) keeps the
|
||||
// write key identical to the read key and avoids racing an instrument switch.
|
||||
function _publishWorkingTuning(songInfo) {
|
||||
const wt = window.feedBack && window.feedBack.workingTuning;
|
||||
if (!wt || typeof wt.set !== 'function') return;
|
||||
if (!songInfo || !Array.isArray(songInfo.tuning) || !songInfo.tuning.length) return;
|
||||
const sel = _state._playerSelected;
|
||||
if (!sel || !sel.key || !(sel.sc > 0)) return; // coverage hasn't resolved the instrument yet
|
||||
const ctx = (typeof window.feedBack?.songTuningContext === 'function')
|
||||
? window.feedBack.songTuningContext(songInfo)
|
||||
: { stringCount: songInfo.stringCount, arrangement: songInfo.arrangement, arrangement_smart_name: songInfo.arrangement_smart_name };
|
||||
const songIsBass = (typeof window.feedBack?.isBassArrangement === 'function')
|
||||
? window.feedBack.isBassArrangement(ctx)
|
||||
: (songInfo.arrangement || '').toLowerCase().includes('bass');
|
||||
if (songIsBass !== sel.isBass) return; // cross-instrument chart — don't pollute the selected slot
|
||||
wt.set({
|
||||
offsets: songInfo.tuning.slice(0, sel.sc),
|
||||
stringCount: sel.sc,
|
||||
instrument: sel.isBass ? 'bass' : 'guitar',
|
||||
referencePitch: sel.refPitch,
|
||||
source: 'tuner',
|
||||
}, { instrument: sel.key, provenance: 'assumed' });
|
||||
}
|
||||
|
||||
// The retune the player would need to match this song, as a structured report:
|
||||
// { covered, retune: [{ from, to }], reference, cantCover }
|
||||
// — covered: the physical tuning already matches (the song's open strings are an
|
||||
// exact contiguous run inside the player's strings) → no retune;
|
||||
// — retune: the per-string note changes (e.g. { from:'B', to:'A' }) of the best
|
||||
// contiguous alignment — what the badge cue names;
|
||||
// — reference: a whole-instrument A4/centOffset mismatch (A440 vs A432, octave);
|
||||
// — cantCover: the song needs more strings than the instrument has.
|
||||
// Conservative: any missing data → { covered:false } so a needed prompt/cue is
|
||||
// never silently dropped on a fetch hiccup.
|
||||
async function _computeCoverageReport(songInfo) {
|
||||
const u = window._tunerUtils;
|
||||
const none = { covered: false, retune: [], reference: false, cantCover: false };
|
||||
if (!u) return none;
|
||||
const song = _songOpenMidis(songInfo);
|
||||
if (!song || !song.length) return none;
|
||||
const player = await _playerTuning();
|
||||
if (!player || !player.midis.length) return none;
|
||||
const reference = Math.abs((Number(songInfo?.centOffset) || 0) - player.refCents) > 25;
|
||||
if (player.midis.length < song.length) return { covered: false, retune: [], reference, cantCover: true };
|
||||
// Best contiguous alignment = the run with the fewest per-string mismatches
|
||||
// (extended-range adds strings at the ends — match by pitch, not index).
|
||||
let best = null;
|
||||
for (let start = 0; start + song.length <= player.midis.length; start++) {
|
||||
const diffs = [];
|
||||
for (let i = 0; i < song.length; i++) {
|
||||
const pm = player.midis[start + i];
|
||||
if (pm !== song[i]) diffs.push({ from: u.midiToNote(pm, false), to: u.midiToNote(song[i], false) });
|
||||
}
|
||||
if (!best || diffs.length < best.length) best = diffs;
|
||||
if (!diffs.length) break;
|
||||
}
|
||||
const covered = !reference && best.length === 0;
|
||||
return { covered, retune: covered ? [] : best, reference, cantCover: false };
|
||||
}
|
||||
|
||||
// Dedup the coverage computation (which fetches /api/settings): the auto-open gate
|
||||
// AND the badge cue both call this on the same song:ready. Cache the in-flight/last
|
||||
// result per song so they share ONE fetch. Invalidated when anything that changes the
|
||||
// answer happens — a new song (song:loading), an instrument switch (instrument:changed),
|
||||
// or a retune (working-tuning-changed) — so the cache can never go stale within a song.
|
||||
let _coverageCache = null; // { key, promise }
|
||||
function _coverageReport(songInfo) {
|
||||
const key = _autoOpenSessionKey(songInfo) + '|'
|
||||
+ (songInfo && Array.isArray(songInfo.tuning) ? songInfo.tuning.join(',') : '')
|
||||
+ '|' + (songInfo && songInfo.centOffset != null ? songInfo.centOffset : ''); // coverage uses centOffset
|
||||
if (_coverageCache && _coverageCache.key === key) return _coverageCache.promise;
|
||||
const promise = _computeCoverageReport(songInfo);
|
||||
_coverageCache = { key, promise };
|
||||
return promise;
|
||||
}
|
||||
function _invalidateCoverageCache() { _coverageCache = null; }
|
||||
|
||||
// Boolean form used to gate the auto-open prompt.
|
||||
async function _coveredByPlayerInstrument(songInfo) {
|
||||
return (await _coverageReport(songInfo)).covered;
|
||||
}
|
||||
|
||||
function _releaseGate() {
|
||||
if (_autoplayRelease) { try { _autoplayRelease(); } catch (_) { /* */ } _autoplayRelease = null; }
|
||||
}
|
||||
|
||||
function _onAutoOpenSongLoadingHandler() {
|
||||
_autoOpenGeneration++;
|
||||
_autoOpenDismissedSessionKey = null;
|
||||
_lastAutoOpenSessionKey = null;
|
||||
_invalidateCoverageCache();
|
||||
// Claim the autoplay gate NOW (synchronously, before song:ready) when the
|
||||
// feature is on, so playback can wait behind a needed retune. Released on
|
||||
// song:ready if we don't open, or when the tuner is dismissed.
|
||||
_releaseGate();
|
||||
_gateClaimed = false;
|
||||
_autoplayRelease = (_state._serverConfig && _state._serverConfig.autoOpenOnTuningChange
|
||||
&& window.feedBack && typeof window.feedBack.holdAutoplay === 'function')
|
||||
? window.feedBack.holdAutoplay() : null;
|
||||
}
|
||||
|
||||
async function _maybeAutoOpenOnTuningChange() {
|
||||
if (!document.getElementById('player')?.classList.contains('active')) return;
|
||||
|
||||
// Opt-in (default off): only auto-open when the user enabled it in the
|
||||
// tuner settings. Ensure config is loaded so the first song:ready after
|
||||
// boot still reads the real flag; fail closed if it can't load.
|
||||
if (!_state._serverConfig) { try { await loadConfig(); } catch (_) { /* */ } }
|
||||
if (!_state._serverConfig || !_state._serverConfig.autoOpenOnTuningChange) return;
|
||||
|
||||
const songInfo = window.highway?.getSongInfo?.() || window.feedBack?.currentSong;
|
||||
if (!songInfo) return;
|
||||
|
||||
@@ -165,10 +418,21 @@
|
||||
if (_lastAutoOpenSessionKey === sessionKey) return;
|
||||
if (!window.tuner || typeof window.tuner.enable !== 'function') return;
|
||||
|
||||
// §4: skip the prompt when the player's physical instrument already covers
|
||||
// this song's tuning (e.g. an 8-string F# playing a 6-/7-string standard
|
||||
// song). Async (fetches /api/settings) — re-check the generation after.
|
||||
const covered = await _coveredByPlayerInstrument(songInfo);
|
||||
if (myGen !== _autoOpenGeneration) return;
|
||||
if (covered) return;
|
||||
|
||||
_lastAutoOpenSessionKey = sessionKey;
|
||||
try {
|
||||
await window.tuner.enable();
|
||||
await window.tuner.enable({ auto: true });
|
||||
if (myGen !== _autoOpenGeneration) return;
|
||||
_gateClaimed = true; // tuner is open → keep the autoplay gate until it's dismissed
|
||||
// The hold is now intentional and user-dismissable — cancel the fail-open
|
||||
// backstop so it can't start playback while the player is still tuning.
|
||||
if (_autoplayRelease && typeof _autoplayRelease.settle === 'function') _autoplayRelease.settle();
|
||||
} catch (e) {
|
||||
console.warn('Tuner: auto-open failed:', e && e.message ? e.message : e);
|
||||
if (_lastAutoOpenSessionKey === sessionKey) _lastAutoOpenSessionKey = null;
|
||||
@@ -183,9 +447,26 @@
|
||||
function _installAutoOpenListeners() {
|
||||
if (_onAutoOpenSongLoading || !window.feedBack?.on) return;
|
||||
_onAutoOpenSongLoading = _onAutoOpenSongLoadingHandler;
|
||||
_onAutoOpenSongReady = () => { _maybeAutoOpenOnTuningChange(); };
|
||||
_onAutoOpenSongReady = async () => {
|
||||
const myGen = _autoOpenGeneration;
|
||||
await _maybeAutoOpenOnTuningChange();
|
||||
// A newer song:loading may have superseded us while awaiting — it owns the
|
||||
// gate/_gateClaimed now, so don't release its hold based on our stale view.
|
||||
if (myGen !== _autoOpenGeneration) return;
|
||||
if (!_gateClaimed) _releaseGate(); // not gating this song → let it play
|
||||
};
|
||||
window.feedBack.on('song:loading', _onAutoOpenSongLoading);
|
||||
window.feedBack.on('song:ready', _onAutoOpenSongReady);
|
||||
// The badge (static/v3/badges.js) emits this on the feedBack bus when the player
|
||||
// switches instrument. Drop the cached selection so a publish-on-clear can't write
|
||||
// to the previously-selected instrument's slot; the next coverage read re-resolves
|
||||
// it. Until then _publishWorkingTuning skips (safe — no mis-slotted write).
|
||||
window.feedBack.on('instrument:changed', () => {
|
||||
_state._playerSelected = null; _invalidatePlayerTuning(); _invalidateCoverageCache();
|
||||
});
|
||||
// A retune (working tuning published on a tuner clear) changes coverage for the
|
||||
// current song — drop the cached player tuning + report so a re-evaluation recomputes.
|
||||
window.feedBack.on('working-tuning-changed', () => { _invalidatePlayerTuning(); _invalidateCoverageCache(); });
|
||||
}
|
||||
|
||||
// ── Player sync helpers ───────────────────────────────────────────
|
||||
@@ -209,6 +490,12 @@
|
||||
const sc = (typeof window.feedBack?.effectiveStringCount === 'function')
|
||||
? window.feedBack.effectiveStringCount(songInfo.tuning, ctx)
|
||||
: (songInfo.stringCount || songInfo.tuning.length);
|
||||
// A tuning change invalidates an in-flight mic-verify — its captured targets
|
||||
// and offsets are now stale, so it must not complete against the old tuning.
|
||||
if (_verify && String(songInfo.tuning.slice(0, sc)) !== String(_verify.offsets)) {
|
||||
verifyCancel();
|
||||
_tunerUIApi?.resetVerify?.();
|
||||
}
|
||||
_state.currentSongOffsets = songInfo.tuning.slice(0, sc);
|
||||
_state.currentSongIsBass = isBass;
|
||||
_state.currentSongStringCount = sc;
|
||||
@@ -341,8 +628,16 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function enable() {
|
||||
async function enable(opts) {
|
||||
if (_state.enabled) return;
|
||||
const myOpen = ++_openGen; // this open's token; a disable()/newer open invalidates it
|
||||
// An AUTO-open (the "this song needs a different tuning" nudge) must
|
||||
// PERSIST: it is NOT dismissed by the autoplay song:play that follows
|
||||
// song entry, a stray click, or a same-screen re-emit — only by the
|
||||
// Skip/× buttons or leaving the song. A manual open keeps the classic
|
||||
// click-away / play-to-close behaviour.
|
||||
const auto = !!(opts && opts.auto);
|
||||
_state.autoOpened = auto;
|
||||
await _loadScript('/api/plugins/tuner/utils/tuning-utils.js');
|
||||
await _loadScript('/api/plugins/tuner/utils/audio.js');
|
||||
await _loadScript('/api/plugins/tuner/utils/ui.js');
|
||||
@@ -371,15 +666,33 @@
|
||||
_state.uiContainer.classList.add('flex');
|
||||
_tunerUIApi.positionPanel();
|
||||
_tunerUIApi.updateFreeTuneUI();
|
||||
// "Skip" is the auto-open nudge's explicit dismiss; hidden for a manual
|
||||
// open (the × / click-away already close those).
|
||||
if (_state.skipBtn) _state.skipBtn.classList.toggle('hidden', !auto);
|
||||
// Auto-open shows the "Back to library" escape hatch and hides the ×:
|
||||
// the Skip / Back buttons + Esc are the auto-open's dismiss surface, so a
|
||||
// gated retune always offers a way forward AND a way out.
|
||||
if (_state.backBtn) _state.backBtn.classList.toggle('hidden', !auto);
|
||||
if (_state.closeBtn) _state.closeBtn.classList.toggle('hidden', !!auto);
|
||||
|
||||
// Close when clicking outside the panel. Deferred so the badge's
|
||||
// opening click doesn't bubble up to the document and fire immediately.
|
||||
if (_outsideClickClose) document.removeEventListener('click', _outsideClickClose);
|
||||
_outsideClickClose = () => { if (_state.enabled) disable(); };
|
||||
setTimeout(() => { if (_outsideClickClose) document.addEventListener('click', _outsideClickClose, { once: true }); }, 0);
|
||||
// Close when clicking outside the panel. Deferred so the badge's opening
|
||||
// click doesn't bubble up to the document and fire immediately. Skipped
|
||||
// for an auto-open: the user never clicked to open it, so their first
|
||||
// unrelated click must not dismiss it (it persists until Skip / Back to
|
||||
// library / Esc).
|
||||
if (!auto) {
|
||||
if (_outsideClickClose) document.removeEventListener('click', _outsideClickClose);
|
||||
_outsideClickClose = () => { if (_state.enabled) disable(); };
|
||||
setTimeout(() => { if (_outsideClickClose) document.addEventListener('click', _outsideClickClose, { once: true }); }, 0);
|
||||
}
|
||||
|
||||
if (window.feedBack && !_onScreenChanged) {
|
||||
_onScreenChanged = () => { disable(); };
|
||||
// Auto-opened: close only when we actually LEAVE the song — a player
|
||||
// re-emit while staying put must not tear down the nudge. Manual:
|
||||
// unchanged (any screen change closes it).
|
||||
_onScreenChanged = () => {
|
||||
if (!_state.autoOpened || !document.getElementById('player')?.classList.contains('active')) disable();
|
||||
};
|
||||
_onSongReady = () => {
|
||||
_tunerUIApi.renderTuningOptions();
|
||||
if (_state.selectedTuningName === '_current') _syncCurrentTuning();
|
||||
@@ -396,6 +709,10 @@
|
||||
{ deviceId: _state.selectedDeviceId, channel: _state.selectedChannel, audioInputMode: _state.audioInputMode },
|
||||
_tunerUIApi.updateUI
|
||||
);
|
||||
// The panel is visible (with ×/Skip) across the audio-start await above, so a
|
||||
// dismiss can land here. If so, disable() already tore the panel down and
|
||||
// bumped _openGen — do NOT flip enabled on (that would leave enabled-but-hidden).
|
||||
if (myOpen !== _openGen) return;
|
||||
_state.enabled = true;
|
||||
if (window.tuner?.updateButtons) window.tuner.updateButtons();
|
||||
} catch (e) {
|
||||
@@ -406,10 +723,16 @@
|
||||
}
|
||||
|
||||
function disable() {
|
||||
_openGen++; // invalidate any in-flight enable() so it won't re-enable after this teardown
|
||||
const wasEnabled = _state.enabled;
|
||||
const wasAutoOpened = _state.autoOpened;
|
||||
const onPlayer = document.getElementById('player')?.classList.contains('active');
|
||||
_state.enabled = false;
|
||||
_state.autoOpened = false;
|
||||
_releaseGate(); // dismissing a gated auto-open releases playback (it starts now)
|
||||
_state.manualTargetFreq = null;
|
||||
verifyCancel(); // a running mic-verify ends when the panel closes
|
||||
_tunerUIApi?.resetVerify?.();
|
||||
if (_outsideClickClose) { document.removeEventListener('click', _outsideClickClose); _outsideClickClose = null; }
|
||||
if (_state.activeViz) { _state.activeViz.destroy(); _state.activeViz = null; }
|
||||
if (_state.uiContainer) { _state.uiContainer.classList.add('hidden'); _state.uiContainer.classList.remove('flex'); }
|
||||
@@ -427,8 +750,17 @@
|
||||
}
|
||||
if (wasEnabled && onPlayer) {
|
||||
const songInfo = window.highway?.getSongInfo?.() || window.feedBack?.currentSong;
|
||||
if (songInfo) _autoOpenDismissedSessionKey = _autoOpenSessionKey(songInfo);
|
||||
if (songInfo) {
|
||||
_autoOpenDismissedSessionKey = _autoOpenSessionKey(songInfo);
|
||||
// Clearing an auto-opened tuner = the player tuned to this song:
|
||||
// publish the song's tuning as their instrument's live working tuning
|
||||
// so coverage stops nagging for it (and prompts on the way back). But
|
||||
// if a mic-verify already wrote 'verified' this session, a plain
|
||||
// 'assumed' publish would immediately clobber it — leave it verified.
|
||||
if (wasAutoOpened && !_verifiedPublished) _publishWorkingTuning(songInfo);
|
||||
}
|
||||
}
|
||||
_verifiedPublished = false; // consumed — fresh for the next tuner session
|
||||
}
|
||||
|
||||
window.tuner = {
|
||||
@@ -472,10 +804,110 @@
|
||||
_installAutoOpenListeners();
|
||||
}).catch(e => console.error(e));
|
||||
_installAutoOpenListeners();
|
||||
|
||||
// ── Mic-verify (working-tuning PR 9b) ──────────────────────────────────────
|
||||
// A choreographed per-string check that promotes the current working tuning
|
||||
// from 'assumed' to 'verified' — the ONLY thing that may ever claim 'verified'
|
||||
// (audio-engine's honesty rule). The player plays each string; once every one
|
||||
// reads in-tune (±VERIFY_TOL_CENTS) and holds for VERIFY_STABLE frames we stamp
|
||||
// provenance:'verified' + verifiedStrings. Cancels on tuner close / tuning change.
|
||||
const VERIFY_TOL_CENTS = 6;
|
||||
const VERIFY_STABLE = 8;
|
||||
let _verify = null;
|
||||
let _verifiedPublished = false; // set when a mic-verify wrote 'verified' this session
|
||||
|
||||
function verifyState() {
|
||||
if (!_verify) return null;
|
||||
return {
|
||||
complete: _verify.complete,
|
||||
done: _verify.targets.map((t) => t.done),
|
||||
remaining: _verify.targets.filter((t) => !t.done).length,
|
||||
};
|
||||
}
|
||||
// Start a verify session for `targets` (freqs; defaults to the selected tuning).
|
||||
// Captures the tuning's OFFSETS now (explicit arg, else the current song's) so that
|
||||
// when it completes we stamp 'verified' onto the exact tuning that was confirmed.
|
||||
// Per-string semitone offsets (from standard) of the tuning we're verifying, derived
|
||||
// from its target freqs. This is authoritative for BOTH the song ('_current') tuning
|
||||
// and a manually-selected tuning — unlike _state.currentSongOffsets, which for a manual
|
||||
// tuning is a stale/different song's tuning that must NOT be stamped 'verified'. The
|
||||
// player's reference pitch scales both the targets and the standard, so it cancels.
|
||||
function _tuningOffsetsFromFreqs(freqs) {
|
||||
const u = window._tunerUtils;
|
||||
if (!u || typeof u.offsetsToFreqs !== 'function' || typeof u.freqToMidi !== 'function') return null;
|
||||
const isBass = /^bass/.test(_state.selectedInstrument || ''); // the selected instrument, not the song's
|
||||
const refScale = (Number(_state.referencePitch) || 440) / 440;
|
||||
const std = u.offsetsToFreqs(new Array(freqs.length).fill(0), isBass);
|
||||
if (!Array.isArray(std) || std.length !== freqs.length) return null;
|
||||
const out = [];
|
||||
for (let i = 0; i < freqs.length; i++) {
|
||||
const f = Number(freqs[i]);
|
||||
const s = Number(std[i]) * refScale;
|
||||
if (!(f > 0) || !(s > 0)) return null;
|
||||
out.push(Math.round(u.freqToMidi(f) - u.freqToMidi(s)) || 0); // normalize -0 → 0
|
||||
}
|
||||
return out;
|
||||
}
|
||||
function verifyStart(targets, offsets) {
|
||||
const freqs = (Array.isArray(targets) && targets.length) ? targets : _state.selectedTuning;
|
||||
if (!Array.isArray(freqs) || !freqs.length) return null;
|
||||
// Explicit offsets win (callers/tests that already have them); otherwise derive
|
||||
// them from the tuning actually being verified.
|
||||
const offs = (Array.isArray(offsets) && offsets.length) ? offsets.slice() : _tuningOffsetsFromFreqs(freqs);
|
||||
_verify = { targets: freqs.map((f) => ({ freq: f, streak: 0, done: false })), complete: false, offsets: offs };
|
||||
_verifiedPublished = false;
|
||||
return verifyState();
|
||||
}
|
||||
function verifyCancel() { _verify = null; }
|
||||
// Feed one processed frame (its matched target freq + cents-off). Requires
|
||||
// CONSECUTIVE in-tune frames per string: the one confirmed string advances, and
|
||||
// every other not-yet-done string's streak resets — so a run can't accumulate across
|
||||
// silence / wrong-string / out-of-tune frames. Completes + stamps 'verified' when all pass.
|
||||
function verifyFeed(targetFreq, cents) {
|
||||
if (!_verify || _verify.complete) return verifyState();
|
||||
let hit = null;
|
||||
if (targetFreq != null) {
|
||||
const t = _verify.targets.find((x) => Math.abs(x.freq - targetFreq) < 0.5);
|
||||
if (t && !t.done && isFinite(cents) && Math.abs(cents) <= VERIFY_TOL_CENTS) hit = t;
|
||||
}
|
||||
for (const t of _verify.targets) {
|
||||
if (t.done) continue;
|
||||
if (t === hit) { if (++t.streak >= VERIFY_STABLE) t.done = true; }
|
||||
else t.streak = 0;
|
||||
}
|
||||
if (_verify.targets.every((x) => x.done)) {
|
||||
_verify.complete = true;
|
||||
_publishVerified();
|
||||
}
|
||||
return verifyState();
|
||||
}
|
||||
// Promote the working tuning to 'verified'. Write the CONFIRMED tuning's offsets
|
||||
// atomically with provenance + verifiedStrings (into the selected instrument's slot),
|
||||
// so 'verified' can never attach to stale offsets the slot happened to hold.
|
||||
function _publishVerified() {
|
||||
const wt = window.feedBack && window.feedBack.workingTuning;
|
||||
if (!wt || typeof wt.set !== 'function') return;
|
||||
const offsets = (_verify && Array.isArray(_verify.offsets)) ? _verify.offsets.slice() : null;
|
||||
if (!offsets || !offsets.length) return; // nothing concrete to claim verified
|
||||
const sel = _state._playerSelected;
|
||||
const next = { offsets: offsets, stringCount: offsets.length, verifiedStrings: offsets.map(() => true) };
|
||||
if (sel && sel.key) { next.instrument = sel.isBass ? 'bass' : 'guitar'; next.referencePitch = sel.refPitch; }
|
||||
const opts = (sel && sel.key) ? { instrument: sel.key, provenance: 'verified' } : { provenance: 'verified' };
|
||||
try { wt.set(next, opts); _verifiedPublished = true; } catch (_) { /* noop */ }
|
||||
}
|
||||
|
||||
window._tunerAutoOpen = {
|
||||
tuningIdentityKey: _tuningIdentityKey,
|
||||
sessionKey: _autoOpenSessionKey,
|
||||
maybeAutoOpenOnTuningChange: _maybeAutoOpenOnTuningChange,
|
||||
coveredByPlayerInstrument: _coveredByPlayerInstrument,
|
||||
coverageReport: _coverageReport,
|
||||
playerTuning: _playerTuning,
|
||||
publishWorkingTuning: _publishWorkingTuning,
|
||||
verifyStart: verifyStart,
|
||||
verifyFeed: verifyFeed,
|
||||
verifyCancel: verifyCancel,
|
||||
verifyState: verifyState,
|
||||
onSongLoading: _onAutoOpenSongLoadingHandler,
|
||||
getState() {
|
||||
return {
|
||||
|
||||
@@ -10,6 +10,17 @@
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between bg-dark-900/50 p-3 rounded-xl border border-gray-800/50">
|
||||
<div>
|
||||
<h3 class="text-sm font-medium text-gray-200">Auto-open on tuning change</h3>
|
||||
<p class="text-[11px] text-gray-500">When a song (or arrangement) needs a different tuning, pop the tuner open automatically. It stays open until you Skip or close it.</p>
|
||||
</div>
|
||||
<label class="relative inline-flex items-center cursor-pointer">
|
||||
<input type="checkbox" id="tuner-auto-open" class="sr-only peer" onchange="window._tunerToggleAutoOpen(this.checked)">
|
||||
<div class="w-9 h-5 bg-gray-700 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-accent"></div>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
if (window.feedBackDesktop && window.feedBackDesktop.isDesktop) {
|
||||
document.currentScript.insertAdjacentHTML('beforebegin', `
|
||||
@@ -107,6 +118,9 @@
|
||||
const browserAudioToggle = document.getElementById('tuner-force-browser-audio');
|
||||
if (browserAudioToggle) browserAudioToggle.checked = config.audioInputMode === 'browser';
|
||||
|
||||
const autoOpenToggle = document.getElementById('tuner-auto-open');
|
||||
if (autoOpenToggle) autoOpenToggle.checked = config.autoOpenOnTuningChange === true;
|
||||
|
||||
render();
|
||||
} catch (e) { console.error('Tuner settings: load failed', e); }
|
||||
}
|
||||
@@ -121,6 +135,11 @@
|
||||
save();
|
||||
};
|
||||
|
||||
window._tunerToggleAutoOpen = (enabled) => {
|
||||
config.autoOpenOnTuningChange = enabled;
|
||||
save();
|
||||
};
|
||||
|
||||
async function save(opts) {
|
||||
try {
|
||||
await fetch('/api/plugins/tuner/config', {
|
||||
|
||||
+107
-1
@@ -305,6 +305,12 @@ window._tunerUI = function(state, actions) {
|
||||
function renderStringNotes() {
|
||||
if (!state.stringNoteContainer) return;
|
||||
state.stringNoteContainer.innerHTML = '';
|
||||
// Show the mic-verify control only for a selected (non-free) tuning.
|
||||
if (state.verifyRow) {
|
||||
const hasTuning = !!(state.selectedTuning && state.selectedTuning.length && !state.freeTune);
|
||||
state.verifyRow.classList.toggle('hidden', !hasTuning);
|
||||
if (!hasTuning) resetVerifyUI();
|
||||
}
|
||||
if (!state.selectedTuning || state.selectedTuning.length === 0) {
|
||||
_syncStringOrderHelp(0);
|
||||
return;
|
||||
@@ -327,6 +333,41 @@ window._tunerUI = function(state, actions) {
|
||||
_syncStringOrderHelp(total);
|
||||
}
|
||||
|
||||
// ── Mic-verify UI (working-tuning PR 9b) ───────────────────────────────────
|
||||
function _markVerifiedStrings(done) {
|
||||
if (!state.stringNoteContainer) return;
|
||||
state.stringNoteContainer.querySelectorAll('[data-freq]').forEach((btn, i) => {
|
||||
btn.classList.toggle('ring-2', !!done[i]);
|
||||
btn.classList.toggle('ring-emerald-400', !!done[i]);
|
||||
});
|
||||
}
|
||||
function _syncVerifyProgress(vs) {
|
||||
if (!vs || !state.verifyStatus) return;
|
||||
const total = vs.done.length;
|
||||
const done = vs.done.filter(Boolean).length;
|
||||
state.verifyStatus.classList.remove('hidden');
|
||||
state.verifyStatus.textContent = vs.complete
|
||||
? '✓ In tune — tuning verified'
|
||||
: (done + ' of ' + total + ' strings in tune');
|
||||
_markVerifiedStrings(vs.done);
|
||||
if (vs.complete && state.verifyBtn) state.verifyBtn.textContent = 'Verify tuning';
|
||||
}
|
||||
function _startVerify() {
|
||||
if (!window._tunerAutoOpen || typeof window._tunerAutoOpen.verifyStart !== 'function') return;
|
||||
const vs = window._tunerAutoOpen.verifyStart();
|
||||
if (!vs) return;
|
||||
if (state.verifyBtn) state.verifyBtn.textContent = 'Verifying — play each string…';
|
||||
_syncVerifyProgress(vs);
|
||||
}
|
||||
function resetVerifyUI() {
|
||||
if (window._tunerAutoOpen && typeof window._tunerAutoOpen.verifyCancel === 'function') {
|
||||
window._tunerAutoOpen.verifyCancel();
|
||||
}
|
||||
if (state.verifyBtn) state.verifyBtn.textContent = 'Verify tuning';
|
||||
if (state.verifyStatus) { state.verifyStatus.classList.add('hidden'); state.verifyStatus.textContent = ''; }
|
||||
_markVerifiedStrings([]);
|
||||
}
|
||||
|
||||
function updateUI(result) {
|
||||
const { smoothedFreq, rms, hasSignal } = result;
|
||||
const vizMode = state.manualTargetFreq ? 'manual'
|
||||
@@ -387,6 +428,13 @@ window._tunerUI = function(state, actions) {
|
||||
if (window.feedBack && window.feedBack.emit) {
|
||||
window.feedBack.emit('tuner:frame', { note, cents, freq: displayFreq, hasSignal: true });
|
||||
}
|
||||
// Mic-verify: feed the matched string + cents to a running verify session
|
||||
// and reflect per-string progress on the panel.
|
||||
if (!isManual && !state.freeTune && window._tunerAutoOpen
|
||||
&& typeof window._tunerAutoOpen.verifyFeed === 'function') {
|
||||
const vs = window._tunerAutoOpen.verifyFeed(targetFreq, Math.round(cents));
|
||||
if (vs) _syncVerifyProgress(vs);
|
||||
}
|
||||
}
|
||||
|
||||
function updateFloatingButtonVisibility() {
|
||||
@@ -565,6 +613,17 @@ window._tunerUI = function(state, actions) {
|
||||
title.textContent = 'TUNER';
|
||||
header.appendChild(title);
|
||||
|
||||
// Explicit close (the panel had no in-box dismiss before; persist mode
|
||||
// needs one). Mirrors the settings gear on the opposite side.
|
||||
const closeBtn = document.createElement('button');
|
||||
closeBtn.className = 'absolute left-0 text-fb-textDim hover:text-fb-text transition-colors text-lg leading-none';
|
||||
closeBtn.setAttribute('aria-label', 'Close tuner');
|
||||
closeBtn.title = 'Close';
|
||||
closeBtn.textContent = '×';
|
||||
closeBtn.onclick = () => actions.disable();
|
||||
state.closeBtn = closeBtn;
|
||||
header.appendChild(closeBtn);
|
||||
|
||||
const settingsBtn = document.createElement('button');
|
||||
settingsBtn.className = 'absolute right-0 text-fb-textDim hover:text-fb-text transition-colors';
|
||||
settingsBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>`;
|
||||
@@ -624,6 +683,48 @@ window._tunerUI = function(state, actions) {
|
||||
state.vizContainer.className = 'w-full';
|
||||
state.uiContainer.appendChild(state.vizContainer);
|
||||
|
||||
// Mic-verify control (working-tuning PR 9b): play each string in tune to
|
||||
// confirm your tuning — promotes 'assumed' → 'verified'. Shown only for a
|
||||
// selected (non-free) tuning; visibility managed in renderStringNotes().
|
||||
state.verifyRow = document.createElement('div');
|
||||
state.verifyRow.className = 'w-full mt-2 hidden';
|
||||
state.verifyBtn = document.createElement('button');
|
||||
state.verifyBtn.className = 'tuner-verify-btn w-full text-[11px] text-fb-textDim hover:text-fb-text border border-fb-border/40 hover:border-fb-border/70 rounded-lg py-1.5 transition-colors';
|
||||
state.verifyBtn.textContent = 'Verify tuning';
|
||||
state.verifyBtn.title = 'Play each string in tune to confirm — marks your tuning verified';
|
||||
state.verifyBtn.onclick = () => _startVerify();
|
||||
state.verifyRow.appendChild(state.verifyBtn);
|
||||
state.verifyStatus = document.createElement('div');
|
||||
state.verifyStatus.className = 'text-[10px] text-fb-textDim text-center mt-1 hidden';
|
||||
state.verifyRow.appendChild(state.verifyStatus);
|
||||
state.uiContainer.appendChild(state.verifyRow);
|
||||
|
||||
// Auto-open nudge's explicit dismiss (hidden unless auto-opened; enable()
|
||||
// toggles it). Closes the same way as the × — disable().
|
||||
const skipBtn = document.createElement('button');
|
||||
skipBtn.className = 'tuner-skip-btn hidden w-full mt-3 text-[11px] text-fb-textDim hover:text-fb-text border border-fb-border/40 hover:border-fb-border/70 rounded-lg py-1.5 transition-colors';
|
||||
skipBtn.textContent = 'Skip';
|
||||
skipBtn.title = "I've tuned — play the song";
|
||||
skipBtn.onclick = () => actions.disable();
|
||||
state.skipBtn = skipBtn;
|
||||
state.uiContainer.appendChild(skipBtn);
|
||||
|
||||
// Auto-open escape hatch: leave the song entirely instead of committing to
|
||||
// the play-now choice — so a gated retune is never a one-way trap. Mirrors
|
||||
// Escape (the player's "Back to library" shortcut) and, like Escape, does
|
||||
// NOT record a tuning (you're leaving, not asserting you tuned).
|
||||
const backBtn = document.createElement('button');
|
||||
backBtn.className = 'tuner-back-btn hidden w-full mt-2 text-[11px] text-fb-textDim hover:text-fb-text border border-fb-border/40 hover:border-fb-border/70 rounded-lg py-1.5 transition-colors';
|
||||
backBtn.textContent = 'Back to library';
|
||||
backBtn.title = 'Leave the song (Esc)';
|
||||
backBtn.onclick = () => {
|
||||
const exit = window.feedBack && window.feedBack.requestExitSong;
|
||||
if (typeof exit === 'function') exit();
|
||||
else if (typeof window.requestExitSong === 'function') window.requestExitSong();
|
||||
};
|
||||
state.backBtn = backBtn;
|
||||
state.uiContainer.appendChild(backBtn);
|
||||
|
||||
document.body.appendChild(state.uiContainer);
|
||||
state.uiContainer.addEventListener('click', (e) => e.stopPropagation());
|
||||
}
|
||||
@@ -683,7 +784,11 @@ window._tunerUI = function(state, actions) {
|
||||
|
||||
const handlePlay = () => {
|
||||
updateFloatingButtonVisibility();
|
||||
if (state.enabled) actions.disable();
|
||||
// A manually-opened tuner closes when playback starts (you don't tune
|
||||
// while playing). An AUTO-opened tuner PERSISTS through the autoplay
|
||||
// song:play that immediately follows song entry — that auto-close was
|
||||
// the "opens then vanishes ~1s later" flash. It closes via Skip/×/leave.
|
||||
if (state.enabled && !state.autoOpened) actions.disable();
|
||||
};
|
||||
const handleStop = () => updateFloatingButtonVisibility();
|
||||
|
||||
@@ -737,6 +842,7 @@ window._tunerUI = function(state, actions) {
|
||||
renderTuningOptions,
|
||||
renderStringNotes,
|
||||
updateUI,
|
||||
resetVerify: resetVerifyUI,
|
||||
updateInstrumentDisplay: _updateInstrumentDisplay,
|
||||
updateSaveAsCustomVisibility: _updateSaveAsCustomVisibility,
|
||||
updateFreeTuneUI,
|
||||
|
||||
@@ -60,6 +60,8 @@ import yaml # noqa: E402
|
||||
|
||||
import notation as notation_mod # noqa: E402, F401 (re-exported for tests)
|
||||
|
||||
from jsonc import load_json # noqa: E402
|
||||
|
||||
# The wire→notation heuristic core lives in ``lib/notation_lift.py`` so it can
|
||||
# be reused in-process (e.g. by the Arrangement Editor's notation save path)
|
||||
# rather than being copy-pasted out of this one-time CLI. Re-exported here so
|
||||
@@ -106,15 +108,16 @@ def _parse_time_signature(raw: object) -> tuple[int, int]:
|
||||
|
||||
|
||||
def _load_song_beats(pak: Path, manifest: dict) -> list[dict]:
|
||||
"""Song-level beats: ``song_timeline.json`` when present, else the first
|
||||
"""Song-level beats: the ``song_timeline`` file when present, else the first
|
||||
arrangement JSON that carries a non-empty ``beats`` array (the loader's
|
||||
legacy convention)."""
|
||||
legacy convention). Both the timeline and arrangement files are read via
|
||||
``load_json``, so either may be ``.json`` or ``.jsonc``."""
|
||||
st_rel = manifest.get("song_timeline")
|
||||
if isinstance(st_rel, str) and st_rel:
|
||||
st_path = _safe_child(pak, st_rel)
|
||||
if st_path is not None and st_path.is_file():
|
||||
try:
|
||||
data = json.loads(st_path.read_text(encoding="utf-8"))
|
||||
data = load_json(st_path)
|
||||
# An empty beats list is not an authoritative timeline — fall
|
||||
# through to the arrangement JSONs rather than ending up with
|
||||
# zero downbeats and skipping the whole sloppak.
|
||||
@@ -134,7 +137,7 @@ def _load_song_beats(pak: Path, manifest: dict) -> list[dict]:
|
||||
if arr_path is None or not arr_path.is_file():
|
||||
continue
|
||||
try:
|
||||
data = json.loads(arr_path.read_text(encoding="utf-8"))
|
||||
data = load_json(arr_path)
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
if isinstance(data, dict):
|
||||
@@ -219,7 +222,7 @@ def lift_sloppak(pak: Path, *, dry_run: bool = False) -> list[str]:
|
||||
continue
|
||||
|
||||
try:
|
||||
arr_data = json.loads(arr_path.read_text(encoding="utf-8"))
|
||||
arr_data = load_json(arr_path)
|
||||
except (OSError, ValueError) as e:
|
||||
log.warning("%s/%s: unreadable arrangement JSON (%s) — skipped",
|
||||
pak.name, arr_id, e)
|
||||
|
||||
@@ -1929,6 +1929,7 @@ class MetadataDB:
|
||||
stems_lacks: list[str] | None = None,
|
||||
has_lyrics: int | None = None,
|
||||
tunings: list[str] | None = None,
|
||||
mastery: list[str] | None = None,
|
||||
naming_mode: str = "legacy") -> tuple[str, list]:
|
||||
"""Shared WHERE-clause builder for query_page / query_artists /
|
||||
query_stats. Returns (where_sql, params). Leading 'WHERE' is
|
||||
@@ -1947,6 +1948,19 @@ class MetadataDB:
|
||||
if album_filter:
|
||||
where += " AND album = ? COLLATE NOCASE"
|
||||
params.append(album_filter)
|
||||
# Mastery bands = best accuracy across a song's arrangements (song_stats,
|
||||
# a separate table -> correlated subquery). mastered >= 0.9, in_progress =
|
||||
# attempted but < 0.9, not_started = no score. OR within the selected set.
|
||||
if mastery:
|
||||
_msub = "(SELECT MAX(best_accuracy) FROM song_stats s WHERE s.filename = songs.filename)"
|
||||
_bands = {
|
||||
"mastered": f"{_msub} >= 0.9",
|
||||
"in_progress": f"({_msub} IS NOT NULL AND {_msub} < 0.9)",
|
||||
"not_started": f"{_msub} IS NULL",
|
||||
}
|
||||
_sel = [_bands[b] for b in mastery if b in _bands]
|
||||
if _sel:
|
||||
where += " AND (" + " OR ".join(_sel) + ")"
|
||||
if q:
|
||||
where += " AND (title LIKE ? COLLATE NOCASE OR artist LIKE ? COLLATE NOCASE OR album LIKE ? COLLATE NOCASE)"
|
||||
params += [f"%{q}%"] * 3
|
||||
@@ -2099,6 +2113,7 @@ class MetadataDB:
|
||||
stems_lacks: list[str] | None = None,
|
||||
has_lyrics: int | None = None,
|
||||
tunings: list[str] | None = None,
|
||||
mastery: list[str] | None = None,
|
||||
after: str | None = None,
|
||||
naming_mode: str = "legacy") -> tuple[list[dict], int]:
|
||||
"""Server-side paginated search. Returns (songs, total_count).
|
||||
@@ -2112,7 +2127,7 @@ class MetadataDB:
|
||||
artist_filter=artist_filter, album_filter=album_filter,
|
||||
arrangements_has=arrangements_has, arrangements_lacks=arrangements_lacks,
|
||||
stems_has=stems_has, stems_lacks=stems_lacks,
|
||||
has_lyrics=has_lyrics, tunings=tunings, naming_mode=naming_mode,
|
||||
has_lyrics=has_lyrics, tunings=tunings, mastery=mastery, naming_mode=naming_mode,
|
||||
)
|
||||
|
||||
sort_map = {
|
||||
@@ -2153,6 +2168,20 @@ class MetadataDB:
|
||||
# '2005' rather than alphabetic.
|
||||
"year": "(year = '') ASC, CAST(year AS INTEGER) ASC",
|
||||
"year-desc": "(year = '') ASC, CAST(year AS INTEGER) DESC",
|
||||
# Mastery = best accuracy across a song's arrangements, from the
|
||||
# separate song_stats table (so via a correlated subquery — this sort
|
||||
# drops to OFFSET paging, like tuning/year). Unscored ("not started")
|
||||
# songs push to the BOTTOM in both directions (the IS NULL term);
|
||||
# ascending is "needs practice first" (weakest measured first),
|
||||
# descending is "most mastered first".
|
||||
"mastery": (
|
||||
"((SELECT MAX(best_accuracy) FROM song_stats s WHERE s.filename = songs.filename) IS NULL) ASC, "
|
||||
"(SELECT MAX(best_accuracy) FROM song_stats s WHERE s.filename = songs.filename) ASC"
|
||||
),
|
||||
"mastery-desc": (
|
||||
"((SELECT MAX(best_accuracy) FROM song_stats s WHERE s.filename = songs.filename) IS NULL) ASC, "
|
||||
"(SELECT MAX(best_accuracy) FROM song_stats s WHERE s.filename = songs.filename) DESC"
|
||||
),
|
||||
}
|
||||
order = sort_map.get(sort, "artist COLLATE NOCASE")
|
||||
# Legacy `dir=desc` toggle: only safe to append on simple sort
|
||||
@@ -4950,7 +4979,7 @@ async def list_library(q: str = "", page: int = 0, size: int = 24, sort: str = "
|
||||
arrangements_has: str = "", arrangements_lacks: str = "",
|
||||
stems_has: str = "", stems_lacks: str = "",
|
||||
has_lyrics: str = "", tunings: str = "", provider: str = "local",
|
||||
after: str = "", naming_mode: str = "legacy"):
|
||||
mastery: str = "", after: str = "", naming_mode: str = "legacy"):
|
||||
"""Paginated library search through the selected library provider.
|
||||
|
||||
`after` is an opaque keyset cursor (feedBack#636 item 3): pass back the
|
||||
@@ -4974,6 +5003,7 @@ async def list_library(q: str = "", page: int = 0, size: int = 24, sort: str = "
|
||||
direction=dir,
|
||||
after=((after or None) if is_local else None),
|
||||
naming_mode=naming_mode,
|
||||
mastery=_split_csv(mastery),
|
||||
**_library_filter_args(
|
||||
q=q, favorites=favorites, format=format,
|
||||
artist=artist, album=album,
|
||||
@@ -7842,15 +7872,63 @@ async def highway_ws(websocket: WebSocket, filename: str, arrangement: int = -1,
|
||||
if 0 <= arrangement < len(song.arrangements):
|
||||
best = arrangement
|
||||
else:
|
||||
# Check user's default arrangement preference
|
||||
# Read the user's config once: their selected instrument (route the chart
|
||||
# to the matching part) and their default-arrangement preference.
|
||||
pref = ""
|
||||
sel_instrument = ""
|
||||
config_file = CONFIG_DIR / "config.json"
|
||||
if config_file.exists():
|
||||
try:
|
||||
pref = json.loads(config_file.read_text(encoding="utf-8")).get("default_arrangement", "")
|
||||
_cfg = json.loads(config_file.read_text(encoding="utf-8"))
|
||||
pref = _cfg.get("default_arrangement", "")
|
||||
sel_instrument = (_cfg.get("instrument", "") or "")
|
||||
except Exception:
|
||||
pass
|
||||
if pref:
|
||||
# Instrument routing: load the part that matches the selected instrument so
|
||||
# "your instrument" and "the chart you play" line up. The default ordering
|
||||
# is Lead/guitar-first, so without this a bass player gets handed a guitar
|
||||
# chart (and any tune-check then compares a 4-string bass against a 6-string
|
||||
# part). Currently routes bass -> a Bass arrangement; guitar — and any
|
||||
# unknown/future instrument (drums, keys) — falls through to the
|
||||
# preference/most-notes logic below, which already lands on a guitar part.
|
||||
# Drums/keys get their own match when those arrangement types + selector
|
||||
# entries land. Only applies when no explicit arrangement was requested, so
|
||||
# a manual arrangement switch is always respected.
|
||||
if sel_instrument.lower() == "bass":
|
||||
# Candidate bass parts, preferring the structured pathBass flag; the
|
||||
# normalized smart name (itself pathBass-derived) and raw name are
|
||||
# fallbacks for sources without the flag.
|
||||
bass_idxs = [
|
||||
i
|
||||
for i, a in enumerate(song.arrangements)
|
||||
if getattr(a, "path_bass", False)
|
||||
or (smart_names[i] or "").lower().startswith("bass")
|
||||
or "bass" in (getattr(a, "name", "") or "").lower()
|
||||
]
|
||||
if bass_idxs:
|
||||
# Among the bass parts: (1) honor the saved default-arrangement
|
||||
# preference if it names one of them (so a bass player who prefers
|
||||
# "Bass 2"/"Alt. Bass" keeps it), (2) else the canonical main "Bass",
|
||||
# (3) else the first bass part in order.
|
||||
pref_bass = -1
|
||||
if pref:
|
||||
for i in bass_idxs:
|
||||
nm = (smart_names[i] if naming_mode == "smart" and i < len(smart_names)
|
||||
else getattr(song.arrangements[i], "name", ""))
|
||||
if nm == pref:
|
||||
pref_bass = i
|
||||
break
|
||||
if pref_bass >= 0:
|
||||
best = pref_bass
|
||||
else:
|
||||
best = next(
|
||||
(i for i in bass_idxs
|
||||
if (smart_names[i] if i < len(smart_names) else "") == "Bass"),
|
||||
bass_idxs[0],
|
||||
)
|
||||
# User's default arrangement preference (only when instrument routing did not
|
||||
# already resolve a part — i.e. guitar, or a bass player with no bass part).
|
||||
if best < 0 and pref:
|
||||
if naming_mode == "smart":
|
||||
best = _pick_smart_arrangement(song.arrangements, smart_names, pref)
|
||||
else:
|
||||
|
||||
+143
-18
@@ -5990,6 +5990,56 @@ function _resolvePlayerOrigin() {
|
||||
// next song:ready. song:ready also fires on arrangement switches / seeks,
|
||||
// which never arm the flag, so those don't auto-restart.
|
||||
let _pendingAutostart = false;
|
||||
// Autoplay gate (window.feedBack.holdAutoplay): a plugin (the tuner) can defer the
|
||||
// auto-start of a freshly-loaded song until it's cleared — "tune before you play".
|
||||
// The hold is claimed synchronously on song:loading (so it beats this song:ready
|
||||
// autostart); release() — or a fail-open backstop — runs the deferred start.
|
||||
// Generation-guarded so a newer song invalidates a stale hold. Manual Play never
|
||||
// flows through here, so Play always wins.
|
||||
let _autoplayHeld = false;
|
||||
let _autoplayStart = null;
|
||||
let _autoplayGen = 0;
|
||||
let _autoplayBackstop = null;
|
||||
const AUTOPLAY_HOLD_BACKSTOP_MS = 12000;
|
||||
function _clearAutoplayHold() {
|
||||
if (_autoplayBackstop) { clearTimeout(_autoplayBackstop); _autoplayBackstop = null; }
|
||||
_autoplayHeld = false;
|
||||
_autoplayStart = null;
|
||||
_autoplayGen++;
|
||||
}
|
||||
function _releaseAutoplay(gen) {
|
||||
if (gen !== _autoplayGen) return; // a newer song superseded this hold
|
||||
if (_autoplayBackstop) { clearTimeout(_autoplayBackstop); _autoplayBackstop = null; }
|
||||
_autoplayHeld = false;
|
||||
const start = _autoplayStart;
|
||||
_autoplayStart = null;
|
||||
if (typeof start === 'function') start();
|
||||
}
|
||||
let _autoplayHoldToken = 0;
|
||||
window.feedBack.holdAutoplay = function () {
|
||||
const gen = _autoplayGen;
|
||||
const token = ++_autoplayHoldToken; // this hold's identity — a stale release from an earlier hold is a no-op
|
||||
_autoplayHeld = true;
|
||||
if (_autoplayBackstop) clearTimeout(_autoplayBackstop);
|
||||
// Fail-open: a hold that's never released (a plugin that claimed but wedged before
|
||||
// it could decide) must never permanently block the song. Once the holder commits
|
||||
// to an intentional, user-dismissable hold it calls release.settle() to cancel this
|
||||
// — so the backstop can't cut off e.g. a user still tuning past the timeout.
|
||||
_autoplayBackstop = setTimeout(() => _releaseAutoplay(gen), AUTOPLAY_HOLD_BACKSTOP_MS);
|
||||
let released = false;
|
||||
function release() {
|
||||
if (released || gen !== _autoplayGen || token !== _autoplayHoldToken) return;
|
||||
released = true;
|
||||
_releaseAutoplay(gen);
|
||||
}
|
||||
// Cancel the fail-open backstop WITHOUT releasing: the holder has taken explicit
|
||||
// responsibility for releasing (on dismiss), and a song switch clears the hold anyway.
|
||||
release.settle = function () {
|
||||
if (gen !== _autoplayGen || token !== _autoplayHoldToken) return;
|
||||
if (_autoplayBackstop) { clearTimeout(_autoplayBackstop); _autoplayBackstop = null; }
|
||||
};
|
||||
return release;
|
||||
};
|
||||
window.feedBack.on('song:ready', () => {
|
||||
if (!_pendingAutostart) return;
|
||||
_pendingAutostart = false;
|
||||
@@ -6014,27 +6064,30 @@ window.feedBack.on('song:ready', () => {
|
||||
if (authors.length) _creditsTimer = setTimeout(hideSongCreditsOverlay, _CREDITS_HOLD_MS);
|
||||
return;
|
||||
}
|
||||
// "Countdown before song": play a 4-beat count-in, then start. Otherwise
|
||||
// reuse the Play button's start path directly (handles HTML5 + _juceMode).
|
||||
if (_countdownBeforeSongEnabled()) {
|
||||
// The count-in (~2.5s) gives the credits their on-screen dwell.
|
||||
Promise.resolve(startSongCountIn()).catch((err) => console.warn('[app] song count-in failed:', err));
|
||||
} else if (authors.length) {
|
||||
// No count-in window — hold the credits a couple seconds, then start.
|
||||
// _cancelCountIn() and changeArrangement() both clear _creditsTimer, so
|
||||
// a teardown / arrangement switch during the hold cancels this play.
|
||||
_creditsTimer = setTimeout(() => {
|
||||
_creditsTimer = null;
|
||||
// If playback doesn't actually start (e.g. HTML5 autoplay rejection),
|
||||
// song:play never fires — clear the credits promptly rather than
|
||||
// waiting for the backstop. On success the song:play listener owns it.
|
||||
// The actual auto-start: a count-in (which handles HTML5 + _juceMode) or the
|
||||
// Play path directly. Guarded so a manual Play during a gate / credits hold
|
||||
// can't double-toggle, and so a stale (released-after-leaving) start never
|
||||
// begins playback off the player.
|
||||
const start = () => {
|
||||
if (isPlaying) return;
|
||||
if (!document.getElementById('player')?.classList.contains('active')) { hideSongCreditsOverlay(); return; }
|
||||
if (_countdownBeforeSongEnabled()) {
|
||||
Promise.resolve(startSongCountIn()).catch((err) => console.warn('[app] song count-in failed:', err));
|
||||
} else {
|
||||
Promise.resolve(togglePlay())
|
||||
.then(() => { if (!isPlaying) hideSongCreditsOverlay(); })
|
||||
.catch((err) => { console.warn('[app] autoplay failed:', err); hideSongCreditsOverlay(); });
|
||||
}, _CREDITS_HOLD_MS);
|
||||
} else {
|
||||
Promise.resolve(togglePlay()).catch((err) => console.warn('[app] autoplay failed:', err));
|
||||
}
|
||||
}
|
||||
};
|
||||
// A plugin (the tuner) may gate playback until it's cleared. The hold was
|
||||
// claimed on song:loading; stash the start and let release()/the backstop run
|
||||
// it. _cancelCountIn()/changeArrangement() clear _creditsTimer below, so a
|
||||
// teardown during the credits dwell still cancels a non-gated play.
|
||||
if (_autoplayHeld) { _autoplayStart = start; return; }
|
||||
// Not gated: a count-in starts now (it owns its on-screen dwell); otherwise
|
||||
// let the credits dwell a couple seconds first, then start.
|
||||
if (_countdownBeforeSongEnabled() || !authors.length) start();
|
||||
else _creditsTimer = setTimeout(() => { _creditsTimer = null; start(); }, _CREDITS_HOLD_MS);
|
||||
});
|
||||
|
||||
// ── Resume last session ────────────────────────────────────────────────────
|
||||
@@ -6328,9 +6381,17 @@ let artAbortController = null;
|
||||
|
||||
async function playSong(filename, arrangement, options) {
|
||||
console.log('playSong called:', filename);
|
||||
// A manual (non-queue) play abandons any active play-queue, so a stale queue
|
||||
// can't hijack the next song's end. The queue passes fromQueue to keep itself.
|
||||
if ((!options || !options.fromQueue) && window.feedBack && window.feedBack.playQueue) {
|
||||
window.feedBack.playQueue.clear();
|
||||
}
|
||||
if (!options || options.bridge !== false) {
|
||||
_recordPlaybackBridge('playback.window-play-song', 'window.playSong', 'legacy playSong entry point used');
|
||||
}
|
||||
// Invalidate any prior song's autoplay gate before plugins re-claim it on the
|
||||
// song:loading emit below.
|
||||
_clearAutoplayHold();
|
||||
window.feedBack.emit('song:loading', { filename, arrangement: arrangement ?? null });
|
||||
|
||||
// Cancel any pending art/metadata requests
|
||||
@@ -6667,11 +6728,75 @@ if (window.feedBack) window.feedBack.restartCurrentSong = restartCurrentSong;
|
||||
// (Esc shortcut uses the same origin-aware target). showScreen() owns the
|
||||
// full teardown: song:stop, audio unload, highway.stop(), count-in cancel.
|
||||
function closeCurrentSong() {
|
||||
// A real close (user Escape/✕, or the queue-aware wrapper once the queue is
|
||||
// exhausted) abandons any play-queue so a stale one can't advance later.
|
||||
if (window.feedBack && window.feedBack.playQueue) window.feedBack.playQueue.clear();
|
||||
return showScreen(_playerOriginScreen || 'home');
|
||||
}
|
||||
window.closeCurrentSong = closeCurrentSong;
|
||||
if (window.feedBack) window.feedBack.closeCurrentSong = closeCurrentSong;
|
||||
|
||||
// ── Play-queue: sequential playback of a playlist / album ──────────────────
|
||||
// Playing a list should advance to the next track when a song ends, instead of
|
||||
// returning to the menu (the long-standing "plays one song then boots to menu"
|
||||
// gap — a queue was simply never implemented). Advancing rides the SAME exit
|
||||
// choke point as auto-exit and a results-card close: window.closeCurrentSong().
|
||||
// Song-end paths call window.closeCurrentSong() (the auto-exit grace timer, and
|
||||
// a results screen's release()), so wrapping it lets the queue advance on song
|
||||
// end AND after the user dismisses a score card. A *user* exit (Escape / the ✕)
|
||||
// calls the bareword closeCurrentSong(), which we deliberately leave alone, so
|
||||
// leaving the player still leaves — and abandons the queue.
|
||||
window.feedBack.playQueue = (function () {
|
||||
let list = [], idx = -1, source = '', arrangements = null;
|
||||
const active = () => idx >= 0 && idx < list.length;
|
||||
const hasNext = () => active() && idx < list.length - 1;
|
||||
function clear() { list = []; idx = -1; source = ''; arrangements = null; }
|
||||
function _play(i) {
|
||||
const fn = list[i];
|
||||
// fromQueue keeps the queue from clearing itself; playSong decodeURIs.
|
||||
window.playSong(encodeURIComponent(fn), arrangements ? arrangements[i] : undefined, { fromQueue: true });
|
||||
}
|
||||
function start(files, opts) {
|
||||
files = (files || []).filter(Boolean);
|
||||
if (!files.length) return false;
|
||||
list = files.slice(); idx = 0;
|
||||
source = (opts && opts.source) || '';
|
||||
arrangements = (opts && opts.arrangements) || null;
|
||||
if (window.fbNotify) {
|
||||
try { window.fbNotify.show({ title: 'Playing ' + (source || 'queue'), message: files.length + ' songs', icon: '▶' }); } catch (e) { /* */ }
|
||||
}
|
||||
_play(idx);
|
||||
return true;
|
||||
}
|
||||
function advance() {
|
||||
if (!hasNext()) { clear(); return false; }
|
||||
idx++;
|
||||
_play(idx);
|
||||
return true;
|
||||
}
|
||||
return {
|
||||
start: start, advance: advance, hasNext: hasNext, active: active, clear: clear,
|
||||
source: function () { return source; },
|
||||
remaining: function () { return active() ? list.length - idx - 1 : 0; },
|
||||
};
|
||||
})();
|
||||
|
||||
// Make the song-end exit queue-aware (see above). Wrap window.closeCurrentSong
|
||||
// (and feedBack.closeCurrentSong) so that when a queue has a next track, we play
|
||||
// it instead of returning to the menu. The bareword closeCurrentSong() used by a
|
||||
// user-initiated exit is unaffected.
|
||||
(function () {
|
||||
const realClose = window.closeCurrentSong;
|
||||
function queueAwareClose() {
|
||||
const q = window.feedBack.playQueue;
|
||||
if (q && q.hasNext()) { q.advance(); return; }
|
||||
if (q) q.clear();
|
||||
return realClose.apply(this, arguments);
|
||||
}
|
||||
window.closeCurrentSong = queueAwareClose;
|
||||
if (window.feedBack) window.feedBack.closeCurrentSong = queueAwareClose;
|
||||
})();
|
||||
|
||||
// ── "Ask before leaving a song" (Gameplay tab, default OFF) ────────────────
|
||||
// Client-only localStorage pref (`confirmExitSong`); absence = OFF. When ON, a
|
||||
// *user-initiated* exit (Escape, or the player ✕) opens a small confirm instead
|
||||
|
||||
@@ -0,0 +1,390 @@
|
||||
// Core "working tuning" capability domain — the live, host-authoritative CURRENT
|
||||
// instrument tuning (session state), distinct from the soft opt-in default and from
|
||||
// any one song's tuning. This is the single source of truth the whole app reads:
|
||||
// the highway, the library/song-picker, Virtuoso, and the minigames all consult it,
|
||||
// and the tuner is the sole WRITER (it updates this when the player retunes, clears
|
||||
// the gate, or switches instruments).
|
||||
//
|
||||
// PER-INSTRUMENT: a player has separate physical instruments, each in its OWN tuning
|
||||
// ("I'm not tuning two instruments when I pick a song"). So state is a MAP keyed by
|
||||
// instrument — `${instrument}-${stringCount}` (e.g. "guitar-6", "bass-4"), the same key
|
||||
// the v3 instrument selector uses. `get()` returns the CURRENTLY-SELECTED instrument's
|
||||
// tuning; switching the selector surfaces that instrument's own remembered tuning. You
|
||||
// only ever deal with the one you've picked.
|
||||
//
|
||||
// Design: WORKING-TUNING-STATE-DESIGN.md (host-first PR series, PR 1 = this file).
|
||||
// Pattern mirrors `capabilities/tuning.js` (capability registration) + the host theme
|
||||
// read-API (`window.feedBack.theme`): a synchronous `get()` plus a `working-tuning-
|
||||
// changed` event that also fires once on hydration.
|
||||
//
|
||||
// State is IN-MEMORY and NOT persisted — reset-to-home on restart is deliberate (a
|
||||
// stale "you're in drop-A" assumption is worse than re-asking). The opt-in "default
|
||||
// tuning on app open" lands later; for now we seed the selected instrument from
|
||||
// /api/settings.
|
||||
//
|
||||
// PR 1 is PURE PLUMBING: it introduces the state + read/write surface + event, but
|
||||
// nothing writes to it yet and no behavior changes. The tuner becomes the writer (and
|
||||
// the gate's E->C# asymmetry is fixed) in a later PR.
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
window.feedBack = window.feedBack || {};
|
||||
// Idempotent: a second injection of this module must not replace the live state
|
||||
// with a fresh (empty) one — once we're registered, re-running is a no-op.
|
||||
if (window.feedBack.workingTuning && window.feedBack.workingTuning.version === 1) return;
|
||||
const capabilities = window.feedBack.capabilities;
|
||||
|
||||
const _byInstrument = {}; // key -> tuning state (the per-instrument map)
|
||||
let _currentKey = null; // the selected instrument's key; cached so get() is sync
|
||||
let _hydrated = false;
|
||||
let _touched = false; // set once anything explicitly writes/selects; gates the async seed
|
||||
|
||||
function _normInstrument(instrument) {
|
||||
return instrument === 'bass' ? 'bass' : 'guitar';
|
||||
}
|
||||
function _keyOf(instrument, stringCount) {
|
||||
const inst = _normInstrument(instrument);
|
||||
const sc = Number(stringCount) || (inst === 'bass' ? 4 : 6);
|
||||
return inst + '-' + sc;
|
||||
}
|
||||
// Like _keyOf, but when the caller omits a string count we resolve it against the
|
||||
// current selection (if it's the same instrument) before falling back to the
|
||||
// per-instrument default — so `set({instrument:'bass'})` targets the selected
|
||||
// bass-5, not a hard-coded bass-4.
|
||||
function _keyOfResolved(instrument, stringCount) {
|
||||
const inst = _normInstrument(instrument);
|
||||
let sc = Number(stringCount);
|
||||
if (!sc) {
|
||||
if (_currentKey) {
|
||||
const cur = _splitKey(_currentKey);
|
||||
if (cur.instrument === inst) sc = cur.stringCount;
|
||||
}
|
||||
if (!sc) sc = (inst === 'bass' ? 4 : 6);
|
||||
}
|
||||
return inst + '-' + sc;
|
||||
}
|
||||
function _splitKey(key) {
|
||||
const parts = (typeof key === 'string' ? key : '').split('-');
|
||||
const inst = parts[0] === 'bass' ? 'bass' : 'guitar';
|
||||
return { instrument: inst, stringCount: Number(parts[1]) || (inst === 'bass' ? 4 : 6) };
|
||||
}
|
||||
|
||||
// The shape every consumer reads. `offsets` are per-string semitone offsets from
|
||||
// standard (same vocabulary as song_info.tuning and /api/tunings); `instrument`
|
||||
// disambiguates the open-string base so offsets resolve to real pitches. A drop-A
|
||||
// 8-string is just an offsets array — fully custom tunings are first-class.
|
||||
// `provenance` is the honesty flag: 'verified' means the tuner did a choreographed
|
||||
// per-string mic check this session; everything else is 'assumed'.
|
||||
function _defaultState(key) {
|
||||
const id = _splitKey(key);
|
||||
return {
|
||||
offsets: null,
|
||||
stringCount: id.stringCount,
|
||||
instrument: id.instrument,
|
||||
referencePitch: 440,
|
||||
provenance: 'assumed',
|
||||
verifiedStrings: null,
|
||||
verifiedAt: null,
|
||||
source: 'default',
|
||||
};
|
||||
}
|
||||
|
||||
// Resolve which instrument key a get/set targets: an explicit arg wins (a string
|
||||
// key "guitar-6", a bare "guitar"/"bass", or { instrument, stringCount }); else the
|
||||
// cached current selection.
|
||||
function _resolveKey(instrument) {
|
||||
if (instrument && typeof instrument === 'object') return _keyOfResolved(instrument.instrument, instrument.stringCount);
|
||||
if (typeof instrument === 'string' && instrument) {
|
||||
return instrument.indexOf('-') > 0 ? instrument : _keyOfResolved(instrument, null);
|
||||
}
|
||||
return _currentKey || _keyOf('guitar', 6);
|
||||
}
|
||||
|
||||
// Synchronous read of an instrument's current tuning (default = selected
|
||||
// instrument). Returns a deep-enough copy — the object plus its mutable array
|
||||
// fields (`offsets`, `verifiedStrings`) — so a reader can't mutate the live state.
|
||||
function get(instrument) {
|
||||
const key = _resolveKey(instrument);
|
||||
const state = Object.assign(_defaultState(key), _byInstrument[key] || {});
|
||||
if (Array.isArray(state.offsets)) state.offsets = state.offsets.slice();
|
||||
if (Array.isArray(state.verifiedStrings)) state.verifiedStrings = state.verifiedStrings.slice();
|
||||
return state;
|
||||
}
|
||||
|
||||
function _emitChanged(key) {
|
||||
if (window.feedBack && typeof window.feedBack.emit === 'function') {
|
||||
window.feedBack.emit('working-tuning-changed', { key: key, instrument: _splitKey(key).instrument, tuning: get(key) });
|
||||
}
|
||||
}
|
||||
|
||||
// The single mutator. The tuner calls this on retune / gate-clear / swap. Writes to
|
||||
// the instrument the state targets (opts.instrument, or next.instrument+stringCount,
|
||||
// or the current selection) and makes that the active instrument. `opts.provenance`
|
||||
// stamps 'verified' (mic-confirmed) vs the default 'assumed'. Changing the tuning
|
||||
// invalidates a prior verification unless fresh verifiedStrings are supplied — fail
|
||||
// toward "assumed".
|
||||
function set(next, opts) {
|
||||
opts = opts || {};
|
||||
next = next || {};
|
||||
// Resolve the target key. An explicit opts.instrument wins; otherwise a
|
||||
// next.instrument/next.stringCount targets that slot — but a bare stringCount
|
||||
// (no instrument) applies to the CURRENTLY-SELECTED instrument, not a hard-coded
|
||||
// guitar, so `set({stringCount:5})` on a selected bass writes bass-5.
|
||||
let key;
|
||||
if (opts.instrument) {
|
||||
key = _resolveKey(opts.instrument);
|
||||
} else if (next.instrument || next.stringCount) {
|
||||
const inst = next.instrument ? _normInstrument(next.instrument)
|
||||
: (_currentKey ? _splitKey(_currentKey).instrument : 'guitar');
|
||||
key = _keyOfResolved(inst, next.stringCount);
|
||||
} else {
|
||||
key = _currentKey || _resolveKey();
|
||||
}
|
||||
const id = _splitKey(key);
|
||||
const merged = Object.assign(get(key), next); // get() gives copies, so `merged` is ours to mutate
|
||||
merged.instrument = id.instrument; // keep coherent with the key
|
||||
merged.stringCount = id.stringCount; // the key is authoritative for string count
|
||||
const tuningChanged = ('offsets' in next) || ('stringCount' in next) || ('referencePitch' in next);
|
||||
|
||||
// Provenance: explicit opts wins; a bare tuning change downgrades to 'assumed'.
|
||||
if (opts.provenance) {
|
||||
merged.provenance = opts.provenance;
|
||||
} else if (tuningChanged) {
|
||||
merged.provenance = 'assumed';
|
||||
}
|
||||
|
||||
// Verification metadata is coherent by construction: a tuning change invalidates
|
||||
// prior per-string verification unless the caller supplies a fresh bundle, and the
|
||||
// metadata exists ONLY while provenance === 'verified'. So verified <=> we hold
|
||||
// verifiedStrings — a "verified with no strings" state is impossible.
|
||||
if (!('verifiedStrings' in next) && tuningChanged) {
|
||||
merged.verifiedStrings = null;
|
||||
}
|
||||
if (merged.provenance === 'verified' && !Array.isArray(merged.verifiedStrings)) {
|
||||
merged.provenance = 'assumed'; // claimed verified but no evidence — fail toward assumed
|
||||
}
|
||||
if (merged.provenance === 'verified') {
|
||||
// verified always carries a real timestamp — a caller-supplied null/NaN/absent
|
||||
// verifiedAt is stamped now, so 'verified' can never mean "at no known time".
|
||||
if (typeof merged.verifiedAt !== 'number' || !isFinite(merged.verifiedAt)) {
|
||||
merged.verifiedAt = Date.now();
|
||||
}
|
||||
} else {
|
||||
merged.verifiedStrings = null;
|
||||
merged.verifiedAt = null;
|
||||
}
|
||||
|
||||
// Store copies of the mutable arrays so a caller can't mutate live state post-set.
|
||||
if (Array.isArray(merged.offsets)) merged.offsets = merged.offsets.slice();
|
||||
if (Array.isArray(merged.verifiedStrings)) merged.verifiedStrings = merged.verifiedStrings.slice();
|
||||
_byInstrument[key] = merged;
|
||||
_currentKey = key; // writing a tuning makes that instrument the active one
|
||||
_touched = true; // an explicit write must not be clobbered by the async seed
|
||||
_emitChanged(key);
|
||||
return get(key);
|
||||
}
|
||||
|
||||
// Tell the host which instrument is now selected (the v3 selector calls this when
|
||||
// the player switches guitar<->bass / string count) so get() returns the right
|
||||
// instrument's tuning. Emits if the selection actually changed.
|
||||
function setCurrentInstrument(instrument, stringCount) {
|
||||
const key = (typeof instrument === 'string' && instrument.indexOf('-') > 0) ? instrument : _keyOfResolved(instrument, stringCount);
|
||||
_touched = true; // an explicit selection must not be reverted by the async seed
|
||||
if (key === _currentKey) return get(key);
|
||||
_currentKey = key;
|
||||
_emitChanged(key);
|
||||
return get(key);
|
||||
}
|
||||
|
||||
// Reset an instrument's live tuning back to its baseline (the home/default).
|
||||
function resetToDefault(instrument) {
|
||||
const key = _resolveKey(instrument);
|
||||
_byInstrument[key] = _defaultState(key);
|
||||
_touched = true;
|
||||
_emitChanged(key);
|
||||
return get(key);
|
||||
}
|
||||
|
||||
// Per-string semitone offsets of a named tuning relative to Standard, derived from
|
||||
// the /api/tunings frequency tables. The reference pitch cancels in the ratio, so
|
||||
// this is pitch-independent. Returns null if either row is missing/mismatched.
|
||||
function _offsetsFromFreqs(named, standard) {
|
||||
if (!Array.isArray(named) || !Array.isArray(standard) || named.length !== standard.length) return null;
|
||||
const out = [];
|
||||
for (let i = 0; i < named.length; i++) {
|
||||
const a = Number(named[i]);
|
||||
const b = Number(standard[i]);
|
||||
if (!(a > 0) || !(b > 0)) return null;
|
||||
out.push(Math.round(12 * Math.log2(a / b)));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- Opt-in "launch tuning" default (soft, per-instrument) -------------------
|
||||
// A convenience the player opts into: "start me in THIS tuning on app open." Off
|
||||
// by default (nothing stored) → boot seeds from /api/settings as before. It is
|
||||
// only a SEED — the live working tuning still resets on restart.
|
||||
const LAUNCH_KEY = 'v3-working-tuning-launch-default';
|
||||
function _readLaunchMap() {
|
||||
try { return JSON.parse(localStorage.getItem(LAUNCH_KEY) || '{}') || {}; }
|
||||
catch (_) { return {}; }
|
||||
}
|
||||
function _writeLaunchMap(map) {
|
||||
try {
|
||||
if (map && Object.keys(map).length) localStorage.setItem(LAUNCH_KEY, JSON.stringify(map));
|
||||
else localStorage.removeItem(LAUNCH_KEY);
|
||||
} catch (_) { /* private mode */ }
|
||||
}
|
||||
function getLaunchDefault(instrument) {
|
||||
const key = _resolveKey(instrument);
|
||||
const d = _readLaunchMap()[key];
|
||||
return d ? Object.assign(_defaultState(key), d, { source: 'launch-default' }) : null;
|
||||
}
|
||||
// Remember an instrument's CURRENT working tuning (or a supplied state) as its
|
||||
// launch default. Opt-in — nothing calls this unless the player asks.
|
||||
function setLaunchDefault(instrument, state) {
|
||||
const key = _resolveKey(instrument);
|
||||
const src = state || get(key);
|
||||
const map = _readLaunchMap();
|
||||
map[key] = {
|
||||
offsets: Array.isArray(src.offsets) ? src.offsets.slice() : null,
|
||||
stringCount: src.stringCount,
|
||||
instrument: _splitKey(key).instrument,
|
||||
referencePitch: src.referencePitch || 440,
|
||||
};
|
||||
_writeLaunchMap(map);
|
||||
return getLaunchDefault(key);
|
||||
}
|
||||
function clearLaunchDefault(instrument) {
|
||||
const key = _resolveKey(instrument);
|
||||
const map = _readLaunchMap();
|
||||
if (key in map) { delete map[key]; _writeLaunchMap(map); }
|
||||
}
|
||||
|
||||
// Seed the SELECTED instrument's slot on boot (best-effort 'assumed' starting
|
||||
// point, NOT a persisted working tuning): the player's opt-in launch default if one
|
||||
// is set for this instrument, else /api/settings — where a NAMED tuning ("Drop D") is
|
||||
// resolved to offsets via /api/tunings so it isn't lost. If neither can be read we
|
||||
// still hydrate so consumers aren't stuck waiting; an explicit set()/select before we
|
||||
// resolve wins (no clobber).
|
||||
function _seedFromSettings() {
|
||||
fetch('/api/settings')
|
||||
.then(function (r) { return r && r.ok ? r.json() : null; })
|
||||
.then(function (s) {
|
||||
if (!s || _touched) return; // nothing to seed, or a consumer already wrote — don't clobber
|
||||
const inst = _normInstrument(s.instrument);
|
||||
const sc = Number(s.string_count) || (inst === 'bass' ? 4 : 6);
|
||||
const key = _keyOf(inst, sc);
|
||||
|
||||
function commit(offsets) {
|
||||
if (_touched) return; // re-check: a write may have raced the /api/tunings fetch
|
||||
_currentKey = key;
|
||||
// Opt-in launch default wins over the raw profile; otherwise use the
|
||||
// resolved `offsets` (a named settings tuning was already turned into
|
||||
// offsets via /api/tunings before commit()).
|
||||
const launch = _readLaunchMap()[key];
|
||||
_byInstrument[key] = launch
|
||||
? {
|
||||
offsets: Array.isArray(launch.offsets) ? launch.offsets.slice(0, sc) : null,
|
||||
stringCount: sc, instrument: inst,
|
||||
referencePitch: Number(launch.referencePitch) || 440,
|
||||
provenance: 'assumed', verifiedStrings: null, verifiedAt: null,
|
||||
source: 'launch-default',
|
||||
}
|
||||
: {
|
||||
offsets: Array.isArray(offsets) ? offsets.slice(0, sc) : null,
|
||||
stringCount: sc, instrument: inst,
|
||||
referencePitch: Number(s.reference_pitch) || 440,
|
||||
provenance: 'assumed', verifiedStrings: null, verifiedAt: null,
|
||||
source: 'settings',
|
||||
};
|
||||
}
|
||||
|
||||
if (Array.isArray(s.tuning)) { commit(s.tuning); return; }
|
||||
if (typeof s.tuning === 'string' && s.tuning) {
|
||||
return fetch('/api/tunings')
|
||||
.then(function (r) { return r && r.ok ? r.json() : null; })
|
||||
.then(function (t) {
|
||||
const byName = t && t[key];
|
||||
commit(byName ? _offsetsFromFreqs(byName[s.tuning], byName.Standard) : null);
|
||||
})
|
||||
.catch(function () { commit(null); });
|
||||
}
|
||||
commit(null);
|
||||
})
|
||||
.catch(function () { /* keep defaults */ })
|
||||
.then(function () { _hydrate(); });
|
||||
}
|
||||
|
||||
function _hydrate() {
|
||||
if (_hydrated) return;
|
||||
_hydrated = true;
|
||||
_emitChanged(_currentKey || _resolveKey());
|
||||
}
|
||||
|
||||
// A per-string mic verification is only trustworthy for the context it was done
|
||||
// in — a new song means the player may have retuned, so a stale 'verified' must
|
||||
// never suppress a needed prompt (fail toward re-checking). Decay the CURRENT
|
||||
// instrument's verification back to 'assumed' on each song load; offsets are kept.
|
||||
function _decayVerifiedOnSongLoad() {
|
||||
const key = _currentKey || _resolveKey();
|
||||
const st = _byInstrument[key];
|
||||
if (st && st.provenance === 'verified') {
|
||||
st.provenance = 'assumed';
|
||||
st.verifiedStrings = null;
|
||||
st.verifiedAt = null;
|
||||
_emitChanged(key);
|
||||
}
|
||||
}
|
||||
if (typeof window.feedBack.on === 'function') {
|
||||
window.feedBack.on('song:loading', _decayVerifiedOnSongLoad);
|
||||
}
|
||||
|
||||
// ---- Capability registration (mirrors capabilities/tuning.js) ----------------
|
||||
if (capabilities && capabilities.version === 1 &&
|
||||
!(window.feedBack.workingTuning && window.feedBack.workingTuning.version === 1)) {
|
||||
capabilities.registerOwner('working-tuning', {
|
||||
description: 'The live, host-authoritative current instrument tuning (session state), per ' +
|
||||
'instrument: offsets + string-count + reference pitch + assumed/verified provenance. ' +
|
||||
'Written by the tuner, read by the highway/library/Virtuoso/minigames.',
|
||||
operations: ['get-working-tuning', 'set-working-tuning'],
|
||||
events: ['working-tuning-changed'],
|
||||
kind: 'command',
|
||||
ownership: 'exclusive-owner',
|
||||
});
|
||||
capabilities.registerParticipant('plugin.tuner', {
|
||||
'working-tuning': {
|
||||
roles: ['contributor', 'requester'],
|
||||
operations: ['get-working-tuning', 'set-working-tuning'],
|
||||
emits: ['working-tuning-changed'],
|
||||
mode: 'active',
|
||||
compatibility: 'none',
|
||||
safety: 'safe',
|
||||
},
|
||||
});
|
||||
capabilities.registerParticipant('core.settings.instruments', {
|
||||
'working-tuning': {
|
||||
roles: ['requester'],
|
||||
operations: ['get-working-tuning'],
|
||||
events: ['working-tuning-changed'],
|
||||
mode: 'active',
|
||||
compatibility: 'none',
|
||||
safety: 'safe',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ---- Public read/write surface (attached defensively, like feedBack.theme) ----
|
||||
window.feedBack.workingTuning = Object.freeze({
|
||||
version: 1,
|
||||
get: get,
|
||||
set: set,
|
||||
setCurrentInstrument: setCurrentInstrument,
|
||||
resetToDefault: resetToDefault,
|
||||
getLaunchDefault: getLaunchDefault,
|
||||
setLaunchDefault: setLaunchDefault,
|
||||
clearLaunchDefault: clearLaunchDefault,
|
||||
});
|
||||
|
||||
_seedFromSettings();
|
||||
})();
|
||||
+2
-1
@@ -24,6 +24,7 @@
|
||||
<script src="/static/capabilities.js"></script>
|
||||
<script src="/static/capabilities/library.js"></script>
|
||||
<script src="/static/capabilities/tuning.js"></script>
|
||||
<script src="/static/capabilities/working-tuning.js"></script>
|
||||
<script src="/static/capabilities/audio-session.js"></script>
|
||||
<script src="/static/capabilities/audio-effects.js"></script>
|
||||
<script src="/static/capabilities/playback.js"></script>
|
||||
@@ -71,7 +72,7 @@
|
||||
|
||||
<!-- Hidden file input shared by the navbar "Upload" link. Kept at body
|
||||
level so it stays reachable regardless of which screen is active. -->
|
||||
<input type="file" id="upload-songs-file" accept=".sloppak" multiple class="hidden" onchange="uploadSongs(this.files); this.value=''">
|
||||
<input type="file" id="upload-songs-file" accept=".feedpak,.sloppak" multiple class="hidden" onchange="uploadSongs(this.files); this.value=''">
|
||||
|
||||
<!-- ══ HOME (Hero + Library) ══════════════════════════════════════════ -->
|
||||
<div id="home" class="screen active">
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
+147
-5
@@ -25,6 +25,13 @@
|
||||
// Tuning names per instrument key (e.g. 'guitar-6', 'bass-4'), loaded from
|
||||
// GET /api/tunings. Falls back to empty arrays until the fetch resolves.
|
||||
let _tuningsByKey = {};
|
||||
// Last instrument-coverage report for the current song (from the tuner plugin) —
|
||||
// drives a passive "different tuning" cue on the tuner badge. null = covered /
|
||||
// unknown / off the player.
|
||||
let _lastCoverageReport = null;
|
||||
// Monotonic token so a slow coverage fetch can't restore a stale cue after a newer
|
||||
// song started loading / we left the player. Bumped on every refresh and clear.
|
||||
let _coverageCueToken = 0;
|
||||
function _tuningsForKey(key) { return Object.keys(_tuningsByKey[key] || {}); }
|
||||
function _tuningsForInstrument(instrument, string_count) {
|
||||
return _tuningsForKey(instrument + '-' + string_count);
|
||||
@@ -53,6 +60,52 @@
|
||||
return typeof settings.tuning === 'string' ? settings.tuning : 'Custom';
|
||||
}
|
||||
|
||||
// The SELECTED instrument's live working tuning (host `workingTuning` capability).
|
||||
// Feature-detected: returns null when the host doesn't expose it, so the card
|
||||
// quietly falls back to the profile tuning. `offsets` are named via the shared
|
||||
// displayTuningName resolver; "home" = still in the profile/default tuning.
|
||||
function workingTuningInfo() {
|
||||
var wt = window.feedBack && window.feedBack.workingTuning;
|
||||
var st = wt && typeof wt.get === 'function' ? wt.get() : null;
|
||||
if (!st) return null;
|
||||
var offsets = Array.isArray(st.offsets) ? st.offsets : null;
|
||||
var nameFor = window.displayTuningName
|
||||
|| (window.feedBack && window.feedBack.displayTuningName);
|
||||
// Resolve BOTH the home tuning and the working tuning through the SAME namer so
|
||||
// "home?" is a like-for-like comparison — comparing a raw settings string ('Custom'
|
||||
// / 'E Standard') against a from-offsets name would mislabel a real home tuning.
|
||||
var homeLabel = (typeof nameFor === 'function')
|
||||
? (nameFor(typeof settings.tuning === 'string' ? settings.tuning : null,
|
||||
Array.isArray(settings.tuning) ? settings.tuning : null) || tuningLabel())
|
||||
: tuningLabel();
|
||||
var label = (offsets && typeof nameFor === 'function') ? nameFor(null, offsets) : homeLabel;
|
||||
return {
|
||||
label: label,
|
||||
short: label.replace(/ Standard\b/, ' Std').replace(/Custom Tuning/, 'Custom'),
|
||||
// Home = no explicit working offsets, OR the working tuning names the same as
|
||||
// the profile's home tuning (both via `nameFor`, so the compare is consistent).
|
||||
isHome: !offsets || label === homeLabel,
|
||||
provenance: st.provenance === 'verified' ? 'verified' : 'assumed',
|
||||
};
|
||||
}
|
||||
|
||||
// Honesty glyph: a hollow diamond for an assumed tuning, a filled one for a
|
||||
// per-string mic-verified tuning (see the workingTuning provenance flag).
|
||||
function provenanceGlyph(p) {
|
||||
return p === 'verified'
|
||||
? '<span title="Verified by a per-string mic check" class="text-emerald-400">◆</span>'
|
||||
: '<span title="Assumed — not mic-verified" class="text-fb-textDim">◇</span>';
|
||||
}
|
||||
|
||||
// Tell the host which instrument is now selected, so workingTuning.get()
|
||||
// surfaces THIS instrument's own remembered tuning. No-op without the capability.
|
||||
function setWorkingInstrument(inst, sc) {
|
||||
var wt = window.feedBack && window.feedBack.workingTuning;
|
||||
if (wt && typeof wt.setCurrentInstrument === 'function') {
|
||||
try { wt.setCurrentInstrument(inst, sc); } catch (_) { /* noop */ }
|
||||
}
|
||||
}
|
||||
|
||||
let settings = { instrument: 'guitar', string_count: 6, tuning: 'Standard', reference_pitch: 440 };
|
||||
|
||||
async function loadTunings() {
|
||||
@@ -122,13 +175,14 @@
|
||||
accepted = !(body && body.error);
|
||||
}
|
||||
} catch (e) { /* non-fatal — leave settings unchanged */ }
|
||||
if (!accepted) return;
|
||||
if (!accepted) return false;
|
||||
Object.assign(settings, patch);
|
||||
if (sm && sm.emit) sm.emit('instrument:changed', {
|
||||
instrument: settings.instrument, stringCount: settings.string_count, tuning: settings.tuning,
|
||||
});
|
||||
pushToTuner();
|
||||
renderTuner(); // reflect new tuning on the tuner card
|
||||
return true;
|
||||
}
|
||||
|
||||
// Drive the tuner plugin's instrument + tuning from the selection.
|
||||
@@ -257,6 +311,52 @@
|
||||
openTuner();
|
||||
});
|
||||
_applyFrame(_lastFrame);
|
||||
_applyCoverageCue(_lastCoverageReport);
|
||||
}
|
||||
|
||||
// Passive "different tuning" cue on the tuner badge: an amber ring + a tooltip
|
||||
// naming the retune (e.g. "B→A"). The diff comes from the tuner plugin's coverage
|
||||
// report; an absent plugin or a covered song → no cue. CSS-free (inline ring +
|
||||
// native title) so it needs no Tailwind rebuild, and it never auto-opens the
|
||||
// panel — it's advisory; the user taps the badge to tune.
|
||||
function _applyCoverageCue(report) {
|
||||
const btn = document.querySelector('#v3-badge-tuner [data-open-tuner]');
|
||||
if (!btn) return;
|
||||
const needs = !!(report && !report.covered);
|
||||
btn.style.boxShadow = needs ? '0 0 0 2px #fbbf24' : '';
|
||||
if (!needs) { btn.title = 'Open tuner'; return; }
|
||||
const summary = report.cantCover ? 'a different instrument'
|
||||
: (report.retune && report.retune.length)
|
||||
? report.retune.map((d) => d.from + '→' + d.to).join(', ')
|
||||
: 'the reference pitch';
|
||||
btn.title = 'This song needs a different tuning — retune ' + summary + '. Click to tune.';
|
||||
}
|
||||
|
||||
// A coverage report only drives the cue when it carries an actual signal: covered
|
||||
// (clears the ring) or a nameable mismatch (retune / reference / cantCover). The
|
||||
// plugin returns a conservative all-false report on a fetch hiccup / missing data —
|
||||
// that's "unknown", NOT "needs retune", so collapse it to null (no cue) rather than
|
||||
// painting an amber "retune the reference pitch" ring with no evidence.
|
||||
function _meaningfulReport(report) {
|
||||
if (!report) return null;
|
||||
if (report.covered) return report;
|
||||
if (report.cantCover || report.reference || (report.retune && report.retune.length)) return report;
|
||||
return null;
|
||||
}
|
||||
|
||||
async function _refreshCoverageCue() {
|
||||
const myToken = ++_coverageCueToken;
|
||||
const songInfo = window.highway && window.highway.getSongInfo && window.highway.getSongInfo();
|
||||
const api = window._tunerAutoOpen;
|
||||
if (!songInfo || !api || typeof api.coverageReport !== 'function') {
|
||||
_lastCoverageReport = null; _applyCoverageCue(null); return;
|
||||
}
|
||||
let report = null;
|
||||
try { report = await api.coverageReport(songInfo); }
|
||||
catch (_e) { report = null; }
|
||||
if (myToken !== _coverageCueToken) return; // superseded by a newer song / a clear
|
||||
_lastCoverageReport = _meaningfulReport(report);
|
||||
_applyCoverageCue(_lastCoverageReport);
|
||||
}
|
||||
|
||||
// ── Instrument selector card (Stitch RightInstrumentSelector) ──────────--
|
||||
@@ -290,14 +390,29 @@
|
||||
function renderInstrument() {
|
||||
const host = document.getElementById('v3-badge-instrument');
|
||||
if (!host) return;
|
||||
const wt = workingTuningInfo();
|
||||
host.innerHTML =
|
||||
'<div id="v3-instrument-wrap" class="relative">' +
|
||||
'<button type="button" data-inst-toggle title="Instrument: ' + esc(settings.string_count + '-str ' + tuningLabel()) + '" ' +
|
||||
'class="bg-fb-card border border-fb-border/50 rounded-2xl h-[92px] w-16 flex flex-col items-center justify-center gap-2 hover:ring-1 hover:ring-fb-primary/40 transition">' +
|
||||
'<button type="button" data-inst-toggle title="Instrument: ' + esc(settings.string_count + '-str ' + (wt ? wt.label : tuningLabel())) + '" ' +
|
||||
'class="bg-fb-card border border-fb-border/50 rounded-2xl h-[92px] w-16 flex flex-col items-center justify-center gap-1.5 hover:ring-1 hover:ring-fb-primary/40 transition">' +
|
||||
guitarIcon +
|
||||
// Live working-tuning label: dim while you're still in your home tuning,
|
||||
// amber once you've retuned. Omitted if the host doesn't expose
|
||||
// workingTuning (feature-detect → the card looks exactly as before).
|
||||
(wt ? '<span class="text-[9px] leading-none font-semibold max-w-full truncate px-0.5 ' +
|
||||
(wt.isHome ? 'text-fb-textDim' : 'text-amber-400') + '">' + esc(wt.short) + '</span>' : '') +
|
||||
'<svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" stroke-width="3" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5"/></svg>' +
|
||||
'</button>' +
|
||||
'<div data-inst-menu class="hidden absolute right-0 mt-2 w-60 bg-fb-card border border-fb-border/50 rounded-xl shadow-xl p-3 z-50 space-y-3">' +
|
||||
// "Now in" banner + one-tap back-to-default — shown only once you've
|
||||
// retuned off your home tuning (workingTuning present and not home).
|
||||
((wt && !wt.isHome)
|
||||
? '<div class="flex items-center justify-between gap-2 pb-1 border-b border-fb-border/40">' +
|
||||
'<div class="min-w-0"><div class="text-[0.625rem] uppercase tracking-wider text-fb-textDim">Now in</div>' +
|
||||
'<div class="text-xs font-semibold text-amber-400 truncate flex items-center gap-1">' + esc(wt.label) + ' ' + provenanceGlyph(wt.provenance) + '</div></div>' +
|
||||
'<button type="button" data-inst-reset title="Reset this instrument to its home tuning" class="shrink-0 text-[11px] text-fb-textDim hover:text-fb-text border border-fb-border/40 hover:border-fb-border/70 rounded-md px-2 py-1 transition-colors">Back to default</button>' +
|
||||
'</div>'
|
||||
: '') +
|
||||
instRow('Instrument', ['guitar', 'bass'].map((v) =>
|
||||
pill('inst', v, v[0].toUpperCase() + v.slice(1), settings.instrument === v)).join('')) +
|
||||
instRow('Strings', STRING_COUNTS[settings.instrument].map((v) =>
|
||||
@@ -335,20 +450,32 @@
|
||||
// unsupported instrument+tuning combo.
|
||||
const newSc = counts.includes(settings.string_count) ? settings.string_count : counts[0];
|
||||
const tunings = _tuningsForInstrument(v, newSc);
|
||||
await saveSettings({
|
||||
const ok = await saveSettings({
|
||||
instrument: v,
|
||||
string_count: newSc,
|
||||
tuning: tunings.includes(settings.tuning) ? settings.tuning : (tunings[0] || settings.tuning),
|
||||
});
|
||||
// Only move the working-tuning context once the switch was actually persisted —
|
||||
// otherwise the selector stays on the old instrument while the card shows the
|
||||
// new one's tuning (settings and workingTuning desync on a rejected save).
|
||||
if (ok) setWorkingInstrument(v, newSc); // surface THIS instrument's own working tuning
|
||||
renderInstrument(); keepOpen();
|
||||
}));
|
||||
menu.querySelectorAll('[data-pill="strings"]').forEach((b) => b.addEventListener('click', async () => {
|
||||
await saveSettings({ string_count: Number(b.getAttribute('data-val')) }); renderInstrument(); keepOpen();
|
||||
await saveSettings({ string_count: Number(b.getAttribute('data-val')) });
|
||||
setWorkingInstrument(settings.instrument, settings.string_count);
|
||||
renderInstrument(); keepOpen();
|
||||
}));
|
||||
menu.querySelector('[data-inst-tuning]').addEventListener('change', (e) => saveSettings({ tuning: e.target.value }));
|
||||
const ref = menu.querySelector('[data-inst-ref]');
|
||||
ref.addEventListener('input', (e) => { menu.querySelector('[data-ref-val]').textContent = e.target.value + ' Hz'; });
|
||||
ref.addEventListener('change', (e) => saveSettings({ reference_pitch: Number(e.target.value) }));
|
||||
const resetBtn = menu.querySelector('[data-inst-reset]');
|
||||
if (resetBtn) resetBtn.addEventListener('click', () => {
|
||||
const wtCap = window.feedBack && window.feedBack.workingTuning;
|
||||
if (wtCap && typeof wtCap.resetToDefault === 'function') wtCap.resetToDefault();
|
||||
renderInstrument(); keepOpen();
|
||||
});
|
||||
}
|
||||
function instRow(label, inner) {
|
||||
return '<div><div class="text-[10px] uppercase tracking-wider text-fb-textDim mb-1">' + label + '</div><div class="flex flex-wrap gap-1">' + inner + '</div></div>';
|
||||
@@ -362,6 +489,11 @@
|
||||
|
||||
async function boot() {
|
||||
await Promise.all([loadTunings(), loadSettings()]);
|
||||
// NB: we deliberately do NOT call setWorkingInstrument() here. The host seeds its
|
||||
// current instrument from the same /api/settings on boot and emits
|
||||
// working-tuning-changed on hydration (which re-renders this card), so the card
|
||||
// aligns without us pre-touching the state — calling setCurrentInstrument() early
|
||||
// would set the capability's `_touched` flag and suppress that seed.
|
||||
renderInstrument();
|
||||
renderTuner();
|
||||
pushToTuner(); // sync the tuner to the persisted selection on load
|
||||
@@ -374,6 +506,16 @@
|
||||
await loadTunings();
|
||||
renderInstrument();
|
||||
});
|
||||
// Passive coverage cue: recompute when a song is ready; clear when a new
|
||||
// song starts loading or we leave the player screen.
|
||||
sm.on('song:ready', () => { _refreshCoverageCue(); });
|
||||
sm.on('song:loading', () => { _coverageCueToken++; _lastCoverageReport = null; _applyCoverageCue(null); });
|
||||
sm.on('screen:changed', (e) => {
|
||||
if (!e || !e.detail || e.detail.id !== 'player') { _coverageCueToken++; _lastCoverageReport = null; _applyCoverageCue(null); }
|
||||
});
|
||||
// The tuner (or a reset) changed the live working tuning → re-render the
|
||||
// card label + the "Now in" banner. No-op if the host lacks the capability.
|
||||
sm.on('working-tuning-changed', () => renderInstrument());
|
||||
}
|
||||
}
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot, { once: true });
|
||||
|
||||
@@ -87,6 +87,7 @@
|
||||
<script src="/static/capabilities.js"></script>
|
||||
<script src="/static/capabilities/library.js"></script>
|
||||
<script src="/static/capabilities/tuning.js"></script>
|
||||
<script src="/static/capabilities/working-tuning.js"></script>
|
||||
<script src="/static/capabilities/audio-session.js"></script>
|
||||
<script src="/static/capabilities/audio-effects.js"></script>
|
||||
<script src="/static/capabilities/playback.js"></script>
|
||||
|
||||
+13
-2
@@ -139,19 +139,30 @@
|
||||
'<button id="v3-pl-back" class="text-sm text-fb-textDim hover:text-fb-text mb-4">← Playlists</button>' +
|
||||
'<div class="flex items-center justify-between mb-6 gap-3">' +
|
||||
'<h2 class="text-3xl font-bold text-fb-text truncate">' + esc(pl.name) + '</h2>' +
|
||||
'<div class="flex gap-2 shrink-0 items-center">' +
|
||||
(pl.songs.length ? '<button id="v3-pl-playall" class="bg-fb-primary hover:bg-fb-primaryHi text-white text-sm font-medium px-4 py-2 rounded-md">▶ Play all</button>' : '') +
|
||||
(isSystem ? '' :
|
||||
'<div class="flex gap-2 shrink-0">' +
|
||||
'<button id="v3-pl-cover" class="text-sm text-fb-textDim hover:text-fb-text px-2">Cover</button>' +
|
||||
(pl.cover_url ? '<button id="v3-pl-cover-rm" class="text-sm text-fb-textDim hover:text-fb-accent px-2">Remove cover</button>' : '') +
|
||||
'<button id="v3-pl-rename" class="text-sm text-fb-textDim hover:text-fb-text px-2">Rename</button>' +
|
||||
'<button id="v3-pl-delete" class="text-sm text-fb-textDim hover:text-fb-accent px-2">Delete</button>' +
|
||||
'<input type="file" id="v3-pl-cover-file" accept="image/*" class="hidden"></div>') +
|
||||
'<input type="file" id="v3-pl-cover-file" accept="image/*" class="hidden">') +
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
(pl.songs.length
|
||||
? '<ul id="v3-pl-songs" class="space-y-1">' + pl.songs.map((s) => songRow(s, { draggable: !isSystem })).join('') + '</ul>'
|
||||
: '<p class="text-fb-textDim">Empty — add songs from the library.</p>') +
|
||||
'</div>';
|
||||
root.querySelector('#v3-pl-back')?.addEventListener('click', renderPlaylists);
|
||||
// Play all: start the play-queue with this playlist's songs (auto-advances
|
||||
// track to track). Falls back to playing the first song on an older core
|
||||
// without the queue, so the button always does something.
|
||||
root.querySelector('#v3-pl-playall')?.addEventListener('click', () => {
|
||||
const files = (pl.songs || []).map((s) => s.filename).filter(Boolean);
|
||||
if (!files.length) return;
|
||||
if (window.feedBack && window.feedBack.playQueue) window.feedBack.playQueue.start(files, { source: pl.name });
|
||||
else if (typeof window.playSong === 'function') window.playSong(encodeURIComponent(files[0]));
|
||||
});
|
||||
const listEl = root.querySelector('#v3-pl-songs');
|
||||
if (listEl) wireSongRows(listEl, pid, () => renderPlaylistDetail(pid));
|
||||
root.querySelector('#v3-pl-rename')?.addEventListener('click', async () => {
|
||||
|
||||
+260
-29
@@ -35,6 +35,9 @@
|
||||
['title', 'Title A–Z'], ['title-desc', 'Title Z–A'],
|
||||
['recent', 'Recently Added'], ['year-desc', 'Year (newest)'],
|
||||
['year', 'Year (oldest)'], ['tuning', 'Tuning'],
|
||||
// Mastery = best accuracy across arrangements (song_stats); unscored songs
|
||||
// sort last either way. Ascending surfaces what needs work; never default.
|
||||
['mastery', 'Needs practice first'], ['mastery-desc', 'Most mastered first'],
|
||||
];
|
||||
const FORMATS = [['', 'All formats'], ['sloppak', 'Feedpak'], ['loose', 'Folder']];
|
||||
const ARRANGEMENTS = ['Lead', 'Rhythm', 'Bass', 'Combo', 'Vocals'];
|
||||
@@ -54,7 +57,7 @@
|
||||
const state = {
|
||||
provider: 'local', view: 'grid', sort: 'artist', format: '', q: '',
|
||||
artist: '', album: '',
|
||||
filters: { arr_has: [], arr_lacks: [], stem_has: [], stem_lacks: [], lyrics: '', tunings: [] },
|
||||
filters: { arr_has: [], arr_lacks: [], stem_has: [], stem_lacks: [], lyrics: '', tunings: [], mastery: [] },
|
||||
page: 0, total: 0, loading: false, built: false, accuracy: {}, tuningNames: [],
|
||||
artistCatalog: [], renderedHash: '',
|
||||
scrollBound: false,
|
||||
@@ -104,7 +107,8 @@
|
||||
function activeFilterCount() {
|
||||
const f = state.filters;
|
||||
return f.arr_has.length + f.arr_lacks.length + f.stem_has.length + f.stem_lacks.length +
|
||||
(f.lyrics ? 1 : 0) + f.tunings.length + (state.artist ? 1 : 0) + (state.album ? 1 : 0);
|
||||
(f.lyrics ? 1 : 0) + f.tunings.length + (f.mastery ? f.mastery.length : 0) +
|
||||
(state.artist ? 1 : 0) + (state.album ? 1 : 0);
|
||||
}
|
||||
|
||||
function _getV3MainScroller() { return document.getElementById('v3-main'); }
|
||||
@@ -126,6 +130,7 @@
|
||||
stem_lacks: [...(f.stem_lacks || [])].sort(),
|
||||
lyrics: f.lyrics || '',
|
||||
tunings: [...(f.tunings || [])].sort(),
|
||||
mastery: [...(f.mastery || [])].sort(),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -239,6 +244,7 @@
|
||||
if (f.stem_lacks.length) p.set('stems_lacks', f.stem_lacks.join(','));
|
||||
if (f.lyrics) p.set('has_lyrics', f.lyrics);
|
||||
if (f.tunings.length) p.set('tunings', f.tunings.join(','));
|
||||
if (f.mastery && f.mastery.length) p.set('mastery', f.mastery.join(','));
|
||||
Object.entries(extra || {}).forEach(([k, v]) => p.set(k, v));
|
||||
return p;
|
||||
}
|
||||
@@ -648,6 +654,41 @@
|
||||
'<button data-arr="' + esc(a.index != null ? a.index : '') + '" title="Play ' + esc(a.name) + '" class="text-[10px] px-1.5 py-0.5 rounded bg-gray-800/60 text-fb-textDim hover:bg-fb-primary hover:text-white transition">' + esc(a.name) + '</button>').join('');
|
||||
}
|
||||
|
||||
// ── Tuning-match flags (working-tuning PR 6) ───────────────────────────────
|
||||
// Colour each song's tuning chip by whether your CURRENT working tuning covers
|
||||
// it: green = play it now, amber = needs a retune. Uses the tuner plugin's
|
||||
// coverage check (async) + the host workingTuning state — BOTH feature-detected,
|
||||
// so without them the chips render exactly as before. Decoration runs AFTER the
|
||||
// (sync) window paint so scrolling stays snappy; a token cancels a superseded pass.
|
||||
let _tuningDecorToken = 0;
|
||||
function _applyChipMatch(chip, stateName) {
|
||||
chip.classList.remove('bg-fb-mid', 'bg-emerald-500', 'bg-amber-400');
|
||||
chip.classList.add(stateName === 'match' ? 'bg-emerald-500'
|
||||
: stateName === 'retune' ? 'bg-amber-400' : 'bg-fb-mid');
|
||||
if (!chip.dataset.baseTitle) chip.dataset.baseTitle = chip.getAttribute('title') || '';
|
||||
chip.setAttribute('title', chip.dataset.baseTitle + (stateName === 'match'
|
||||
? ' — matches your tuning' : stateName === 'retune' ? ' — needs a retune' : ''));
|
||||
}
|
||||
async function decorateTuningChips(grid) {
|
||||
if (!grid) return;
|
||||
const cov = window._tunerAutoOpen && window._tunerAutoOpen.coverageReport;
|
||||
const hasWT = window.feedBack && window.feedBack.workingTuning
|
||||
&& typeof window.feedBack.workingTuning.get === 'function';
|
||||
if (typeof cov !== 'function' || !hasWT) return; // feature-detect → no flags
|
||||
const token = ++_tuningDecorToken;
|
||||
const chips = grid.querySelectorAll('[data-tuning-chip][data-tuning-offsets]');
|
||||
for (const chip of chips) {
|
||||
const offs = chip.getAttribute('data-tuning-offsets').split(',').map(Number);
|
||||
if (!offs.length || offs.some((n) => !isFinite(n))) continue;
|
||||
// Pass the instrument so coverage uses the right base pitches (bass vs guitar).
|
||||
const arrangement = chip.dataset.tuningBass === '1' ? 'Bass' : 'Lead';
|
||||
let rep = null;
|
||||
try { rep = await cov({ tuning: offs, stringCount: offs.length, arrangement: arrangement }); } catch (_) { rep = null; }
|
||||
if (token !== _tuningDecorToken) return; // superseded by a re-paint / tuning change
|
||||
if (rep) _applyChipMatch(chip, rep.covered ? 'match' : 'retune');
|
||||
}
|
||||
}
|
||||
|
||||
function songCard(song) {
|
||||
const fav = song.favorite;
|
||||
const key = cardKey(song);
|
||||
@@ -670,11 +711,22 @@
|
||||
? ('Custom Tuning: ' + targetNotes)
|
||||
: tuningLabel;
|
||||
const pos = 'absolute top-2 ' + (state.selectMode ? 'left-9' : 'left-2');
|
||||
// Tag the chip with its offsets so decorateTuningChips() can colour it
|
||||
// green (matches your current tuning) / amber (needs a retune) after paint.
|
||||
// Also flag a bass-only song (every arrangement is a bass part) so coverage
|
||||
// scores its bass tuning against the bass base pitches, not guitar — otherwise
|
||||
// a 4-string bass tuning read as guitar can false-match a guitar player.
|
||||
const chipArrs = song.arrangements || [];
|
||||
const chipIsBass = chipArrs.length > 0
|
||||
&& chipArrs.every((a) => /\bbass\b/i.test((a && a.name) || ''));
|
||||
const matchAttr = (rawOffsets && rawOffsets.length)
|
||||
? ' data-tuning-chip data-tuning-offsets="' + esc(rawOffsets.join(',')) + '"'
|
||||
+ (chipIsBass ? ' data-tuning-bass="1"' : '') : '';
|
||||
if (targetNotes) {
|
||||
tuning = '<span class="' + pos + ' bg-fb-mid text-black text-[9px] font-bold px-1.5 py-0.5 rounded-sm leading-tight max-w-[5.5rem] text-center" title="' + esc(badgeTitle) + '">'
|
||||
tuning = '<span class="' + pos + ' bg-fb-mid text-black text-[9px] font-bold px-1.5 py-0.5 rounded-sm leading-tight max-w-[5.5rem] text-center"' + matchAttr + ' title="' + esc(badgeTitle) + '">'
|
||||
+ esc('Custom Tuning') + '<br><span class="font-semibold tracking-wide">' + esc(targetNotes) + '</span></span>';
|
||||
} else {
|
||||
tuning = '<span class="' + pos + ' bg-fb-mid text-black text-[10px] font-bold px-1.5 py-0.5 rounded-sm" title="' + esc(badgeTitle) + '">' + esc(tuningLabel) + '</span>';
|
||||
tuning = '<span class="' + pos + ' bg-fb-mid text-black text-[10px] font-bold px-1.5 py-0.5 rounded-sm"' + matchAttr + ' title="' + esc(badgeTitle) + '">' + esc(tuningLabel) + '</span>';
|
||||
}
|
||||
}
|
||||
// Display-only (pointer-events-none) so a click falls through to the
|
||||
@@ -859,33 +911,122 @@
|
||||
finishBatch();
|
||||
}
|
||||
|
||||
// Prompt for a target playlist (pick a listed number, or type a new name to
|
||||
// create it) and add the given song filenames to it. Shared by the
|
||||
// select-mode batch bar and the per-card ⋮ menu's single-song add. Returns
|
||||
// the playlist id (or null if cancelled).
|
||||
// Modern "Add to playlist" picker - replaces the old run-on numbered prompt
|
||||
// ("1. Foo 2. Bar ...", which didn't scale past a couple of playlists). Shows a
|
||||
// checkbox list of playlists with membership PRE-CHECK (a song already in a
|
||||
// playlist shows checked; a multi-song selection shows the indeterminate box
|
||||
// when only some are in), an inline "New playlist" row, and a search box once
|
||||
// the list is long. Toggling a row adds/removes the given songs via the
|
||||
// existing REST; only rows the user actually TOUCHED are changed. Resolves
|
||||
// true if any change was applied, else null (cancelled / no-op). Shared by the
|
||||
// per-card more-menu and the select-mode batch bar.
|
||||
function openPlaylistPicker(fns) {
|
||||
return new Promise((resolve) => { (async () => {
|
||||
const lists = ((await jget('/api/playlists')) || []).filter((p) => !p.system_key);
|
||||
// Pre-check membership: fetch each playlist's songs once (playlists are
|
||||
// few, and this is a one-off on open, not a hot path). ALL selected in
|
||||
// -> checked; SOME -> indeterminate.
|
||||
const counts = await Promise.all(lists.map(async (p) => {
|
||||
const pl = await jget('/api/playlists/' + p.id);
|
||||
const has = new Set(((pl && pl.songs) || []).map((s) => s.filename));
|
||||
return fns.reduce((n, fn) => n + (has.has(fn) ? 1 : 0), 0);
|
||||
}));
|
||||
const rows = lists.map((p, i) => ({
|
||||
id: p.id, name: p.name, count: p.count || 0,
|
||||
initial: counts[i] === fns.length ? 'all' : (counts[i] > 0 ? 'some' : 'none'),
|
||||
checked: counts[i] === fns.length, touched: false,
|
||||
}));
|
||||
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'fixed inset-0 z-[200] bg-black/60 backdrop-blur-sm flex items-center justify-center p-4';
|
||||
let query = '';
|
||||
const onKey = (e) => { if (e.key === 'Escape') { e.preventDefault(); done(null); } };
|
||||
function done(applied) { overlay.remove(); document.removeEventListener('keydown', onKey); resolve(applied || null); }
|
||||
document.addEventListener('keydown', onKey);
|
||||
overlay.addEventListener('click', (e) => { if (e.target === overlay) done(null); });
|
||||
|
||||
const boxFor = (r) => r.touched ? (r.checked ? '☑' : '☐')
|
||||
: (r.initial === 'all' ? '☑' : r.initial === 'some' ? '▣' : '☐');
|
||||
function rowHtml(r) {
|
||||
return '<button type="button" data-pl="' + esc(String(r.id)) + '" class="w-full flex items-center gap-3 px-3 py-2 rounded-md hover:bg-white/5 text-left">' +
|
||||
'<span class="text-lg leading-none w-5 text-fb-primary">' + boxFor(r) + '</span>' +
|
||||
'<span class="flex-1 truncate text-sm text-fb-text">' + esc(r.name) + '</span>' +
|
||||
'<span class="text-xs text-fb-textDim">' + (r.count || 0) + '</span></button>';
|
||||
}
|
||||
function listHtml() {
|
||||
const q = query.trim().toLowerCase();
|
||||
const shown = q ? rows.filter((r) => r.name.toLowerCase().includes(q)) : rows;
|
||||
if (!shown.length) return '<p class="text-sm text-fb-textDim text-center py-6">' + (rows.length ? 'No matches.' : 'No playlists yet - create one above.') + '</p>';
|
||||
return shown.map(rowHtml).join('');
|
||||
}
|
||||
function bindRows() {
|
||||
overlay.querySelectorAll('[data-pl]').forEach((b) => b.addEventListener('click', () => {
|
||||
const r = rows.find((x) => String(x.id) === b.getAttribute('data-pl'));
|
||||
if (!r) return;
|
||||
r.touched = true; r.checked = !r.checked;
|
||||
repaintList();
|
||||
}));
|
||||
}
|
||||
function repaintList() { const el = overlay.querySelector('[data-list]'); if (el) { el.innerHTML = listHtml(); bindRows(); } }
|
||||
async function createNew() {
|
||||
const inp = overlay.querySelector('[data-new]');
|
||||
const name = ((inp && inp.value) || '').trim();
|
||||
if (!name) return;
|
||||
const created = await jsend('POST', '/api/playlists', { name });
|
||||
if (created && created.id) {
|
||||
rows.unshift({ id: created.id, name: created.name || name, count: 0, initial: 'none', checked: true, touched: true });
|
||||
query = ''; paint();
|
||||
overlay.querySelector('[data-new]')?.focus();
|
||||
}
|
||||
}
|
||||
async function apply() {
|
||||
// Act only where the final state differs from what's already stored.
|
||||
const acts = rows.filter((r) => r.touched && ((r.checked && r.initial !== 'all') || (!r.checked && r.initial !== 'none')));
|
||||
for (const r of acts) {
|
||||
for (const fn of fns) {
|
||||
try {
|
||||
if (r.checked) await fetch('/api/playlists/' + r.id + '/songs', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ filename: fn }) });
|
||||
else await fetch('/api/playlists/' + r.id + '/songs/' + encodeURIComponent(fn), { method: 'DELETE' });
|
||||
} catch (e) { /* */ }
|
||||
}
|
||||
}
|
||||
if (window.v3Playlists) { try { window.v3Playlists.refresh(); } catch (e) { /* */ } }
|
||||
if (acts.length && window.fbNotify) {
|
||||
try { window.fbNotify.show({ title: 'Playlists updated', message: 'Updated ' + acts.length + ' playlist' + (acts.length === 1 ? '' : 's'), icon: '\U0001f3b5' }); } catch (e) { /* */ }
|
||||
}
|
||||
done(acts.length ? true : null);
|
||||
}
|
||||
function paint() {
|
||||
overlay.innerHTML =
|
||||
'<div class="bg-fb-card rounded-xl border border-fb-border/50 w-full max-w-md p-5 space-y-4" role="dialog" aria-label="Add to playlist">' +
|
||||
'<div class="flex items-center justify-between"><h3 class="text-lg font-semibold text-fb-text">Add ' + fns.length + ' song' + (fns.length === 1 ? '' : 's') + ' to playlist</h3>' +
|
||||
'<button type="button" data-x class="text-fb-textDim hover:text-fb-text text-xl leading-none">✕</button></div>' +
|
||||
'<div class="flex gap-2"><input data-new type="text" placeholder="+ New playlist name" class="' + btnCtrl + ' flex-1"><button type="button" data-create class="bg-fb-card/60 hover:bg-fb-card border border-fb-border/50 text-fb-text px-3 rounded-md text-sm">Create</button></div>' +
|
||||
(rows.length > 8 ? '<input data-search type="text" placeholder="Search playlists..." class="' + btnCtrl + ' w-full" value="' + esc(query) + '">' : '') +
|
||||
'<div data-list class="max-h-72 overflow-y-auto v3-scroll -mx-1 px-1">' + listHtml() + '</div>' +
|
||||
'<div class="flex justify-end"><button type="button" data-done class="bg-fb-primary hover:bg-fb-primaryHi text-white text-sm font-medium px-5 py-2 rounded-md">Done</button></div>' +
|
||||
'</div>';
|
||||
overlay.querySelector('[data-x]').addEventListener('click', () => done(null));
|
||||
overlay.querySelector('[data-done]').addEventListener('click', apply);
|
||||
overlay.querySelector('[data-create]').addEventListener('click', createNew);
|
||||
overlay.querySelector('[data-new]').addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); createNew(); } });
|
||||
const s = overlay.querySelector('[data-search]');
|
||||
if (s) s.addEventListener('input', (e) => { query = e.target.value; repaintList(); });
|
||||
bindRows();
|
||||
}
|
||||
|
||||
document.body.appendChild(overlay);
|
||||
paint();
|
||||
(overlay.querySelector('[data-search]') || overlay.querySelector('[data-new]'))?.focus();
|
||||
})(); });
|
||||
}
|
||||
|
||||
// Open the picker for the given song filenames. Shared by the select-mode
|
||||
// batch bar and the per-card more-menu. Resolves truthy if a change was applied.
|
||||
async function addFilenamesToPlaylist(filenames) {
|
||||
const fns = Array.from(filenames || []);
|
||||
if (!fns.length) return null;
|
||||
const lists = (await jget('/api/playlists')) || [];
|
||||
const choices = lists.filter((p) => !p.system_key);
|
||||
const labels = choices.map((p, i) => (i + 1) + '. ' + p.name).join(' ');
|
||||
const ans = ((await window.uiPrompt({
|
||||
title: 'Add ' + fns.length + ' song' + (fns.length === 1 ? '' : 's') + ' to a playlist',
|
||||
label: (labels ? labels + ' ' : '') + 'Type a number above, or a new playlist name:',
|
||||
okLabel: 'Add',
|
||||
placeholder: 'Number or new playlist name',
|
||||
})) || '').trim();
|
||||
if (!ans) return null;
|
||||
let pid = null;
|
||||
const num = parseInt(ans, 10);
|
||||
if (!isNaN(num) && choices[num - 1]) pid = choices[num - 1].id;
|
||||
else { const created = await jsend('POST', '/api/playlists', { name: ans }); pid = created && created.id; }
|
||||
if (!pid) return null;
|
||||
for (const fn of fns) {
|
||||
try { await fetch('/api/playlists/' + pid + '/songs', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ filename: fn }) }); } catch (e) { /* */ }
|
||||
}
|
||||
if (window.v3Playlists) { try { window.v3Playlists.refresh(); } catch (e) { /* */ } }
|
||||
return pid;
|
||||
return openPlaylistPicker(fns);
|
||||
}
|
||||
|
||||
async function batchAddToPlaylist() {
|
||||
@@ -1076,6 +1217,7 @@
|
||||
grid.style.top = (firstRow * rowH) + 'px';
|
||||
grid.innerHTML = _renderCardsRange(start, end);
|
||||
wireCards(grid);
|
||||
decorateTuningChips(grid); // colour tuning chips by working-tuning match (async, feature-detected)
|
||||
state.winRange = { start, end };
|
||||
state.renderedSelectMode = state.selectMode;
|
||||
if (sm && typeof sm.emit === 'function') {
|
||||
@@ -1453,6 +1595,8 @@
|
||||
section('Arrangements', ARRANGEMENTS.map((a) => triPill('arr', a, a, triState(f.arr_has, f.arr_lacks, a))).join('')) +
|
||||
section('Stems (sloppak)', STEMS.map((s) => triPill('stem', s, s, triState(f.stem_has, f.stem_lacks, s))).join('')) +
|
||||
section('Lyrics', ['', '1', '0'].map((v) => '<button data-lyrics="' + v + '" class="px-2 py-1 rounded-md text-xs border ' + (f.lyrics === v ? 'bg-fb-primary text-white border-fb-primary' : 'bg-gray-800/50 text-fb-textDim border-gray-700') + '">' + (v === '' ? 'Any' : v === '1' ? 'Has lyrics' : 'No lyrics') + '</button>').join('')) +
|
||||
// Progress (mastery bands) — multi-select; server filters via song_stats.
|
||||
section('Progress', [['mastered', 'Mastered'], ['in_progress', 'In progress'], ['not_started', 'Not started']].map((it) => '<button data-mastery="' + it[0] + '" class="px-2 py-1 rounded-md text-xs border ' + (f.mastery.includes(it[0]) ? 'bg-fb-primary text-white border-fb-primary' : 'bg-gray-800/50 text-fb-textDim border-gray-700') + '">' + it[1] + '</button>').join('')) +
|
||||
section('Tuning', (state.tuningNames || []).map((t) => {
|
||||
// Filter on the server's grouping key (raw offsets for customs)
|
||||
// so two "Custom Tuning" entries are distinct; show their target
|
||||
@@ -1484,10 +1628,11 @@
|
||||
renderDrawer();
|
||||
}));
|
||||
d.querySelectorAll('[data-lyrics]').forEach((b) => b.addEventListener('click', () => { f.lyrics = b.getAttribute('data-lyrics'); renderDrawer(); }));
|
||||
d.querySelectorAll('[data-mastery]').forEach((b) => b.addEventListener('click', () => { const v = b.getAttribute('data-mastery'); const i = f.mastery.indexOf(v); if (i >= 0) f.mastery.splice(i, 1); else f.mastery.push(v); renderDrawer(); }));
|
||||
d.querySelector('[data-drawer-save]')?.addEventListener('click', saveCurrentAsCollection);
|
||||
d.querySelector('[data-drawer-close]')?.addEventListener('click', closeDrawer);
|
||||
d.querySelector('[data-drawer-clear]')?.addEventListener('click', async () => {
|
||||
state.filters = { arr_has: [], arr_lacks: [], stem_has: [], stem_lacks: [], lyrics: '', tunings: [] };
|
||||
state.filters = { arr_has: [], arr_lacks: [], stem_has: [], stem_lacks: [], lyrics: '', tunings: [], mastery: [] };
|
||||
state.artist = '';
|
||||
state.album = '';
|
||||
renderDrawer();
|
||||
@@ -1615,6 +1760,7 @@
|
||||
'<select id="v3-songs-format" class="' + ctrl + '">' + opt(FORMATS, state.format) + '</select>' +
|
||||
'<button id="v3-songs-filters" class="relative ' + ctrl + ' flex items-center gap-2">Filters<span id="v3-songs-filter-count" class="hidden bg-fb-primary text-white text-xs rounded-full px-1.5">0</span></button>' +
|
||||
'<button id="v3-songs-select" class="' + ctrl + (state.selectMode ? ' bg-fb-primary text-white' : '') + '">Select</button>' +
|
||||
'<button id="v3-songs-refresh" title="Refresh library (scan for new songs)" class="' + ctrl + '">⟳ Refresh</button>' +
|
||||
'<button id="v3-songs-upload" class="' + ctrl + '">Upload</button>' +
|
||||
'</div></div></div>' +
|
||||
// Practice-aware library home: a repertoire progress meter + a
|
||||
@@ -1672,6 +1818,16 @@
|
||||
if (legacy) { legacy.click(); watchUploadScan(); }
|
||||
});
|
||||
byId('v3-songs-select').addEventListener('click', () => setSelectMode(!state.selectMode));
|
||||
byId('v3-songs-refresh')?.addEventListener('click', refreshLibrary);
|
||||
// Reflect a scan already in progress (Settings button or a background
|
||||
// pass) on the Refresh button, so its state isn't just tied to clicks here.
|
||||
(async () => {
|
||||
try {
|
||||
const r = await fetch('/api/scan-status');
|
||||
const sd = r.ok ? await r.json() : null;
|
||||
if (sd && sd.running) { _setRefreshState(sd); _watchScan({ announce: false }); }
|
||||
} catch (e) { /* */ }
|
||||
})();
|
||||
|
||||
// Bulletproof multi-select: in select mode, a capture-phase click on the
|
||||
// grid toggles the card and STOPS the event, so nothing (a per-card
|
||||
@@ -1801,6 +1957,73 @@
|
||||
// legacy screens, so without this newly-uploaded songs wouldn't appear in
|
||||
// v3 until a manual refresh. Bounded so a no-op upload can't poll forever.
|
||||
let _uploadScanTimer = null;
|
||||
// ── Library refresh (rescan) from the Songs toolbar ───────────────────────
|
||||
// The tester ask: a media-server-style "I dropped files in my folder, hit
|
||||
// refresh" button, with live progress. Reuses the SAME machinery the Settings
|
||||
// Rescan buttons drive (/api/rescan + /api/scan-status) and emits
|
||||
// library:changed so the grid reloads. A scan already running (Settings or a
|
||||
// background pass) is reflected on the button too.
|
||||
let _refreshPoll = null;
|
||||
function _setRefreshState(sd) {
|
||||
const btn = document.getElementById('v3-songs-refresh');
|
||||
if (!btn) return;
|
||||
if (sd && sd.running) {
|
||||
// Determinate count only exists in the 'scanning' stage; 'listing' is
|
||||
// indeterminate (total 0), so show a plain "Scanning…" then.
|
||||
const det = (sd.stage === 'scanning' && sd.total) ? ' ' + sd.done + '/' + sd.total : '';
|
||||
btn.textContent = '⟳ Scanning' + det + '…';
|
||||
btn.disabled = true;
|
||||
btn.classList.add('opacity-70');
|
||||
const pct = sd.total ? Math.round((sd.done / sd.total) * 100) + '% · ' : '';
|
||||
btn.title = 'Scanning new/changed songs… ' + pct + (sd.current || '');
|
||||
} else {
|
||||
btn.textContent = '⟳ Refresh';
|
||||
btn.disabled = false;
|
||||
btn.classList.remove('opacity-70');
|
||||
btn.title = 'Refresh library (scan for new songs)';
|
||||
}
|
||||
}
|
||||
// Show a completion toast (reuses the shared fbNotify surface), suppressed
|
||||
// while in a song. Honest + never-punishing copy; the precise "N added" count
|
||||
// arrives with the background-scan delta work — until then this is a generic,
|
||||
// truthful confirmation.
|
||||
function _scanCompleteToast(sd) {
|
||||
if (document.querySelector('.screen.active') && document.querySelector('.screen.active').id === 'player') return;
|
||||
if (!window.fbNotify) return;
|
||||
const msg = (sd && sd.error) ? 'Scan finished with an error' : 'Your library is up to date';
|
||||
try { window.fbNotify.show({ title: 'Library scan complete', message: msg, icon: '🔄', accent: '#22C55E' }); } catch (e) { /* */ }
|
||||
}
|
||||
// Poll scan-status until the scan finishes, driving the button state. On
|
||||
// completion, emit library:changed (grid reloads via the listener below) and,
|
||||
// for a user-initiated refresh (announce), show the toast. announce:false is
|
||||
// used when we only attached to a scan we didn't start.
|
||||
function _watchScan(opts) {
|
||||
if (_refreshPoll) return;
|
||||
const announce = !opts || opts.announce !== false;
|
||||
let sawRunning = false, ticks = 0;
|
||||
_refreshPoll = setInterval(async () => {
|
||||
ticks++;
|
||||
let sd = null;
|
||||
try { const r = await fetch('/api/scan-status'); if (r.ok) sd = await r.json(); } catch (e) { /* */ }
|
||||
_setRefreshState(sd);
|
||||
if (sd && sd.running) sawRunning = true;
|
||||
// A user-initiated refresh that never saw a running scan = nothing to
|
||||
// do (already up to date); give prompt feedback instead of waiting.
|
||||
const noopDone = announce && !sawRunning && ticks >= 3;
|
||||
if ((sawRunning && sd && !sd.running) || noopDone || ticks >= 180) {
|
||||
clearInterval(_refreshPoll); _refreshPoll = null;
|
||||
_setRefreshState(null);
|
||||
if (sawRunning && window.feedBack) { try { window.feedBack.emit('library:changed', { reason: 'rescan' }); } catch (e) { /* */ } }
|
||||
if (announce) _scanCompleteToast(sd);
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
async function refreshLibrary() {
|
||||
if (_refreshPoll) return; // a scan is already in progress
|
||||
try { await fetch('/api/rescan', { method: 'POST' }); } catch (e) { /* */ }
|
||||
_watchScan({ announce: true });
|
||||
}
|
||||
|
||||
function watchUploadScan() {
|
||||
if (_uploadScanTimer) clearInterval(_uploadScanTimer);
|
||||
let sawRunning = false, ticks = 0;
|
||||
@@ -1906,5 +2129,13 @@
|
||||
if (active && active.id === 'v3-songs') { _libraryDirty = false; reload(); }
|
||||
else _libraryDirty = true;
|
||||
});
|
||||
// Your live tuning changed (retune / instrument swap / reset) → re-colour the
|
||||
// visible tuning chips against the new tuning. Cheap: re-decorates in place,
|
||||
// no re-fetch or re-paint. No-op off the Songs grid or without the capability.
|
||||
sm.on('working-tuning-changed', () => {
|
||||
if (typeof songsActive === 'function' && !songsActive()) return;
|
||||
if (state.view !== 'grid') return;
|
||||
decorateTuningChips(_gridEl());
|
||||
});
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -120,11 +120,11 @@ test('applySize caches the pane aspect for camUpdate', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('camUpdate reads the live tune bridge and respects splitOnly', () => {
|
||||
test('camUpdate resolves a per-pane tune and respects splitOnly', () => {
|
||||
assert.match(
|
||||
src,
|
||||
/const\s+_aspTune\s*=\s*_aspectTune\(\)\s*;[\s\S]*?_aspTune\.splitOnly\s*&&\s*!_ssActive\(\)/,
|
||||
'camUpdate must read the bridge via _aspectTune() and gate splitOnly on _ssActive()',
|
||||
/const\s+_aspTune\s*=\s*_resolveTuneFor\(\s*_paneKey\s*\)\s*;[\s\S]*?_aspTune\.splitOnly\s*&&\s*!_ssActive\(\)/,
|
||||
'camUpdate must resolve the tune per pane via _resolveTuneFor(_paneKey) and gate splitOnly',
|
||||
);
|
||||
});
|
||||
|
||||
@@ -136,11 +136,151 @@ test('the tune bridge seeds from localStorage (persisted sessions apply on load)
|
||||
);
|
||||
});
|
||||
|
||||
test('a floating tuner panel is built and toggled with the A/B state', () => {
|
||||
test('a floating tuner panel is built and can be shown/hidden', () => {
|
||||
assert.match(src, /function\s+_ensureAspectPanel\s*\(\)/,
|
||||
'_ensureAspectPanel() must exist to build the live panel');
|
||||
assert.match(src, /function\s+_setAspectPanelVisible\s*\(/,
|
||||
'_setAspectPanelVisible() must show/hide the panel with the feature');
|
||||
'_setAspectPanelVisible() must show/hide the panel');
|
||||
});
|
||||
|
||||
// ── Per-pane targeting ────────────────────────────────────────────────────────
|
||||
|
||||
test('the tune resolves per pane with a sparse override map', () => {
|
||||
// _resolveTuneFor overlays a pane's __panels[key] overrides onto the base so
|
||||
// one split pane can be framed independently of the others.
|
||||
assert.match(
|
||||
src,
|
||||
/function\s+_resolveTuneFor\s*\(\s*paneKey\s*\)[\s\S]*?base\.__panels\s*&&\s*base\.__panels\[\s*paneKey\s*\]/,
|
||||
'_resolveTuneFor must overlay per-pane overrides from base.__panels',
|
||||
);
|
||||
});
|
||||
|
||||
test('panel writes route to the selected target (base or a pane override)', () => {
|
||||
// _aspectWriteVal writes to the base when target is empty, else into the
|
||||
// pane override sub-object; camUpdate consumes it via _resolveTuneFor.
|
||||
assert.match(
|
||||
src,
|
||||
/function\s+_aspectWriteVal\s*\([\s\S]*?if\s*\(\s*!_aspectEditTarget\s*\)[\s\S]*?base\.__panels\b[\s\S]*?\[\s*_aspectEditTarget\s*\]/,
|
||||
'_aspectWriteVal must target base for "all" and __panels[target] for a pane',
|
||||
);
|
||||
});
|
||||
|
||||
test('a Target select and pane registry drive the per-pane picker', () => {
|
||||
assert.match(src, /_aspectTargetSel\s*=\s*document\.createElement\(\s*'select'\s*\)/,
|
||||
'the panel must build a Target <select>');
|
||||
assert.match(src, /function\s+_aspectRegisterPane\s*\(/,
|
||||
'_aspectRegisterPane must record live panes for the picker');
|
||||
assert.match(src, /if\s*\(\s*window\.__h3dAspectPanelOpen\s*\)\s*_aspectRegisterPane\(\s*_paneKey\s*\)/,
|
||||
'camUpdate must register its pane only while the tuner panel is open');
|
||||
});
|
||||
|
||||
test('panes are keyed by arrangement (stable across songs, no split-API dep)', () => {
|
||||
// 'arr:<name>' keys are distinct between split panes AND stable across
|
||||
// songs, without depending on the external splitscreen panel index (which
|
||||
// isn't always available). A per-instance id is the no-arrangement fallback.
|
||||
assert.match(
|
||||
src,
|
||||
/function\s+_aspectPaneKey\s*\(\s*arrangement\s*,\s*uid\s*\)[\s\S]*?'arr:'\s*\+\s*a[\s\S]*?'pane:'\s*\+\s*uid/,
|
||||
'_aspectPaneKey must prefer arr:<name> and fall back to pane:<uid>',
|
||||
);
|
||||
assert.match(
|
||||
src,
|
||||
/const\s+_paneKey\s*=\s*_aspectPaneKey\(\s*[\s\S]*?songInfo[\s\S]*?arrangement\s*,\s*_paneUid\s*\)\s*;/,
|
||||
'camUpdate must key the pane by arrangement (with the uid fallback)',
|
||||
);
|
||||
});
|
||||
|
||||
test('arrangement-keyed overrides persist; instance-id keys stay session-only', () => {
|
||||
assert.match(
|
||||
src,
|
||||
/function\s+_aspectPersist\s*\(\)[\s\S]*?k\.slice\(0,\s*4\)\s*===\s*'arr:'[\s\S]*?out\.__panels\s*=\s*p/,
|
||||
'_aspectPersist must persist only arr:* overrides so they carry across songs',
|
||||
);
|
||||
});
|
||||
|
||||
test('the target dropdown prunes dead panes and does not rebuild while focused', () => {
|
||||
assert.match(src, /function\s+_aspectPrunePanes\s*\(\)[\s\S]*?delete\s+reg\[k\]/,
|
||||
'_aspectPrunePanes must drop panes not seen recently');
|
||||
assert.match(src, /_aspectPrunePanes\(\)\s*;[\s\S]*?if\s*\(\s*_aspectPanesDirty\s*\)\s*_aspectBuildTargets\(\)/,
|
||||
'the readout tick must prune then rebuild only when dirty');
|
||||
assert.match(src, /function\s+_aspectBuildTargets\s*\(\)[\s\S]*?document\.activeElement\s*===\s*_aspectTargetSel[\s\S]*?return/,
|
||||
'_aspectBuildTargets must skip rebuilding while the select is focused');
|
||||
});
|
||||
|
||||
test('programmatic sync does not write back into the tune', () => {
|
||||
// _syncAspectPanel dispatches synthetic input events to refresh labels; the
|
||||
// slider handler must skip the write while syncing, else opening/switching a
|
||||
// target would populate a full override for every field.
|
||||
assert.match(src, /_aspectSyncing\s*=\s*true[\s\S]*?finally[\s\S]*?_aspectSyncing\s*=\s*false/,
|
||||
'_syncAspectPanel must set/reset the _aspectSyncing guard');
|
||||
assert.match(src, /if\s*\(\s*!_aspectSyncing\s*\)\s*_aspectWriteVal\(\s*f\.k\s*,/,
|
||||
'the slider input handler must skip the write while syncing');
|
||||
});
|
||||
|
||||
test('unchecking hfov override clears a pane override key (re-inherits base)', () => {
|
||||
assert.match(
|
||||
src,
|
||||
/function\s+_aspectClearVal\s*\(\s*k\s*\)[\s\S]*?delete\s+ov\[k\][\s\S]*?delete\s+m\[\s*_aspectEditTarget\s*\]/,
|
||||
'_aspectClearVal must delete the pane override key (and empty object)',
|
||||
);
|
||||
assert.match(src, /else\s+_aspectClearVal\(\s*'hfovDeg'\s*\)/,
|
||||
'unchecking the hfov override must call _aspectClearVal');
|
||||
});
|
||||
|
||||
test('pruning drops the matching readout slot and a dangling __last', () => {
|
||||
assert.match(
|
||||
src,
|
||||
/delete\s+reg\[k\]\s*;[\s\S]*?delete\s+ro\[k\]\s*;\s*if\s*\(\s*ro\.__last\s*===\s*k\s*\)\s*delete\s+ro\.__last/,
|
||||
'_aspectPrunePanes must prune the readout cache alongside the registry',
|
||||
);
|
||||
});
|
||||
|
||||
test('single-pane forces the edit target back to All (no hidden pane edits)', () => {
|
||||
assert.match(
|
||||
src,
|
||||
/if\s*\(\s*keys\.length\s*<=\s*1\s*\|\|\s*\(\s*_aspectEditTarget\s*&&\s*!reg\[_aspectEditTarget\]\s*\)\s*\)\s*\{\s*_aspectEditTarget\s*=\s*''/,
|
||||
'_aspectBuildTargets must reset the edit target to "" when the Target row is hidden',
|
||||
);
|
||||
});
|
||||
|
||||
test('resolved per-pane tune is memoized and invalidated by a revision', () => {
|
||||
assert.match(src, /_aspectRev\s*\+\+/, 'a mutation revision must be bumped on persist');
|
||||
assert.match(
|
||||
src,
|
||||
/_aspectResolveCache\.get\(\s*paneKey\s*\)[\s\S]*?c\.rev\s*===\s*_aspectRev[\s\S]*?return\s+c\.obj/,
|
||||
'_resolveTuneFor must return a cached object when the revision is unchanged',
|
||||
);
|
||||
});
|
||||
|
||||
test('the pane clock falls back to Date.now so pruning keeps working', () => {
|
||||
assert.match(
|
||||
src,
|
||||
/function\s+_aspectNowMs\s*\(\)[\s\S]*?performance\.now\(\)[\s\S]*?return\s+Date\.now\(\)/,
|
||||
'_aspectNowMs must fall back to Date.now() when the Performance API is absent',
|
||||
);
|
||||
});
|
||||
|
||||
test('opening the panel prunes before the first dropdown build', () => {
|
||||
assert.match(
|
||||
src,
|
||||
/if\s*\(\s*on\s*\)\s*\{\s*_aspectPrunePanes\(\)\s*;\s*_aspectBuildTargets\(\)/,
|
||||
'_setAspectPanelVisible must prune stale panes before building the dropdown',
|
||||
);
|
||||
});
|
||||
|
||||
test('Reset on All restores defaults exactly (no forced enabled)', () => {
|
||||
// Panel visibility is independent of the enabled flag now, so Reset must not
|
||||
// force enabled true — it should restore _ASPECT_DEFAULTS verbatim.
|
||||
assert.doesNotMatch(src, /Object\.keys\(_ASPECT_DEFAULTS\)[\s\S]*?base\.enabled\s*=\s*true/,
|
||||
'Reset must not override the default enabled state');
|
||||
});
|
||||
|
||||
test('the panel has a dismiss (close) control', () => {
|
||||
assert.match(
|
||||
src,
|
||||
/close\.textContent\s*=\s*'×'[\s\S]*?_setAspectPanelVisible\(\s*false\s*\)/,
|
||||
'the panel header must have a × button that hides the panel',
|
||||
);
|
||||
});
|
||||
|
||||
test('camUpdate only writes cam.fov when it actually changes', () => {
|
||||
@@ -153,14 +293,16 @@ test('camUpdate only writes cam.fov when it actually changes', () => {
|
||||
);
|
||||
});
|
||||
|
||||
// ── A/B toggle + lifecycle reset ──────────────────────────────────────────────
|
||||
// ── Shortcut (open/close) + lifecycle reset ───────────────────────────────────
|
||||
|
||||
test('an A/B toggle shortcut flips the tune enabled flag', () => {
|
||||
test('the shortcut opens/closes the tuner panel', () => {
|
||||
assert.match(
|
||||
src,
|
||||
/registerShortcut\(\{[\s\S]*?const\s+t\s*=\s*_aspectTune\(\)\s*;[\s\S]*?t\.enabled\s*=\s*!\s*t\.enabled/,
|
||||
'a registerShortcut handler must toggle the bridge enabled flag',
|
||||
/registerShortcut\(\{[\s\S]*?_toggleAspectPanel\(\)/,
|
||||
'a registerShortcut handler must toggle the tuner panel',
|
||||
);
|
||||
assert.match(src, /function\s+_toggleAspectPanel\s*\(\)/,
|
||||
'_toggleAspectPanel() must exist to reveal/dismiss the panel');
|
||||
});
|
||||
|
||||
test('destroy() resets the pane aspect and restores the base fov', () => {
|
||||
|
||||
@@ -148,6 +148,7 @@ function loadPlaySong(sandbox) {
|
||||
var _playerOriginScreen = null;
|
||||
var _pendingAutostart = false;
|
||||
function _clearAutoExit() {}
|
||||
function _clearAutoplayHold() {}
|
||||
function _resolvePlayerOrigin() { return 'home'; }
|
||||
function _recordPlaybackBridge() {}
|
||||
function _cancelCountIn() {}
|
||||
|
||||
@@ -8,6 +8,8 @@ const vm = require('node:vm');
|
||||
|
||||
const APP_JS = path.join(__dirname, '..', '..', 'static', 'app.js');
|
||||
const TUNER_SCREEN_JS = path.join(__dirname, '..', '..', 'plugins', 'tuner', 'screen.js');
|
||||
const TUNING_UTILS_JS = path.join(__dirname, '..', '..', 'plugins', 'tuner', 'utils', 'tuning-utils.js');
|
||||
const TUNER_UI_JS = path.join(__dirname, '..', '..', 'plugins', 'tuner', 'utils', 'ui.js');
|
||||
|
||||
function loadTuningHelpers() {
|
||||
const src = fs.readFileSync(APP_JS, 'utf8');
|
||||
@@ -26,7 +28,14 @@ function loadTuningHelpers() {
|
||||
|
||||
const feedBackHelpers = loadTuningHelpers();
|
||||
|
||||
function createTunerSandbox() {
|
||||
function createTunerSandbox(opts) {
|
||||
// Auto-open is opt-in (default off in prod). The sandbox defaults it ON so the
|
||||
// behaviour tests exercise the feature; pass { autoOpen: false } to gate it off.
|
||||
const autoOpen = !opts || opts.autoOpen !== false;
|
||||
// The player's physical instrument for the §4 coverage check (core /api/settings).
|
||||
// Absent → the endpoint reports not-ok → coverage stays conservative (can't
|
||||
// decide → don't suppress the prompt), preserving the pre-coverage behaviour.
|
||||
const playerSettings = (opts && opts.player) || null;
|
||||
const enableCalls = [];
|
||||
let playerActive = true;
|
||||
let songInfo = null;
|
||||
@@ -38,12 +47,19 @@ function createTunerSandbox() {
|
||||
setTimeout(fn) { fn(); return 0; },
|
||||
clearTimeout() {},
|
||||
fetch(url) {
|
||||
if (String(url).includes('/config')) {
|
||||
const _u = String(url);
|
||||
if (_u.includes('/api/settings')) {
|
||||
return Promise.resolve(playerSettings
|
||||
? { ok: true, json: () => Promise.resolve(playerSettings) }
|
||||
: { ok: false, json: () => Promise.resolve({}) });
|
||||
}
|
||||
if (_u.includes('/config')) {
|
||||
return Promise.resolve({
|
||||
json: () => Promise.resolve({
|
||||
showFloatingButton: true,
|
||||
visualizationMode: 'default',
|
||||
audioInputMode: 'auto',
|
||||
autoOpenOnTuningChange: autoOpen,
|
||||
lastInstrument: 'guitar-6',
|
||||
lastTuning: 'Standard',
|
||||
freeTune: false,
|
||||
@@ -120,12 +136,8 @@ function createTunerSandbox() {
|
||||
sandbox.window.highway = {
|
||||
getSongInfo: () => songInfo,
|
||||
};
|
||||
sandbox.window._tunerUtils = {
|
||||
preferFlats: () => false,
|
||||
offsetsToFreqs: (offsets) => offsets.map((o, i) => 80 + i * 10),
|
||||
freqToMidi: () => 40,
|
||||
midiToNote: () => 'E',
|
||||
};
|
||||
// _tunerUtils comes from the REAL tuning-utils.js (loaded into the sandbox
|
||||
// below) so the §4 coverage check runs real pitch math, not stubbed values.
|
||||
sandbox.window._tunerUI = () => ({
|
||||
addButton() {},
|
||||
initUI() {},
|
||||
@@ -152,12 +164,13 @@ function createTunerSandbox() {
|
||||
});
|
||||
|
||||
vm.createContext(sandbox);
|
||||
vm.runInContext(fs.readFileSync(TUNING_UTILS_JS, 'utf8'), sandbox);
|
||||
vm.runInContext(fs.readFileSync(TUNER_SCREEN_JS, 'utf8'), sandbox);
|
||||
|
||||
const realEnable = sandbox.window.tuner.enable.bind(sandbox.window.tuner);
|
||||
sandbox.window.tuner.enable = async () => {
|
||||
enableCalls.push(1);
|
||||
return realEnable();
|
||||
sandbox.window.tuner.enable = async (enableOpts) => {
|
||||
enableCalls.push(enableOpts || {});
|
||||
return realEnable(enableOpts);
|
||||
};
|
||||
|
||||
return sandbox;
|
||||
@@ -315,6 +328,37 @@ test('song:loading clears dismiss state for next load', async () => {
|
||||
assert.equal(sandbox.__enableCalls.length, 2);
|
||||
});
|
||||
|
||||
test('auto-open is gated off when the setting is disabled (opt-in)', async () => {
|
||||
const sandbox = createTunerSandbox({ autoOpen: false });
|
||||
sandbox.window._tunerAutoOpen.resetState();
|
||||
await ready(sandbox, CUSTOM_GUITAR);
|
||||
await ready(sandbox, E_STANDARD); // a real tuning change, but the setting is off
|
||||
assert.equal(sandbox.__enableCalls.length, 0);
|
||||
});
|
||||
|
||||
test('auto-open enables in persist mode (passes { auto: true })', async () => {
|
||||
const sandbox = createTunerSandbox();
|
||||
sandbox.window._tunerAutoOpen.resetState();
|
||||
await ready(sandbox, CUSTOM_GUITAR);
|
||||
await ready(sandbox, E_STANDARD);
|
||||
assert.equal(sandbox.__enableCalls.length, 1);
|
||||
assert.equal(sandbox.__enableCalls[0].auto, true);
|
||||
});
|
||||
|
||||
test('persist: an auto-opened tuner is not torn down by autoplay / stray clicks', () => {
|
||||
const screenSrc = fs.readFileSync(TUNER_SCREEN_JS, 'utf8');
|
||||
const uiSrc = fs.readFileSync(
|
||||
path.join(__dirname, '..', '..', 'plugins', 'tuner', 'utils', 'ui.js'), 'utf8');
|
||||
// The gate is opt-in on the server config flag.
|
||||
assert.match(screenSrc, /autoOpenOnTuningChange/);
|
||||
// enable() records whether this was an auto-open …
|
||||
assert.match(screenSrc, /_state\.autoOpened\s*=\s*auto/);
|
||||
// … the outside-click dismiss is armed only for a manual open …
|
||||
assert.match(screenSrc, /if \(!auto\)[\s\S]*?addEventListener\('click'/);
|
||||
// … and the autoplay song:play closer ignores an auto-opened tuner (the flash fix).
|
||||
assert.match(uiSrc, /state\.enabled && !state\.autoOpened/);
|
||||
});
|
||||
|
||||
test('screen.js registers song:loading and song:ready auto-open listeners at boot', () => {
|
||||
const src = fs.readFileSync(TUNER_SCREEN_JS, 'utf8');
|
||||
assert.match(src, /function _installAutoOpenListeners/);
|
||||
@@ -324,7 +368,400 @@ test('screen.js registers song:loading and song:ready auto-open listeners at boo
|
||||
assert.doesNotMatch(src, /restartCurrentSong/);
|
||||
});
|
||||
|
||||
// ── §4 instrument-coverage (E1.5) ──────────────────────────────────────────
|
||||
// Player physical instruments (core /api/settings shape: instrument/string_count/
|
||||
// tuning offsets/reference_pitch).
|
||||
const PLAYER_GUITAR_8_FS = { instrument: 'guitar', string_count: 8, tuning: [0, 0, 0, 0, 0, 0, 0, 0], reference_pitch: 440 }; // F# standard
|
||||
const PLAYER_GUITAR_6 = { instrument: 'guitar', string_count: 6, tuning: [0, 0, 0, 0, 0, 0], reference_pitch: 440 }; // E standard
|
||||
const SONG_7B = { filename: '7b.sloppak', arrangement: 'Lead', arrangement_index: 0, stringCount: 7, tuning: [0, 0, 0, 0, 0, 0, 0] }; // B standard 7
|
||||
const SONG_DROP_A7 = { filename: 'dropa7.sloppak', arrangement: 'Lead', arrangement_index: 0, stringCount: 7, tuning: [-2, 0, 0, 0, 0, 0, 0] }; // Drop A 7
|
||||
|
||||
test('coverage: an 8-string F# player is NOT prompted for a covered 6-/7-string standard song', async () => {
|
||||
const sandbox = createTunerSandbox({ player: PLAYER_GUITAR_8_FS });
|
||||
sandbox.window._tunerAutoOpen.resetState();
|
||||
await ready(sandbox, DROP_D); // first song → sets lastTuningKey, no open
|
||||
await ready(sandbox, E_STANDARD); // 6-E lives on the 8-string's top 6 → suppressed
|
||||
assert.equal(sandbox.__enableCalls.length, 0);
|
||||
await ready(sandbox, SONG_7B); // 7-B lives on the 8-string's top 7 → suppressed
|
||||
assert.equal(sandbox.__enableCalls.length, 0);
|
||||
});
|
||||
|
||||
test('coverage: a Drop-A 7-string song STILL prompts the 8-string F# player (dropped string absent)', async () => {
|
||||
const sandbox = createTunerSandbox({ player: PLAYER_GUITAR_8_FS });
|
||||
sandbox.window._tunerAutoOpen.resetState();
|
||||
await ready(sandbox, E_STANDARD); // first → no open
|
||||
await ready(sandbox, SONG_DROP_A7); // needs an open A1; the 8-string has F#1/B1, not A1 → prompt
|
||||
assert.equal(sandbox.__enableCalls.length, 1);
|
||||
});
|
||||
|
||||
test('coverage: a 6-string-standard player IS prompted for Drop D', async () => {
|
||||
const sandbox = createTunerSandbox({ player: PLAYER_GUITAR_6 });
|
||||
sandbox.window._tunerAutoOpen.resetState();
|
||||
await ready(sandbox, E_STANDARD); // first → no open
|
||||
await ready(sandbox, DROP_D); // low E must drop to D → not covered → prompt
|
||||
assert.equal(sandbox.__enableCalls.length, 1);
|
||||
});
|
||||
|
||||
test('coverage: a reference-pitch mismatch (A432 player vs A440 song) prompts even when the shape matches', async () => {
|
||||
const sandbox = createTunerSandbox({ player: { ...PLAYER_GUITAR_6, reference_pitch: 432 } });
|
||||
sandbox.window._tunerAutoOpen.resetState();
|
||||
await ready(sandbox, DROP_D); // first → no open
|
||||
await ready(sandbox, E_STANDARD); // shape matches, but the whole instrument is ~32¢ flat → prompt
|
||||
assert.equal(sandbox.__enableCalls.length, 1);
|
||||
});
|
||||
|
||||
test('coverage: covered/uncovered is decided by contiguous pitch alignment (direct)', async () => {
|
||||
const sandbox = createTunerSandbox({ player: PLAYER_GUITAR_8_FS });
|
||||
const cover = (song) => sandbox.window._tunerAutoOpen.coveredByPlayerInstrument(song);
|
||||
assert.equal(await cover(E_STANDARD), true); // 6-E is a run inside 8-string F#
|
||||
assert.equal(await cover(SONG_7B), true); // 7-B is a run inside 8-string F#
|
||||
assert.equal(await cover(SONG_DROP_A7), false); // Drop-A's low A1 isn't an open string on it
|
||||
});
|
||||
|
||||
test('coverage: with no declared instrument it stays conservative (prompts as before)', async () => {
|
||||
const sandbox = createTunerSandbox(); // no /api/settings instrument
|
||||
sandbox.window._tunerAutoOpen.resetState();
|
||||
await ready(sandbox, CUSTOM_GUITAR);
|
||||
await ready(sandbox, E_STANDARD);
|
||||
assert.equal(sandbox.__enableCalls.length, 1);
|
||||
});
|
||||
|
||||
// ── §4 coverage report + badge cue (E1.6) ──────────────────────────────────
|
||||
test('coverage report names the string(s) to retune', async () => {
|
||||
// Note: report objects come from the vm sandbox realm, so compare fields, not
|
||||
// deepStrictEqual (which checks prototype identity across realms).
|
||||
const sandbox = createTunerSandbox({ player: PLAYER_GUITAR_8_FS });
|
||||
const rep = (s) => sandbox.window._tunerAutoOpen.coverageReport(s);
|
||||
const covered = await rep(E_STANDARD);
|
||||
assert.equal(covered.covered, true);
|
||||
assert.equal(covered.retune.length, 0);
|
||||
assert.equal(covered.reference, false);
|
||||
const dropA = await rep(SONG_DROP_A7);
|
||||
assert.equal(dropA.covered, false);
|
||||
assert.equal(dropA.retune.length, 1);
|
||||
assert.equal(dropA.retune[0].from, 'B'); // the user's exact case → "retune B → A"
|
||||
assert.equal(dropA.retune[0].to, 'A');
|
||||
});
|
||||
|
||||
test('coverage report flags a whole-instrument reference mismatch', async () => {
|
||||
const sandbox = createTunerSandbox({ player: { ...PLAYER_GUITAR_6, reference_pitch: 432 } });
|
||||
const rep = await sandbox.window._tunerAutoOpen.coverageReport(E_STANDARD);
|
||||
assert.equal(rep.covered, false);
|
||||
assert.equal(rep.reference, true);
|
||||
});
|
||||
|
||||
test('the tuner badge surfaces a passive coverage cue (badges.js)', () => {
|
||||
const badgesSrc = fs.readFileSync(
|
||||
path.join(__dirname, '..', '..', 'static', 'v3', 'badges.js'), 'utf8');
|
||||
// Recomputes via the tuner plugin's coverageReport on song:ready …
|
||||
assert.match(badgesSrc, /api\.coverageReport/);
|
||||
assert.match(badgesSrc, /sm\.on\('song:ready'/);
|
||||
// … and shows an advisory ring + tooltip naming the retune (it never auto-opens).
|
||||
assert.match(badgesSrc, /function _applyCoverageCue/);
|
||||
assert.match(badgesSrc, /report\.retune/);
|
||||
assert.match(badgesSrc, /boxShadow/);
|
||||
});
|
||||
|
||||
// ── Autoplay gate (E2) ─────────────────────────────────────────────────────
|
||||
test('gate: claims an autoplay hold on song:loading and releases it on dismiss', async () => {
|
||||
const sandbox = createTunerSandbox({ player: PLAYER_GUITAR_6 });
|
||||
let holds = 0, releases = 0;
|
||||
sandbox.window.feedBack.holdAutoplay = () => { holds++; return () => { releases++; }; };
|
||||
const api = sandbox.window._tunerAutoOpen;
|
||||
await ready(sandbox, DROP_D); // loads config (feature on)
|
||||
api.resetState();
|
||||
api.onSongLoading(); // song:loading → claim the gate
|
||||
assert.equal(holds, 1);
|
||||
assert.equal(releases, 0);
|
||||
sandbox.window.tuner.disable(); // dismiss → release (playback proceeds)
|
||||
assert.equal(releases, 1);
|
||||
});
|
||||
|
||||
test('gate: does not claim a hold when the feature is off', async () => {
|
||||
const sandbox = createTunerSandbox({ player: PLAYER_GUITAR_6, autoOpen: false });
|
||||
let holds = 0;
|
||||
sandbox.window.feedBack.holdAutoplay = () => { holds++; return () => {}; };
|
||||
const api = sandbox.window._tunerAutoOpen;
|
||||
await ready(sandbox, DROP_D); // loads config (feature OFF)
|
||||
api.onSongLoading();
|
||||
assert.equal(holds, 0);
|
||||
});
|
||||
|
||||
test('the autoplay gate is a generic core hook with a fail-open backstop (app.js)', () => {
|
||||
const appSrc = fs.readFileSync(APP_JS, 'utf8');
|
||||
assert.match(appSrc, /window\.feedBack\.holdAutoplay = function/);
|
||||
assert.match(appSrc, /AUTOPLAY_HOLD_BACKSTOP_MS/); // fail-open: never strand the song
|
||||
assert.match(appSrc, /if \(_autoplayHeld\) \{ _autoplayStart = start;/); // a gated start is stashed
|
||||
assert.match(appSrc, /_clearAutoplayHold\(\);[\s\S]{0,160}emit\('song:loading'/); // reset before plugins re-claim
|
||||
// Per-hold identity: a stale release from an earlier hold must not clear a later one.
|
||||
assert.match(appSrc, /token !== _autoplayHoldToken/);
|
||||
// settle(): a committed holder can cancel the fail-open backstop (no timed release).
|
||||
assert.match(appSrc, /release\.settle = function/);
|
||||
// The hook is generic — app.js still doesn't reference the tuner's internals.
|
||||
assert.doesNotMatch(appSrc, /_tunerAutoOpen|maybeAutoOpenOnTuningChange/);
|
||||
});
|
||||
|
||||
test('the tuner gates playback via holdAutoplay (screen.js)', () => {
|
||||
const src = fs.readFileSync(TUNER_SCREEN_JS, 'utf8');
|
||||
assert.match(src, /window\.feedBack\.holdAutoplay\(\)/); // claimed on song:loading
|
||||
assert.match(src, /_gateClaimed = true/); // kept when the tuner opens
|
||||
assert.match(src, /if \(!_gateClaimed\) _releaseGate\(\)/); // released when we don't open
|
||||
assert.match(src, /_releaseGate\(\);[\s\S]{0,80}dismissing a gated/); // released on dismiss
|
||||
// Once open, the tuner settles the hold so the 12s backstop can't start playback
|
||||
// while the player is still tuning.
|
||||
assert.match(src, /_autoplayRelease\.settle\(\)/);
|
||||
// The async song:ready handler is generation-guarded so it can't release a NEWER
|
||||
// song's gate after its await.
|
||||
assert.match(src, /_onAutoOpenSongReady = async \(\) => \{[\s\S]{0,320}myGen !== _autoOpenGeneration\) return;[\s\S]{0,120}_releaseGate/);
|
||||
});
|
||||
|
||||
test('gate escape hatch: auto-open offers "Back to library" (+ Esc) and hides the × (ui.js/screen.js)', () => {
|
||||
const ui = fs.readFileSync(TUNER_UI_JS, 'utf8');
|
||||
assert.match(ui, /Back to library/); // an explicit way out, not only play-now
|
||||
assert.match(ui, /requestExitSong/); // reuses the standard song-exit path (mirrors Esc)
|
||||
assert.match(ui, /state\.backBtn =/);
|
||||
assert.match(ui, /state\.closeBtn =/); // × captured so it can be toggled
|
||||
|
||||
const screen = fs.readFileSync(TUNER_SCREEN_JS, 'utf8');
|
||||
assert.match(screen, /_state\.backBtn[\s\S]{0,60}toggle\('hidden', !auto\)/); // shown on auto-open
|
||||
assert.match(screen, /_state\.closeBtn[\s\S]{0,60}toggle\('hidden', !!auto\)/); // × hidden on auto-open
|
||||
});
|
||||
|
||||
test('auto-open does not require app.js changes', () => {
|
||||
const appSrc = fs.readFileSync(APP_JS, 'utf8');
|
||||
assert.doesNotMatch(appSrc, /_tunerAutoOpen|maybeAutoOpenOnTuningChange/);
|
||||
});
|
||||
|
||||
// ── PR 3: per-instrument live working tuning (the both-directions fix) ──────
|
||||
test('coverage reads the live per-instrument working tuning, so it prompts BOTH directions', async () => {
|
||||
// GUITAR-6 selected; the player's LIVE working tuning is Drop-D (they retuned).
|
||||
const sandbox = createTunerSandbox({ player: { instrument: 'guitar', string_count: 6, tuning: 'Standard' } });
|
||||
sandbox.window.feedBack.workingTuning = {
|
||||
get: () => ({ offsets: [-2, 0, 0, 0, 0, 0], stringCount: 6, instrument: 'guitar', referencePitch: 440 }),
|
||||
set() {},
|
||||
};
|
||||
const rep = (s) => sandbox.window._tunerAutoOpen.coverageReport(s);
|
||||
// The Drop-D song now MATCHES the live tuning → covered (no prompt).
|
||||
assert.equal((await rep(DROP_D)).covered, true);
|
||||
// An E-standard song NO LONGER matches (the player is in Drop-D) → not covered →
|
||||
// prompts to tune the low string back UP to E. The old static-profile logic missed
|
||||
// this "coming back" direction entirely.
|
||||
const estd = await rep(E_STANDARD);
|
||||
assert.equal(estd.covered, false);
|
||||
assert.equal(estd.retune.length, 1);
|
||||
assert.equal(estd.retune[0].from, 'D'); // player low string is D…
|
||||
assert.equal(estd.retune[0].to, 'E'); // …song wants E → "tune D → E" (up)
|
||||
});
|
||||
|
||||
// Wire a set-capturing workingTuning stub, then run a coverage read so the tuner caches
|
||||
// the selected-instrument identity (publish is synchronous and writes to that cached
|
||||
// slot — an auto-open always runs coverage first, so this mirrors real ordering).
|
||||
async function _primeSets(sandbox, get = () => ({ offsets: null })) {
|
||||
const sets = [];
|
||||
sandbox.window.feedBack.workingTuning = { get, set: (state, opts) => sets.push({ state, opts }) };
|
||||
await sandbox.window._tunerAutoOpen.playerTuning();
|
||||
return sets;
|
||||
}
|
||||
|
||||
test('clearing the auto-opened tuner publishes the song tuning to the right instrument slot', async () => {
|
||||
const sandbox = createTunerSandbox({ player: { instrument: 'guitar', string_count: 6, tuning: 'Standard' } });
|
||||
const sets = await _primeSets(sandbox);
|
||||
sandbox.window._tunerAutoOpen.publishWorkingTuning(DROP_D);
|
||||
assert.equal(sets.length, 1);
|
||||
assert.deepEqual(sets[0].state.offsets, [-2, 0, 0, 0, 0, 0]); // the song's tuning
|
||||
assert.equal(sets[0].state.instrument, 'guitar');
|
||||
assert.equal(sets[0].opts.instrument, 'guitar-6'); // targets the guitar slot
|
||||
assert.equal(sets[0].opts.provenance, 'assumed'); // a guess, not mic-verified
|
||||
});
|
||||
|
||||
test('publish targets the SELECTED instrument slot, not a song-derived one (string-count mismatch)', async () => {
|
||||
// A 5-string bass is selected; the cleared song is a 4-string bass chart. The publish
|
||||
// must land in bass-5 (what coverage reads), NOT bass-4 (where it would be stranded).
|
||||
const sandbox = createTunerSandbox({ player: { instrument: 'bass', string_count: 5, tuning: 'Standard' } });
|
||||
const sets = await _primeSets(sandbox);
|
||||
sandbox.window._tunerAutoOpen.publishWorkingTuning(BASS_EADG);
|
||||
assert.equal(sets.length, 1);
|
||||
assert.equal(sets[0].opts.instrument, 'bass-5'); // the selected instrument's slot
|
||||
assert.equal(sets[0].state.instrument, 'bass');
|
||||
});
|
||||
|
||||
test('publish skips a cross-instrument chart (bass arrangement while guitar is selected)', async () => {
|
||||
// Guitar selected, but the player manually opened the Bass arrangement and cleared.
|
||||
// That is not evidence the guitar was retuned — do not pollute either slot.
|
||||
const sandbox = createTunerSandbox({ player: { instrument: 'guitar', string_count: 6, tuning: 'Standard' } });
|
||||
const sets = await _primeSets(sandbox);
|
||||
sandbox.window._tunerAutoOpen.publishWorkingTuning(BASS_EADG);
|
||||
assert.equal(sets.length, 0);
|
||||
});
|
||||
|
||||
test('publish carries the player reference pitch so the slot is self-consistent', async () => {
|
||||
const sandbox = createTunerSandbox({ player: { instrument: 'guitar', string_count: 6, tuning: 'Standard', reference_pitch: 432 } });
|
||||
const sets = await _primeSets(sandbox);
|
||||
sandbox.window._tunerAutoOpen.publishWorkingTuning(DROP_D);
|
||||
assert.equal(sets.length, 1);
|
||||
assert.equal(sets[0].state.referencePitch, 432);
|
||||
});
|
||||
|
||||
test('publish skips when the instrument could not be confidently resolved (settings unreadable)', async () => {
|
||||
// No player settings → /api/settings reports not-ok → we never cached a confident
|
||||
// selection, so publish must NOT write to a guessed default slot.
|
||||
const sandbox = createTunerSandbox(); // no player
|
||||
const sets = await _primeSets(sandbox);
|
||||
sandbox.window._tunerAutoOpen.publishWorkingTuning(DROP_D);
|
||||
assert.equal(sets.length, 0);
|
||||
});
|
||||
|
||||
// ── #655 fix: transactional open — a dismiss during the audio-start await must not
|
||||
// re-enable the tuner afterward (no zombie enabled-but-hidden state). See issue #675.
|
||||
test('dismiss during the audio-start await does not leave a zombie enabled tuner', async () => {
|
||||
const sandbox = createTunerSandbox({ player: { instrument: 'guitar', string_count: 6, tuning: 'Standard' } });
|
||||
// Minimal UI so real enable() gets past the panel-show line to the audio-start await
|
||||
// (the default sandbox _tunerUI is a no-op that never creates uiContainer).
|
||||
const el = () => ({
|
||||
classList: { add() {}, remove() {}, toggle() {}, contains: () => false },
|
||||
querySelector: () => null, appendChild() {}, remove() {}, style: {},
|
||||
});
|
||||
const origTunerUI = sandbox.window._tunerUI; // the sandbox's full no-op method set
|
||||
sandbox.window._tunerUI = (state, actions) => {
|
||||
const api = origTunerUI(state, actions);
|
||||
state.uiContainer = el();
|
||||
state.vizContainer = el();
|
||||
state.skipBtn = el();
|
||||
api.showMicError = api.showMicError || (() => {});
|
||||
return api;
|
||||
};
|
||||
// The OPEN's audio start resolves only AFTER a ×/Skip dismiss has landed — i.e. the
|
||||
// user dismissed while audio was starting. (disable()'s own background-audio resume
|
||||
// is a later call and resolves at once.)
|
||||
let firstStart = true;
|
||||
sandbox.window._tunerAudio.start = () => {
|
||||
if (!firstStart) return Promise.resolve();
|
||||
firstStart = false;
|
||||
return Promise.resolve().then(() => { sandbox.window.tuner.disable(); });
|
||||
};
|
||||
await sandbox.window.tuner.enable({ auto: true });
|
||||
assert.equal(sandbox.window._tunerAutoOpen.getState().enabled, false,
|
||||
'a mid-open dismiss must win — the tuner stays disabled, not enabled-but-hidden');
|
||||
});
|
||||
// ── #656 fix: coverage stays conservative when the instrument identity is unknown.
|
||||
// A fresh profile (/api/settings omits instrument/string_count/tuning) must NOT be
|
||||
// assumed to be standard guitar and silently suppress the prompt. See issue #677.
|
||||
test('coverage is conservative when settings carry no instrument identity', async () => {
|
||||
const sandbox = createTunerSandbox({ player: {} }); // settings object, but no instrument fields
|
||||
const covered = await sandbox.window._tunerAutoOpen.coveredByPlayerInstrument(E_STANDARD);
|
||||
assert.equal(covered, false, 'unknown instrument → not covered → still prompt');
|
||||
});
|
||||
|
||||
test('a configured standard-guitar player still covers a standard song', async () => {
|
||||
const sandbox = createTunerSandbox({ player: { instrument: 'guitar', string_count: 6, tuning: 'Standard' } });
|
||||
const covered = await sandbox.window._tunerAutoOpen.coveredByPlayerInstrument(E_STANDARD);
|
||||
assert.equal(covered, true, 'a known standard guitar covers a standard song (no regression)');
|
||||
});
|
||||
// ── #657 fix (#680) + #668 fix: coverage is deduped, and the player tuning is memoized
|
||||
// across songs (it depends on the selected instrument, not the song). Many coverage
|
||||
// calls — the auto-open gate, the badge cue, AND the library's per-song tuning-match
|
||||
// chips — share ONE /api/settings fetch until the instrument / working tuning changes.
|
||||
test('coverage reports share one /api/settings fetch across songs (player tuning memoized)', async () => {
|
||||
const sandbox = createTunerSandbox({ player: { instrument: 'guitar', string_count: 6, tuning: 'Standard' } });
|
||||
let settingsFetches = 0;
|
||||
const origFetch = sandbox.window.fetch;
|
||||
sandbox.window.fetch = (url) => {
|
||||
if (String(url).includes('/api/settings')) settingsFetches += 1;
|
||||
return origFetch(url);
|
||||
};
|
||||
const api = sandbox.window._tunerAutoOpen;
|
||||
const [a, b] = await Promise.all([api.coverageReport(DROP_D), api.coverageReport(DROP_D)]);
|
||||
assert.equal(settingsFetches, 1, 'concurrent reports for the same song share one fetch');
|
||||
assert.deepEqual(a, b);
|
||||
// A different song re-evaluates coverage but reuses the memoized player tuning — the
|
||||
// player didn't retune or switch instruments, so no second /api/settings read.
|
||||
api.onSongLoading();
|
||||
await api.coverageReport(E_STANDARD);
|
||||
assert.equal(settingsFetches, 1, 'a different song reuses the memoized player tuning — no refetch');
|
||||
});
|
||||
|
||||
// ── #668 fix: a transient /api/settings failure must NOT be pinned by the player-tuning
|
||||
// memo — the next read retries (else one hiccup freezes coverage as "unknown" for good).
|
||||
test('a transient /api/settings failure is not cached — the next coverage read retries', async () => {
|
||||
const sandbox = createTunerSandbox({ player: { instrument: 'guitar', string_count: 6, tuning: 'Standard' } });
|
||||
let failNext = true;
|
||||
const origFetch = sandbox.window.fetch;
|
||||
sandbox.window.fetch = (url) => {
|
||||
if (String(url).includes('/api/settings') && failNext) { failNext = false; return Promise.reject(new Error('boom')); }
|
||||
return origFetch(url);
|
||||
};
|
||||
const api = sandbox.window._tunerAutoOpen;
|
||||
const r1 = await api.coverageReport(DROP_D); // settings read failed → conservative "none" report
|
||||
assert.equal(r1.retune.length, 0, 'a fetch failure yields the empty/unknown report');
|
||||
api.onSongLoading(); // clear the coverage cache to force a recompute
|
||||
const r2 = await api.coverageReport(DROP_D); // retry: settings now readable → a real report
|
||||
assert.equal(r2.retune.length, 1, 'the retry actually computes coverage (Drop-D low string vs standard)');
|
||||
});
|
||||
// ── PR 9b: mic-verify (assumed -> verified via a per-string check) ──────────
|
||||
const VERIFY_TARGETS = [82.41, 110, 146.83, 196, 246.94, 329.63]; // guitar-6 standard freqs
|
||||
|
||||
test('mic-verify: all strings in-tune-and-stable promotes to verified (with the confirmed offsets)', () => {
|
||||
const sandbox = createTunerSandbox();
|
||||
const sets = [];
|
||||
sandbox.window.feedBack.workingTuning = { get: () => ({ offsets: [0, 0, 0, 0, 0, 0] }), set: (n, o) => sets.push({ n, o }) };
|
||||
const api = sandbox.window._tunerAutoOpen;
|
||||
assert.ok(api.verifyStart(VERIFY_TARGETS, [-2, 0, 0, 0, 0, 0])); // verifying a Drop-D tuning
|
||||
for (let i = 0; i < 8; i++) api.verifyFeed(82.41, 2); // one string alone isn't enough
|
||||
assert.equal(api.verifyState().complete, false);
|
||||
for (const f of VERIFY_TARGETS) { for (let i = 0; i < 8; i++) api.verifyFeed(f, 2); }
|
||||
assert.equal(api.verifyState().complete, true);
|
||||
assert.equal(sets.length, 1);
|
||||
assert.equal(sets[0].o.provenance, 'verified');
|
||||
// The stamp carries the CONFIRMED offsets, not whatever stale offsets the slot held.
|
||||
assert.deepEqual(sets[0].n.offsets, [-2, 0, 0, 0, 0, 0]);
|
||||
assert.equal(sets[0].n.verifiedStrings.length, 6);
|
||||
});
|
||||
|
||||
test('mic-verify: derives the verified offsets from the tuning being checked (no song context)', () => {
|
||||
// A manually-selected tuning (no '_current' song) must still stamp the RIGHT offsets,
|
||||
// derived from the freqs being verified — not a stale currentSongOffsets.
|
||||
const sandbox = createTunerSandbox();
|
||||
const sets = [];
|
||||
sandbox.window.feedBack.workingTuning = { get: () => ({ offsets: [0, 0, 0, 0, 0, 0] }), set: (n, o) => sets.push({ n, o }) };
|
||||
const api = sandbox.window._tunerAutoOpen;
|
||||
const DROP_D_FREQS = [73.42, 110, 146.83, 196, 246.94, 329.63]; // drop-D guitar
|
||||
assert.ok(api.verifyStart(DROP_D_FREQS)); // NO explicit offsets, no song context
|
||||
for (const f of DROP_D_FREQS) { for (let i = 0; i < 8; i++) api.verifyFeed(f, 2); }
|
||||
assert.equal(api.verifyState().complete, true);
|
||||
assert.equal(sets.length, 1);
|
||||
assert.deepEqual(Array.from(sets[0].n.offsets), [-2, 0, 0, 0, 0, 0]); // derived Drop D
|
||||
});
|
||||
|
||||
test('mic-verify: an out-of-tune string never completes; cancel clears', () => {
|
||||
const sandbox = createTunerSandbox();
|
||||
sandbox.window.feedBack.workingTuning = { get: () => ({}), set() {} };
|
||||
const api = sandbox.window._tunerAutoOpen;
|
||||
api.verifyStart([82.41, 110]);
|
||||
for (let i = 0; i < 30; i++) api.verifyFeed(82.41, 25); // 25c off -> never passes
|
||||
assert.equal(api.verifyState().complete, false);
|
||||
assert.deepEqual(api.verifyState().done, [false, false]);
|
||||
api.verifyCancel();
|
||||
assert.equal(api.verifyState(), null);
|
||||
});
|
||||
|
||||
test('mic-verify: the in-tune streak resets if a frame drifts out', () => {
|
||||
const sandbox = createTunerSandbox();
|
||||
sandbox.window.feedBack.workingTuning = { get: () => ({}), set() {} };
|
||||
const api = sandbox.window._tunerAutoOpen;
|
||||
api.verifyStart([100]);
|
||||
for (let i = 0; i < 5; i++) api.verifyFeed(100, 2); // 5 in tune (need 8)
|
||||
api.verifyFeed(100, 30); // drift out -> streak resets
|
||||
for (let i = 0; i < 7; i++) api.verifyFeed(100, 2); // 7 more (not yet 8 in a row)
|
||||
assert.equal(api.verifyState().done[0], false);
|
||||
api.verifyFeed(100, 2); // 8th consecutive -> done
|
||||
assert.equal(api.verifyState().complete, true);
|
||||
});
|
||||
|
||||
test('the tuner exposes the mic-verify API and only it claims verified (screen.js)', () => {
|
||||
const src = fs.readFileSync(TUNER_SCREEN_JS, 'utf8');
|
||||
assert.match(src, /verifyStart:/);
|
||||
assert.match(src, /verifyFeed:/);
|
||||
assert.match(src, /provenance: 'verified'/); // the only place that stamps verified
|
||||
// A just-earned 'verified' is not clobbered by the assumed publish-on-clear.
|
||||
assert.match(src, /wasAutoOpened && !_verifiedPublished/);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
// Behavioral harness for the host `window.feedBack.workingTuning` capability
|
||||
// (static/capabilities/working-tuning.js) — the per-instrument, in-memory current
|
||||
// tuning. Runs the real capability in a stubbed window (same strategy as
|
||||
// midi_input_domain.test.js) with a controllable fetch, and asserts the per-instrument
|
||||
// state machine: isolated guitar/bass slots, selector switch, defensive copies, the
|
||||
// provenance/verification invariant, unambiguous key routing, named-tuning seeding, and
|
||||
// the boot-race guard.
|
||||
|
||||
const { test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const { createWindow, ROOT } = require('./capabilities_test_harness');
|
||||
|
||||
const CAPABILITIES_JS = path.join(ROOT, 'static', 'capabilities.js');
|
||||
const WORKING_TUNING_JS = path.join(ROOT, 'static', 'capabilities', 'working-tuning.js');
|
||||
|
||||
// A /api/tunings-shaped fixture (frequencies at 440), enough to resolve names to offsets.
|
||||
const TUNINGS = {
|
||||
'guitar-6': {
|
||||
Standard: [82.41, 110.00, 146.83, 196.00, 246.94, 329.63],
|
||||
'Drop D': [73.42, 110.00, 146.83, 196.00, 246.94, 329.63],
|
||||
},
|
||||
'bass-5': {
|
||||
Standard: [30.87, 41.20, 55.00, 73.42, 98.00],
|
||||
},
|
||||
};
|
||||
|
||||
function deferred() {
|
||||
let resolve;
|
||||
const promise = new Promise((r) => { resolve = r; });
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
// `routes` maps a URL to: a plain JSON value (served as {ok:true}), a thenable that
|
||||
// resolves to a full response object (for deferral/races), or nothing (served {ok:false}).
|
||||
function loadWorkingTuning(routes = {}) {
|
||||
const window = createWindow();
|
||||
const changes = [];
|
||||
window.fetch = function (url) {
|
||||
const entry = routes[url];
|
||||
if (entry && typeof entry.then === 'function') return entry;
|
||||
if (entry !== undefined) return Promise.resolve({ ok: true, json: () => Promise.resolve(entry) });
|
||||
return Promise.resolve({ ok: false, json: () => Promise.resolve(null) });
|
||||
};
|
||||
const context = vm.createContext(window);
|
||||
vm.runInContext(fs.readFileSync(CAPABILITIES_JS, 'utf8'), context, { filename: CAPABILITIES_JS });
|
||||
vm.runInContext(fs.readFileSync(WORKING_TUNING_JS, 'utf8'), context, { filename: WORKING_TUNING_JS });
|
||||
// capabilities.js replaces window.feedBack with an EventTarget bus — subscribe on it,
|
||||
// not on window. Attaching after load still catches the async hydration event.
|
||||
window.feedBack.on('working-tuning-changed', (ev) => changes.push(ev.detail));
|
||||
return { window, wt: window.feedBack.workingTuning, changes };
|
||||
}
|
||||
|
||||
// Rebase a possibly-vm-realm array into this realm so deepStrictEqual compares by value,
|
||||
// not by (cross-realm) Array.prototype identity.
|
||||
const nums = (a) => (a == null ? a : Array.from(a));
|
||||
|
||||
// Drain the seed's fetch/promise chain (settings -> tunings -> hydrate).
|
||||
const flush = async () => { for (let i = 0; i < 4; i++) await new Promise((r) => setImmediate(r)); };
|
||||
|
||||
test('registers a working-tuning exclusive-owner capability + versioned surface', () => {
|
||||
const { window, wt } = loadWorkingTuning();
|
||||
assert.equal(wt.version, 1);
|
||||
const pipeline = window.feedBack.capabilities.inspect('working-tuning');
|
||||
assert.ok(pipeline, 'working-tuning pipeline exists');
|
||||
const owner = (pipeline.participants || []).find((p) => p.pluginId === 'core.working-tuning');
|
||||
assert.ok(owner, 'core.working-tuning owner registered');
|
||||
for (const op of ['get-working-tuning', 'set-working-tuning']) {
|
||||
assert.ok(owner.operations.includes(op), `owner exposes ${op}`);
|
||||
}
|
||||
});
|
||||
|
||||
test('get() defaults to a synchronous guitar-6 assumed seed before hydration', () => {
|
||||
const { wt } = loadWorkingTuning();
|
||||
const s = wt.get();
|
||||
assert.equal(s.instrument, 'guitar');
|
||||
assert.equal(s.stringCount, 6);
|
||||
assert.equal(s.provenance, 'assumed');
|
||||
assert.equal(s.offsets, null);
|
||||
});
|
||||
|
||||
test('per-instrument slots are isolated; the selector surfaces the right one', async () => {
|
||||
const { wt } = loadWorkingTuning();
|
||||
await flush();
|
||||
wt.set({ offsets: [-2, 0, 0, 0, 0, 0] }, { instrument: 'guitar-6' });
|
||||
wt.set({ offsets: [0, 0, 0, 0] }, { instrument: 'bass-4' });
|
||||
assert.deepEqual(nums(wt.get('guitar-6').offsets), [-2, 0, 0, 0, 0, 0]);
|
||||
assert.deepEqual(nums(wt.get('bass-4').offsets), [0, 0, 0, 0]);
|
||||
// Selecting an instrument makes get() (no arg) return that instrument's own state.
|
||||
wt.setCurrentInstrument('guitar', 6);
|
||||
assert.deepEqual(nums(wt.get().offsets), [-2, 0, 0, 0, 0, 0]);
|
||||
wt.setCurrentInstrument('bass', 4);
|
||||
assert.deepEqual(nums(wt.get().offsets), [0, 0, 0, 0]);
|
||||
});
|
||||
|
||||
test('defensive copies: readers and post-set callers cannot mutate live state', async () => {
|
||||
const { wt } = loadWorkingTuning();
|
||||
await flush();
|
||||
const input = [-2, -2, -2, -2, -2, -2];
|
||||
wt.set({ offsets: input }, { instrument: 'guitar-6' });
|
||||
input[0] = 99; // mutate caller's array after set()
|
||||
assert.deepEqual(nums(wt.get('guitar-6').offsets), [-2, -2, -2, -2, -2, -2], 'set() stored a copy');
|
||||
const read = wt.get('guitar-6');
|
||||
read.offsets[0] = 99; // mutate a returned copy
|
||||
assert.deepEqual(nums(wt.get('guitar-6').offsets), [-2, -2, -2, -2, -2, -2], 'get() returned a copy');
|
||||
});
|
||||
|
||||
test('verification invariant: verified <=> we hold verifiedStrings', async () => {
|
||||
const { wt } = loadWorkingTuning();
|
||||
await flush();
|
||||
// A complete verified bundle stamps verified + a timestamp.
|
||||
let s = wt.set({ offsets: [0, 0, 0, 0, 0, 0], verifiedStrings: [1, 1, 1, 1, 1, 1] },
|
||||
{ instrument: 'guitar-6', provenance: 'verified' });
|
||||
assert.equal(s.provenance, 'verified');
|
||||
assert.deepEqual(nums(s.verifiedStrings), [1, 1, 1, 1, 1, 1]);
|
||||
assert.equal(typeof s.verifiedAt, 'number');
|
||||
|
||||
// Claiming verified on a tuning change WITHOUT fresh strings is impossible — it
|
||||
// fails toward assumed and drops the metadata (no "verified with null strings").
|
||||
s = wt.set({ offsets: [-2, 0, 0, 0, 0, 0] }, { instrument: 'guitar-6', provenance: 'verified' });
|
||||
assert.equal(s.provenance, 'assumed');
|
||||
assert.equal(s.verifiedStrings, null);
|
||||
assert.equal(s.verifiedAt, null);
|
||||
|
||||
// verified always carries a real timestamp — an explicit verifiedAt:null is stamped now.
|
||||
s = wt.set({ verifiedStrings: [1, 1, 1, 1, 1, 1], verifiedAt: null },
|
||||
{ instrument: 'guitar-6', provenance: 'verified' });
|
||||
assert.equal(s.provenance, 'verified');
|
||||
assert.equal(typeof s.verifiedAt, 'number');
|
||||
});
|
||||
|
||||
test('a tuning change invalidates a prior verification', async () => {
|
||||
const { wt } = loadWorkingTuning();
|
||||
await flush();
|
||||
wt.set({ offsets: [0, 0, 0, 0, 0, 0], verifiedStrings: [1, 1, 1, 1, 1, 1] },
|
||||
{ instrument: 'guitar-6', provenance: 'verified' });
|
||||
const s = wt.set({ offsets: [-2, 0, 0, 0, 0, 0] }, { instrument: 'guitar-6' });
|
||||
assert.equal(s.provenance, 'assumed');
|
||||
assert.equal(s.verifiedStrings, null);
|
||||
assert.equal(s.verifiedAt, null);
|
||||
});
|
||||
|
||||
test('bare-instrument writes target the current selection, not a hard-coded default', async () => {
|
||||
const { wt } = loadWorkingTuning();
|
||||
await flush();
|
||||
wt.setCurrentInstrument('bass', 5); // a 5-string bass is selected
|
||||
// A bare instrument string must write bass-5, not bass-4.
|
||||
wt.set({ offsets: [0, 0, 0, 0, 0] }, { instrument: 'bass' });
|
||||
assert.deepEqual(nums(wt.get('bass-5').offsets), [0, 0, 0, 0, 0]);
|
||||
assert.equal(wt.get('bass-4').offsets, null, 'bass-4 slot untouched');
|
||||
// A bare stringCount (no instrument) applies to the selected instrument.
|
||||
const s = wt.set({ stringCount: 5, offsets: [-1, -1, -1, -1, -1] });
|
||||
assert.equal(s.instrument, 'bass');
|
||||
assert.equal(s.stringCount, 5);
|
||||
});
|
||||
|
||||
test('seed resolves a NAMED tuning to offsets via /api/tunings', async () => {
|
||||
const { wt, changes } = loadWorkingTuning({
|
||||
'/api/settings': { instrument: 'guitar', string_count: 6, tuning: 'Drop D', reference_pitch: 440 },
|
||||
'/api/tunings': TUNINGS,
|
||||
});
|
||||
await flush();
|
||||
const s = wt.get('guitar-6');
|
||||
assert.deepEqual(nums(s.offsets), [-2, 0, 0, 0, 0, 0], 'Drop D resolved to a -2 low string');
|
||||
assert.equal(s.source, 'settings');
|
||||
assert.equal(s.provenance, 'assumed');
|
||||
// Hydration emitted once, carrying the seeded instrument.
|
||||
const hydrations = changes.filter((c) => c.instrument === 'guitar');
|
||||
assert.ok(hydrations.length >= 1, 'a working-tuning-changed fired for the seeded instrument');
|
||||
});
|
||||
|
||||
test('seed accepts an offsets-list tuning directly', async () => {
|
||||
const { wt } = loadWorkingTuning({
|
||||
'/api/settings': { instrument: 'bass', string_count: 4, tuning: [-2, 0, 0, 0] },
|
||||
});
|
||||
await flush();
|
||||
assert.deepEqual(nums(wt.get('bass-4').offsets), [-2, 0, 0, 0]);
|
||||
});
|
||||
|
||||
test('boot race: an explicit set() before settings resolve is not clobbered by the seed', async () => {
|
||||
const settings = deferred();
|
||||
const { wt } = loadWorkingTuning({
|
||||
'/api/settings': settings.promise, // held open
|
||||
'/api/tunings': TUNINGS,
|
||||
});
|
||||
// A consumer writes before the seed lands.
|
||||
wt.set({ offsets: [-5, -5, -5, -5, -5, -5] }, { instrument: 'guitar-6' });
|
||||
// Now the seed resolves with a DIFFERENT tuning.
|
||||
settings.resolve({ ok: true, json: () => Promise.resolve({ instrument: 'guitar', string_count: 6, tuning: 'Drop D' }) });
|
||||
await flush();
|
||||
assert.deepEqual(nums(wt.get('guitar-6').offsets), [-5, -5, -5, -5, -5, -5], 'explicit write survived the seed');
|
||||
});
|
||||
|
||||
test('resetToDefault clears a slot back to its baseline and emits', async () => {
|
||||
const { wt, changes } = loadWorkingTuning();
|
||||
await flush();
|
||||
wt.set({ offsets: [-2, -2, -2, -2, -2, -2] }, { instrument: 'guitar-6', provenance: 'verified', verifiedStrings: [1, 1, 1, 1, 1, 1] });
|
||||
const before = changes.length;
|
||||
const s = wt.resetToDefault('guitar-6');
|
||||
assert.equal(s.offsets, null);
|
||||
assert.equal(s.provenance, 'assumed');
|
||||
assert.equal(s.verifiedStrings, null);
|
||||
assert.ok(changes.length > before, 'reset emitted working-tuning-changed');
|
||||
});
|
||||
@@ -0,0 +1,144 @@
|
||||
'use strict';
|
||||
|
||||
// State-machine smoke tests for the host working-tuning capability
|
||||
// (static/capabilities/working-tuning.js). Runs the real module in a vm sandbox
|
||||
// with stubbed window.feedBack (emit/on + capabilities), localStorage and fetch.
|
||||
|
||||
const { test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
|
||||
const SRC = fs.readFileSync(
|
||||
path.join(__dirname, '..', '..', 'static', 'capabilities', 'working-tuning.js'), 'utf8');
|
||||
|
||||
function makeSandbox(opts) {
|
||||
opts = opts || {};
|
||||
const listeners = {};
|
||||
const store = opts.localStorage || {};
|
||||
const settings = opts.settings || { instrument: 'guitar', string_count: 6, tuning: 'Standard', reference_pitch: 440 };
|
||||
const localStorage = {
|
||||
getItem: (k) => (k in store ? store[k] : null),
|
||||
setItem: (k, v) => { store[k] = String(v); },
|
||||
removeItem: (k) => { delete store[k]; },
|
||||
};
|
||||
const sandbox = {
|
||||
window: {
|
||||
feedBack: {
|
||||
capabilities: { version: 1, registerOwner() {}, registerParticipant() {} },
|
||||
emit(ev, detail) { (listeners[ev] || []).slice().forEach((fn) => fn(detail)); },
|
||||
on(ev, fn) { (listeners[ev] = listeners[ev] || []).push(fn); },
|
||||
},
|
||||
localStorage,
|
||||
},
|
||||
localStorage,
|
||||
fetch: () => Promise.resolve({ ok: true, json: () => Promise.resolve(settings) }),
|
||||
console, Promise, Date, Array, Object, JSON, Number, isFinite, setTimeout,
|
||||
};
|
||||
vm.createContext(sandbox);
|
||||
vm.runInContext(SRC, sandbox);
|
||||
return {
|
||||
wt: () => sandbox.window.feedBack.workingTuning,
|
||||
emit: (ev, d) => sandbox.window.feedBack.emit(ev, d),
|
||||
on: (ev, fn) => sandbox.window.feedBack.on(ev, fn),
|
||||
reinject: () => vm.runInContext(SRC, sandbox),
|
||||
store,
|
||||
};
|
||||
}
|
||||
const tick = () => new Promise((r) => setTimeout(r, 0));
|
||||
|
||||
test('defaults: an unset instrument is assumed with null offsets', () => {
|
||||
const d = makeSandbox().wt().get('guitar-6');
|
||||
assert.equal(d.offsets, null);
|
||||
assert.equal(d.provenance, 'assumed');
|
||||
});
|
||||
|
||||
test('set + get round-trips, per-instrument isolation (guitar vs bass)', () => {
|
||||
const s = makeSandbox();
|
||||
s.wt().set({ offsets: [-2, 0, 0, 0, 0, 0], stringCount: 6 }, { instrument: 'guitar-6' });
|
||||
assert.deepEqual(s.wt().get('guitar-6').offsets, [-2, 0, 0, 0, 0, 0]);
|
||||
assert.equal(s.wt().get('bass-4').offsets, null);
|
||||
});
|
||||
|
||||
test('both directions: E → Drop D → back to E via set()', () => {
|
||||
const s = makeSandbox();
|
||||
s.wt().set({ offsets: [-2, 0, 0, 0, 0, 0] }, { instrument: 'guitar-6' });
|
||||
assert.deepEqual(s.wt().get('guitar-6').offsets, [-2, 0, 0, 0, 0, 0]);
|
||||
s.wt().set({ offsets: [0, 0, 0, 0, 0, 0] }, { instrument: 'guitar-6' });
|
||||
assert.deepEqual(s.wt().get('guitar-6').offsets, [0, 0, 0, 0, 0, 0]); // came back
|
||||
});
|
||||
|
||||
test('changing the tuning invalidates a prior verification', () => {
|
||||
const s = makeSandbox();
|
||||
s.wt().set({ offsets: [0, 0, 0, 0, 0, 0], verifiedStrings: [1, 1, 1, 1, 1, 1] }, { instrument: 'guitar-6', provenance: 'verified' });
|
||||
assert.equal(s.wt().get('guitar-6').provenance, 'verified');
|
||||
s.wt().set({ offsets: [-2, 0, 0, 0, 0, 0] }, { instrument: 'guitar-6' });
|
||||
assert.equal(s.wt().get('guitar-6').provenance, 'assumed');
|
||||
});
|
||||
|
||||
test('verified decays to assumed on song:loading (offsets kept)', () => {
|
||||
const s = makeSandbox();
|
||||
s.wt().set({ offsets: [0, 0, 0, 0, 0, 0], verifiedStrings: [1, 1, 1, 1, 1, 1] }, { instrument: 'guitar-6', provenance: 'verified' });
|
||||
assert.equal(s.wt().get('guitar-6').provenance, 'verified');
|
||||
s.emit('song:loading', { filename: 'x' });
|
||||
assert.equal(s.wt().get('guitar-6').provenance, 'assumed');
|
||||
assert.deepEqual(s.wt().get('guitar-6').offsets, [0, 0, 0, 0, 0, 0]);
|
||||
});
|
||||
|
||||
test('resetToDefault clears back to defaults', () => {
|
||||
const s = makeSandbox();
|
||||
s.wt().set({ offsets: [-2, 0, 0, 0, 0, 0] }, { instrument: 'guitar-6' });
|
||||
s.wt().resetToDefault('guitar-6');
|
||||
assert.equal(s.wt().get('guitar-6').offsets, null);
|
||||
});
|
||||
|
||||
test('launch default: setLaunchDefault persists + getLaunchDefault returns it', () => {
|
||||
const s = makeSandbox();
|
||||
s.wt().set({ offsets: [-2, 0, 0, 0, 0, 0], stringCount: 6 }, { instrument: 'guitar-6' });
|
||||
s.wt().setLaunchDefault('guitar-6');
|
||||
assert.deepEqual(s.wt().getLaunchDefault('guitar-6').offsets, [-2, 0, 0, 0, 0, 0]);
|
||||
assert.ok('v3-working-tuning-launch-default' in s.store);
|
||||
});
|
||||
|
||||
test('launch default is opt-in: none set → getLaunchDefault is null', () => {
|
||||
assert.equal(makeSandbox().wt().getLaunchDefault('guitar-6'), null);
|
||||
});
|
||||
|
||||
test('launch default seeds a fresh boot and wins over the raw profile', async () => {
|
||||
const store = {};
|
||||
const s1 = makeSandbox({ localStorage: store });
|
||||
s1.wt().set({ offsets: [-2, 0, 0, 0, 0, 0], stringCount: 6 }, { instrument: 'guitar-6' });
|
||||
s1.wt().setLaunchDefault('guitar-6');
|
||||
// Fresh boot with the SAME localStorage; settings say Standard → launch default wins.
|
||||
const s2 = makeSandbox({ localStorage: store, settings: { instrument: 'guitar', string_count: 6, tuning: 'Standard', reference_pitch: 440 } });
|
||||
await tick();
|
||||
assert.deepEqual(s2.wt().get('guitar-6').offsets, [-2, 0, 0, 0, 0, 0]);
|
||||
assert.equal(s2.wt().get('guitar-6').source, 'launch-default');
|
||||
});
|
||||
|
||||
test('clearLaunchDefault removes it', () => {
|
||||
const s = makeSandbox();
|
||||
s.wt().set({ offsets: [-2, 0, 0, 0, 0, 0], stringCount: 6 }, { instrument: 'guitar-6' });
|
||||
s.wt().setLaunchDefault('guitar-6');
|
||||
s.wt().clearLaunchDefault('guitar-6');
|
||||
assert.equal(s.wt().getLaunchDefault('guitar-6'), null);
|
||||
});
|
||||
|
||||
test('idempotent re-injection: a second load does NOT clobber live state', () => {
|
||||
const s = makeSandbox();
|
||||
s.wt().set({ offsets: [-2, 0, 0, 0, 0, 0], stringCount: 6 }, { instrument: 'guitar-6' });
|
||||
s.reinject(); // run the module source again in the same context
|
||||
assert.deepEqual(s.wt().get('guitar-6').offsets, [-2, 0, 0, 0, 0, 0]); // preserved
|
||||
});
|
||||
|
||||
test('working-tuning-changed fires on set with the changed instrument', () => {
|
||||
const s = makeSandbox();
|
||||
const seen = [];
|
||||
s.on('working-tuning-changed', (e) => seen.push(e));
|
||||
s.wt().set({ offsets: [-2, 0, 0, 0, 0, 0], stringCount: 6 }, { instrument: 'guitar-6' });
|
||||
assert.ok(seen.length >= 1);
|
||||
const last = seen[seen.length - 1];
|
||||
assert.equal(last.instrument, 'guitar');
|
||||
assert.deepEqual(last.tuning.offsets, [-2, 0, 0, 0, 0, 0]);
|
||||
});
|
||||
@@ -95,6 +95,20 @@ class TestConfigPersistence:
|
||||
client.post("/api/plugins/tuner/config", json={"audioInputMode": "browser"})
|
||||
assert client.get("/api/plugins/tuner/config").json()["audioInputMode"] == "browser"
|
||||
|
||||
def test_auto_open_defaults_false(self, client):
|
||||
assert client.get("/api/plugins/tuner/config").json()["autoOpenOnTuningChange"] is False
|
||||
|
||||
def test_auto_open_true_accepted(self, client):
|
||||
client.post("/api/plugins/tuner/config", json={"autoOpenOnTuningChange": True})
|
||||
assert client.get("/api/plugins/tuner/config").json()["autoOpenOnTuningChange"] is True
|
||||
|
||||
def test_auto_open_fail_closed_on_non_bool(self, client):
|
||||
# A hand-edited / bad-client non-boolean (e.g. the string "false") must NOT be
|
||||
# coerced to True by bool() — the opt-in stays off.
|
||||
for bad in ("false", "0", "1", "yes", 1, {}):
|
||||
client.post("/api/plugins/tuner/config", json={"autoOpenOnTuningChange": bad})
|
||||
assert client.get("/api/plugins/tuner/config").json()["autoOpenOnTuningChange"] is False, bad
|
||||
|
||||
def test_disabled_tunings_strips_entries_without_colon(self, client):
|
||||
client.post("/api/plugins/tuner/config", json={
|
||||
"disabledTunings": ["guitar-6:Drop D", "legacy-entry", "bass-4:Standard"]
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
"""Tests for instrument->chart arrangement routing in the highway WS.
|
||||
|
||||
When no explicit arrangement is requested, the WS picks the arrangement matching
|
||||
the player's selected instrument (config.json `instrument`) so a bass player gets
|
||||
the Bass part instead of the default Lead/guitar chart. An explicit arrangement
|
||||
request always wins.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import json
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
def _arr(notes):
|
||||
return {
|
||||
"notes": notes,
|
||||
"chords": [],
|
||||
"anchors": [],
|
||||
"handshapes": [],
|
||||
"templates": [],
|
||||
"beats": [{"time": 0.0, "measure": 1}],
|
||||
"sections": [{"name": "intro", "number": 1, "time": 0.0}],
|
||||
}
|
||||
|
||||
|
||||
def _write_multi_arr_sloppak(dlc_root):
|
||||
"""A song with a Lead (guitar) and a Bass arrangement, Lead first (index 0)."""
|
||||
pak = dlc_root / "multi.sloppak"
|
||||
pak.mkdir()
|
||||
(pak / "arrangements").mkdir()
|
||||
(pak / "arrangements" / "lead.json").write_text(json.dumps(_arr([])))
|
||||
(pak / "arrangements" / "bass.json").write_text(json.dumps(_arr([])))
|
||||
manifest = {
|
||||
"title": "Multi",
|
||||
"artist": "Tester",
|
||||
"album": "",
|
||||
"year": 2026,
|
||||
"duration": 10.0,
|
||||
"arrangements": [
|
||||
{"id": "lead", "name": "Lead", "file": "arrangements/lead.json"},
|
||||
{"id": "bass", "name": "Bass", "file": "arrangements/bass.json"},
|
||||
],
|
||||
"stems": [],
|
||||
}
|
||||
(pak / "manifest.yaml").write_text(yaml.safe_dump(manifest, sort_keys=False))
|
||||
return pak
|
||||
|
||||
|
||||
def _write_sloppak(dlc_root, name, arrangements):
|
||||
"""Write a .sloppak whose arrangements are (id, display-name) pairs, in order."""
|
||||
pak = dlc_root / f"{name}.sloppak"
|
||||
pak.mkdir()
|
||||
(pak / "arrangements").mkdir()
|
||||
manifest_arrs = []
|
||||
for arr_id, arr_name in arrangements:
|
||||
(pak / "arrangements" / f"{arr_id}.json").write_text(json.dumps(_arr([])))
|
||||
manifest_arrs.append(
|
||||
{"id": arr_id, "name": arr_name, "file": f"arrangements/{arr_id}.json"}
|
||||
)
|
||||
manifest = {
|
||||
"title": name,
|
||||
"artist": "Tester",
|
||||
"album": "",
|
||||
"year": 2026,
|
||||
"duration": 10.0,
|
||||
"arrangements": manifest_arrs,
|
||||
"stems": [],
|
||||
}
|
||||
(pak / "manifest.yaml").write_text(yaml.safe_dump(manifest, sort_keys=False))
|
||||
return pak
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def make_client(tmp_path, monkeypatch):
|
||||
def _make(instrument=None, default_arrangement=None):
|
||||
cfg = tmp_path / "config"
|
||||
cfg.mkdir(exist_ok=True)
|
||||
conf = {}
|
||||
if instrument is not None:
|
||||
conf["instrument"] = instrument
|
||||
if default_arrangement is not None:
|
||||
conf["default_arrangement"] = default_arrangement
|
||||
if conf:
|
||||
(cfg / "config.json").write_text(json.dumps(conf), encoding="utf-8")
|
||||
monkeypatch.setenv("CONFIG_DIR", str(cfg))
|
||||
monkeypatch.setenv("DLC_DIR", str(tmp_path / "dlc"))
|
||||
monkeypatch.setenv("FEEDBACK_SYNC_STARTUP", "1")
|
||||
sys.modules.pop("server", None)
|
||||
server = importlib.import_module("server")
|
||||
monkeypatch.setattr(server, "load_plugins", lambda *a, **kw: None)
|
||||
monkeypatch.setattr(server, "startup_scan", lambda: None)
|
||||
monkeypatch.setattr(server, "SLOPPAK_CACHE_DIR", tmp_path / "cache")
|
||||
return server
|
||||
|
||||
(tmp_path / "dlc").mkdir()
|
||||
yield _make
|
||||
server = sys.modules.get("server")
|
||||
conn = getattr(getattr(server, "meta_db", None), "conn", None)
|
||||
if conn is not None:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _arr_index(client, path):
|
||||
with client.websocket_connect(path) as ws:
|
||||
for _ in range(200):
|
||||
msg = ws.receive_json()
|
||||
if msg.get("error"):
|
||||
raise AssertionError(f"WS error frame: {msg}")
|
||||
if msg.get("type") == "song_info":
|
||||
return msg["arrangement_index"]
|
||||
if msg.get("type") == "ready":
|
||||
break
|
||||
raise AssertionError("no song_info frame received")
|
||||
|
||||
|
||||
def test_bass_instrument_routes_to_bass_arrangement(make_client):
|
||||
server = make_client(instrument="bass")
|
||||
_write_multi_arr_sloppak(server._get_dlc_dir())
|
||||
with TestClient(server.app) as client:
|
||||
# No explicit arrangement → route to Bass (index 1), not the default Lead.
|
||||
idx = _arr_index(client, "/ws/highway/multi.sloppak?naming_mode=smart")
|
||||
assert idx == 1
|
||||
|
||||
|
||||
def test_guitar_instrument_keeps_default(make_client):
|
||||
server = make_client(instrument="guitar")
|
||||
_write_multi_arr_sloppak(server._get_dlc_dir())
|
||||
with TestClient(server.app) as client:
|
||||
idx = _arr_index(client, "/ws/highway/multi.sloppak?naming_mode=smart")
|
||||
assert idx == 0 # guitar falls through to the default → Lead
|
||||
|
||||
|
||||
def test_explicit_arrangement_overrides_instrument(make_client):
|
||||
server = make_client(instrument="bass")
|
||||
_write_multi_arr_sloppak(server._get_dlc_dir())
|
||||
with TestClient(server.app) as client:
|
||||
# An explicit arrangement request wins even for a bass player.
|
||||
idx = _arr_index(client, "/ws/highway/multi.sloppak?arrangement=0")
|
||||
assert idx == 0
|
||||
|
||||
|
||||
def test_bass_with_no_bass_part_falls_through_to_guitar(make_client):
|
||||
server = make_client(instrument="bass")
|
||||
# Lead + Rhythm, no bass part at all.
|
||||
_write_sloppak(server._get_dlc_dir(), "gtr", [("lead", "Lead"), ("rhythm", "Rhythm")])
|
||||
with TestClient(server.app) as client:
|
||||
idx = _arr_index(client, "/ws/highway/gtr.sloppak")
|
||||
assert idx == 0 # no bass candidate → existing default (a guitar part)
|
||||
|
||||
|
||||
def test_bass_no_pref_picks_the_primary_bass_not_an_alt(make_client):
|
||||
server = make_client(instrument="bass")
|
||||
# Lead + two bass parts; the canonical "Bass" should win over "Bass 2".
|
||||
_write_sloppak(
|
||||
server._get_dlc_dir(), "bb",
|
||||
[("lead", "Lead"), ("bass", "Bass"), ("bass2", "Bass 2")],
|
||||
)
|
||||
with TestClient(server.app) as client:
|
||||
idx = _arr_index(client, "/ws/highway/bb.sloppak")
|
||||
assert idx == 1 # the primary Bass, not the first-in-order-if-it-were-an-alt
|
||||
|
||||
|
||||
def test_bass_honors_saved_pref_within_the_bass_parts(make_client):
|
||||
# A bass player who saved "Bass 2" keeps it — instrument routing must not clobber
|
||||
# the preference with the primary Bass.
|
||||
server = make_client(instrument="bass", default_arrangement="Bass 2")
|
||||
_write_sloppak(
|
||||
server._get_dlc_dir(), "bb",
|
||||
[("lead", "Lead"), ("bass", "Bass"), ("bass2", "Bass 2")],
|
||||
)
|
||||
with TestClient(server.app) as client:
|
||||
idx = _arr_index(client, "/ws/highway/bb.sloppak")
|
||||
assert idx == 2 # the preferred Bass 2, not the primary Bass (index 1)
|
||||
|
||||
|
||||
def test_guitar_still_honors_saved_pref(make_client):
|
||||
# Guitar routing unchanged: a saved default_arrangement still applies.
|
||||
server = make_client(instrument="guitar", default_arrangement="Rhythm")
|
||||
_write_sloppak(
|
||||
server._get_dlc_dir(), "gtr2",
|
||||
[("lead", "Lead"), ("rhythm", "Rhythm"), ("bass", "Bass")],
|
||||
)
|
||||
with TestClient(server.app) as client:
|
||||
idx = _arr_index(client, "/ws/highway/gtr2.sloppak")
|
||||
assert idx == 1 # Rhythm, per preference
|
||||
@@ -0,0 +1,335 @@
|
||||
"""Tests for .jsonc support in the sloppak/feedpak loaders (feedpak-spec §8).
|
||||
|
||||
When a manifest pointer resolves to a ``.jsonc`` file, the reader MUST strip
|
||||
C-style comments (``//`` line and ``/* */`` block) before parsing. These tests
|
||||
exercise every side-file reader in ``lib/sloppak.py`` (arrangement, notation,
|
||||
drum_tab, song_timeline, lyrics, keys) plus the arrangement/song_timeline
|
||||
reads in ``scripts/lift_keys_notation.py`` against ``.jsonc`` inputs, and pin
|
||||
the string-boundary rule (comment-like text inside a JSON string survives).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
import sloppak as sloppak_mod
|
||||
from jsonc import parse_jsonc
|
||||
from scripts.lift_keys_notation import _load_song_beats
|
||||
|
||||
|
||||
# ── jsonc.parse_jsonc unit tests ─────────────────────────────────────────────
|
||||
|
||||
def test_parse_jsonc_strips_line_comment():
|
||||
assert parse_jsonc('{"a": 1 // c\n}') == {"a": 1}
|
||||
|
||||
|
||||
def test_parse_jsonc_strips_block_comment():
|
||||
assert parse_jsonc('{"a": /* x */ 2}') == {"a": 2}
|
||||
|
||||
|
||||
def test_parse_jsonc_strips_multiline_block_comment():
|
||||
text = '{\n /* multi\n line */\n "a": 1\n}'
|
||||
assert parse_jsonc(text) == {"a": 1}
|
||||
|
||||
|
||||
def test_parse_jsonc_preserves_comment_like_text_in_strings():
|
||||
# ``//`` and ``/*`` inside a JSON string literal must NOT be treated as
|
||||
# comments — the string-aware regex keeps them verbatim.
|
||||
text = '{"url": "https://x/y", "note": "// not a comment /* still not */"}'
|
||||
out = parse_jsonc(text)
|
||||
assert out["url"] == "https://x/y"
|
||||
assert out["note"] == "// not a comment /* still not */"
|
||||
|
||||
|
||||
def test_parse_jsonc_rejects_malformed():
|
||||
with pytest.raises(json.JSONDecodeError):
|
||||
parse_jsonc('{"a": // comment breaks value\n}')
|
||||
|
||||
|
||||
def test_parse_jsonc_plain_json_passes_through():
|
||||
assert parse_jsonc('{"a": 1}') == {"a": 1}
|
||||
|
||||
|
||||
# ── Fixture builder ──────────────────────────────────────────────────────────
|
||||
|
||||
def _base_arrangement(*, beats=None) -> dict:
|
||||
return {
|
||||
"name": "Lead", "tuning": [0, 0, 0, 0, 0, 0], "capo": 0,
|
||||
"notes": [], "chords": [], "anchors": [], "handshapes": [],
|
||||
"templates": [], "beats": beats or [], "sections": [],
|
||||
}
|
||||
|
||||
|
||||
def _write_sloppak(root: Path, *, manifest_extras: dict, side_files: dict) -> Path:
|
||||
"""Build a minimal directory-form sloppak.
|
||||
|
||||
``side_files`` maps a pak-relative filename (e.g. ``"arrangements/lead.jsonc"``)
|
||||
to the exact text to write — so the caller controls comments / extensions.
|
||||
"""
|
||||
pak = root / f"{root.name}.sloppak"
|
||||
pak.mkdir()
|
||||
(pak / "arrangements").mkdir()
|
||||
# A default lead arrangement file the manifest references; can be overridden
|
||||
# via side_files if the caller wants a .jsonc arrangement.
|
||||
if "arrangements/lead.json" not in side_files and "arrangements/lead.jsonc" not in side_files:
|
||||
(pak / "arrangements" / "lead.json").write_text(
|
||||
json.dumps(_base_arrangement())
|
||||
)
|
||||
for rel, text in side_files.items():
|
||||
target = pak / rel
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text(text, encoding="utf-8")
|
||||
manifest = {
|
||||
"title": "Test", "artist": "Tester", "album": "", "year": 2026,
|
||||
"duration": 10.0,
|
||||
"arrangements": [{"id": "lead", "name": "Lead", "file": "arrangements/lead.json"}],
|
||||
"stems": [{"id": "full", "file": "stems/full.ogg", "default": True}],
|
||||
}
|
||||
manifest.update(manifest_extras)
|
||||
(pak / "manifest.yaml").write_text(yaml.safe_dump(manifest, sort_keys=False))
|
||||
return pak
|
||||
|
||||
|
||||
def _load(pak_path: Path, tmp_path: Path):
|
||||
dlc_root = pak_path.parent
|
||||
cache = tmp_path / "cache"
|
||||
cache.mkdir()
|
||||
return sloppak_mod.load_song(pak_path.name, dlc_root, cache)
|
||||
|
||||
|
||||
# ── Arrangement .jsonc ───────────────────────────────────────────────────────
|
||||
|
||||
def test_load_arrangement_jsonc_with_comments(tmp_path: Path):
|
||||
arr_text = (
|
||||
'// lead chart\n'
|
||||
'{\n'
|
||||
' "name": "Lead",\n'
|
||||
' "tuning": [0, 0, 0, 0, 0, 0],\n'
|
||||
' "capo": 0,\n'
|
||||
' /* no notes yet */\n'
|
||||
' "notes": [{"t": 0.5, "s": 0, "f": 5, "sus": 0}],\n'
|
||||
' "chords": [], "anchors": [], "handshapes": [], "templates": [],\n'
|
||||
' "beats": [], "sections": []\n'
|
||||
'}'
|
||||
)
|
||||
pak = _write_sloppak(
|
||||
tmp_path,
|
||||
manifest_extras={
|
||||
"arrangements": [{"id": "lead", "name": "Lead",
|
||||
"file": "arrangements/lead.jsonc"}]
|
||||
},
|
||||
side_files={"arrangements/lead.jsonc": arr_text},
|
||||
)
|
||||
loaded = _load(pak, tmp_path)
|
||||
assert len(loaded.song.arrangements) == 1
|
||||
arr = loaded.song.arrangements[0]
|
||||
assert arr.name == "Lead"
|
||||
assert len(arr.notes) == 1
|
||||
assert arr.notes[0].fret == 5
|
||||
|
||||
|
||||
def test_load_arrangement_jsonc_malformed_is_skipped(tmp_path: Path):
|
||||
# A .jsonc file that is still invalid after stripping comments must be
|
||||
# skipped gracefully (the loader's existing permissive path), not crash.
|
||||
pak = _write_sloppak(
|
||||
tmp_path,
|
||||
manifest_extras={
|
||||
"arrangements": [{"id": "lead", "name": "Lead",
|
||||
"file": "arrangements/lead.jsonc"}]
|
||||
},
|
||||
side_files={"arrangements/lead.jsonc": '{"notes": // broken\n}'},
|
||||
)
|
||||
loaded = _load(pak, tmp_path)
|
||||
# The malformed arrangement is skipped; load still returns a song shell.
|
||||
assert len(loaded.song.arrangements) == 0
|
||||
|
||||
|
||||
# ── Notation .jsonc ──────────────────────────────────────────────────────────
|
||||
|
||||
def test_load_notation_jsonc_with_comments(tmp_path: Path):
|
||||
from tests.test_sloppak_notation_load import VALID_NOTATION
|
||||
payload = VALID_NOTATION
|
||||
text = (
|
||||
'/* notation for keys */\n'
|
||||
+ json.dumps(payload)
|
||||
)
|
||||
pak = _write_sloppak(
|
||||
tmp_path,
|
||||
manifest_extras={
|
||||
"arrangements": [{"id": "lead", "name": "Lead",
|
||||
"file": "arrangements/lead.json",
|
||||
"notation": "notation_lead.jsonc"}]
|
||||
},
|
||||
side_files={"notation_lead.jsonc": text},
|
||||
)
|
||||
loaded = _load(pak, tmp_path)
|
||||
assert loaded.notation_by_id is not None
|
||||
assert "lead" in loaded.notation_by_id
|
||||
|
||||
|
||||
# ── drum_tab .jsonc ──────────────────────────────────────────────────────────
|
||||
|
||||
def test_load_drum_tab_jsonc_with_comments(tmp_path: Path):
|
||||
payload = {
|
||||
"version": 1, "name": "Drums",
|
||||
"kit": [{"id": "kick", "name": "Kick"}],
|
||||
"hits": [{"t": 0.5, "p": "kick", "v": 110}],
|
||||
}
|
||||
text = '// drum tab\n' + json.dumps(payload)
|
||||
pak = _write_sloppak(
|
||||
tmp_path,
|
||||
manifest_extras={"drum_tab": "drum_tab.jsonc"},
|
||||
side_files={"drum_tab.jsonc": text},
|
||||
)
|
||||
loaded = _load(pak, tmp_path)
|
||||
assert loaded.drum_tab is not None
|
||||
assert loaded.drum_tab["hits"][0]["p"] == "kick"
|
||||
|
||||
|
||||
# ── song_timeline .jsonc ─────────────────────────────────────────────────────
|
||||
|
||||
def test_load_song_timeline_jsonc_with_comments(tmp_path: Path):
|
||||
payload = {
|
||||
"beats": [{"time": 0.0, "measure": 0}, {"time": 0.5, "measure": 0}],
|
||||
"sections": [{"name": "intro", "number": 0, "time": 0.0}],
|
||||
}
|
||||
text = '/* timeline */\n' + json.dumps(payload)
|
||||
pak = _write_sloppak(
|
||||
tmp_path,
|
||||
manifest_extras={"song_timeline": "song_timeline.jsonc"},
|
||||
side_files={"song_timeline.jsonc": text},
|
||||
)
|
||||
loaded = _load(pak, tmp_path)
|
||||
assert loaded.song_timeline is not None
|
||||
assert len(loaded.song.beats) == 2
|
||||
assert loaded.song.sections[0].name == "intro"
|
||||
|
||||
|
||||
# ── lyrics .jsonc ────────────────────────────────────────────────────────────
|
||||
|
||||
def test_load_lyrics_jsonc_with_comments(tmp_path: Path):
|
||||
payload = [
|
||||
{"w": "Hel", "t": 0.0, "d": 0.2},
|
||||
{"w": "lo", "t": 0.2, "d": 0.3},
|
||||
]
|
||||
text = '// syllable lyrics\n' + json.dumps(payload)
|
||||
pak = _write_sloppak(
|
||||
tmp_path,
|
||||
manifest_extras={"lyrics": "lyrics.jsonc"},
|
||||
side_files={"lyrics.jsonc": text},
|
||||
)
|
||||
loaded = _load(pak, tmp_path)
|
||||
assert len(loaded.song.lyrics) == 2
|
||||
assert loaded.song.lyrics[0]["w"] == "Hel"
|
||||
|
||||
|
||||
# ── keys .jsonc ──────────────────────────────────────────────────────────────
|
||||
|
||||
def test_load_keys_jsonc_with_comments(tmp_path: Path):
|
||||
payload = {
|
||||
"version": 1,
|
||||
"events": [{"t": 0.0, "key": "Em", "scale": "natural_minor"}],
|
||||
}
|
||||
text = '/* key/scale track */\n' + json.dumps(payload)
|
||||
pak = _write_sloppak(
|
||||
tmp_path,
|
||||
manifest_extras={"keys": "keys.jsonc"},
|
||||
side_files={"keys.jsonc": text},
|
||||
)
|
||||
loaded = _load(pak, tmp_path)
|
||||
assert loaded.keys is not None
|
||||
assert loaded.keys["events"][0]["key"] == "Em"
|
||||
|
||||
|
||||
# ── Comment-like text inside strings is preserved end-to-end ─────────────────
|
||||
|
||||
def test_load_arrangement_jsonc_preserves_comment_like_string_values(tmp_path: Path):
|
||||
# A note whose fret label (if it had one) or a string field contains ``//``
|
||||
# must survive the strip. We put a ``//`` inside the arrangement name and a
|
||||
# ``/* */`` inside a beat section name to exercise both comment shapes.
|
||||
arr_text = (
|
||||
'{\n'
|
||||
' "name": "Lead // solo",\n'
|
||||
' "tuning": [0, 0, 0, 0, 0, 0], "capo": 0,\n'
|
||||
' "notes": [], "chords": [], "anchors": [], "handshapes": [], "templates": [],\n'
|
||||
' "beats": [],\n'
|
||||
' "sections": [{"name": "verse /* important */", "number": 0, "time": 0.0}]\n'
|
||||
'}'
|
||||
)
|
||||
pak = _write_sloppak(
|
||||
tmp_path,
|
||||
manifest_extras={
|
||||
"arrangements": [{"id": "lead", "name": "Lead",
|
||||
"file": "arrangements/lead.jsonc"}]
|
||||
},
|
||||
side_files={"arrangements/lead.jsonc": arr_text},
|
||||
)
|
||||
loaded = _load(pak, tmp_path)
|
||||
arr = loaded.song.arrangements[0]
|
||||
# The manifest's ``name: Lead`` overrides the arrangement JSON's name, so
|
||||
# assert on the section name instead — it flows straight from the parsed
|
||||
# .jsonc with no manifest override, proving the comment-like text inside
|
||||
# the string survived the strip.
|
||||
assert arr.name == "Lead"
|
||||
assert loaded.song.sections[0].name == "verse /* important */"
|
||||
|
||||
|
||||
# ── lift_keys_notation reads .jsonc arrangements / song_timeline ─────────────
|
||||
|
||||
def test_lift_keys_notation_loads_song_beats_from_jsonc_timeline(tmp_path: Path):
|
||||
"""``_load_song_beats`` (the helper the lifter uses to find downbeats) must
|
||||
read a ``.jsonc`` song_timeline when the manifest points at one."""
|
||||
timeline_text = (
|
||||
'// timeline\n'
|
||||
+ json.dumps({
|
||||
"beats": [{"time": 0.0, "measure": 0}, {"time": 0.5, "measure": 0},
|
||||
{"time": 1.0, "measure": 1}],
|
||||
"sections": [],
|
||||
})
|
||||
)
|
||||
pak = tmp_path / "song.sloppak"
|
||||
pak.mkdir()
|
||||
(pak / "arrangements").mkdir()
|
||||
(pak / "arrangements" / "keys.json").write_text(json.dumps(_base_arrangement()))
|
||||
(pak / "song_timeline.jsonc").write_text(timeline_text, encoding="utf-8")
|
||||
manifest = {
|
||||
"title": "T", "artist": "A", "duration": 4.0,
|
||||
"arrangements": [{"id": "keys", "name": "Keys",
|
||||
"file": "arrangements/keys.json"}],
|
||||
"song_timeline": "song_timeline.jsonc",
|
||||
"stems": [{"id": "full", "file": "stems/full.ogg"}],
|
||||
}
|
||||
(pak / "manifest.yaml").write_text(yaml.safe_dump(manifest, sort_keys=False))
|
||||
beats = _load_song_beats(pak, manifest)
|
||||
assert len(beats) == 3
|
||||
assert beats[2]["measure"] == 1
|
||||
|
||||
|
||||
def test_lift_keys_notation_falls_back_to_jsonc_arrangement_beats(tmp_path: Path):
|
||||
"""When no song_timeline is present, ``_load_song_beats`` falls back to the
|
||||
first arrangement JSON carrying beats — and that arrangement may be ``.jsonc``."""
|
||||
arr_text = (
|
||||
'/* keys */\n'
|
||||
+ json.dumps({
|
||||
**_base_arrangement(),
|
||||
"beats": [{"time": 0.0, "measure": 0}, {"time": 1.0, "measure": 1}],
|
||||
})
|
||||
)
|
||||
pak = tmp_path / "song.sloppak"
|
||||
pak.mkdir()
|
||||
(pak / "arrangements").mkdir()
|
||||
(pak / "arrangements" / "keys.jsonc").write_text(arr_text, encoding="utf-8")
|
||||
manifest = {
|
||||
"title": "T", "artist": "A", "duration": 4.0,
|
||||
"arrangements": [{"id": "keys", "name": "Keys",
|
||||
"file": "arrangements/keys.jsonc"}],
|
||||
"stems": [{"id": "full", "file": "stems/full.ogg"}],
|
||||
}
|
||||
(pak / "manifest.yaml").write_text(yaml.safe_dump(manifest, sort_keys=False))
|
||||
beats = _load_song_beats(pak, manifest)
|
||||
assert len(beats) == 2
|
||||
assert beats[1]["measure"] == 1
|
||||
Reference in New Issue
Block a user