diff --git a/src/renderer/screen.js b/src/renderer/screen.js index c9c189b..c26564b 100644 --- a/src/renderer/screen.js +++ b/src/renderer/screen.js @@ -3219,6 +3219,13 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; const hw = window.highway || window._slopsmithHighway; if (!hw) return; + // A whole-song tone lock beats per-tone mappings too. + const lockedForSong = getSongToneLock(songKey); + if (lockedForSong) { + await applySongToneLock(lockedForSong); + return; + } + // Tone Automation overrides manual tone mappings: it owns the chain // while enabled and reacts to song/tone events through its own switcher. if (!options.force && window._aeToneAutomation?.isEnabled?.()) { @@ -3316,7 +3323,73 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; closeTonePanel(); } + // Whole-song tone picker in the player menu ("Tone & tuning" group via + // data-ae-chain). "Follow song" = normal switching (Tone Automation / + // mappings); a preset = hold it for this whole song, remembered per song. + function playerControlsContainer() { + const fb = window.feedBack; + const slot = (fb && fb.uiVersion === 'v3' && fb.ui && typeof fb.ui.playerControlSlot === 'function') + ? fb.ui.playerControlSlot() : null; + return slot || document.getElementById('player-controls'); + } + async function onSongTonePick(pick) { + const songKey = getCurrentSongKey(); + setSongToneLock(songKey, pick || null); + if (playQueueActive()) _queueToneLock = pick || null; + if (pick) { + await applySongToneLock(pick); + return; + } + // Back to following the song: re-run the normal per-song tone setup. + window._toneSwitcher = null; + window._toneMappingsDirty = true; + const hwNow = window.highway || window._slopsmithHighway; + const tcNow = hwNow?.getToneChanges ? hwNow.getToneChanges() : []; + const tbNow = hwNow?.getToneBase ? hwNow.getToneBase() : ''; + if (window._aeToneAutomation?.isEnabled?.()) { + const ok = await window._aeToneAutomation.installSwitcherForSong(songKey, tcNow, tbNow); + // startToneAutoSwitch lives in a later closure; use its export. + if (ok && window._aeStartToneAutoSwitch) window._aeStartToneAutoSwitch(); + } else { + await applyToneMappingsNow(songKey); + } + } + function injectSongTonePicker() { + const controls = playerControlsContainer(); + if (!controls) return; + let sel = document.getElementById('ae-song-tone-pick'); + if (!sel) { + sel = document.createElement('select'); + sel.id = 'ae-song-tone-pick'; + sel.setAttribute('data-ae-chain', 'song-tone'); + sel.title = 'Tone for this whole song'; + sel.className = 'px-2 py-1.5 bg-dark-600 hover:bg-dark-500 rounded-lg text-xs text-gray-300 transition'; + sel.addEventListener('change', () => { + onSongTonePick(sel.value).catch((e) => console.warn('[tone-lock] pick failed:', e)); + }); + sel.addEventListener('pointerdown', () => fillSongTonePicker(sel, false)); + sel.addEventListener('focus', () => fillSongTonePicker(sel, false)); + } + if (!controls.contains(sel)) controls.appendChild(sel); + fillSongTonePicker(sel, true); + } + // (Re)build the options. On open (pointerdown/focus) it only rewrites when + // the preset list changed, so a tone saved mid-song shows up without + // reloading the song and an unchanged list never touches the DOM. + function fillSongTonePicker(sel, force) { + const names = Object.keys(getPresets()); + const sig = names.join(''); + if (!force && sel._aeSig === sig) return; + const keep = force ? (getSongToneLock(getCurrentSongKey()) || '') : sel.value; + sel._aeSig = sig; + sel.innerHTML = `` + + names.map(n => ``).join(''); + sel.value = names.includes(keep) ? keep : ''; + } + window._aeInjectSongTonePicker = injectSongTonePicker; + function injectPlayerToneButton() { + injectSongTonePicker(); const controls = document.getElementById('player-controls'); if (!shouldShowPlayerChainButton()) { removePlayerChainButton(); @@ -3484,6 +3557,7 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; `; + if (toneNamesOrdered.length === 0) { const arrangementName = getCurrentArrangementName(); const originalNames = await getOriginalToneNames(songKey, arrangementName); @@ -3609,6 +3683,7 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; player.style.position = 'relative'; player.appendChild(panel); + // Active indicator — shows the live tone state resolved through whichever // engine is currently driving `_toneSwitcher` (Tone Automation, manual // bypass mappings, or MIDI PC). When a preset is known, it's rendered as @@ -4062,6 +4137,62 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; }; } + // ── Whole-song tone lock ───────────────────────────────────────────── + // "Hard set" one saved preset for an entire song from the in-player Tone + // Switching panel: Tone Automation / per-tone mappings are skipped for + // that song and its tone changes are ignored. Stored per song key so a + // replay keeps the pick; choosing "Follow tone changes" clears it. + const SONG_TONE_LOCK_KEY = 'slopsmith-song-tone-lock'; + function readSongToneLocks() { + try { + const v = JSON.parse(localStorage.getItem(SONG_TONE_LOCK_KEY) || '{}'); + return (v && typeof v === 'object' && !Array.isArray(v)) ? v : {}; + } catch (e) { return {}; } + } + // A pick made while a queue / album playthrough is running holds for the + // rest of that run (not just the song it was picked on). Cleared by + // picking "follow song", or when the queue ends. + let _queueToneLock = null; + function playQueueActive() { + const q = window.feedBack && window.feedBack.playQueue; + try { return !!(q && typeof q.active === 'function' && q.active()); } catch (e) { return false; } + } + try { + window.feedBack?.on?.('queue:changed', (e) => { + const d = (e && e.detail) || e || {}; + if (d.active === false) _queueToneLock = null; + }); + } catch (e) { /* host without the event bus */ } + function getSongToneLock(songKey) { + if (!songKey) return null; + const presets = getPresets(); + const name = readSongToneLocks()[songKey]; + if (typeof name === 'string' && name && presets[name]) return name; + if (_queueToneLock) { + if (playQueueActive() && presets[_queueToneLock]) return _queueToneLock; + _queueToneLock = null; + } + return null; + } + function setSongToneLock(songKey, presetName) { + if (!songKey) return; + const locks = readSongToneLocks(); + if (presetName) locks[songKey] = presetName; else delete locks[songKey]; + try { localStorage.setItem(SONG_TONE_LOCK_KEY, JSON.stringify(locks)); } catch (e) { /* ignore */ } + } + // Load the locked preset and install a switcher that ignores tone changes. + async function applySongToneLock(presetName) { + window._toneSwitcher = { + activeTone: null, + songLock: presetName, + switchToTone(name) { this.activeTone = name; }, + }; + const ok = await loadPresetByName(presetName); + if (ok) console.log('[tone-lock] whole song →', presetName); + return ok; + } + window._aeSongToneLock = { get: getSongToneLock, set: setSongToneLock, apply: applySongToneLock }; + async function loadPresetByName(presetName) { if (!presetName) return false; const presets = getPresets(); @@ -4135,6 +4266,13 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; async function installTaSwitcherForSong(songKey, toneChanges, toneBase) { const cfg = readTaStore(); if (!cfg.enabled) return false; + // Every Tone Automation install path funnels through here, so the + // whole-song lock is enforced in one place. + const locked = getSongToneLock(songKey); + if (locked) { + await applySongToneLock(locked); + return true; + } const switcher = new ToneAutomationSwitcher(); window._toneSwitcher = switcher; const initialInput = String(toneBase || songKey || '').trim(); @@ -4312,6 +4450,9 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; const normalizeSongKey = window._aeNormalizeSongKey || ((raw) => String(raw || '').replace(/\\/g, '/').trim()); const getCurrentSongKey = window._aeGetCurrentSongKey || (() => normalizeSongKey(window._slopsmithPlaybackSettingsKey || window._currentSongFile || window._slopsmithSongKey || '')); const getToneChangeTime = window._aeGetToneChangeTime || ((tc) => { const t = tc?.t ?? tc?.time ?? tc?.timestamp ?? tc?.at; return Number.isFinite(t) ? t : Infinity; }); + // Bypass-mode preload reads preset item lists; the helper lives in the first IIFE (a bare + // getPresetItems() here threw ReferenceError, caught by the renderer-iife-scope test). + const getPresetItems = (preset) => (Array.isArray(preset?.items) ? preset.items : []); function getTonePreloadCacheKey() { const sk = getCurrentSongKey(); @@ -4526,7 +4667,7 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; // poll would see activeTone === _lastTone and skip it. if (window._toneSwitcher) { _lastTone = activeTone; - showToneToast(activeTone); + if (!window._toneSwitcher.songLock) showToneToast(activeTone); window._toneSwitcher.switchToTone(activeTone); _toneSwitcherWarned = false; } else if (!_toneSwitcherWarned) { @@ -4721,6 +4862,17 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; const songKey = getCurrentSongKey(); + // A whole-song tone lock beats every switching mode. The lock helpers live in the + // first IIFE; this preload runs in the second, so reach them through their export + // (a bare call threw ReferenceError on every song — issue #12). + const songLock = window._aeSongToneLock; + const lockedPreset = songLock && typeof songLock.get === 'function' ? songLock.get(songKey) : null; + if (lockedPreset) { + await songLock.apply(lockedPreset); + _preloadedToneCacheKey = null; + return; + } + // Check for MIDI PC mode let allMappingsData = {}; try { allMappingsData = JSON.parse(localStorage.getItem('slopsmith-tone-mappings') || '{}') || {}; } diff --git a/tests/renderer-iife-scope.test.js b/tests/renderer-iife-scope.test.js new file mode 100644 index 0000000..6704198 --- /dev/null +++ b/tests/renderer-iife-scope.test.js @@ -0,0 +1,78 @@ +// src/renderer/screen.js is several sibling IIFEs. A function declared inside one is invisible +// to the others, and a bare call across that boundary only fails at runtime (issue #12: +// `getSongToneLock is not defined` on every song). Pin it statically: no IIFE may call a +// top-level function that only exists in a different IIFE — cross-IIFE access goes through +// a `window.*` export. + +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const SRC = fs.readFileSync(path.join(__dirname, '..', 'src', 'renderer', 'screen.js'), 'utf8').replace(/\r\n/g, '\n'); + +function iifes(src) { + const lines = src.split('\n'); + const segs = []; + let cur = null; + lines.forEach((line) => { + if (/^\(function\s*\(\)\s*\{/.test(line)) { cur = []; return; } + if (/^\}\)\(\);/.test(line)) { if (cur) segs.push(cur.join('\n')); cur = null; return; } + if (cur) cur.push(line); + }); + return segs; +} + +// Function declarations at the IIFE's own top level (4-space indent). +function topLevelFns(seg) { + const out = new Set(); + for (const m of seg.matchAll(/^ {4}(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(/gm)) out.add(m[1]); + return out; +} +// Names an IIFE defines for itself as variables (e.g. `const getCurrentSongKey = window._ae… || …`). +function topLevelVars(seg) { + const out = new Set(); + for (const m of seg.matchAll(/^ {4}(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=/gm)) out.add(m[1]); + return out; +} + +// Code only: drop comments and string/template literals so prose mentions don't count. +function codeOnly(seg) { + return seg + .replace(/\/\*[\s\S]*?\*\//g, ' ') + .replace(/\/\/[^\n]*/g, ' ') + .replace(/`(?:\\[\s\S]|[^`\\])*`/g, '``') + .replace(/'(?:\\.|[^'\\\n])*'/g, "''") + .replace(/"(?:\\.|[^"\\\n])*"/g, '""'); +} + +test('screen.js is made of several IIFEs', () => { + assert.ok(iifes(SRC).length >= 2); +}); + +test('no IIFE calls a top-level function that only another IIFE declares', () => { + const segs = iifes(SRC); + const decl = segs.map(topLevelFns); + const vars = segs.map(topLevelVars); + const problems = []; + segs.forEach((seg, i) => { + const code = codeOnly(seg); + decl.forEach((names, j) => { + if (i === j) return; + for (const name of names) { + if (decl[i].has(name) || vars[i].has(name)) continue; // its own copy / alias + // a bare call: not a property access (x.name) or a declaration + const re = new RegExp(`(^|[^.\\w$])${name.replace(/\$/g, '\\$')}\\s*\\(`, 'm'); + if (re.test(code)) problems.push(`IIFE ${i + 1} calls ${name}() declared only in IIFE ${j + 1}`); + } + }); + }); + assert.deepEqual(problems, []); +}); + +test('the song-start lock check goes through the window export', () => { + assert.match(SRC, /const songLock = window\._aeSongToneLock;/); + assert.match(SRC, /songLock\.get\(songKey\)/); +}); diff --git a/tests/song-tone-lock.test.js b/tests/song-tone-lock.test.js new file mode 100644 index 0000000..0c1ec2f --- /dev/null +++ b/tests/song-tone-lock.test.js @@ -0,0 +1,154 @@ +// Whole-song tone lock: one saved preset held for an entire song from the +// in-player Tone Switching panel, overriding Tone Automation / per-tone maps. + +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const path = require('node:path'); +const fs = require('node:fs'); +const vm = require('node:vm'); + +const SCREEN_JS = fs.readFileSync(path.join(__dirname, '..', 'src', 'renderer', 'screen.js'), 'utf8'); + +function extractFunction(src, name) { + const start = src.search(new RegExp(`(async )?function ${name}\\(`)); + assert.ok(start !== -1, `function '${name}' not found`); + let i = src.indexOf('{', src.indexOf(')', start)) + 1; + let depth = 1; + while (i < src.length && depth > 0) { + if (src[i] === '{') depth++; + else if (src[i] === '}') depth--; + i++; + } + return src.slice(start, i); +} + +function harness(presets, { queue } = {}) { + const store = {}; + const loads = []; + const q = { on: !!queue }; + const ctx = { + window: { feedBack: { playQueue: { active: () => q.on } } }, + console: { log() {} }, + localStorage: { + getItem: (k) => (k in store ? store[k] : null), + setItem: (k, v) => { store[k] = String(v); }, + }, + getPresets: () => presets, + loadPresetByName: async (n) => { loads.push(n); return true; }, + }; + const code = [ + "const SONG_TONE_LOCK_KEY = 'slopsmith-song-tone-lock';", + 'let _queueToneLock = null;', + extractFunction(SCREEN_JS, 'playQueueActive'), + extractFunction(SCREEN_JS, 'readSongToneLocks'), + extractFunction(SCREEN_JS, 'getSongToneLock'), + extractFunction(SCREEN_JS, 'setSongToneLock'), + extractFunction(SCREEN_JS, 'applySongToneLock'), + 'this.get = getSongToneLock; this.set = setSongToneLock; this.apply = applySongToneLock;', + 'this.setQueueLock = (v) => { _queueToneLock = v; }; this.queueLock = () => _queueToneLock;', + ].join('\n'); + vm.runInNewContext(code, ctx); + return { ctx, store, loads, q }; +} + +const PRESETS = { 'Main Lead': {}, 'Auto · Lead (Mesa Mark V)': {} }; + +test('a lock is stored per song and read back', () => { + const { ctx } = harness(PRESETS); + assert.equal(ctx.get('song-a'), null); + ctx.set('song-a', 'Main Lead'); + assert.equal(ctx.get('song-a'), 'Main Lead'); + assert.equal(ctx.get('song-b'), null, 'other songs are unaffected'); +}); + +test('"Follow tone changes" clears the lock', () => { + const { ctx } = harness(PRESETS); + ctx.set('song-a', 'Main Lead'); + ctx.set('song-a', null); + assert.equal(ctx.get('song-a'), null); +}); + +test('a lock on a deleted preset is ignored', () => { + const { ctx } = harness(PRESETS); + ctx.set('song-a', 'Gone Preset'); + assert.equal(ctx.get('song-a'), null); +}); + +test('corrupt storage reads as no locks', () => { + const { ctx, store } = harness(PRESETS); + store['slopsmith-song-tone-lock'] = '{not json'; + assert.equal(ctx.get('song-a'), null); + ctx.set('song-a', 'Main Lead'); + assert.equal(ctx.get('song-a'), 'Main Lead'); +}); + +test('applying a lock loads the preset and ignores later tone changes', async () => { + const { ctx, loads } = harness(PRESETS); + await ctx.apply('Main Lead'); + assert.deepEqual(loads, ['Main Lead']); + const sw = ctx.window._toneSwitcher; + assert.equal(sw.songLock, 'Main Lead'); + sw.switchToTone('mychdead_solo'); + assert.deepEqual(loads, ['Main Lead'], 'a solo tone change does not switch presets'); +}); + +test('song start checks the lock before any switching mode', () => { + const lockAt = SCREEN_JS.indexOf('const lockedPreset = songLock && typeof songLock.get'); + const midiAt = SCREEN_JS.indexOf('// Check for MIDI PC mode', lockAt); + const taAt = SCREEN_JS.indexOf('window._aeToneAutomation.installSwitcherForSong(', lockAt); + assert.ok(lockAt > 0 && midiAt > lockAt && taAt > lockAt); + assert.match(SCREEN_JS, /if \(!window\._toneSwitcher\.songLock\) showToneToast\(activeTone\);/); +}); + +test('the picker lives in the player menu, in the Tone & tuning group', () => { + const inject = extractFunction(SCREEN_JS, 'injectSongTonePicker'); + assert.match(inject, /sel\.id = 'ae-song-tone-pick'/); + assert.match(inject, /setAttribute\('data-ae-chain'/, 'data-ae-chain puts it in the "Tone & tuning" group'); + assert.match(extractFunction(SCREEN_JS, 'fillSongTonePicker'), /Tone: follow song/); + // Injected with the chain button on every song, regardless of provider. + const btn = extractFunction(SCREEN_JS, 'injectPlayerToneButton'); + assert.ok(btn.indexOf('injectSongTonePicker();') < btn.indexOf('shouldShowPlayerChainButton()')); +}); + +test('every switching path honours the lock', () => { + const ta = extractFunction(SCREEN_JS, 'installTaSwitcherForSong'); + assert.match(ta, /const locked = getSongToneLock\(songKey\);/); + const maps = extractFunction(SCREEN_JS, '_applyToneMappingsImpl'); + assert.match(maps, /const lockedForSong = getSongToneLock\(songKey\);/); + // onSongTonePick sits outside the preload closure: it must not touch + // _preloadedToneCacheKey (a ReferenceError there broke "follow song"). + const pick = extractFunction(SCREEN_JS, 'onSongTonePick'); + assert.doesNotMatch(pick, /_preloadedToneCacheKey|[^.]startToneAutoSwitch\(/); +}); + +test('a pick during a queue / album playthrough holds for the next songs', () => { + const { ctx, q } = harness(PRESETS, { queue: true }); + ctx.setQueueLock('Main Lead'); // what onSongTonePick does mid-queue + assert.equal(ctx.get('next-song'), 'Main Lead', 'the next song in the run keeps the pick'); + q.on = false; // the queue ended + assert.equal(ctx.get('later-song'), null, 'songs after the run follow their tones again'); + assert.equal(ctx.queueLock(), null, 'and the run lock is cleared'); +}); + +test('a song lock wins over the run lock; picking during a run sets both', () => { + const { ctx } = harness(PRESETS, { queue: true }); + ctx.set('song-a', 'Auto · Lead (Mesa Mark V)'); + ctx.setQueueLock('Main Lead'); + assert.equal(ctx.get('song-a'), 'Auto · Lead (Mesa Mark V)'); + assert.equal(ctx.get('song-b'), 'Main Lead'); + const pick = extractFunction(SCREEN_JS, 'onSongTonePick'); + assert.match(pick, /if \(playQueueActive\(\)\) _queueToneLock = pick \|\| null;/); + // The run lock clears when the queue reports inactive. + assert.match(SCREEN_JS, /'queue:changed'[\s\S]{0,160}if \(d\.active === false\) _queueToneLock = null;/); +}); + +test('the picker reloads its list on open, so a tone saved mid-song shows up', () => { + const inject = extractFunction(SCREEN_JS, 'injectSongTonePicker'); + assert.match(inject, /addEventListener\('pointerdown', \(\) => fillSongTonePicker\(sel, false\)\)/); + assert.match(inject, /addEventListener\('focus', \(\) => fillSongTonePicker\(sel, false\)\)/); + const fill = extractFunction(SCREEN_JS, 'fillSongTonePicker'); + // An unchanged list never touches the DOM (no flicker / no popup churn). + assert.match(fill, /if \(!force && sel\._aeSig === sig\) return;/); +});