diff --git a/src/renderer/live-retune/screen.js b/src/renderer/live-retune/screen.js index a325bdf..a32df19 100644 --- a/src/renderer/live-retune/screen.js +++ b/src/renderer/live-retune/screen.js @@ -245,7 +245,79 @@ render(); } - window.__liveRetune = { state, set, apply, songTuningSt, followSt, shiftSt }; + // ── Instrument-menu section ("Shift my guitar") ──────────────────────── + // The core's v3 guitar dropdown (static/v3/badges.js) takes extra sections via + // v3Badges.registerMenuSection. This one drives the same state as the player + // bar: pick what the guitar should SOUND as and the engine shifts the signal; + // the strings (and the tuner) stay where they are. + const escText = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ( + { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); + // What the strings are tuned to (the host's working tuning), as offsets. + function guitarOffsets() { + const wt = window.feedBack && window.feedBack.workingTuning; + let st = null; + try { st = wt && typeof wt.get === 'function' ? wt.get() : null; } catch (_) { st = null; } + const n = (st && Number(st.stringCount)) || 6; + const off = st && Array.isArray(st.offsets) ? st.offsets : []; + const out = []; + for (let i = 0; i < n; i++) out.push(Number.isFinite(Number(off[i])) ? Number(off[i]) : 0); + return out; + } + // Name of the guitar's tuning moved by `st` semitones, e.g. E Standard -2 -> "D Standard". + function shiftedTuningName(offsets, st) { + const moved = offsets.map((o) => o + st); + const nameFor = window.displayTuningName || (window.feedBack && window.feedBack.displayTuningName); + const name = typeof nameFor === 'function' ? nameFor(null, moved) : ''; + if (name && name !== 'Custom Tuning') return name; + return st === 0 ? 'No shift' : `${st > 0 ? '+' : ''}${st} st`; + } + function renderMenuSection(slot, ctx) { + const base = guitarOffsets(); + const cur = state.semitones; + const fst = followSt(); + const pill = (attr, label, active, title) => ''; + let opts = ''; + for (let st = -MAX_ST; st <= MAX_ST; st++) { + opts += ''; + } + const status = supported === false ? 'Not supported by this audio engine' + : (shiftSt() || state.cents || matchCents()) + ? 'Sounding as ' + shiftedTuningName(base, shiftSt()) + (state.cents ? ` ${state.cents > 0 ? '+' : ''}${state.cents}c` : '') + : 'No shift'; + slot.innerHTML = '
' + + '
Shift my guitar
' + + '
' + escText(status) + '
' + + '
' + + pill('data-lr-down', '−', false, 'Down a semitone') + + '' + + pill('data-lr-up', '+', false, 'Up a semitone') + + '
' + + '
' + + pill('data-lr-follow', 'Follow song' + (state.follow && fst ? ` ${fst > 0 ? '+' : ''}${fst}` : ''), state.follow, + 'Also shift by the song’s tuning when every string is down (or up) by the same amount, so a guitar in E plays Eb/D songs without retuning.') + + (cur || state.cents ? pill('data-lr-zero', 'No shift', false, 'Back to no shift') : '') + + '
'; + const setAndRefresh = (patch) => { set(patch); ctx.refresh(); }; + slot.querySelector('[data-lr-sound-as]').addEventListener('change', (e) => setAndRefresh({ semitones: Number(e.target.value) })); + slot.querySelector('[data-lr-down]').addEventListener('click', () => setAndRefresh({ semitones: state.semitones - 1 })); + slot.querySelector('[data-lr-up]').addEventListener('click', () => setAndRefresh({ semitones: state.semitones + 1 })); + slot.querySelector('[data-lr-follow]').addEventListener('click', () => setAndRefresh({ follow: !state.follow })); + const zero = slot.querySelector('[data-lr-zero]'); + if (zero) zero.addEventListener('click', () => setAndRefresh({ semitones: 0, cents: 0 })); + } + (function registerMenuSection() { + const section = { id: 'live-retune-shift', render: renderMenuSection, order: 10 }; + if (window.v3Badges && typeof window.v3Badges.registerMenuSection === 'function') { + window.v3Badges.registerMenuSection(section.id, section.render, section); + } else { + window._v3BadgesPendingSections = window._v3BadgesPendingSections || []; + window._v3BadgesPendingSections.push(section); + } + })(); + + window.__liveRetune = { state, set, apply, songTuningSt, followSt, shiftSt, shiftedTuningName, renderMenuSection }; window.addEventListener('songcents:change', () => { apply(); render(); }); const bus = window.feedBack || window.slopsmith; diff --git a/src/renderer/screen.js b/src/renderer/screen.js index 2f1e85d..c9bc8c9 100644 --- a/src/renderer/screen.js +++ b/src/renderer/screen.js @@ -2280,6 +2280,144 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; else localStorage.setItem('slopsmith-default-preset-name', name); } + // ── Top tones (instrument menu) ────────────────────────────────────────── + // Starred presets first, then the most-loaded ones, as one-click buttons in + // the core's instrument menu. Stars: array of preset names. Counts: name → n, + // bumped by recordPresetUse on every load of a named preset except the + // startup default (which would just count app launches). + const PRESET_STARS_KEY = 'slopsmith-preset-stars'; + const PRESET_USES_KEY = 'slopsmith-preset-use-counts'; + const TOP_TONES_LIMIT = 5; + function readPresetStars() { + try { + const v = JSON.parse(localStorage.getItem(PRESET_STARS_KEY) || '[]'); + return Array.isArray(v) ? v.filter((n) => typeof n === 'string' && n) : []; + } catch (e) { return []; } + } + function writePresetStars(names) { + try { localStorage.setItem(PRESET_STARS_KEY, JSON.stringify(names)); } catch (e) { + console.warn('[audio-engine] could not save starred presets:', e); + } + } + function readPresetUses() { + try { + const v = JSON.parse(localStorage.getItem(PRESET_USES_KEY) || '{}'); + return (v && typeof v === 'object' && !Array.isArray(v)) ? v : {}; + } catch (e) { return {}; } + } + function writePresetUses(uses) { + try { localStorage.setItem(PRESET_USES_KEY, JSON.stringify(uses)); } catch (e) { + console.warn('[audio-engine] could not save preset use counts:', e); + } + } + function togglePresetStar(name) { + const stars = readPresetStars(); + const i = stars.indexOf(name); + if (i >= 0) stars.splice(i, 1); else stars.push(name); + writePresetStars(stars); + return i < 0; + } + function recordPresetUse(name) { + if (!name) return; + const uses = readPresetUses(); + uses[name] = (Number(uses[name]) || 0) + 1; + writePresetUses(uses); + } + // Drop a deleted preset from stars and counts. + function forgetPresetStats(name) { + const stars = readPresetStars(); + if (stars.includes(name)) writePresetStars(stars.filter((n) => n !== name)); + const uses = readPresetUses(); + if (name in uses) { delete uses[name]; writePresetUses(uses); } + } + /** Starred (in star order), then most used (ties by name), only presets that + * still exist, at most `limit`. */ + function topTonePresetNames(presets, stars, uses, limit) { + const exists = (n) => Object.prototype.hasOwnProperty.call(presets || {}, n); + const out = []; + for (const n of stars || []) if (exists(n) && !out.includes(n)) out.push(n); + const used = Object.keys(uses || {}) + .filter((n) => exists(n) && !out.includes(n) && Number(uses[n]) > 0) + .sort((a, b) => (Number(uses[b]) - Number(uses[a])) || a.localeCompare(b)); + return out.concat(used).slice(0, limit); + } + /** How much each preset is used: counted loads, plus the choices already on + * record before counting existed (each song's whole-song tone lock, and each + * Tone Automation slot that targets it), so Top tones isn't empty on day one. */ + function presetUseScores(uses, songLocks, taTargets) { + const out = {}; + const add = (n, k) => { if (typeof n === 'string' && n) out[n] = (out[n] || 0) + k; }; + for (const [n, c] of Object.entries(uses || {})) add(n, Number(c) || 0); + for (const n of Object.values(songLocks || {})) add(n, 1); + // The 'bass' slot is the tone for bass arrangements, not a guitar tone. + for (const [slot, n] of Object.entries(taTargets || {})) if (slot !== 'bass') add(n, 1); + return out; + } + // The one manual "load this preset now" path (Settings → Load and the + // instrument menu's top tones). Snapshots the chain so a failed load rolls back. + // Runs under the tone chain lock so it can't interleave with a song's chain + // rebuild, and refuses while a song is loading (that rebuild would replace it). + async function loadPresetManually(name, source) { + const p = getPresets()[name]; + if (!p) return false; + if (isSongTransitioning()) { + console.warn('[audio-engine] Not loading preset during a song load:', name); + return false; + } + const ok = await withToneChainLock(() => replaceChainWithPresetBlob(p, `${source}:${name}`)); + if (ok) { + recordPresetUse(name); + console.log('[audio-engine] Preset loaded:', name); + } + return ok; + } + let _instMenuLoading = null; + function renderInstMenuTopTones(slot, ctx) { + const presets = getPresets(); + if (!Object.keys(presets).length) { slot.innerHTML = ''; return; } + const scores = presetUseScores(readPresetUses(), readSongToneLocks(), (readTaStore() || {}).targets); + const names = topTonePresetNames(presets, readPresetStars(), scores, TOP_TONES_LIMIT); + const stars = readPresetStars(); + const head = '
Top tones
'; + if (!names.length) { + slot.innerHTML = '
' + head + + '
Star tones in Audio Engine settings to pin them here.
'; + return; + } + slot.innerHTML = '
' + head + '
' + + names.map((n) => { + const busy = n === _instMenuLoading; + return ''; + }).join('') + '
'; + slot.querySelectorAll('[data-top-tone]').forEach((b) => b.addEventListener('click', async () => { + const name = b.getAttribute('data-top-tone'); + if (_instMenuLoading) return; + _instMenuLoading = name; + ctx.refresh(); + try { + if (!(await loadPresetManually(name, 'inst-menu'))) console.warn('[audio-engine] top tone did not load:', name); + } finally { + _instMenuLoading = null; + ctx.refresh(); + } + })); + } + // Core's v3 instrument menu (static/v3/badges.js) takes extra sections via + // v3Badges.registerMenuSection; queue the section if it hasn't loaded yet. + // Older cores without the hook just don't show top tones. + (function registerTopTones() { + const section = { id: 'audio-engine-top-tones', render: renderInstMenuTopTones, order: 20 }; + if (window.v3Badges && typeof window.v3Badges.registerMenuSection === 'function') { + window.v3Badges.registerMenuSection(section.id, section.render, section); + } else { + window._v3BadgesPendingSections = window._v3BadgesPendingSections || []; + window._v3BadgesPendingSections.push(section); + } + })(); + /** Older saved presets may omit `items`; iterating undefined throws and can crash the embedded UI. */ function getPresetItems(preset) { const items = preset?.items; @@ -2637,7 +2775,9 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; const div = document.createElement('div'); div.className = 'flex items-center gap-2 p-2 rounded bg-slate-800/50 text-sm'; const eName = escHtml(name); + const starred = readPresetStars().includes(name); div.innerHTML = ` + ${eName}${name === defaultPresetName ? ' (default)' : ''} ${getPresetItems(presets[name]).length} processors @@ -2648,12 +2788,12 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; setDefaultPresetName(name); renderPresetList(); }); + div.querySelector('[data-action="star"]').addEventListener('click', () => { + togglePresetStar(name); + renderPresetList(); + }); div.querySelector('[data-action="load"]').addEventListener('click', async () => { - const p = getPresets()[name]; - if (!p) return; - if (await replaceChainWithPresetBlob(p, `settings-load:${name}`)) { - console.log('[audio-engine] Preset loaded:', name); - } + await loadPresetManually(name, 'settings-load'); }); div.querySelector('[data-action="delete"]').addEventListener('click', () => { const ps = getPresets(); @@ -2672,6 +2812,7 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; if (presetRef === name) { delete taCfg.targets[cat]; taDirty = true; } } if (taDirty) writeTaStore(taCfg); + forgetPresetStats(name); renderPresetList(); renderToneAutomationTargets(); }); @@ -4248,6 +4389,7 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; if (!preset?.nativePreset) return false; const ok = await replaceChainWithPresetBlob(preset, `tone-automation:${presetName}`, { snapshot: false }); if (!ok) console.error('[tone-automation] Failed to load preset:', presetName); + else recordPresetUse(presetName); return ok; } diff --git a/tests/live-retune-menu.test.js b/tests/live-retune-menu.test.js new file mode 100644 index 0000000..4093a2c --- /dev/null +++ b/tests/live-retune-menu.test.js @@ -0,0 +1,108 @@ +// Live Retune's "Shift my guitar" section in the core's guitar dropdown: picking +// what the guitar should sound as drives the engine's live pitch shift. Runs the +// real plugin script in a vm with a stub engine bridge, a stub v3Badges hook and a +// fake menu slot. + +'use strict'; + +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, '..', 'src', 'renderer', 'live-retune', 'screen.js'), 'utf8'); + +function fakeSlot() { + const els = {}; + return { + innerHTML: '', + els, + querySelector(sel) { + if (!this.innerHTML.includes(sel.replace(/^\[|\]$/g, ''))) return null; + return els[sel] || (els[sel] = { handlers: {}, addEventListener(t, f) { this.handlers[t] = f; } }); + }, + }; +} + +function run({ saved = {}, offsets = null, withHook = true } = {}) { + const calls = []; + const registered = []; + const store = { liveRetune: JSON.stringify(saved) }; + const window = { + feedBackDesktop: { + audio: { + setLivePitch: (p) => { calls.push(p); return Promise.resolve(); }, + getLivePitch: () => Promise.resolve({ supported: true, cents: 0, windowMs: 14, latencyMs: 0 }), + }, + }, + feedBack: { workingTuning: { get: () => ({ stringCount: 6, offsets }) } }, + displayTuningName: (v, o) => ({ + '0,0,0,0,0,0': 'E Standard', '-1,-1,-1,-1,-1,-1': 'Eb Standard', '-2,-2,-2,-2,-2,-2': 'D Standard', + '-2,0,0,0,0,0': 'Drop D', '-3,-1,-1,-1,-1,-1': 'Drop C#', + })[o.join(',')] || 'Custom Tuning', + highway: { getSongInfo: () => ({ tuning: [0, 0, 0, 0, 0, 0] }) }, + addEventListener: () => {}, + }; + if (withHook) window.v3Badges = { registerMenuSection: (id, render, opts) => { registered.push({ id, render, opts }); return true; } }; + const ctx = { + window, + document: { getElementById: () => null, createElement: () => ({}) }, + localStorage: { getItem: (k) => store[k] ?? null, setItem: (k, v) => { store[k] = v; } }, + setInterval: () => 0, + Promise, + }; + vm.runInNewContext(SRC, ctx); + return { window, lr: window.__liveRetune, calls, registered, last: () => calls[calls.length - 1] }; +} + +test('registers a "Shift my guitar" section ahead of other sections', () => { + const { registered } = run(); + assert.equal(registered.length, 1); + assert.equal(registered[0].id, 'live-retune-shift'); + assert.equal(registered[0].opts.order, 10); +}); + +test('queues the section when the core hook is not loaded yet', () => { + const { window } = run({ withHook: false }); + assert.equal(window._v3BadgesPendingSections.length, 1); + assert.equal(window._v3BadgesPendingSections[0].id, 'live-retune-shift'); +}); + +test('"Sound as" names the shifted tuning from the guitar tuning', () => { + const { lr } = run(); + assert.equal(lr.shiftedTuningName([0, 0, 0, 0, 0, 0], -2), 'D Standard'); + assert.equal(lr.shiftedTuningName([-2, 0, 0, 0, 0, 0], -1), 'Drop C#'); + assert.equal(lr.shiftedTuningName([0, 0, 0, 0, 0, 0], 3), '+3 st', 'unnamed shifts show the semitones'); +}); + +test('picking a tuning in the menu shifts the guitar signal', () => { + const { registered, last } = run(); + const slot = fakeSlot(); + let refreshed = 0; + registered[0].render(slot, { refresh: () => { refreshed++; } }); + assert.match(slot.innerHTML, /Shift my guitar/); + assert.match(slot.innerHTML, /