From 95ae4bb7b6a154f91b16af139eaea45de74ad5f0 Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:33:42 -0800 Subject: [PATCH 1/5] feat(renderer): top tones in the instrument menu Star presets in the Audio Engine preset list; the core's instrument menu then shows starred tones first, filled out with the most-loaded ones (up to 5), as one-click loads. Uses are counted on manual loads and tone automation / tone-lock loads, not the startup default. Deleting a preset drops its star and count. Settings -> Load and the menu share one loadPresetManually path. Needs a core with v3Badges.registerMenuSection (feat/inst-menu-tuning); older cores just don't show the section. Co-Authored-By: Claude Opus 5.5 --- src/renderer/screen.js | 136 +++++++++++++++++++++++++++++++++-- tests/test-inventory.test.js | 2 +- tests/top-tones.test.js | 112 +++++++++++++++++++++++++++++ 3 files changed, 244 insertions(+), 6 deletions(-) create mode 100644 tests/top-tones.test.js diff --git a/src/renderer/screen.js b/src/renderer/screen.js index 2f1e85d..655479f 100644 --- a/src/renderer/screen.js +++ b/src/renderer/screen.js @@ -2280,6 +2280,128 @@ 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); + } + // 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. + async function loadPresetManually(name, source) { + const p = getPresets()[name]; + if (!p) return false; + const ok = await replaceChainWithPresetBlob(p, `${source}:${name}`); + if (ok) { + recordPresetUse(name); + console.log('[audio-engine] Preset loaded:', name); + } + return ok; + } + let _instMenuLastTone = null; + let _instMenuLoading = null; + function renderInstMenuTopTones(slot, ctx) { + const presets = getPresets(); + if (!Object.keys(presets).length) { slot.innerHTML = ''; return; } + const names = topTonePresetNames(presets, readPresetStars(), readPresetUses(), 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 active = n === _instMenuLastTone; + 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')) _instMenuLastTone = name; + else console.warn('[audio-engine] top tone failed to 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 }; + if (window.v3Badges && typeof window.v3Badges.registerMenuSection === 'function') { + window.v3Badges.registerMenuSection(section.id, section.render); + } 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 +2759,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 +2772,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 +2796,7 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; if (presetRef === name) { delete taCfg.targets[cat]; taDirty = true; } } if (taDirty) writeTaStore(taCfg); + forgetPresetStats(name); renderPresetList(); renderToneAutomationTargets(); }); @@ -4248,6 +4373,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/test-inventory.test.js b/tests/test-inventory.test.js index 7a1ea6d..aaebbc6 100644 --- a/tests/test-inventory.test.js +++ b/tests/test-inventory.test.js @@ -27,7 +27,7 @@ const ALL = [ 'live-pitch', 'live-retune-follow-song', 'midi-chain-preserve', 'ml-note-detection', 'monitor-mute-suppression', 'multi-source', 'napi-arg-fuzz', 'preset-swap-mute', 'renderer-capability-migration', 'renderer-iife-scope', - 'song-tone-lock', 'startup-missing-input', 'test-inventory', + 'song-tone-lock', 'startup-missing-input', 'test-inventory', 'top-tones', 'tone-automation-base-tone', 'tone-load-no-stall', 'tone-switcher-parity', 'window-bounds', ]; diff --git a/tests/top-tones.test.js b/tests/top-tones.test.js new file mode 100644 index 0000000..57b2198 --- /dev/null +++ b/tests/top-tones.test.js @@ -0,0 +1,112 @@ +// Top tones in the core's instrument menu: starred presets first, then the +// most-loaded ones. Pins the ordering, the use counting, the delete scrub and +// the registration with the core's v3Badges.registerMenuSection hook. + +'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, { loadOk = true } = {}) { + const store = {}; + const loads = []; + const ctx = { + console: { log() {}, warn() {} }, + localStorage: { + getItem: (k) => (k in store ? store[k] : null), + setItem: (k, v) => { store[k] = String(v); }, + }, + getPresets: () => presets, + replaceChainWithPresetBlob: async (p, tag) => { loads.push(tag); return loadOk; }, + }; + const code = [ + "const PRESET_STARS_KEY = 'slopsmith-preset-stars';", + "const PRESET_USES_KEY = 'slopsmith-preset-use-counts';", + ...['readPresetStars', 'writePresetStars', 'readPresetUses', 'writePresetUses', + 'togglePresetStar', 'recordPresetUse', 'forgetPresetStats', 'topTonePresetNames', + 'loadPresetManually'].map((n) => extractFunction(SCREEN_JS, n)), + 'Object.assign(this, { readPresetStars, readPresetUses, togglePresetStar, recordPresetUse, forgetPresetStats, topTonePresetNames, loadPresetManually });', + ].join('\n'); + vm.runInNewContext(code, ctx); + return { ctx, store, loads }; +} + +const PRESETS = { 'Main Lead': {}, 'Black Parade Lead': {}, Clean: {}, Crunch: {} }; +const arr = (a) => Array.from(a); + +test('starred presets come first, in star order, then most used', () => { + const { ctx } = harness(PRESETS); + const names = ctx.topTonePresetNames(PRESETS, ['Clean', 'Main Lead'], { Crunch: 2, 'Black Parade Lead': 9, 'Main Lead': 50 }, 5); + assert.deepEqual(arr(names), ['Clean', 'Main Lead', 'Black Parade Lead', 'Crunch']); +}); + +test('drops deleted presets, unused ones, and respects the limit', () => { + const { ctx } = harness(PRESETS); + assert.deepEqual(arr(ctx.topTonePresetNames(PRESETS, ['Gone'], { Gone: 5, Clean: 0, Crunch: 1 }, 5)), ['Crunch']); + assert.deepEqual(arr(ctx.topTonePresetNames(PRESETS, [], { Clean: 1, Crunch: 1, 'Main Lead': 1 }, 2)), ['Clean', 'Crunch'], 'ties sort by name'); +}); + +test('star toggles on and off', () => { + const { ctx } = harness(PRESETS); + assert.equal(ctx.togglePresetStar('Clean'), true); + assert.deepEqual(arr(ctx.readPresetStars()), ['Clean']); + assert.equal(ctx.togglePresetStar('Clean'), false); + assert.deepEqual(arr(ctx.readPresetStars()), []); +}); + +test('a manual load counts a use; a failed one does not', async () => { + const ok = harness(PRESETS); + assert.equal(await ok.ctx.loadPresetManually('Main Lead', 'inst-menu'), true); + assert.deepEqual(ok.loads, ['inst-menu:Main Lead']); + assert.equal(ok.ctx.readPresetUses()['Main Lead'], 1); + + const bad = harness(PRESETS, { loadOk: false }); + assert.equal(await bad.ctx.loadPresetManually('Main Lead', 'inst-menu'), false); + assert.equal(bad.ctx.readPresetUses()['Main Lead'], undefined); + assert.equal(await bad.ctx.loadPresetManually('Nope', 'inst-menu'), false); +}); + +test('deleting a preset forgets its star and count', () => { + const { ctx } = harness(PRESETS); + ctx.togglePresetStar('Clean'); + ctx.recordPresetUse('Clean'); + ctx.recordPresetUse('Crunch'); + ctx.forgetPresetStats('Clean'); + assert.deepEqual(arr(ctx.readPresetStars()), []); + assert.deepEqual(Object.keys(ctx.readPresetUses()), ['Crunch']); +}); + +test('corrupt storage reads as empty', () => { + const { ctx, store } = harness(PRESETS); + store['slopsmith-preset-stars'] = '{oops'; + store['slopsmith-preset-use-counts'] = '[1,2]'; + assert.deepEqual(arr(ctx.readPresetStars()), []); + assert.deepEqual(Object.keys(ctx.readPresetUses()), []); +}); + +test('wiring: Settings Load and tone automation count uses; delete scrubs; section registers', () => { + assert.match(SCREEN_JS, /data-action="load"\]'\)\.addEventListener\('click', async \(\) => \{\s*await loadPresetManually\(name, 'settings-load'\);/); + assert.match(extractFunction(SCREEN_JS, 'loadPresetByName'), /recordPresetUse\(presetName\)/); + assert.match(SCREEN_JS, /forgetPresetStats\(name\);\s*renderPresetList\(\);/); + assert.doesNotMatch(extractFunction(SCREEN_JS, 'loadDefaultPreset'), /recordPresetUse/, 'startup default load is not a use'); + assert.match(SCREEN_JS, /registerMenuSection\(section\.id, section\.render\)/); + assert.match(SCREEN_JS, /_v3BadgesPendingSections\.push\(section\)/); +}); From 67db82a562359374f78656c9e1960a804a562b71 Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:38:16 -0800 Subject: [PATCH 2/5] fix(renderer): top tones load under the chain lock, not mid song-load Manual preset loads (Settings -> Load, instrument menu) now run under withToneChainLock and refuse while a song is loading, so they can't interleave with a song's chain rebuild. Drops the menu's 'last loaded' highlight, which went stale when anything else swapped the chain. Co-Authored-By: Claude Opus 5.5 --- src/renderer/screen.js | 17 ++++++++++------- tests/top-tones.test.js | 11 ++++++++++- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/src/renderer/screen.js b/src/renderer/screen.js index 655479f..e7fbd08 100644 --- a/src/renderer/screen.js +++ b/src/renderer/screen.js @@ -2343,17 +2343,22 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; } // 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; - const ok = await replaceChainWithPresetBlob(p, `${source}:${name}`); + 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 _instMenuLastTone = null; let _instMenuLoading = null; function renderInstMenuTopTones(slot, ctx) { const presets = getPresets(); @@ -2368,10 +2373,9 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; } slot.innerHTML = '
' + head + '
' + names.map((n) => { - const active = n === _instMenuLastTone; const busy = n === _instMenuLoading; return ''; }).join('') + '
'; @@ -2381,8 +2385,7 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; _instMenuLoading = name; ctx.refresh(); try { - if (await loadPresetManually(name, 'inst-menu')) _instMenuLastTone = name; - else console.warn('[audio-engine] top tone failed to load:', name); + if (!(await loadPresetManually(name, 'inst-menu'))) console.warn('[audio-engine] top tone did not load:', name); } finally { _instMenuLoading = null; ctx.refresh(); @@ -2761,7 +2764,7 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; const eName = escHtml(name); const starred = readPresetStars().includes(name); div.innerHTML = ` - + ${eName}${name === defaultPresetName ? ' (default)' : ''} ${getPresetItems(presets[name]).length} processors diff --git a/tests/top-tones.test.js b/tests/top-tones.test.js index 57b2198..be72d5e 100644 --- a/tests/top-tones.test.js +++ b/tests/top-tones.test.js @@ -25,10 +25,14 @@ function extractFunction(src, name) { return src.slice(start, i); } -function harness(presets, { loadOk = true } = {}) { +function harness(presets, { loadOk = true, transitioning = false } = {}) { const store = {}; const loads = []; + const locked = []; const ctx = { + isSongTransitioning: () => transitioning, + withToneChainLock: (job) => { locked.push(true); return job(); }, + locked, console: { log() {}, warn() {} }, localStorage: { getItem: (k) => (k in store ? store[k] : null), @@ -76,8 +80,13 @@ test('a manual load counts a use; a failed one does not', async () => { const ok = harness(PRESETS); assert.equal(await ok.ctx.loadPresetManually('Main Lead', 'inst-menu'), true); assert.deepEqual(ok.loads, ['inst-menu:Main Lead']); + assert.equal(ok.ctx.locked.length, 1, 'the load runs under the tone chain lock'); assert.equal(ok.ctx.readPresetUses()['Main Lead'], 1); + const mid = harness(PRESETS, { transitioning: true }); + assert.equal(await mid.ctx.loadPresetManually('Main Lead', 'inst-menu'), false, 'no manual load during a song load'); + assert.deepEqual(mid.loads, []); + const bad = harness(PRESETS, { loadOk: false }); assert.equal(await bad.ctx.loadPresetManually('Main Lead', 'inst-menu'), false); assert.equal(bad.ctx.readPresetUses()['Main Lead'], undefined); From 407245be5c42d46eef9e2b99316e07738a86ea68 Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:48:44 -0800 Subject: [PATCH 3/5] feat(live-retune): shift the guitar from the guitar dropdown Live Retune adds a "Shift my guitar" section to the core's instrument menu: a "Sound as" list (+-5 semitones, named from the guitar's current tuning, e.g. E Standard -> Eb/D Standard), -/+ buttons, No shift and the Follow song toggle. It drives the same engine live pitch shift as the player bar; the strings and the tuner are untouched. Sections now pass an order (shift 10, top tones 20). Co-Authored-By: Claude Opus 5.5 --- src/renderer/live-retune/screen.js | 74 +++++++++++++++++++- src/renderer/screen.js | 4 +- tests/live-retune-menu.test.js | 108 +++++++++++++++++++++++++++++ tests/test-inventory.test.js | 2 +- tests/top-tones.test.js | 3 +- 5 files changed, 186 insertions(+), 5 deletions(-) create mode 100644 tests/live-retune-menu.test.js 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 e7fbd08..fa77b4e 100644 --- a/src/renderer/screen.js +++ b/src/renderer/screen.js @@ -2396,9 +2396,9 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; // 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 }; + 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); + window.v3Badges.registerMenuSection(section.id, section.render, section); } else { window._v3BadgesPendingSections = window._v3BadgesPendingSections || []; window._v3BadgesPendingSections.push(section); 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, /