Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
154 changes: 153 additions & 1 deletion src/renderer/screen.js
Original file line number Diff line number Diff line change
Expand Up @@ -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?.()) {
Expand Down Expand Up @@ -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 = `<option value="">Tone: follow song</option>`
+ names.map(n => `<option value="${escHtml(n)}">Tone: ${escHtml(n)}</option>`).join('');
sel.value = names.includes(keep) ? keep : '';
}
window._aeInjectSongTonePicker = injectSongTonePicker;

function injectPlayerToneButton() {
injectSongTonePicker();
const controls = document.getElementById('player-controls');
if (!shouldShowPlayerChainButton()) {
removePlayerChainButton();
Expand Down Expand Up @@ -3484,6 +3557,7 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {};
<button type="button" onclick="window._closeChainPanel && window._closeChainPanel()" class="text-slate-500 hover:text-white text-lg leading-none">&times;</button>
</div>`;


if (toneNamesOrdered.length === 0) {
const arrangementName = getCurrentArrangementName();
const originalNames = await getOriginalToneNames(songKey, arrangementName);
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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') || '{}') || {}; }
Expand Down
78 changes: 78 additions & 0 deletions tests/renderer-iife-scope.test.js
Original file line number Diff line number Diff line change
@@ -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\)/);
});
Loading
Loading