Repository navigation
Expand file tree
/
Copy pathmusic-app.ts
More file actions
494 lines (456 loc) · 18.4 KB
/
Copy pathmusic-app.ts
File metadata and controls
494 lines (456 loc) · 18.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
import { getDefaultMediumFont, getDefaultSmallFont } from "../../graphics/bdffont";
import { GrayImage } from "../../graphics/image";
import { wrapText, truncateText } from "../../graphics/textwrap";
import { clamp } from "../../util/numeric-util";
import {
GESTURE_CLICK,
GESTURE_DOUBLE_CLICK,
GESTURE_SCROLL,
GESTURE_SCROLL_DOWN,
GESTURE_SCROLL_UP,
} from "../gestures";
import { MenuLayer, drawSelectionHighlight, drawSubmenuIndicator } from "../menu";
import {
mediaControllerBridge,
type MediaControllerState,
type MediaQueueItem,
} from "../../native/media-controller";
import { mediaBrowserBridge, type MediaBrowserApp } from "../../native/media-browser";
import { MediaBrowseLayer } from "../apps/media-browse";
import { Layer, type DashboardInputEvent, type LayerContext, type PaintBelow } from "../layers";
import {
createInProcessWindow,
YieldAtRootLayer,
type InProcessAppOptions,
type InProcessWindow,
} from "./in-process-window";
export const MUSIC_WINDOW_ID = "music";
export const MUSIC_SURFACE_ID = "window:music";
const ART_SIZE = 96;
const ART_X = 22;
const ART_Y = 8;
const META_X = ART_X + ART_SIZE + 14;
const LIST_TOP = 120;
const ROW_HEIGHT = 16;
const ACTION_X = 22;
const ACTION_WIDTH = 154;
const COLUMN_DIVIDER_X = 190;
const QUEUE_X = 204;
const FOOTER_HEIGHT = 20;
const PLAYLIST_ACTION_INDEX = 1;
type MusicAction =
| { kind: "play-pause"; label: string; enabled: boolean }
| { kind: "previous"; label: string; enabled: boolean }
| { kind: "next"; label: string; enabled: boolean }
| { kind: "volume"; label: string; enabled: boolean }
| { kind: "playlist"; label: string; enabled: boolean }
| { kind: "browse"; label: string; enabled: boolean };
type FocusColumn = "actions" | "playlist";
/**
* Music controller app: metadata + album art + transport controls for the
* active Android media session (any player that publishes one), plus the
* player's queue when it exposes one (scroll to a track, click to jump).
*/
class MusicAppLayer implements Layer {
private focusColumn: FocusColumn = "actions";
private selectedActionIndex = 0;
private selectedQueueIndex = 0;
private queueScrollRow = 0;
private art: GrayImage | null = null;
private artKey = "";
isPlaylistFocused(): boolean {
return this.focusColumn === "playlist";
}
paint(ctx: LayerContext): GrayImage {
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
const media = mediaControllerBridge.snapshot();
if (!media.accessEnabled) {
const lines = wrapText(
font,
"Notification access is required before Android exposes media sessions. Click to open settings.",
width - 48,
);
for (let index = 0; index < lines.length; index++) {
image.drawText(font, 24, 16 + index * 14, lines[index]!, 180);
}
image.drawText(font, 20, height - 16, `${GESTURE_CLICK} open settings ${GESTURE_DOUBLE_CLICK} back`, 110);
return image;
}
if (!media.available) {
image.drawText(font, 24, 16, "No active media session.", 180);
if (mediaBrowserBridge.listBrowsableApps().length) {
image.drawText(font, 24, 34, "Click to browse a music app's library,", 150);
image.drawText(font, 24, 48, "or start playback on the phone.", 150);
image.drawText(font, 20, height - 16, `${GESTURE_CLICK} browse ${GESTURE_DOUBLE_CLICK} back`, 110);
} else {
image.drawText(font, 24, 34, "Start playback in another app on the phone.", 150);
image.drawText(font, 20, height - 16, `${GESTURE_DOUBLE_CLICK} back`, 110);
}
return image;
}
this.drawArt(image, media);
const metaWidth = width - META_X - 24;
const titleLines = wrapText(font, media.title || "Unknown title", metaWidth).slice(0, 2);
for (let index = 0; index < titleLines.length; index++) {
image.drawText(font, META_X, ART_Y + 2 + index * 15, titleLines[index]!, 230);
}
image.drawText(font, META_X, ART_Y + 36, media.artist || "Unknown artist", 180);
if (media.album) {
image.drawText(font, META_X, ART_Y + 52, truncateText(font, media.album, metaWidth), 150);
}
image.drawText(font, META_X, ART_Y + 68, truncateText(font, media.appName || media.packageName, metaWidth), 110);
this.drawProgress(image, media, metaWidth);
const queue = mediaControllerBridge.getQueue();
const actions = this.buildActions(media, queue);
this.reconcileSelection(actions, queue);
const listHeight = height - LIST_TOP - FOOTER_HEIGHT;
const visibleRows = Math.max(1, (listHeight / ROW_HEIGHT) | 0);
if (this.selectedQueueIndex < this.queueScrollRow) {
this.queueScrollRow = this.selectedQueueIndex;
} else if (this.selectedQueueIndex >= this.queueScrollRow + visibleRows) {
this.queueScrollRow = this.selectedQueueIndex - visibleRows + 1;
}
this.queueScrollRow = clamp(this.queueScrollRow, 0, Math.max(0, queue.length - visibleRows));
for (let index = 0; index < actions.length; index++) {
const action = actions[index]!;
const y = LIST_TOP + index * ROW_HEIGHT;
const selected = index === this.selectedActionIndex;
const highlightX = ACTION_X - 6;
const highlightY = y - 1;
const highlightWidth = ACTION_WIDTH + 8;
const highlightHeight = ROW_HEIGHT - 1;
if (selected) {
drawSelectionHighlight(
image,
highlightX,
highlightY,
highlightWidth,
highlightHeight,
ctx.stack.isFocused() && this.focusColumn === "actions",
4,
);
}
const value = !action.enabled ? (selected ? 130 : 90) : selected ? 255 : 200;
image.drawText(font, ACTION_X, y + 1, truncateText(font, action.label, ACTION_WIDTH - 16), value);
if ((action.kind === "playlist" || action.kind === "browse") && action.enabled) {
drawSubmenuIndicator(image, font, highlightX, highlightY, highlightWidth, highlightHeight, value);
}
}
image.drawLine(COLUMN_DIVIDER_X, LIST_TOP - 3, COLUMN_DIVIDER_X, height - FOOTER_HEIGHT - 3, 45);
if (!queue.length) {
image.drawText(font, QUEUE_X, LIST_TOP + 1, "Playlist unavailable", 90);
} else {
const queueWidth = width - QUEUE_X - 20;
const lastVisible = Math.min(queue.length, this.queueScrollRow + visibleRows);
for (let index = this.queueScrollRow; index < lastVisible; index++) {
const item = queue[index]!;
const y = LIST_TOP + (index - this.queueScrollRow) * ROW_HEIGHT;
const selected = index === this.selectedQueueIndex;
if (selected) {
drawSelectionHighlight(
image,
QUEUE_X - 6,
y - 1,
queueWidth + 8,
ROW_HEIGHT - 1,
ctx.stack.isFocused() && this.focusColumn === "playlist",
4,
);
}
const label = `${item.active ? "> " : " "}${item.title || "(untitled)"}`;
image.drawText(font, QUEUE_X, y + 1, truncateText(font, label, queueWidth - 4), selected ? 255 : 200);
}
if (queue.length > visibleRows) {
const trackHeight = visibleRows * ROW_HEIGHT - 4;
const trackX = width - 12;
image.fillRect(trackX, LIST_TOP, 3, trackHeight, 30);
const thumbHeight = Math.max(8, (trackHeight * visibleRows / queue.length) | 0);
const maxScrollRow = queue.length - visibleRows;
const thumbY = LIST_TOP + (((trackHeight - thumbHeight) * this.queueScrollRow / maxScrollRow) | 0);
image.fillRect(trackX, thumbY, 3, thumbHeight, 120);
}
}
const backTarget = this.focusColumn === "playlist" ? "actions" : "back";
image.drawText(
font,
20,
height - 16,
`${GESTURE_SCROLL} select ${GESTURE_CLICK} activate ${GESTURE_DOUBLE_CLICK} ${backTarget}`,
110,
);
return image;
}
async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> {
if (event.type === "double-click" && this.focusColumn === "playlist") {
this.focusColumn = "actions";
this.selectedActionIndex = PLAYLIST_ACTION_INDEX;
return;
}
const media = mediaControllerBridge.snapshot();
if (!media.accessEnabled) {
if (event.type === "click") {
mediaControllerBridge.openNotificationAccessSettings();
} else if (event.type === "double-click") {
ctx.stack.pop();
}
return;
}
if (!media.available) {
if (event.type === "click") {
this.openBrowse(ctx);
}
return;
}
const queue = mediaControllerBridge.getQueue();
const actions = this.buildActions(media, queue);
this.reconcileSelection(actions, queue);
switch (event.type) {
case "scroll-up":
if (this.focusColumn === "playlist") {
this.selectedQueueIndex = Math.max(0, this.selectedQueueIndex - 1);
} else {
this.selectedActionIndex = (this.selectedActionIndex + actions.length - 1) % actions.length;
}
return;
case "scroll-down":
if (this.focusColumn === "playlist") {
this.selectedQueueIndex = Math.min(Math.max(0, queue.length - 1), this.selectedQueueIndex + 1);
} else {
this.selectedActionIndex = (this.selectedAction
8000
Index + 1) % actions.length;
}
return;
case "click": {
if (this.focusColumn === "playlist") {
const item = queue[this.selectedQueueIndex];
if (item) {
await mediaControllerBridge.skipToQueueItem(item.id);
// The player rebuilds the queue with the chosen track at index 0.
this.selectedQueueIndex = 0;
this.queueScrollRow = 0;
}
return;
}
const action = actions[this.selectedActionIndex];
if (!action || !action.enabled) return;
if (action.kind === "play-pause") await mediaControllerBridge.playPause();
else if (action.kind === "previous") await mediaControllerBridge.skipPrevious();
else if (action.kind === "next") await mediaControllerBridge.skipNext();
else if (action.kind === "browse") this.openBrowse(ctx);
else if (action.kind === "volume") {
ctx.stack.push(new VolumeModalLayer(mediaControllerBridge.getMediaVolumePercent()));
} else if (action.kind === "playlist") {
const activeIndex = queue.findIndex((item) => item.active);
if (activeIndex >= 0) this.selectedQueueIndex = activeIndex;
this.focusColumn = "playlist";
}
return;
}
default:
return;
}
}
/**
* Open the media-library browser (the Android Auto MediaBrowserService
* path): with one browsable player installed go straight to its library,
* otherwise offer a picker first.
*/
private openBrowse(ctx: LayerContext): void {
const apps = mediaBrowserBridge.listBrowsableApps(true);
if (!apps.length) return;
const pushBrowser = (target: LayerContext, app: MediaBrowserApp) => {
target.stack.push(
new MediaBrowseLayer({
app,
onPlayed: (browseCtx) => browseCtx.stack.pop(),
onLeave: (browseCtx) => browseCtx.stack.pop(),
}),
);
};
if (apps.length === 1) {
pushBrowser(ctx, apps[0]!);
return;
}
ctx.stack.push(
new MenuLayer(
"Browse library",
apps.map((app) => ({
label: app.appName,
onSelect: (menuCtx: LayerContext) => {
menuCtx.stack.pop();
pushBrowser(menuCtx, app);
},
})),
),
);
}
private buildActions(media: MediaControllerState, queue: MediaQueueItem[]): MusicAction[] {
const volume = mediaControllerBridge.getMediaVolumePercent();
return [
{
kind: "play-pause",
label: media.playbackState === "playing" ? "Pause" : "Play",
enabled: media.canPlayPause,
},
{ kind: "playlist", label: "Playlist", enabled: queue.length > 0 },
{ kind: "browse", label: "Browse library", enabled: mediaBrowserBridge.listBrowsableApps().length > 0 },
{ kind: "volume", label: volume >= 0 ? `Volume (${volume})` : "Volume", enabled: volume >= 0 },
{ kind: "next", label: "Next track", enabled: media.canSkipNext },
{ kind: "previous", label: "Previous track", enabled: media.canSkipPrevious },
];
}
private reconcileSelection(actions: MusicAction[], queue: MediaQueueItem[]): void {
this.selectedActionIndex = clamp(this.selectedActionIndex, 0, actions.length - 1);
this.selectedQueueIndex = clamp(this.selectedQueueIndex, 0, Math.max(0, queue.length - 1));
if (!queue.length && this.focusColumn === "playlist") {
this.focusColumn = "actions";
this.selectedActionIndex = PLAYLIST_ACTION_INDEX;
}
}
private drawProgress(image: GrayImage, media: MediaControllerState, width: number): void {
if (media.durationMs <= 0 || media.positionMs < 0) return;
const font = getDefaultSmallFont();
const y = ART_Y + 84;
const elapsed = formatMediaTime(media.positionMs);
const duration = formatMediaTime(media.durationMs);
image.drawText(font, META_X, y, elapsed, 140);
image.drawText(font, META_X + width - font.measureText(duration), y, duration, 140);
const barY = ART_Y + 100;
image.drawRect(META_X, barY, width, 5, 55);
const progress = clamp(media.positionMs / media.durationMs, 0, 1);
image.fillRect(META_X + 1, barY + 1, Math.round((width - 2) * progress), 3, 170);
}
private drawArt(image: GrayImage, media: MediaControllerState): void {
const key = `${media.packageName}|${media.title}|${media.album}`;
if (key !== this.artKey) {
this.artKey = key;
this.art = mediaControllerBridge.getAlbumArt(ART_SIZE);
}
if (this.art) {
// Center within the art box.
const dx = ART_X + Math.max(0, ((ART_SIZE - this.art.width) / 2) | 0);
const dy = ART_Y + Math.max(0, ((ART_SIZE - this.art.height) / 2) | 0);
image.bitBlt(this.art, dx, dy);
image.drawRect(dx - 1, dy - 1, this.art.width + 2, this.art.height + 2, 60);
} else {
image.drawRect(ART_X, ART_Y, ART_SIZE, ART_SIZE, 60);
const font = getDefaultSmallFont();
image.drawText(font, ART_X + 22, ART_Y + ART_SIZE / 2 - 7, "no art", 90);
}
}
}
/** Centered volume control overlay; scroll gestures adjust a 0..100 target by two. */
class VolumeModalLayer implements Layer {
private volume: number;
constructor(initialVolume: number) {
this.volume = clamp(initialVolume, 0, 100);
}
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
const image = paintBelow();
const small = getDefaultSmallFont();
const medium = getDefaultMediumFont();
const { width, height } = ctx.stack.getBaseSize();
const boxWidth = 340;
const boxHeight = 150;
const x = ((width - boxWidth) / 2) | 0;
const y = ((height - boxHeight) / 2) | 0;
image.fillRoundedRect(x, y, boxWidth, boxHeight, 1, 8);
image.drawRoundedRect(x, y, boxWidth, boxHeight, 95, 8);
image.drawText(small, x + 18, y + 14, "Media volume", 180);
const value = `${this.volume} / 100`;
const valueX = x + (((boxWidth - medium.measureText(value)) / 2) | 0);
image.drawText(medium, valueX, y + 45, value, 245);
const barX = x + 28;
const barY = y + 83;
const barWidth = boxWidth - 56;
image.drawRect(barX, barY, barWidth, 9, 65);
image.fillRect(barX + 1, barY + 1, Math.round((barWidth - 2) * this.volume / 100), 7, 175);
const hint = `${GESTURE_SCROLL_UP} +2 ${GESTURE_SCROLL_DOWN} -2 ${GESTURE_DOUBLE_CLICK} done`;
const hintX = x + (((boxWidth - small.measureText(hint)) / 2) | 0);
image.drawText(small, hintX, y + 116, hint, 120);
return image;
}
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
if (event.type === "scroll-up") {
this.adjust(2);
} else if (event.type === "scroll-down") {
this.adjust(-2);
} else if (event.type === "double-click") {
ctx.stack.pop();
}
}
private adjust(delta: number): void {
this.volume = clamp(this.volume + delta, 0, 100);
mediaControllerBridge.setMediaVolumePercent(this.volume);
}
}
/** Let back leave the playlist column before the root wrapper yields to the shell. */
class MusicRootLayer implements Layer {
private readonly yieldAtRoot: YieldAtRootLayer;
constructor(private readonly music: MusicAppLayer) {
this.yieldAtRoot = new YieldAtRootLayer(music);
}
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
return this.yieldAtRoot.paint(ctx, paintBelow);
}
async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> {
if (event.type === "double-click" && this.music.isPlaylistFocused()) {
await this.music.handleInput(event, ctx);
return;
}
await this.yieldAtRoot.handleInput(event, ctx);
}
onRemoved(): void {
this.yieldAtRoot.onRemoved();
}
}
export function createMusicAppWindow(options: InProcessAppOptions): InProcessWindow {
let unsubscribe: (() => void) | null = null;
let progressTimer: ReturnType<typeof setInterval> | null = null;
const musicLayer = new MusicAppLayer();
const stopProgressTimer = () => {
if (progressTimer !== null) {
clearInterval(progressTimer);
progressTimer = null;
}
};
const app = createInProcessWindow({
appId: "music",
windowId: MUSIC_WINDOW_ID,
title: "Music",
iconLetter: "M",
icon: "music",
closeable: true,
actions: options.actions,
baseLayer: new MusicRootLayer(musicLayer),
submitFrame: options.submitFrame,
setSurfaceVisible: options.setSurfaceVisible,
removeSurface: options.removeSurface,
onClosed: () => {
stopProgressTimer();
unsubscribe?.();
unsubscribe = null;
options.onClosed();
},
});
unsubscribe = mediaControllerBridge.onStateChange((state) => {
if (state.playbackState === "playing" && state.durationMs > 0 && state.positionMs >= 0) {
progressTimer ??= setInterval(() => app.requestRender(), 1_000);
} else {
stopProgressTimer();
}
app.requestRender();
});
return app;
}
function formatMediaTime(milliseconds: number): string {
const totalSeconds = Math.max(0, Math.floor(milliseconds / 1_000));
const seconds = totalSeconds % 60;
const totalMinutes = Math.floor(totalSeconds / 60);
const minutes = totalMinutes % 60;
const hours = Math.floor(totalMinutes / 60);
return hours > 0
? `${hours}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`
: `${minutes}:${String(seconds).padStart(2, "0")}`;
}