@trippnology/mixshell 0.0.0-stage → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +320 -2
  3. package/assets/mixshell-screenshot.png +0 -0
  4. package/package.json +74 -5
  5. package/src/alsa-pulse.conf +20 -0
  6. package/src/alsa-setup.js +15 -0
  7. package/src/components/browser.js +193 -0
  8. package/src/components/config.js +168 -0
  9. package/src/components/durations.js +151 -0
  10. package/src/components/library.js +679 -0
  11. package/src/components/mediakeys.js +222 -0
  12. package/src/components/mpris.js +309 -0
  13. package/src/components/player.js +436 -0
  14. package/src/components/playlist.js +335 -0
  15. package/src/components/session.js +96 -0
  16. package/src/constants.js +164 -0
  17. package/src/engines/ffmpeg.js +610 -0
  18. package/src/engines/index.js +14 -0
  19. package/src/engines/webaudio.js +317 -0
  20. package/src/index.js +188 -0
  21. package/src/mediakeys/macos-nowplaying.js +227 -0
  22. package/src/ui/app.js +56 -0
  23. package/src/ui/artPane.js +314 -0
  24. package/src/ui/confirmPrompt.js +34 -0
  25. package/src/ui/constants.js +133 -0
  26. package/src/ui/controller.js +1654 -0
  27. package/src/ui/dom.js +9 -0
  28. package/src/ui/goToPrompt.js +105 -0
  29. package/src/ui/index.html +78 -0
  30. package/src/ui/libraryPanel.js +415 -0
  31. package/src/ui/listView.js +209 -0
  32. package/src/ui/onboarding.js +353 -0
  33. package/src/ui/playlistPanel.js +207 -0
  34. package/src/ui/settingsPanel.js +473 -0
  35. package/src/ui/shortcuts.js +30 -0
  36. package/src/ui/splash.js +302 -0
  37. package/src/ui/style.css +532 -0
  38. package/src/ui/subtabs.js +31 -0
  39. package/src/ui/visualizer/bars.js +74 -0
  40. package/src/ui/visualizer/circles.js +64 -0
  41. package/src/ui/visualizer/color.js +61 -0
  42. package/src/ui/visualizer/cube.js +105 -0
  43. package/src/ui/visualizer/grid.js +68 -0
  44. package/src/ui/visualizer/index.js +65 -0
  45. package/src/ui/visualizer/onset.js +130 -0
  46. package/src/ui/visualizer/spectrum.js +34 -0
  47. package/src/ui/visualizer/vu.js +71 -0
  48. package/src/ui/visualizer/waveform.js +58 -0
  49. package/src/utils/audioAnalyzer.js +362 -0
  50. package/src/utils/audioDevices.js +222 -0
  51. package/src/utils/cellart.js +75 -0
  52. package/src/utils/debug.js +7 -0
  53. package/src/utils/durationProbe.js +48 -0
  54. package/src/utils/folderArt.js +46 -0
  55. package/src/utils/format.js +20 -0
  56. package/src/utils/id3.js +84 -0
  57. package/src/utils/pathInput.js +76 -0
  58. package/src/utils/playlistIO.js +176 -0
  59. package/src/utils/terminalGraphics.js +47 -0
@@ -0,0 +1,227 @@
1
+ // MixShell media-key helper for macOS (issues/048).
2
+ //
3
+ // Run by `osascript -l JavaScript` from src/components/mediakeys.js. It only
4
+ // uses the public MediaPlayer framework — MPNowPlayingInfoCenter publishes the
5
+ // Now Playing card, MPRemoteCommandCenter receives the F7–F9 keys and Control
6
+ // Center commands — so there is nothing to compile and no private API to
7
+ // re-verify after each macOS release.
8
+ //
9
+ // Protocol (newline-delimited JSON over stdio), MixShell → helper:
10
+ // {"type":"state","status":"playing|paused|stopped","position":<s>,
11
+ // "duration":<s>,"title":"…","artist":"…","album":"…"} whole snapshot
12
+ // helper → MixShell:
13
+ // {"type":"ready"}
14
+ // {"type":"command","name":"play|pause|toggle|stop|next|previous"}
15
+ // {"type":"seek","position":<seconds>}
16
+ // EOF on stdin means MixShell has quit: clear the card and exit.
17
+ //
18
+ // Written against the documented JXA ObjC-bridge forms only (property access
19
+ // for zero-argument methods, JSExport names for the rest, target/action
20
+ // instead of blocks) because this file can't be exercised off macOS. The
21
+ // framework's own key constants (`$.MPMediaItemPropertyTitle`, …) are used
22
+ // as-is: their exported strings are easy to get wrong and a wrong key fails
23
+ // silently, so there are no hand-typed fallbacks. Syntax likewise stays
24
+ // plain — no `?.` or `??`, which the system JavaScriptCore of macOS 10.15
25
+ // (Node 22's floor) predates.
26
+ //
27
+ // JXA quirk to keep in mind while editing: C `long`/`unsigned long` results
28
+ // come back as JS strings, hence every `Number(...)` below.
29
+
30
+ // NSApplicationActivationPolicyProhibited
31
+ const PROHIBITED = 2;
32
+ // MPNowPlayingPlaybackState
33
+ const STOPPED = 0;
34
+ const PLAYING = 1;
35
+ const PAUSED = 2;
36
+
37
+ function main() {
38
+ ObjC.import('Cocoa');
39
+ ObjC.import('MediaPlayer');
40
+
41
+ const out = $.NSFileHandle.fileHandleWithStandardOutput;
42
+ const input = $.NSFileHandle.fileHandleWithStandardInput;
43
+ const center = $.MPNowPlayingInfoCenter.defaultCenter;
44
+ const commands = $.MPRemoteCommandCenter.sharedCommandCenter;
45
+ const newline = $('\n').dataUsingEncoding($.NSUTF8StringEncoding);
46
+ const track = {
47
+ status: 'stopped',
48
+ position: 0,
49
+ duration: 0,
50
+ title: '',
51
+ artist: '',
52
+ album: '',
53
+ };
54
+ let running = true;
55
+ // Raw bytes of the stdin line(s) not yet terminated.
56
+ let buffer = $.NSData.data;
57
+
58
+ function emit(message) {
59
+ const line = $(`${JSON.stringify(message)}\n`);
60
+ out.writeData(line.dataUsingEncoding($.NSUTF8StringEncoding));
61
+ }
62
+
63
+ // Mirror MixShell's state onto the Now Playing card. Stopped means no
64
+ // card, which hands the media keys back to whichever app played last.
65
+ function publish() {
66
+ if (track.status === 'stopped') {
67
+ center.setNowPlayingInfo($());
68
+ center.setPlaybackState(STOPPED);
69
+ return;
70
+ }
71
+ const info = $.NSMutableDictionary.dictionary;
72
+ info.setObjectForKey($(track.title), $.MPMediaItemPropertyTitle);
73
+ info.setObjectForKey($(track.artist), $.MPMediaItemPropertyArtist);
74
+ info.setObjectForKey($(track.album), $.MPMediaItemPropertyAlbumTitle);
75
+ info.setObjectForKey(
76
+ $(track.position),
77
+ $.MPNowPlayingInfoPropertyElapsedPlaybackTime,
78
+ );
79
+ // The rate lets the system advance the scrubber between updates.
80
+ info.setObjectForKey(
81
+ $(track.status === 'playing' ? 1 : 0),
82
+ $.MPNowPlayingInfoPropertyPlaybackRate,
83
+ );
84
+ if (track.duration > 0)
85
+ info.setObjectForKey(
86
+ $(track.duration),
87
+ $.MPMediaItemPropertyPlaybackDuration,
88
+ );
89
+ center.setNowPlayingInfo(info);
90
+ center.setPlaybackState(track.status === 'playing' ? PLAYING : PAUSED);
91
+ }
92
+
93
+ // MixShell sends whole snapshots, so a state line is simply the new
94
+ // track record.
95
+ function apply(message) {
96
+ if (!message) return;
97
+ if (message.type !== 'state') return;
98
+ delete message.type;
99
+ Object.assign(track, message);
100
+ publish();
101
+ }
102
+
103
+ // Split on newline *bytes* before decoding, so a chunk that ends mid
104
+ // UTF-8 sequence can't corrupt a title.
105
+ function drain() {
106
+ for (;;) {
107
+ const total = Number(buffer.length);
108
+ const range = buffer.rangeOfDataOptionsRange(
109
+ newline,
110
+ 0,
111
+ $.NSMakeRange(0, total),
112
+ );
113
+ const end = Number(range.location);
114
+ if (end === Number($.NSNotFound)) return;
115
+ const line = buffer.subdataWithRange($.NSMakeRange(0, end));
116
+ buffer = buffer.subdataWithRange($.NSMakeRange(end + 1, total - end - 1));
117
+ const text = $.NSString.alloc.initWithDataEncoding(
118
+ line,
119
+ $.NSUTF8StringEncoding,
120
+ );
121
+ if (text.isNil()) continue;
122
+ try {
123
+ apply(JSON.parse(text.js));
124
+ } catch {
125
+ // Not JSON: ignore the line, keep the helper alive.
126
+ }
127
+ }
128
+ }
129
+
130
+ ObjC.registerSubclass({
131
+ name: 'MixShellStdinReader',
132
+ methods: {
133
+ 'readCompleted:': {
134
+ types: ['void', ['id']],
135
+ implementation: (notification) => {
136
+ const data = notification.userInfo.objectForKey(
137
+ $.NSFileHandleNotificationDataItem,
138
+ );
139
+ // An empty read is EOF: MixShell has exited.
140
+ if (data.isNil() || Number(data.length) === 0) {
141
+ running = false;
142
+ return;
143
+ }
144
+ buffer = buffer.dataByAppendingData(data);
145
+ drain();
146
+ input.readInBackgroundAndNotify;
147
+ },
148
+ },
149
+ },
150
+ });
151
+ const reader = $.MixShellStdinReader.alloc.init;
152
+
153
+ const handlers = {};
154
+ for (const [selector, name] of [
155
+ ['play:', 'play'],
156
+ ['pause:', 'pause'],
157
+ ['toggle:', 'toggle'],
158
+ ['stop:', 'stop'],
159
+ ['next:', 'next'],
160
+ ['previous:', 'previous'],
161
+ ]) {
162
+ handlers[selector] = {
163
+ types: ['void', ['id']],
164
+ implementation: () => emit({ type: 'command', name }),
165
+ };
166
+ }
167
+ handlers['position:'] = {
168
+ types: ['void', ['id']],
169
+ // The scrubber in Control Center / Now Playing: an absolute seek.
170
+ implementation: (event) => {
171
+ const position = Number(event.positionTime);
172
+ if (Number.isFinite(position)) emit({ type: 'seek', position });
173
+ },
174
+ };
175
+ ObjC.registerSubclass({ name: 'MixShellCommandTarget', methods: handlers });
176
+ const target = $.MixShellCommandTarget.alloc.init;
177
+
178
+ // MPRemoteCommandCenter only routes key events to a live NSApplication;
179
+ // Prohibited keeps this helper out of the Dock and the Cmd-Tab switcher.
180
+ const app = $.NSApplication.sharedApplication;
181
+ app.setActivationPolicy(PROHIBITED);
182
+
183
+ // Every command touched here exists since macOS 10.13; Node 22, MixShell's
184
+ // floor, needs 10.15. An unknown selector would simply kill the helper
185
+ // into MixShell's one-debug-line failure path.
186
+ commands.playCommand.addTargetAction(target, 'play:');
187
+ commands.pauseCommand.addTargetAction(target, 'pause:');
188
+ commands.togglePlayPauseCommand.addTargetAction(target, 'toggle:');
189
+ commands.stopCommand.addTargetAction(target, 'stop:');
190
+ commands.nextTrackCommand.addTargetAction(target, 'next:');
191
+ commands.previousTrackCommand.addTargetAction(target, 'previous:');
192
+ commands.changePlaybackPositionCommand.addTargetAction(target, 'position:');
193
+ // Everything else would only advertise buttons MixShell can't honour.
194
+ commands.changePlaybackRateCommand.setEnabled(false);
195
+ commands.seekBackwardCommand.setEnabled(false);
196
+ commands.seekForwardCommand.setEnabled(false);
197
+ commands.skipBackwardCommand.setEnabled(false);
198
+ commands.skipForwardCommand.setEnabled(false);
199
+ commands.ratingCommand.setEnabled(false);
200
+ commands.likeCommand.setEnabled(false);
201
+ commands.dislikeCommand.setEnabled(false);
202
+ commands.bookmarkCommand.setEnabled(false);
203
+
204
+ $.NSNotificationCenter.defaultCenter.addObserverSelectorNameObject(
205
+ reader,
206
+ 'readCompleted:',
207
+ $.NSFileHandleReadCompletionNotification,
208
+ input,
209
+ );
210
+ input.readInBackgroundAndNotify;
211
+ emit({ type: 'ready' });
212
+
213
+ const loop = $.NSRunLoop.currentRunLoop;
214
+ const soon = () => $.NSDate.dateWithTimeIntervalSinceNow(0.25);
215
+ while (running) {
216
+ // runMode returns at once when nothing is scheduled — sleep rather
217
+ // than spin. Wakes are at most 50 ms late, the loop itself blocks.
218
+ if (!loop.runModeBeforeDate('NSDefaultRunLoopMode', soon()))
219
+ $.NSThread.sleepForTimeInterval(0.05);
220
+ }
221
+
222
+ // EOF: MixShell is gone — clear the card so the keys move on.
223
+ center.setNowPlayingInfo($());
224
+ center.setPlaybackState(STOPPED);
225
+ }
226
+
227
+ main();
package/src/ui/app.js ADDED
@@ -0,0 +1,56 @@
1
+ import { readFile } from 'node:fs/promises';
2
+
3
+ import { TermDOM } from '@b9g/termdom';
4
+
5
+ import { init } from './controller.js';
6
+
7
+ /**
8
+ * Boot the TermDOM interface for the given app components.
9
+ * @param {{player: object, playlist: object, browser: object, config: object, library: object, analyzer: object}} app
10
+ * @returns {Promise<{cleanup: Function}>}
11
+ */
12
+ export async function startUI(app) {
13
+ // 0.2.0 dropped COLORTERM env reading in favour of querying the terminal,
14
+ // which Konsole et al. answer wrong (drops us to 256 colors). Replicate the
15
+ // old behaviour until upstream detection improves.
16
+ const term = new TermDOM({
17
+ colorDepth: ['truecolor', '24bit'].includes(process.env.COLORTERM)
18
+ ? 24
19
+ : 'auto',
20
+ });
21
+ const { document } = term;
22
+ document.title = 'MixShell';
23
+
24
+ document.body.innerHTML = await readFile(
25
+ new URL('./index.html', import.meta.url),
26
+ 'utf8',
27
+ );
28
+
29
+ // Pretty-printed HTML leaves whitespace text nodes that act as extra flex
30
+ // items in the terminal (no inline-layout absorption). Strip them.
31
+ stripWhitespace(document.body);
32
+
33
+ const style = document.createElement('style');
34
+ style.textContent = await readFile(
35
+ new URL('./style.css', import.meta.url),
36
+ 'utf8',
37
+ );
38
+ document.head.appendChild(style);
39
+
40
+ // Attach without awaiting: listeners registered after an awaited attach
41
+ // never receive events (TermDOM quirk); the promise is passed on so
42
+ // measureCell can run once the attach is settled (before that: null).
43
+ const attachReady = term.attach().catch(() => {});
44
+
45
+ return init(term, app, attachReady);
46
+ }
47
+
48
+ function stripWhitespace(node) {
49
+ for (const child of [...node.childNodes]) {
50
+ if (child.nodeType === 3 && child.textContent.trim() === '') {
51
+ child.remove();
52
+ } else {
53
+ stripWhitespace(child);
54
+ }
55
+ }
56
+ }
@@ -0,0 +1,314 @@
1
+ import { cellAspect, sampleCells, sniffImageMime } from '../utils/cellart.js';
2
+ import { DBG } from '../utils/debug.js';
3
+ import { MODES } from './visualizer/index.js';
4
+
5
+ // Album art / visualizer canvases (issues/035). A canvas holds exactly one
6
+ // context for life, so the two roles own separate nodes inside #artBox.
7
+ // #artCanvas always takes a plain 2d context: its bitmap is what the engine
8
+ // ships as a kitty graphics image on kitty/Ghostty (full native pixel
9
+ // resolution, zlib-deflated RGBA, cached per version) and rasterizes to
10
+ // half blocks on every other terminal — TermDOM's auto fallback IS the
11
+ // capability layer, there is no renderer setting. #vizCanvas always
12
+ // carries the termdom-cellgrid context (direct cell writes; the
13
+ // 2d-fillRect mask cost is why the cellgrid won — see visualizer/grid.js) and
14
+ // serves both the visualizer modes and the charset album-art styles (the
15
+ // glyph grid is cell-native; per-cell text on the 2d context would land
16
+ // as terminal text runs with no resolution gain). Art and viz are
17
+ // mutually exclusive modes, so only one canvas is visible at a time.
18
+
19
+ export function createArtPane({ els, win, document, config, visualizer, log }) {
20
+ // The offscreen 2d sampler canvas lives as long as the document.
21
+ let artSampler = null;
22
+ let artToken = 0;
23
+ let cellRatio = 2;
24
+ let cellPx = null; // measureCell's {width, height} device px, for bitmap sizing
25
+ let vizKey = null;
26
+ const vizFrames = [];
27
+ let vizDrawMs = 0;
28
+
29
+ // The cellgrid canvas is shared by the visualizer modes and the charset
30
+ // album-art styles — the controller never runs both at once (viz modes
31
+ // and art mode are exclusive). getContext is a per-canvas cache lookup,
32
+ // not a constructor, so no memoization is needed.
33
+ function showCanvas(front) {
34
+ els.artBox.classList.remove('hidden');
35
+ for (const canvas of [els.artCanvas, els.vizCanvas]) {
36
+ canvas.classList.toggle('hidden', canvas !== front);
37
+ }
38
+ }
39
+
40
+ function hide() {
41
+ artToken++;
42
+ els.artBox.classList.add('hidden');
43
+ for (const canvas of [els.artCanvas, els.vizCanvas]) {
44
+ canvas.classList.add('hidden');
45
+ }
46
+ }
47
+
48
+ // Fit an art aspect (w × h in cell space) into the main panel: 80% of
49
+ // the usable width, capped by the box's inner rows. The box fills every
50
+ // row the panel has left under the track meta (flex in style.css) and
51
+ // JS reads that height back after layout (issues/066) — the old window
52
+ // budget assumed a three-row meta block and clipped long track info.
53
+ // The art is drawn centered in the box at the fitted size, so the box
54
+ // can be taller than the art without stretching it.
55
+ // The width snaps to one of a few candidates below the maximum: single
56
+ // rounding of rows is up to ±0.5 rows of error, worth 20-50% distortion
57
+ // when the grid is only a few rows tall (narrow windows), so the pair
58
+ // with the least aspect error wins. A candidate that exceeds the box
59
+ // height is refit from the clamped rows instead.
60
+ function fitArtSize(w, h) {
61
+ const availW = artAvailW();
62
+ const box = boxRows();
63
+ let best = null;
64
+ for (let cols = availW; cols >= Math.max(1, availW - 3); cols--) {
65
+ let rows = Math.round((cols * h) / w);
66
+ let fitCols = cols;
67
+ if (rows > box) {
68
+ rows = box;
69
+ fitCols = Math.max(1, Math.round((rows * w) / h));
70
+ }
71
+ rows = Math.max(1, rows);
72
+ const err = Math.abs(fitCols / rows - w / h) / (w / h);
73
+ if (best === null || err < best.err) {
74
+ best = { cols: fitCols, rows, err };
75
+ }
76
+ }
77
+ return { cols: best.cols, rows: best.rows, boxRows: box };
78
+ }
79
+
80
+ // Width budget from the window; height comes from the laid-out box
81
+ // (border only — .art has no vertical padding). Read after the box is
82
+ // shown: the engine's rect is correct straight after flex sizes it.
83
+ const artAvailW = () =>
84
+ Math.max(4, Math.floor((win.innerWidth - 8) * 0.8) - 4);
85
+ const boxRows = () =>
86
+ Math.round(els.artBox.getBoundingClientRect().height) - 2;
87
+
88
+ // Width snug around the art (border + side padding); the layout owns
89
+ // the height. Returns the art fit plus the box rows read back, which
90
+ // drive the bitmap height and the cellgrid poll.
91
+ function applyArtSize(w, h) {
92
+ const fit = fitArtSize(w, h);
93
+ els.artBox.style.width = `${fit.cols + 4}px`;
94
+ return fit;
95
+ }
96
+
97
+ // Refit the wrapper for the visualizer: the box is sized to the bars,
98
+ // not the bars to the box. numBars = the bar count (quality cap vs the
99
+ // standard 2-cell bar + 1-cell gap stride) that fits the width budget,
100
+ // then cols = 3n-1 exactly — bars.js splits the leftover evenly,
101
+ // so every bar renders the same width instead of a 2/3-cell mix. The
102
+ // wrapper must be its own width budget (cols+4) so grid.cols lands on
103
+ // 3n-1; the panel centers the box in the leftover width. The layout
104
+ // owns the height. maxBars rides the key: a quality change must refit
105
+ // even if the terminal didn't resize.
106
+ // Mode-aware: the registry's box shape picks bar-stride sizing or a
107
+ // visually square box (width = height × cell aspect).
108
+ // The mode and ratio ride the key so a mode switch or measurement
109
+ // change refits even when the terminal itself didn't resize.
110
+ function fitVizBox() {
111
+ const key = `${win.innerWidth}x${win.innerHeight}x${visualizer.maxBars || 0}x${visualizer.mode}x${cellRatio}`;
112
+ if (vizKey === key) return;
113
+ vizKey = key;
114
+ if (MODES[visualizer.mode]?.box === 'square') {
115
+ const rows = boxRows();
116
+ const cols = Math.min(artAvailW(), Math.round(rows * cellRatio));
117
+ els.artBox.style.width = `${cols + 4}px`;
118
+ return;
119
+ }
120
+ const fitBars = Math.max(1, Math.floor((artAvailW() + 1) / 3));
121
+ const numBars = Math.max(
122
+ 1,
123
+ Math.min(visualizer.maxBars || fitBars, fitBars),
124
+ );
125
+ els.artBox.style.width = `${3 * numBars - 1 + 4}px`;
126
+ }
127
+
128
+ // Colors resolve from the CSS vars each draw, so theme cycling recolors
129
+ // the viz without extra wiring. System-color themes (terminal) return
130
+ // names like "LinkText", which the engine's canvas color parser accepts.
131
+ function vizColor(name, fallback) {
132
+ const value = win
133
+ .getComputedStyle(document.body)
134
+ .getPropertyValue(name)
135
+ .trim();
136
+ return value || fallback;
137
+ }
138
+
139
+ function vizColors() {
140
+ return {
141
+ accent: vizColor('--accent', '#f87a52'),
142
+ playing: vizColor('--playing', '#9ece6a'),
143
+ muted: vizColor('--muted', 'gray'),
144
+ bg: vizColor('--bg', '#101010'),
145
+ };
146
+ }
147
+
148
+ function drawViz() {
149
+ // Mutual exclusion with a pending art paint: bumping the token
150
+ // orphans any in-flight renderArt callback.
151
+ artToken++;
152
+ // The visualizer always draws on the cellgrid (issues/035): the kitty
153
+ // path re-uploads the whole canvas bitmap every frame — one-shot fine
154
+ // for album art, ruinous at animation cadence — while cellgrid fills
155
+ // stay cheap per-cell writes.
156
+ const grid = els.vizCanvas.getContext('termdom-cellgrid');
157
+ if (!grid) return;
158
+ showCanvas(els.vizCanvas);
159
+ fitVizBox();
160
+ const colors = vizColors();
161
+ const t0 = performance.now();
162
+ visualizer.drawCells(grid, colors);
163
+ const drawMs = performance.now() - t0;
164
+
165
+ // Rolling 1s window of draw timestamps = achieved fps; draw cost is
166
+ // an EMA so single slow frames don't flicker the readout.
167
+ vizFrames.push(t0);
168
+ while (vizFrames.length && t0 - vizFrames[0] >= 1000) {
169
+ vizFrames.shift();
170
+ }
171
+ if (config.get('showFPS')) {
172
+ vizDrawMs = vizDrawMs * 0.9 + drawMs * 0.1;
173
+ const label = `${vizFrames.length} fps ${vizDrawMs.toFixed(1)} ms`;
174
+ grid.fillStyle = colors.muted;
175
+ grid.fillText(label, grid.cols - label.length - 1, 0);
176
+ }
177
+ }
178
+
179
+ function decodeArtBitmap(song) {
180
+ if (song.artBitmap) return Promise.resolve(song.artBitmap);
181
+ const bytes = song.images[0].data;
182
+ const blob = new Blob([bytes], { type: sniffImageMime(bytes) });
183
+ return win.createImageBitmap(blob).then((bitmap) => {
184
+ song.artBitmap = bitmap;
185
+ return bitmap;
186
+ });
187
+ }
188
+
189
+ // Charset-style draw on the shared cellgrid canvas at the fitted
190
+ // cols × rows, centered vertically at `dy` inside the (possibly taller)
191
+ // box grid — never stretched to the grid, or the letterbox rows become
192
+ // image distortion.
193
+ function drawArtCells(bitmap, style, cols, rows, dy) {
194
+ const ctx = els.vizCanvas.getContext('termdom-cellgrid');
195
+ if (cols < 1 || rows < 1) return;
196
+ ctx.clearRect(0, 0, ctx.cols, ctx.rows);
197
+
198
+ // Upstream #82 sampler: one pixel per cell — drawImage averages the
199
+ // bitmap pixels each pixel covers — then luminance picks the charset
200
+ // glyph and the pixel color paints it.
201
+ if (!artSampler) artSampler = document.createElement('canvas');
202
+ artSampler.width = cols;
203
+ artSampler.height = rows;
204
+ const sctx = artSampler.getContext('2d');
205
+ sctx.drawImage(bitmap, 0, 0, cols, rows);
206
+ const cells = sampleCells(sctx.getImageData(0, 0, cols, rows), style);
207
+ for (let y = 0; y < rows; y++) {
208
+ for (let x = 0; x < cols; x++) {
209
+ const cell = cells[y][x];
210
+ if (cell.color) {
211
+ ctx.fillStyle = cell.color;
212
+ ctx.fillText(cell.ch, x, y + dy);
213
+ }
214
+ }
215
+ }
216
+ }
217
+
218
+ // Album-art draw (issues/035): the bitmap goes onto the art canvas's
219
+ // plain 2d context at device-pixel size (cols × measured cell px), so
220
+ // the engine's kitty path ships it as a full-resolution graphics image;
221
+ // on non-kitty terminals the engine rasterizes that same bitmap to half
222
+ // blocks. The bitmap is version-stamped and the engine rescales it on
223
+ // relayout, so there is no grid-wait poll here — the cellgrid path
224
+ // needs one only because its grid re-derives a frame or more after the
225
+ // wrapper resizes.
226
+ function drawArtPixels(bitmap, cols, rows, boxRows) {
227
+ // A long meta block can leave the box at border-only height (issues/066):
228
+ // the canvas is then 0×0 and has no 2d context. Nothing to draw.
229
+ if (cols < 1 || rows < 1 || boxRows < 1) return;
230
+ const ctx = els.artCanvas.getContext('2d');
231
+ if (!ctx) return;
232
+ const px = cellPx ?? { width: 10, height: 10 * cellRatio };
233
+ // Bitmap = the box's device pixels. .art is border-box: width
234
+ // cols+4 minus border(2) + side padding(2) leaves exactly cols for
235
+ // the canvas — a wider bitmap letterboxes inside its CSS box and
236
+ // shows as a gap at the art's right edge.
237
+ els.artCanvas.width = cols * px.width;
238
+ els.artCanvas.height = boxRows * px.height;
239
+ ctx.clearRect(0, 0, els.artCanvas.width, els.artCanvas.height);
240
+ const dy = ((boxRows - rows) / 2) * px.height;
241
+ ctx.drawImage(bitmap, 0, dy, cols * px.width, rows * px.height);
242
+ }
243
+
244
+ function renderArt(song) {
245
+ if (!song?.images?.length) {
246
+ hide();
247
+ return;
248
+ }
249
+ const token = ++artToken;
250
+ // Charset styles are cell-native glyphs (luminance ramps per cell) —
251
+ // they draw on the shared cellgrid canvas; 'blocks' is the only
252
+ // bitmap style and gets the native-pixel 2d path.
253
+ const style = config.get('albumArtStyle') || 'blocks';
254
+ showCanvas(style === 'blocks' ? els.artCanvas : els.vizCanvas);
255
+ decodeArtBitmap(song).then(
256
+ (bitmap) => {
257
+ if (token !== artToken) return;
258
+ // Bitmap pixels map to cells at the terminal's measured cell
259
+ // aspect (measureCell/cellchange; 2:1 until the terminal's
260
+ // cell-size answer lands — or forever if it never does).
261
+ const aspect = cellAspect(bitmap.width, bitmap.height, cellRatio);
262
+ const { cols, rows, boxRows } = applyArtSize(
263
+ aspect.width,
264
+ aspect.height,
265
+ );
266
+ // The wrapper now holds the art fit, not the viz fit — drop the
267
+ // window-key cache or the next drawViz would keep the art-sized
268
+ // box whenever the terminal itself hasn't resized.
269
+ vizKey = null;
270
+ if (style === 'blocks') {
271
+ drawArtPixels(bitmap, cols, rows, boxRows);
272
+ return;
273
+ }
274
+ const dy = (boxRows - rows) >> 1;
275
+ // The engine relayouts the replaced canvas a frame or more after
276
+ // the wrapper resizes; wait for the grid to match the box before
277
+ // painting or the glyphs land in the previous box's grid.
278
+ let tries = 0;
279
+ const paint = () => {
280
+ if (token !== artToken) return;
281
+ const ctx = els.vizCanvas.getContext('termdom-cellgrid');
282
+ if ((ctx.cols !== cols || ctx.rows !== boxRows) && ++tries < 30) {
283
+ win.requestAnimationFrame(paint);
284
+ return;
285
+ }
286
+ drawArtCells(bitmap, style, cols, rows, dy);
287
+ };
288
+ win.requestAnimationFrame(paint);
289
+ },
290
+ (err) => {
291
+ if (token !== artToken) return;
292
+ const reason = err?.message || String(err);
293
+ log(`Album art decode failed: ${reason}`);
294
+ DBG(`album art error: ${reason}`);
295
+ },
296
+ );
297
+ }
298
+
299
+ // Terminal cell size changed (measureCell / cellchange): the viz refits
300
+ // against the new ratio on next draw, and the bitmap art canvas resizes
301
+ // to the new device pixels.
302
+ function setCellRatio(ratio, px) {
303
+ cellRatio = ratio;
304
+ cellPx = px;
305
+ vizKey = null;
306
+ }
307
+
308
+ return {
309
+ drawViz,
310
+ renderArt,
311
+ hide,
312
+ setCellRatio,
313
+ };
314
+ }
@@ -0,0 +1,34 @@
1
+ // Shared Y/N toast prompt (issues/053): other keys leave the question up and
2
+ // fall through, so global shortcuts (playback, quit) keep working.
3
+ export function createConfirm({ showMessage, hideMessage }) {
4
+ let pending = null;
5
+
6
+ function ask(question, onYes, onNo) {
7
+ pending = { onYes, onNo };
8
+ showMessage(question, { sticky: true });
9
+ }
10
+
11
+ function key(e) {
12
+ if (!pending) return false;
13
+ const answer = e.key;
14
+ const yes = answer === 'y' || answer === 'Y';
15
+ const no =
16
+ answer === 'n' ||
17
+ answer === 'N' ||
18
+ answer === 'Escape' ||
19
+ answer === 'Enter';
20
+ if (!yes && !no) return false;
21
+ const { onYes, onNo } = pending;
22
+ pending = null;
23
+ if (yes) onYes();
24
+ else onNo();
25
+ return true;
26
+ }
27
+
28
+ function cancel() {
29
+ pending = null;
30
+ hideMessage();
31
+ }
32
+
33
+ return { ask, key, cancel, isOpen: () => Boolean(pending) };
34
+ }