Refactor: Organize files by app

This commit is contained in:
James Babcock committed 2026-08-03 00:08:52 -07:00
1 parent 1ec6b3ff83
commit 9b3832d7a7
40 files changed
+175 -175

No files matched your search

-143
View File
@@ -1,143 +0,0 @@
import { getDefaultMediumFont, getDefaultSmallFont } from "../../graphics/bdffont";
import { GrayImage } from "../../graphics/image";
import { clamp } from "../../util/numeric-util";
import { addImuListener, imuSourceLabel, setImuReportEnabled, type ImuReading } from "../../native/imu";
import { GESTURE_DOUBLE_CLICK } from "../gestures";
import { Layer, type DashboardInputEvent, type LayerContext } from "../layers";
import { shell } from "../shell/shell";
// IMU report pace. This is NOT a literal Hz — the firmware only accepts the
// ImuReportPace codes 100..1000 (step 100); the real delivery rate is
// device-defined. An out-of-range value makes the firmware stream empty
// (all-zero) samples. 200 matches the reference EvenHub running-tracker app.
const IMU_REPORT_PACE = 200;
// How often to reconcile the IMU on/off state with window visibility.
const RECONCILE_INTERVAL_MS = 400;
/**
* Accelerometer demo: turns the IMU stream on while this page is visible (the
* Debug tests window is foregrounded and the screen is on), off otherwise, and
* shows the latest x/y/z reading with a simple per-axis bar.
*
* The IMU stream is experimental — the firmware may never populate it — so the
* page also reports how many samples have arrived.
*/
export class AccelerometerDemoLayer implements Layer {
private reading: ImuReading | null = null;
private sampleCount = 0;
private peak = 0;
private enabled = false;
private removed = false;
private reconcileTimer: ReturnType<typeof setInterval> | null = null;
private unsubscribe: (() => void) | null = null;
constructor(
private readonly windowId: string,
private readonly requestRender: () => void,
) {
this.start();
}
private start(): void {
this.unsubscribe = addImuListener((reading) => {
if (this.removed) return;
this.reading = reading;
this.sampleCount++;
this.peak = Math.max(this.peak, Math.abs(reading.x), Math.abs(reading.y), Math.abs(reading.z));
this.requestRender();
});
this.reconcileTimer = setInterval(() => this.reconcile(), RECONCILE_INTERVAL_MS);
this.reconcile();
}
/** Match the IMU on/off state to whether this page is currently visible. */
private reconcile(): void {
if (this.removed) return;
const visible = shell.isWindowVisible(this.windowId);
if (visible === this.enabled) return;
this.enabled = visible;
setImuReportEnabled(visible, IMU_REPORT_PACE);
this.requestRender();
}
onRemoved(): void {
this.removed = true;
if (this.reconcileTimer !== null) {
clearInterval(this.reconcileTimer);
this.reconcileTimer = null;
}
this.unsubscribe?.();
this.unsubscribe = null;
if (this.enabled) {
setImuReportEnabled(false, IMU_REPORT_PACE);
this.enabled = false;
}
}
paint(ctx: LayerContext): GrayImage {
const small = getDefaultSmallFont();
const medium = getDefaultMediumFont();
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
image.drawText(small, 20, 8, "Accelerometer", 220);
const status = this.enabled ? "IMU on" : "IMU off";
image.drawText(small, width - 20 - small.measureText(status), 8, status, 150);
if (this.reading) {
const axes: Array<[string, number]> = [
["X", this.reading.x],
["Y", this.reading.y],
["Z", this.reading.z],
];
const barX = 118;
const barW = width - barX - 24;
const scale = Math.max(this.peak, 1e-6);
let y = 40;
for (const [label, value] of axes) {
image.drawText(medium, 22, y, label, 210);
image.drawText(medium, 44, y, value.toFixed(3), 235);
drawCenteredBar(image, barX, y + 2, barW, 12, clamp(value / scale, -1, 1));
y += 30;
}
image.drawText(
small,
22,
y + 6,
`source: ${imuSourceLabel(this.reading.source)} samples: ${this.sampleCount}`,
130,
);
} else {
const message = this.enabled
? "Waiting for IMU data…"
: "Paused (page not visible).";
image.drawText(small, 22, 44, message, 190);
image.drawText(small, 22, 66, "The firmware may not report the", 120);
image.drawText(small, 22, 82, "accelerometer at all — experimental.", 120);
}
image.drawText(small, 20, height - 16, `${GESTURE_DOUBLE_CLICK} back`, 110);
return image;
}
async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> {
if (event.type === "double-click") {
ctx.stack.pop();
}
}
}
/** Horizontal bar centered at its midpoint; frac in [-1, 1] fills left/right. */
function drawCenteredBar(image: GrayImage, x: number, y: number, width: number, height: number, frac: number): void {
const mid = x + Math.round(width / 2);
image.fillRect(x, y, width, height, 20);
image.setPixel(mid, y - 1, 90);
image.setPixel(mid, y + height, 90);
const half = width / 2;
const px = Math.round(clamp(frac, -1, 1) * half);
if (px >= 0) {
image.fillRect(mid, y, Math.max(1, px), height, 200);
} else {
image.fillRect(mid + px, y, -px, height, 200);
}
}
-108
View File
@@ -1,108 +0,0 @@
import { getDefaultSmallFont } from "../../graphics/bdffont";
import { GrayImage } from "../../graphics/image";
import { clamp } from "../../util/numeric-util";
import { Layer, type DashboardInputEvent, type LayerActions, type LayerContext } from "../layers";
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_SCROLL } from "../gestures";
import { drawSelectionHighlight, scrollToKeepSelectionVisible } from "../menu";
import {
buildSoundSequencePayload,
CFW_SEQ_MAX,
effectPhrases,
phraseDurationMs,
SOUND_EFFECTS,
type SoundEffect,
} from "./sound-effects";
const HEADER_HEIGHT = 30;
const ROW_HEIGHT = 16;
const LIST_X = 20;
const FOOTER_HEIGHT = 22;
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* Buzzer demo: pick a sound effect from the catalog and play it on the
* glasses' piezo. Multi-phrase effects are paced phrase-by-phrase so each
* sequencer message lands as the previous phrase finishes.
*/
export class BuzzerDemoLayer implements Layer {
private selectedIndex = 0;
private scrollRow = 0;
private playing: string | null = null;
paint(ctx: LayerContext): GrayImage {
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
image.drawText(font, 20, 8, "Buzzer demo", 220);
const status = this.playing ? `Playing: ${this.playing}` : `${GESTURE_CLICK} play`;
image.drawText(font, width - 24 - font.measureText(status), 8, status, 140);
const listHeight = height - HEADER_HEIGHT - FOOTER_HEIGHT;
const visibleRows = Math.max(1, (listHeight / ROW_HEIGHT) | 0);
this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, this.selectedIndex, visibleRows, SOUND_EFFECTS.length);
const lastVisible = Math.min(SOUND_EFFECTS.length, this.scrollRow + visibleRows);
for (let index = this.scrollRow; index < lastVisible; index++) {
const effect = SOUND_EFFECTS[index]!;
const y = HEADER_HEIGHT + (index - this.scrollRow) * ROW_HEIGHT;
const selected = index === this.selectedIndex;
if (selected) {
drawSelectionHighlight(image, LIST_X - 6, y - 1, width - 2 * LIST_X + 12, ROW_HEIGHT - 1, ctx.stack.isFocused(), 4);
}
image.drawText(font, LIST_X, y + 1, effect.name, selected ? 255 : 200);
image.drawText(font, LIST_X + 110, y + 1, effect.desc, selected ? 180 : 120);
}
image.drawText(font, 20, height - 16, `${GESTURE_SCROLL} select ${GESTURE_CLICK} play ${GESTURE_DOUBLE_CLICK} back`, 110);
return image;
}
async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> {
switch (event.type) {
case "scroll-up":
this.selectedIndex = Math.max(0, this.selectedIndex - 1);
return;
case "scroll-down":
this.selectedIndex = Math.min(SOUND_EFFECTS.length - 1, this.selectedIndex + 1);
return;
case "click": {
const effect = SOUND_EFFECTS[clamp(this.selectedIndex, 0, SOUND_EFFECTS.length - 1)];
if (effect && !this.playing) {
// Fire-and-forget: playback paces itself with sleeps between
// phrases; awaiting it here would stall input for seconds.
void this.playEffect(effect, ctx.actions).catch((error) => {
console.warn(`buzzer effect failed: ${error}`);
});
}
return;
}
case "double-click":
ctx.stack.pop();
return;
default:
return;
}
}
private async playEffect(effect: SoundEffect, actions: LayerActions): Promise<void> {
this.playing = effect.name;
actions.requestRender();
try {
for (const phrase of effectPhrases(effect.make())) {
// Safety net: chop any over-long phrase into <=48-step messages.
for (let index = 0; index < phrase.length; index += CFW_SEQ_MAX) {
const chunk = phrase.slice(index, index + CFW_SEQ_MAX);
await actions.playBuzzerSequence(buildSoundSequencePayload(chunk));
await sleep(phraseDurationMs(chunk));
}
}
} finally {
this.playing = null;
actions.requestRender();
}
}
}
-191
View File
@@ -1,191 +0,0 @@
import { getDefaultSmallFont, type BdfFont } from "../../graphics/bdffont";
import { GrayImage } from "../../graphics/image";
import { wrapText, truncateText } from "../../graphics/textwrap";
import { clamp } from "../../util/numeric-util";
import { readUpcomingEvents, type CalendarEvent } from "../../native/calendar";
import { timeFormatSetting } from "../dashboard-settings";
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK } from "../gestures";
import { hasCalendarPermission } from "../../g2/android-permissions";
import { type DashboardInputEvent, type Layer, type LayerContext } from "../layers";
const PAGE_X = 12;
const PAGE_Y = 12;
const LIST_TOP = 38;
const ROW_X = 16;
const LINE_HEIGHT = 14;
const DAY_HEADER_HEIGHT = 16;
const ROW_GAP = 4;
const MAX_EVENTS = 50;
const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
type EventRow = {
event: CalendarEvent;
/** Day header text drawn above this row, or null when it shares the prior day. */
dayHeader: string | null;
lines: string[];
height: number;
};
/**
* The Calendar app's single screen. Without calendar permission it shows a
* prompt telling the user to grant access on the phone (the launch path also
* fires the system permission dialog); with permission it lists upcoming
* events grouped by day, scrollable when they overflow the viewport.
*/
export class CalendarLayer implements Layer {
private selectedIndex = 0;
constructor(private readonly requestPermission: () => void) {}
paint(ctx: LayerContext): GrayImage {
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
image.drawText(font, PAGE_X + 12, PAGE_Y + 9, "Calendar", 220);
if (!hasCalendarPermission()) {
this.paintPermissionPrompt(image, font, width, height);
return image;
}
const events = readUpcomingEvents(MAX_EVENTS);
if (!events.length) {
image.drawText(font, 24, 72, "No upcoming events.", 190);
image.drawText(font, 24, height - 36, `${GESTURE_DOUBLE_CLICK} back`, 110);
return image;
}
const rows = buildEventRows(events);
this.selectedIndex = clamp(this.selectedIndex, 0, rows.length - 1);
image.drawText(font, width - 96, PAGE_Y + 9, `${this.selectedIndex + 1}/${rows.length}`, 150);
const listBottom = height;
const scrollY = scrollForSelected(rows, this.selectedIndex, listBottom - LIST_TOP);
let cursorY = LIST_TOP - scrollY;
for (let index = 0; index < rows.length; index++) {
const row = rows[index]!;
if (cursorY + row.height >= LIST_TOP && cursorY <= listBottom) {
drawEventRow(image, font, row, ROW_X, cursorY, width, index === this.selectedIndex);
}
cursorY += row.height + ROW_GAP;
if (cursorY > listBottom + 80) break;
}
return image;
}
handleInput(event: DashboardInputEvent): void {
if (!hasCalendarPermission()) {
// Any tap on the prompt re-triggers the phone-side permission request.
if (event.type === "click") this.requestPermission();
return;
}
const rows = buildEventRows(readUpcomingEvents(MAX_EVENTS));
if (!rows.length) return;
if (event.type === "scroll-up") {
this.selectedIndex = Math.max(0, this.selectedIndex - 1);
} else if (event.type === "scroll-down") {
this.selectedIndex = Math.min(rows.length - 1, this.selectedIndex + 1);
}
}
private paintPermissionPrompt(image: GrayImage, font: BdfFont, width: number, height: number): void {
const message = "Grant calendar permission on your phone to see your events on the glasses.";
const lines = wrapText(font, message, width - 48);
for (let index = 0; index < lines.length; index++) {
image.drawText(font, 24, 72 + index * LINE_HEIGHT, lines[index]!, 190);
}
image.drawText(font, 24, height - 36, `${GESTURE_CLICK} request ${GESTURE_DOUBLE_CLICK} back`, 110);
}
}
function buildEventRows(events: CalendarEvent[]): EventRow[] {
const rows: EventRow[] = [];
let previousDayKey = "";
for (const event of events) {
const dayKey = dayKeyOf(event.startMs);
const dayHeader = dayKey === previousDayKey ? null : dayHeaderLabel(event.startMs);
previousDayKey = dayKey;
const lines: string[] = [];
const timeLabel = event.allDay ? "All day" : formatEventTime(event.startMs);
lines.push(`${timeLabel} ${event.title || "(untitled)"}`);
if (event.location) {
lines.push(event.location);
}
rows.push({
event,
dayHeader,
lines,
height: (dayHeader ? DAY_HEADER_HEIGHT : 0) + 6 + lines.length * LINE_HEIGHT,
});
}
return rows;
}
function drawEventRow(
image: GrayImage,
font: BdfFont,
row: EventRow,
x: number,
y: number,
width: number,
selected: boolean,
): void {
let cursorY = y;
if (row.dayHeader) {
image.drawText(font, x, cursorY + 2, row.dayHeader, 150);
cursorY += DAY_HEADER_HEIGHT;
}
const bodyHeight = row.lines.length * LINE_HEIGHT + 4;
if (selected) {
image.fillRoundedRect(x - 6, cursorY, width - 2 * (x - 6), bodyHeight, 15, 6);
image.drawRoundedRect(x - 6, cursorY, width - 2 * (x - 6), bodyHeight, 90, 6);
}
const maxTextWidth = width - 2 * x;
for (let index = 0; index < row.lines.length; index++) {
const value = index === 0 ? (selected ? 235 : 205) : 160;
image.drawText(font, x, cursorY + 3 + index * LINE_HEIGHT, truncateText(font, row.lines[index]!, maxTextWidth), value);
}
}
function scrollForSelected(rows: EventRow[], selectedIndex: number, viewportHeight: number): number {
let selectedTop = 0;
for (let index = 0; index < selectedIndex; index++) {
selectedTop += rows[index]!.height + ROW_GAP;
}
const selectedBottom = selectedTop + rows[selectedIndex]!.height;
const contentHeight = rows.reduce((sum, row) => sum + row.height + ROW_GAP, 0);
const maxScroll = Math.max(0, contentHeight - viewportHeight);
const centered = selectedTop - Math.max(0, (viewportHeight - (selectedBottom - selectedTop)) / 2);
return clamp(centered | 0, 0, maxScroll);
}
function dayKeyOf(timestampMs: number): string {
const date = new Date(timestampMs);
return `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;
}
function dayHeaderLabel(timestampMs: number): string {
const date = new Date(timestampMs);
const now = new Date();
const midnight = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
const dayDelta = Math.round((midnight(date) - midnight(now)) / (24 * 60 * 60 * 1000));
const base = `${WEEKDAYS[date.getDay()]} ${date.getDate()} ${MONTHS[date.getMonth()]}`;
if (dayDelta === 0) return `Today ${base}`;
if (dayDelta === 1) return `Tomorrow ${base}`;
return base;
}
function formatEventTime(timestampMs: number): string {
const date = new Date(timestampMs);
const minutes = String(date.getMinutes()).padStart(2, "0");
const hour24 = date.getHours();
if (timeFormatSetting.get() === "12h") {
const hour12 = ((hour24 + 11) % 12) + 1;
return `${hour12}:${minutes} ${hour24 < 12 ? "AM" : "PM"}`;
}
return `${String(hour24).padStart(2, "0")}:${minutes}`;
}
-591
View File
@@ -1,591 +0,0 @@
import { getDefaultSmallFont, type BdfFont } from "../../graphics/bdffont";
import { truncateText, truncateLeft } from "../../graphics/textwrap";
import { GrayImage } from "../../graphics/image";
import { renderIcon, type IconName } from "../../graphics/icons";
import { clamp } from "../../util/numeric-util";
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_SCROLL } from "../gestures";
import { drawListScrollbar, drawSelectionHighlight, scrollToKeepSelectionVisible, type MenuItem } from "../menu";
import { ConfigSettingEnum } from "../dashboard-settings";
import { getStringSetting, setStringSetting } from "../../native/settings-store";
import {
externalStorageRootPath,
hasAllFilesAccess,
listDirectory,
requestAllFilesAccess,
statPath,
type DirectoryEntry,
} from "../../native/file-access";
import { Layer, type DashboardInputEvent, type LayerContext } from "../layers";
const HEADER_HEIGHT = 34;
const ROW_HEIGHT = 16;
const LIST_X = 20;
const FOOTER_HEIGHT = 22;
const GRID_COLS = 5;
const GRID_VISIBLE_ROWS = 3;
const GRID_BOTTOM_MARGIN = 20;
const ICON_SIZE = 44;
const LABEL_GAP = 2;
export type FilesViewMode = "icons" | "list";
export const filesViewModeSetting = new ConfigSettingEnum<FilesViewMode>({
id: "files-view-mode",
label: "View",
storageKey: "files.viewMode",
defaultValue: "icons",
values: ["icons", "list"],
formatValue: (value) => (value === "icons" ? "Icons" : "List"),
});
// Bookmarked paths, in bookmarking order, stored as a JSON string array.
const BOOKMARKS_KEY = "files.bookmarks";
export function getBookmarkedPaths(): string[] {
try {
const parsed = JSON.parse(getStringSetting(BOOKMARKS_KEY, "[]"));
return Array.isArray(parsed) ? parsed.filter((path): path is string => typeof path === "string") : [];
} catch {
return [];
}
}
export function isBookmarked(path: string): boolean {
return getBookmarkedPaths().includes(path);
}
export function toggleBookmark(path: string): void {
const paths = getBookmarkedPaths();
const next = paths.includes(path) ? paths.filter((p) => p !== path) : [...paths, path];
setStringSetting(BOOKMARKS_KEY, JSON.stringify(next));
}
const TEXT_EXT = /\.(txt|md|markdown|log|json|xml|csv|ini|conf|cfg|yaml|yml|ts|js|py|java|c|cpp|h|sh|html|css)$/i;
const IMAGE_EXT = /\.(png|jpe?g|gif|bmp|webp|heic|heif|svg)$/i;
const VIDEO_EXT = /\.(mp4|mkv|webm|avi|mov|3gp|m4v)$/i;
const AUDIO_EXT = /\.(mp3|m4a|aac|ogg|oga|opus|flac|wav|mid)$/i;
function fileIconName(name: string): IconName {
if (TEXT_EXT.test(name)) return "file-text";
if (IMAGE_EXT.test(name)) return "image";
if (VIDEO_EXT.test(name)) return "film";
if (AUDIO_EXT.test(name)) return "music";
return "file";
}
export type FileBrowserOptions = {
/** Files failing this are listed dimmed (not viewable); picking them still fires onFilePicked. */
isSupportedFile: (name: string) => boolean;
onFilePicked: (entry: DirectoryEntry, ctx: LayerContext) => void;
/** Double-click while already at the Places level (leave the browser). */
onLeave: () => void;
};
type EntryItem = {
kind: "entry";
label: string;
icon: IconName;
entry: DirectoryEntry;
supported: boolean;
/** A bookmark whose path no longer exists (listed only for unbookmarking). */
missing?: boolean;
/** An item on the Places level (a bookmark or a fixed storage root). */
place: boolean;
/** Fixed Places roots cannot be bookmarked or unbookmarked. */
fixed: boolean;
};
type BrowserItem = { kind: "grant"; label: string } | { kind: "info"; label: string } | EntryItem;
type IconRow =
| { kind: "special"; item: BrowserItem; flatIndex: number }
| { kind: "grid"; items: EntryItem[]; firstIndex: number };
type IconMode = "row" | "item";
/**
* Filesystem browser with two views. The top "Places" level lists bookmarks
* and the storage roots; descending browses real directories. Icons view is a
* 5-column grid with launcher-style two-level selection (scroll picks a row,
* click drops into the row, scroll picks the item); list view is a flat list.
* Click descends into a directory or picks a supported file; double-click
* backs out one level (item selection, then parent directory, then Places,
* then leaving the browser). Sized to its hosting stack.
*/
export class FileBrowserLayer implements Layer {
/** Current directory, or null at the Places level. */
private location: string | null = null;
/** The Places entry we descended through; going up from it returns to Places. */
private navRoot: string | null = null;
private entries: DirectoryEntry[] | null = null;
private listingFailed = false;
private listIndex = 0;
private selectedRow = 0;
private selectedCol = 0;
private iconMode: IconMode = "row";
private scrollRow = 0;
constructor(private readonly options: FileBrowserOptions) {}
paint(ctx: LayerContext): GrayImage {
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
const rows = this.flatRows();
image.drawText(font, 20, 8, "Files", 220);
const pathLabel = this.location === null ? "Places" : this.location;
image.drawText(font, 20, 22, truncateLeft(font, pathLabel, width - 40), 130);
if (filesViewModeSetting.get() === "list") {
this.paintList(image, font, rows, ctx);
} else {
this.paintIcons(image, font, rows, ctx);
}
return image;
}
private paintList(image: GrayImage, font: BdfFont, rows: BrowserItem[], ctx: LayerContext): void {
const { width, height } = ctx.stack.getBaseSize();
this.listIndex = clamp(this.listIndex, 0, Math.max(0, rows.length - 1));
const listHeight = height - HEADER_HEIGHT - FOOTER_HEIGHT;
const visibleRows = Math.max(1, (listHeight / ROW_HEIGHT) | 0);
this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, this.listIndex, visibleRows, rows.length);
const lastVisible = Math.min(rows.length, this.scrollRow + visibleRows);
for (let index = this.scrollRow; index < lastVisible; index++) {
const row = rows[index]!;
const y = HEADER_HEIGHT + (index - this.scrollRow) * ROW_HEIGHT;
const selected = index === this.listIndex;
if (selected) {
drawSelectionHighlight(image, LIST_X - 6, y - 1, width - 2 * LIST_X + 12, ROW_HEIGHT - 1, ctx.stack.isFocused(), 4);
}
const value = itemValue(row, selected);
image.drawText(font, LIST_X, y + 1, truncateText(font, row.label, width - 2 * LIST_X), value);
}
image.drawText(font, 20, height - 16, `${GESTURE_CLICK} open ${GESTURE_DOUBLE_CLICK} up / back`, 110);
}
private paintIcons(image: GrayImage, font: BdfFont, rows: BrowserItem[], ctx: LayerContext): void {
const { width, height } = ctx.stack.getBaseSize();
const focused = ctx.stack.isFocused();
const iconRows = buildIconRows(rows);
this.selectedRow = clamp(this.selectedRow, 0, Math.max(0, iconRows.length - 1));
const gridTop = HEADER_HEIGHT;
const gridBottom = height - GRID_BOTTOM_MARGIN;
const rowH = Math.floor((gridBottom - gridTop) / GRID_VISIBLE_ROWS);
const colW = width / GRID_COLS;
this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, this.selectedRow, GRID_VISIBLE_ROWS, iconRows.length);
const lastVisible = Math.min(iconRows.length, this.scrollRow + GRID_VISIBLE_ROWS);
for (let rowIndex = this.scrollRow; rowIndex < lastVisible; rowIndex++) {
const row = iconRows[rowIndex]!;
const y = gridTop + (rowIndex - this.scrollRow) * rowH;
const selected = rowIndex === this.selectedRow;
if (row.kind === "special") {
const textY = y + (((rowH - font.lineHeight) / 2) | 0);
if (selected) {
drawSelectionHighlight(image, LIST_X - 6, textY - 2, width - 2 * LIST_X + 12, font.lineHeight + 4, focused, 4);
}
image.drawText(font, LIST_X, textY, truncateText(font, row.item.label, width - 2 * LIST_X), itemValue(row.item, selected));
continue;
}
if (selected) {
if (this.iconMode === "row") {
drawSelectionHighlight(image, 4, y + 1, width - 8, rowH - 2, focused, 6);
} else {
this.selectedCol = clamp(this.selectedCol, 0, row.items.length - 1);
drawSelectionHighlight(image, this.selectedCol * colW + 4, y + 1, colW - 8, rowH - 2, focused, 6);
}
}
for (let col = 0; col < row.items.length; col++) {
const item = row.items[col]!;
const centerX = col * colW + colW / 2;
const blockTop = y + Math.max(2, (rowH - ICON_SIZE - font.lineHeight - LABEL_GAP) / 2);
const icon = renderIcon(item.icon, ICON_SIZE);
if (icon) {
image.bitBlt(item.supported ? icon : dimmedIcon(item.icon, icon), Math.round(centerX - icon.width / 2), Math.round(blockTop), {
transparentZero: true,
});
}
const label = truncateText(font, item.label, colW - 8);
const labelY = Math.round(blockTop + ICON_SIZE + LABEL_GAP);
image.drawText(font, Math.round(centerX - font.measureText(label) / 2), labelY, label, item.supported ? 210 : 100);
}
}
if (iconRows.length > GRID_VISIBLE_ROWS) {
drawListScrollbar(image, width - 5, gridTop, GRID_VISIBLE_ROWS * rowH - 4, this.scrollRow, GRID_VISIBLE_ROWS, iconRows.length);
}
const hint =
this.iconMode === "row"
? `${GESTURE_SCROLL} row ${GESTURE_CLICK} pick ${GESTURE_DOUBLE_CLICK} up / back`
: `${GESTURE_SCROLL} item ${GESTURE_CLICK} open ${GESTURE_DOUBLE_CLICK} row`;
image.drawText(font, 20, height - 16, hint, 110);
}
async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> {
if (filesViewModeSetting.get() === "list") {
await this.handleListInput(event, ctx);
} else {
await this.handleIconsInput(event, ctx);
}
}
private async handleListInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> {
const rows = this.flatRows();
switch (event.type) {
case "scroll-up":
this.listIndex = Math.max(0, this.listIndex - 1);
return;
case "scroll-down":
this.listIndex = Math.min(Math.max(0, rows.length - 1), this.listIndex + 1);
return;
case "click": {
const row = rows[clamp(this.listIndex, 0, Math.max(0, rows.length - 1))];
if (row) await this.activateItem(row, ctx);
return;
}
case "double-click":
this.navigateUp();
return;
default:
return;
}
}
private async handleIconsInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> {
const rows = this.flatRows();
const iconRows = buildIconRows(rows);
this.selectedRow = clamp(this.selectedRow, 0, Math.max(0, iconRows.length - 1));
const row = iconRows[this.selectedRow];
switch (event.type) {
case "scroll-up":
case "scroll-down": {
const delta = event.type === "scroll-down" ? 1 : -1;
if (this.iconMode === "item") {
// Item selection traverses linearly: past a row's edge it continues
// onto the adjacent row (a special row counts as a single item).
if (row?.kind === "grid") {
const next = clamp(this.selectedCol, 0, row.items.length - 1) + delta;
if (next >= 0 && next < row.items.length) {
this.selectedCol = next;
return;
}
}
const adjacentIndex = this.selectedRow + delta;
if (adjacentIndex < 0 || adjacentIndex >= iconRows.length) return;
this.selectedRow = adjacentIndex;
const adjacent = iconRows[adjacentIndex]!;
if (adjacent.kind === "grid") {
this.selectedCol = delta > 0 ? 0 : adjacent.items.length - 1;
}
} else {
this.selectedRow = clamp(this.selectedRow + delta, 0, Math.max(0, iconRows.length - 1));
}
return;
}
case "click": {
if (!row) return;
if (row.kind === "special") {
await this.activateItem(row.item, ctx);
return;
}
if (this.iconMode === "row") {
this.iconMode = "item";
// Default to the middle column (clamped to the row's item count).
this.selectedCol = Math.min(Math.floor(GRID_COLS / 2), row.items.length - 1);
} else {
const item = row.items[clamp(this.selectedCol, 0, row.items.length - 1)];
if (item) await this.activateItem(item, ctx);
}
return;
}
case "double-click":
if (this.iconMode === "item") {
this.iconMode = "row";
} else {
this.navigateUp();
}
return;
default:
return;
}
}
/**
* App-specific entries for the window long-press menu: the view switch,
* plus bookmark/unbookmark for the selected entry (in icons view only once
* an item, not just a row, is selected).
*/
buildMenuItems(): MenuItem[] {
const items: MenuItem[] = [];
const mode = filesViewModeSetting.get();
items.push({
label: mode === "icons" ? "View as list" : "View as icons",
onSelect: (ctx) => {
this.setViewMode(mode === "icons" ? "list" : "icons");
ctx.stack.pop();
},
});
const target = this.currentItem();
if (target && target.kind === "entry" && !target.fixed) {
const path = target.entry.path;
const name = truncateChars(target.entry.name || path, 24);
items.push({
label: isBookmarked(path) ? `Remove bookmark: ${name}` : `Bookmark: ${name}`,
onSelect: (ctx) => {
toggleBookmark(path);
const rows = this.flatRows();
this.listIndex = clamp(this.listIndex, 0, Math.max(0, rows.length - 1));
ctx.stack.pop();
},
});
}
return items;
}
/** The item an entry-specific action would apply to, if one is selected. */
private currentItem(): BrowserItem | null {
const rows = this.flatRows();
if (!rows.length) return null;
if (filesViewModeSetting.get() === "list") {
return rows[clamp(this.listIndex, 0, rows.length - 1)] ?? null;
}
const iconRows = buildIconRows(rows);
const row = iconRows[clamp(this.selectedRow, 0, iconRows.length - 1)];
if (!row) return null;
if (row.kind === "special") return row.item;
if (this.iconMode !== "item") return null;
return row.items[clamp(this.selectedCol, 0, row.items.length - 1)] ?? null;
}
private setViewMode(mode: FilesViewMode): void {
if (filesViewModeSetting.get() === mode) return;
const rows = this.flatRows();
const iconRows = buildIconRows(rows);
if (mode === "list") {
// Carry the icon-grid selection into the flat list (clamped column when
// only a row was selected).
const row = iconRows[clamp(this.selectedRow, 0, Math.max(0, iconRows.length - 1))];
if (row) {
this.listIndex =
row.kind === "special" ? row.flatIndex : row.firstIndex + clamp(this.selectedCol, 0, row.items.length - 1);
}
} else {
this.setGridSelectionFromFlatIndex(rows, clamp(this.listIndex, 0, Math.max(0, rows.length - 1)));
this.iconMode = "row";
}
filesViewModeSetting.set(mode);
this.scrollRow = 0;
}
private async activateItem(item: BrowserItem, ctx: LayerContext): Promise<void> {
if (item.kind === "grant") {
requestAllFilesAccess();
this.entries = null; // re-list after the user returns from Settings
return;
}
if (item.kind !== "entry" || item.missing) return;
if (item.entry.isDirectory) {
this.navigateTo(item.entry.path, item.place);
} else {
// Every real file opens the picked-file dialog, viewable or not (the
// dialog shows metadata; open actions depend on the type).
this.options.onFilePicked(item.entry, ctx);
}
}
private navigateTo(path: string, asRoot = false): void {
if (asRoot) this.navRoot = path;
this.location = path;
this.entries = null;
this.resetSelection();
}
private navigateUp(): void {
const from = this.location;
if (from === null) {
this.options.onLeave();
return;
}
if (from === this.navRoot || from === "/") {
this.location = null;
this.entries = null;
this.resetSelection();
this.selectPath(this.navRoot ?? from);
this.navRoot = null;
return;
}
const parentRaw = from.slice(0, from.lastIndexOf("/"));
this.navigateTo(parentRaw.length ? parentRaw : "/");
this.selectPath(from);
}
private resetSelection(): void {
this.listIndex = 0;
this.selectedRow = 0;
this.selectedCol = 0;
this.iconMode = "row";
this.scrollRow = 0;
}
/** Select the item with the given path (e.g. the directory just left). */
private selectPath(path: string): void {
const rows = this.flatRows();
const index = rows.findIndex((row) => row.kind === "entry" && row.entry.path === path);
if (index < 0) return;
this.listIndex = index;
this.setGridSelectionFromFlatIndex(rows, index);
}
private setGridSelectionFromFlatIndex(rows: BrowserItem[], index: number): void {
const specials = leadingSpecialCount(rows);
if (index < specials) {
this.selectedRow = index;
this.selectedCol = 0;
return;
}
const ordinal = index - specials;
this.selectedRow = specials + Math.floor(ordinal / GRID_COLS);
this.selectedCol = ordinal % GRID_COLS;
}
private flatRows(): BrowserItem[] {
const rows: BrowserItem[] = [];
if (!hasAllFilesAccess()) {
rows.push({ kind: "grant", label: "Grant file access (opens phone Settings)" });
}
if (this.location === null) {
for (const path of getBookmarkedPaths()) {
rows.push(this.bookmarkItem(path));
}
rows.push(this.placeItem("Internal storage", externalStorageRootPath()));
rows.push(this.placeItem("/", "/"));
return rows;
}
this.loadEntries();
for (const entry of this.entries ?? []) {
rows.push({
kind: "entry",
entry,
label: entry.isDirectory ? `${entry.name}/` : entry.name,
icon: entry.isDirectory ? "folder" : fileIconName(entry.name),
supported: entry.isDirectory || this.options.isSupportedFile(entry.name),
place: false,
fixed: false,
});
}
if (!rows.some((row) => row.kind === "entry")) {
rows.push({ kind: "info", label: this.listingFailed ? "(unreadable directory)" : "(empty directory)" });
}
return rows;
}
private placeItem(label: string, path: string): EntryItem {
return {
kind: "entry",
entry: { name: label, path, isDirectory: true, sizeBytes: 0, modifiedMs: 0 },
label,
icon: "hard-drive",
supported: true,
place: true,
fixed: true,
};
}
private bookmarkItem(path: string): EntryItem {
const stat = statPath(path);
if (!stat) {
const name = basename(path);
return {
kind: "entry",
entry: { name, path, isDirectory: false, sizeBytes: 0, modifiedMs: 0 },
label: `${name} (missing)`,
icon: "file",
supported: false,
missing: true,
place: true,
fixed: false,
};
}
const name = stat.name || path;
return {
kind: "entry",
entry: stat,
label: stat.isDirectory ? `${name}/` : name,
icon: stat.isDirectory ? "folder" : fileIconName(name),
supported: stat.isDirectory || this.options.isSupportedFile(name),
place: true,
fixed: false,
};
}
private loadEntries(): void {
if (this.entries !== null || this.location === null) return;
const listing = listDirectory(this.location);
this.listingFailed = listing === null;
this.entries = listing ?? [];
}
}
function buildIconRows(flat: BrowserItem[]): IconRow[] {
const rows: IconRow[] = [];
let index = 0;
// Special rows (grant prompt, empty/unreadable info) lead the list; each
// gets a full-width row of its own. Entries follow, chunked into grid rows.
while (index < flat.length && flat[index]!.kind !== "entry") {
rows.push({ kind: "special", item: flat[index]!, flatIndex: index });
index++;
}
for (; index < flat.length; index += GRID_COLS) {
rows.push({ kind: "grid", items: flat.slice(index, index + GRID_COLS) as EntryItem[], firstIndex: index });
}
return rows;
}
function leadingSpecialCount(rows: BrowserItem[]): number {
let count = 0;
while (count < rows.length && rows[count]!.kind !== "entry") count++;
return count;
}
function itemValue(item: BrowserItem, selected: boolean): number {
if (item.kind === "info") return 120;
if (item.kind === "grant") return selected ? 255 : 210;
if (!item.supported) return selected ? 140 : 100;
return selected ? 255 : 200;
}
// Unsupported files draw their grid icon at half brightness; rendered once
// per icon name and cached (all grid icons share one size).
const dimmedIconCache = new Map<IconName, GrayImage>();
function dimmedIcon(name: IconName, icon: GrayImage): GrayImage {
const cached = dimmedIconCache.get(name);
if (cached) return cached;
const dimmed = new GrayImage(icon.width, icon.height, 0);
for (let i = 0; i < icon.pixels.length; i++) {
dimmed.pixels[i] = icon.pixels[i]! >> 1;
}
dimmedIconCache.set(name, dimmed);
return dimmed;
}
function basename(path: string): string {
const parts = path.split("/").filter((part) => part.length > 0);
return parts[parts.length - 1] ?? path;
}
function truncateChars(text: string, maxLength: number): string {
return text.length <= maxLength ? text : `${text.slice(0, Math.max(0, maxLength - 3))}...`;
}
-119
View File
@@ -1,119 +0,0 @@
import { getDefaultSmallFont } from "../../graphics/bdffont";
import { GrayImage } from "../../graphics/image";
import { wrapText } from "../../graphics/textwrap";
import type { DirectoryEntry } from "../../native/file-access";
import { GESTURE_DOUBLE_CLICK } from "../gestures";
import { Layer, type DashboardInputEvent, type LayerContext, type PaintBelow } from "../layers";
import { drawSelectionHighlight } from "../menu";
const DIALOG_X = 8;
const DIALOG_Y = 8;
const DIALOG_WIDTH = 272;
const PADDING = 10;
const INFO_LINE_STEP = 14;
const ACTION_ROW_HEIGHT = 20;
const MAX_NAME_LINES = 3;
export type FileInfoAction = {
label: string;
onSelect: (ctx: LayerContext) => Promise<void> | void;
};
/**
* The picked-file dialog: metadata (full untruncated name, size, modified
* date) followed by the open actions for viewable file types — possibly none
* for files nothing can open. Opened by the browser for every file;
* double-click closes it.
*/
export class FileInfoDialogLayer implements Layer {
private selectedIndex = 0;
constructor(
private readonly entry: DirectoryEntry,
private readonly actions: FileInfoAction[],
) {}
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
const font = getDefaultSmallFont();
const { height: viewportHeight } = ctx.stack.getBaseSize();
const image = paintBelow();
const textWidth = DIALOG_WIDTH - 2 * PADDING - 4;
const nameLines = wrapText(font, this.entry.name, textWidth, { breakLongWords: true }).slice(0, MAX_NAME_LINES);
const infoLines = [
`Size: ${formatSize(this.entry.sizeBytes)}`,
`Modified: ${formatDate(this.entry.modifiedMs)}`,
];
const bodyTop = PADDING + (nameLines.length + infoLines.length) * INFO_LINE_STEP + 6;
const bodyHeight = this.actions.length ? this.actions.length * ACTION_ROW_HEIGHT : INFO_LINE_STEP;
const height = Math.min(bodyTop + bodyHeight + PADDING, viewportHeight - 2 * DIALOG_Y);
// Fill 1, not 0: identical after 4bpp quantization, but 0 is the
// transparent color key when painting on the shell surface.
image.fillRoundedRect(DIALOG_X, DIALOG_Y, DIALOG_WIDTH, height, 1);
image.drawRoundedRect(DIALOG_X, DIALOG_Y, DIALOG_WIDTH, height, 72);
let y = DIALOG_Y + PADDING;
for (const line of nameLines) {
image.drawText(font, DIALOG_X + PADDING + 2, y, line, 230);
y += INFO_LINE_STEP;
}
for (const line of infoLines) {
image.drawText(font, DIALOG_X + PADDING + 2, y, line, 150);
y += INFO_LINE_STEP;
}
y += 6;
if (!this.actions.length) {
image.drawText(font, DIALOG_X + PADDING + 2, y + 3, `${GESTURE_DOUBLE_CLICK} close`, 110);
return image;
}
const focused = ctx.stack.isFocused();
for (let index = 0; index < this.actions.length; index++) {
const rowY = y + index * ACTION_ROW_HEIGHT;
const selected = index === this.selectedIndex;
if (selected) {
drawSelectionHighlight(image, DIALOG_X + 12, rowY, DIALOG_WIDTH - 24, ACTION_ROW_HEIGHT - 1, focused, 8);
}
image.drawText(font, DIALOG_X + 22, rowY + 3, this.actions[index]!.label, selected ? 255 : 200);
}
return image;
}
async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> {
switch (event.type) {
case "scroll-up":
if (this.actions.length) {
this.selectedIndex = (this.selectedIndex + this.actions.length - 1) % this.actions.length;
}
return;
case "scroll-down":
if (this.actions.length) {
this.selectedIndex = (this.selectedIndex + 1) % this.actions.length;
}
return;
case "click":
await this.actions[this.selectedIndex]?.onSelect(ctx);
return;
case "double-click":
ctx.stack.pop();
return;
default:
return;
}
}
}
function formatSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}
function formatDate(ms: number): string {
if (!ms) return "unknown";
const date = new Date(ms);
const pad = (n: number) => String(n).padStart(2, "0");
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
}
-57
View File
@@ -1,57 +0,0 @@
import { getDefaultSmallFont, type BdfFont } from "../../graphics/bdffont";
import { truncateText } from "../../graphics/textwrap";
import { GrayImage } from "../../graphics/image";
import { loadImageFileAsGray } from "../../native/image-files";
import { GESTURE_DOUBLE_CLICK } from "../gestures";
import { Layer, type DashboardInputEvent, type LayerContext } from "../layers";
const MARGIN_X = 18;
const TITLE_Y = 8;
const BODY_TOP = 24;
const BODY_MARGIN = 2;
/**
* Image viewer for a file on disk: title line, then the image decoded to
* grayscale and downscaled to fit the remaining area (never upscaled).
* Double-click closes it. Sized to its hosting stack (a Files document
* window, or pushed over the file browser for view-in-place).
*/
export class ImageViewerLayer implements Layer {
private image: GrayImage | null = null;
private loadAttempted = false;
constructor(
private readonly path: string,
private readonly title: string,
) {}
paint(ctx: LayerContext): GrayImage {
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const out = new GrayImage(width, height, 0);
out.drawText(font, MARGIN_X, TITLE_Y, truncateText(font, this.title, width - 2 * MARGIN_X), 220);
const bodyHeight = height - BODY_TOP - BODY_MARGIN;
if (!this.loadAttempted) {
this.loadAttempted = true;
this.image = loadImageFileAsGray(this.path, width - 2 * BODY_MARGIN, bodyHeight);
}
if (!this.image) {
out.drawText(font, MARGIN_X, BODY_TOP + 16, "(could not load image)", 160);
out.drawText(font, MARGIN_X, height - 16, `${GESTURE_DOUBLE_CLICK} back`, 110);
return out;
}
out.bitBlt(
this.image,
Math.round((width - this.image.width) / 2),
BODY_TOP + Math.round((bodyHeight - this.image.height) / 2),
);
return out;
}
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
if (event.type === "double-click") {
ctx.stack.pop();
}
}
}
-304
View File
@@ -1,304 +0,0 @@
import { getDefaultSmallFont, type BdfFont } from "../../graphics/bdffont";
import { GrayImage } from "../../graphics/image";
import { clamp } from "../../util/numeric-util";
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_SCROLL } from "../gestures";
import {
MenuLayer,
drawListScrollbar,
drawSelectionHighlight,
drawSubmenuIndicator,
scrollToKeepSelectionVisible,
} from "../menu";
import {
mediaBrowserBridge,
type MediaBrowseItem,
type MediaBrowserApp,
} from "../../native/media-browser";
import { Layer, type DashboardInputEvent, type LayerContext } from "../layers";
const HEADER_HEIGHT = 34;
const ROW_HEIGHT = 16;
const LIST_X = 20;
const FOOTER_HEIGHT = 22;
export type MediaBrowseOptions = {
app: MediaBrowserApp;
/** Called after playback of a picked item has been requested. */
onPlayed: (ctx: LayerContext) => void;
/** Double-click at the library root (leave the browser). */
onLeave: (ctx: LayerContext) => void;
};
type BrowseLevel = {
parentId: string;
title: string;
/** null while the listing is loading. */
items: MediaBrowseItem[] | null;
error: string;
selectedIndex: number;
scrollRow: number;
};
type BrowsePhase = "idle" | "connecting" | "ready" | "failed";
/**
* Library browser over another app's MediaBrowserService (the Android Auto
* mechanism): connecting starts the player's process if needed, so this works
* with no media session active and the phone locked. Scroll to select, click
* to open a folder or play an item, double-click to go up (leaving the browser
* when already at the root).
*/
export class MediaBrowseLayer implements Layer {
private phase: BrowsePhase = "idle";
private connectError = "";
private levels: BrowseLevel[] = [];
private removed = false;
constructor(private readonly options: MediaBrowseOptions) {}
paint(ctx: LayerContext): GrayImage {
if (this.phase === "idle") {
this.startConnect(ctx);
}
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
image.drawText(font, 20, 8, `Library: ${this.options.app.appName}`, 220);
if (this.phase === "connecting" || this.phase === "idle") {
image.drawText(font, 24, HEADER_HEIGHT + 8, `Starting ${this.options.app.appName}...`, 150);
image.drawText(font, 20, height - 16, `${GESTURE_DOUBLE_CLICK} back`, 110);
return image;
}
if (this.phase === "failed") {
image.drawText(font, 24, HEADER_HEIGHT + 8, "Could not connect:", 180);
image.drawText(font, 24, HEADER_HEIGHT + 24, truncateRight(font, this.connectError, width - 48), 140);
image.drawText(font, 20, height - 16, `${GESTURE_CLICK} retry ${GESTURE_DOUBLE_CLICK} back`, 110);
return image;
}
const level = this.currentLevel();
const path = this.levels.map((entry) => entry.title).join(" / ");
image.drawText(font, 20, 22, truncateLeft(font, path, width - 40), 130);
if (!level || level.items === null) {
image.drawText(font, 24, HEADER_HEIGHT + 8, level?.error ? level.error : "Loading...", level?.error ? 140 : 150);
image.drawText(font, 20, height - 16, `${GESTURE_DOUBLE_CLICK} up / back`, 110);
return image;
}
const items = level.items;
if (!items.length) {
image.drawText(font, 24, HEADER_HEIGHT + 8, "(empty)", 120);
image.drawText(font, 20, height - 16, `${GESTURE_DOUBLE_CLICK} up / back`, 110);
return image;
}
level.selectedIndex = clamp(level.selectedIndex, 0, items.length - 1);
const listHeight = height - HEADER_HEIGHT - FOOTER_HEIGHT;
const visibleRows = Math.max(1, (listHeight / ROW_HEIGHT) | 0);
level.scrollRow = scrollToKeepSelectionVisible(level.scrollRow, level.selectedIndex, visibleRows, items.length);
const rowWidth = width - 2 * LIST_X;
const lastVisible = Math.min(items.length, level.scrollRow + visibleRows);
for (let index = level.scrollRow; index < lastVisible; index++) {
const item = items[index]!;
const y = HEADER_HEIGHT + (index - level.scrollRow) * ROW_HEIGHT;
const selected = index === level.selectedIndex;
const highlightX = LIST_X - 6;
const highlightY = y - 1;
const highlightWidth = rowWidth + 12;
const highlightHeight = ROW_HEIGHT - 1;
if (selected) {
drawSelectionHighlight(image, highlightX, highlightY, highlightWidth, highlightHeight, ctx.stack.isFocused(), 4);
}
const value = selected ? 255 : 200;
const title = truncateRight(font, item.title || "(untitled)", rowWidth - 16);
image.drawText(font, LIST_X, y + 1, title, value);
if (item.subtitle) {
const titleWidth = font.measureText(title);
const subtitleWidth = font.measureText(item.subtitle);
if (titleWidth + subtitleWidth + 24 <= rowWidth - 16) {
image.drawText(font, LIST_X + rowWidth - 16 - subtitleWidth, y + 1, item.subtitle, 110);
}
}
if (item.browsable) {
drawSubmenuIndicator(image, font, highlightX, highlightY, highlightWidth, highlightHeight, selected ? value : 110);
}
}
if (items.length > visibleRows) {
drawListScrollbar(
image,
width - 12,
HEADER_HEIGHT,
visibleRows * ROW_HEIGHT - 4,
level.scrollRow,
visibleRows,
items.length,
);
}
image.drawText(
font,
20,
height - 16,
`${GESTURE_SCROLL} select ${GESTURE_CLICK} open/play ${GESTURE_DOUBLE_CLICK} up / back`,
110,
);
return image;
}
async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> {
if (this.phase === "failed") {
if (event.type === "click") {
this.phase = "idle";
this.connectError = "";
} else if (event.type === "double-click") {
this.leave(ctx);
}
return;
}
if (event.type === "double-click") {
if (this.levels.length > 1) {
this.levels.pop();
} else {
this.leave(ctx);
}
return;
}
const level = this.currentLevel();
const items = level?.items;
if (!level || !items || !items.length) return;
switch (event.type) {
case "scroll-up":
level.selectedIndex = Math.max(0, level.selectedIndex - 1);
return;
case "scroll-down":
level.selectedIndex = Math.min(items.length - 1, level.selectedIndex + 1);
return;
case "click": {
const item = items[clamp(level.selectedIndex, 0, items.length - 1)];
if (!item) return;
if (item.browsable && item.playable) {
ctx.stack.push(
new MenuLayer(truncateRight(getDefaultSmallFont(), item.title || "(untitled)", 230), [
{
label: "Play",
onSelect: (menuCtx) => {
menuCtx.stack.pop();
this.play(menuCtx, item);
},
},
{
label: "Open",
onSelect: (menuCtx) => {
menuCtx.stack.pop();
this.descendInto(menuCtx, item);
},
},
]),
);
} else if (item.browsable) {
this.descendInto(ctx, item);
} else if (item.playable) {
this.play(ctx, item);
}
return;
}
default:
return;
}
}
onRemoved(): void {
this.removed = true;
mediaBrowserBridge.disconnect();
}
private currentLevel(): BrowseLevel | undefined {
return this.levels[this.levels.length - 1];
}
private leave(ctx: LayerContext): void {
this.options.onLeave(ctx);
}
private play(ctx: LayerContext, item: MediaBrowseItem): void {
mediaBrowserBridge.playFromMediaId(item.mediaId);
this.options.onPlayed(ctx);
}
private descendInto(ctx: LayerContext, item: MediaBrowseItem): void {
const level: BrowseLevel = {
parentId: item.mediaId,
title: item.title || "(untitled)",
items: null,
error: "",
selectedIndex: 0,
scrollRow: 0,
};
this.levels.push(level);
this.loadLevel(ctx, level);
}
private startConnect(ctx: LayerContext): void {
this.phase = "connecting";
mediaBrowserBridge
.connect(this.options.app)
.then((rootId) => {
if (this.removed) return;
this.phase = "ready";
const root: BrowseLevel = {
parentId: rootId,
title: "Library",
items: null,
error: "",
selectedIndex: 0,
scrollRow: 0,
};
this.levels = [root];
this.loadLevel(ctx, root);
ctx.actions.requestRender();
})
.catch((error) => {
if (this.removed) return;
this.phase = "failed";
this.connectError = error instanceof Error ? error.message : String(error);
ctx.actions.requestRender();
});
}
private loadLevel(ctx: LayerContext, level: BrowseLevel): void {
mediaBrowserBridge
.browse(level.parentId)
.then((items) => {
if (this.removed) return;
level.items = items;
ctx.actions.requestRender();
})
.catch((error) => {
if (this.removed) return;
level.error = error instanceof Error ? error.message : String(error);
ctx.actions.requestRender();
});
}
}
function truncateRight(font: BdfFont, text: string, maxWidth: number): string {
if (font.measureText(text) <= maxWidth) return text;
let out = text;
while (out.length > 1 && font.measureText(`${out}...`) > maxWidth) {
out = out.slice(0, -1);
}
return `${out}...`;
}
function truncateLeft(font: BdfFont, text: string, maxWidth: number): string {
if (font.measureText(text) <= maxWidth) return text;
let out = text;
while (out.length > 1 && font.measureText(`...${out}`) > maxWidth) {
out = out.slice(1);
}
return `...${out}`;
}
-404
View File
@@ -1,404 +0,0 @@
import { BdfFont, getDefaultLargeFont, getDefaultSmallFont } from "../../graphics/bdffont";
import { GrayImage, imageFromAsciiArt } from "../../graphics/image";
import { DashboardInputEvent, Layer, LayerContext } from "../layers";
import { nightscoutBridge, type NightscoutState } from "../../native/nightscout-bridge";
import {
isNightscoutSettingsConfigured,
nightscoutApiTokenSetting,
nightscoutSiteUrlSetting,
textSettingMenuItem,
} from "../dashboard-settings";
import { formatAgeShortFromTimestamp, formatTimestamp } from "~/util/date-util";
import { MenuLayer } from "../menu";
import { openSettingsSubMenu } from "../dashboard/settings-panel";
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK } from "../gestures";
const nightscoutLargeFont = getDefaultLargeFont();
const NIGHTSCOUT_STALE_MS = 15 * 60 * 1000;
const NIGHTSCOUT_GRAPH_WINDOW_MS = 2 * 60 * 60 * 1000;
const NIGHTSCOUT_GRAPH_TIME_QUANTUM_MS = 60 * 1000;
function drawDirectionIndicator(
image: GrayImage,
font: BdfFont,
x: number,
y: number,
direction: string,
shade: number,
): void {
const label = directionGlyphLabel(font, direction);
if (label) {
image.drawText(font, x, y, label, shade);
return;
}
const art = directionAsciiArt(direction);
if (art) {
image.bitBlt(imageFromAsciiArt(art, shade), x, y + 1);
return;
}
if (direction) {
image.drawText(font, x, y, truncateLine(direction, 10), shade);
}
}
function directionGlyphLabel(font: BdfFont, direction: string): string {
switch (direction) {
case "DoubleUp":
return font.hasGlyph("↑".codePointAt(0)!) ? "↑↑" : "";
case "SingleUp":
return font.hasGlyph("↑".codePointAt(0)!) ? "↑" : "";
case "FortyFiveUp":
return font.hasGlyph("↗".codePointAt(0)!) ? "↗" : "";
case "Flat":
return font.hasGlyph("→".codePointAt(0)!) ? "→" : "";
case "FortyFiveDown":
return font.hasGlyph("↘".codePointAt(0)!) ? "↘" : "";
case "SingleDown":
return font.hasGlyph("↓".codePointAt(0)!) ? "↓" : "";
case "DoubleDown":
return font.hasGlyph("↓".codePointAt(0)!) ? "↓↓" : "";
default:
return "";
}
}
function directionAsciiArt(direction: string): readonly string[] | undefined {
switch (direction) {
case "FortyFiveUp":
return [" ##", " ###", " # ##", "# ##", " ##"];
case "FortyFiveDown":
return [" ##", "# ##", " # ##", " ###", " ##"];
default:
return undefined;
}
}
function truncateLine(text: string, maxChars: number): string {
if (text.length <= maxChars) return text;
return `${text.slice(0, Math.max(0, maxChars - 3))}...`;
}
function formatDelta(delta: number | null): string {
if (delta === null) return "--";
return `${delta >= 0 ? "+" : ""}${Math.round(delta)}`;
}
function formatWholeNumber(value: number): string {
return `${Math.round(value)}`;
}
function formatBolusLabel(value: number): string {
return Number.isInteger(value) ? `${value}` : value.toFixed(1);
}
function drawNightscoutGraph(
image: GrayImage,
bounds: { x: number; y: number; width: number; height: number },
nightscout: NightscoutState,
nowMs: number,
font: BdfFont,
): void {
if (bounds.width <= 2 || bounds.height <= 2) {
return;
}
const graphNowMs = minuteBucketTimestampMs(nowMs);
const windowStartMs = graphNowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
const visibleHistory = nightscout.history.filter((point) => {
const pointTimestampMs = minuteBucketTimestampMs(point.timestampMs);
return pointTimestampMs >= windowStartMs && pointTimestampMs <= graphNowMs;
});
if (visibleHistory.length === 0) {
return;
}
const values = visibleHistory.map((point) => point.sgv);
const min = Math.min(...values, 60);
const max = Math.max(...values, 200);
const range = Math.max(20, max - min);
const paddedMin = min - range * 0.1;
const paddedMax = max + range * 0.1;
image.drawRect(bounds.x, bounds.y, bounds.width, bounds.height, 56);
drawNightscoutBasalOverlay(image, bounds, nightscout.basal, graphNowMs);
drawNightscoutReferenceLine(image, bounds, paddedMin, paddedMax, 60, 40);
drawNightscoutReferenceLine(image, bounds, paddedMin, paddedMax, 100, 40);
drawNightscoutReferenceLine(image, bounds, paddedMin, paddedMax, 180, 40);
const plotted = visibleHistory.map((point) => ({
point,
x: timeToGraphX(bounds, windowStartMs, point.timestampMs),
y:
bounds.y +
bounds.height -
1 -
Math.round(((point.sgv - paddedMin) / Math.max(1, paddedMax - paddedMin)) * Math.max(1, bounds.height - 1)),
}));
for (let i = 0; i < plotted.length; i++) {
const current = plotted[i]!;
const previous = i > 0 ? plotted[i - 1]! : null;
const next = i + 1 < plotted.length ? plotted[i + 1]! : null;
const connectedToPrevious =
previous !== null && current.point.timestampMs - previous.point.timestampMs <= NIGHTSCOUT_STALE_MS;
const connectedToNext =
next !== null && next.point.timestampMs - current.point.timestampMs <= NIGHTSCOUT_STALE_MS;
if (connectedToPrevious && previous) {
image.drawLine(previous.x, previous.y, current.x, current.y, 220);
}
if (!connectedToPrevious && !connectedToNext) {
image.fillRect(current.x - 1, current.y - 1, 2, 2, 220);
}
}
drawNightscoutCarbMarkers(image, bounds, font, nightscout.carbs, graphNowMs);
drawNightscoutBolusMarkers(image, bounds, font, nightscout.boluses, graphNowMs);
}
function drawNightscoutBasalOverlay(
image: GrayImage,
bounds: { x: number; y: number; width: number; height: number },
basalEvents: NightscoutState["basal"],
nowMs: number,
): void {
const graphNowMs = minuteBucketTimestampMs(nowMs);
const windowStartMs = graphNowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
const visibleEvents = basalEvents.filter(
(event) =>
minuteBucketTimestampMs(event.timestampMs + event.durationMinutes * 60_000) >= windowStartMs &&
minuteBucketTimestampMs(event.timestampMs) <= graphNowMs,
);
if (visibleEvents.length === 0) {
return;
}
const maxRate = Math.max(...visibleEvents.map((event) => event.rate), 0);
if (maxRate <= 0) {
return;
}
const overlayHeight = Math.max(8, Math.min(18, Math.floor(bounds.height * 0.22)));
const bottomY = bounds.y + bounds.height - 2;
for (const event of visibleEvents) {
const startMs = Math.max(windowStartMs, minuteBucketTimestampMs(event.timestampMs));
const endMs = Math.min(graphNowMs, minuteBucketTimestampMs(event.timestampMs + event.durationMinutes * 60_000));
if (endMs <= startMs) {
continue;
}
const leftX = timeToGraphX(bounds, windowStartMs, startMs);
const rightX = timeToGraphX(bounds, windowStartMs, endMs);
const height = Math.max(1, Math.round((event.rate / maxRate) * overlayHeight));
image.fillRect(leftX, bottomY - height + 1, Math.max(1, rightX - leftX + 1), height, 15);
}
}
function drawNightscoutCarbMarkers(
image: GrayImage,
bounds: { x: number; y: number; width: number; height: number },
font: BdfFont,
carbEvents: NightscoutState["carbs"],
nowMs: number,
): void {
const graphNowMs = minuteBucketTimestampMs(nowMs);
const windowStartMs = graphNowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
const baselineY = bounds.y + bounds.height - 2;
for (const event of carbEvents) {
const eventTimestampMs = minuteBucketTimestampMs(event.timestampMs);
if (eventTimestampMs < windowStartMs || eventTimestampMs > graphNowMs) {
continue;
}
const x = timeToGraphX(bounds, windowStartMs, eventTimestampMs);
image.drawLine(x, baselineY, x, baselineY - 6, 150);
drawTextCentered(image, font, x, Math.max(bounds.y + 2, baselineY - 18), `${Math.round(event.carbs)}`, 150, bounds);
}
}
function drawNightscoutBolusMarkers(
image: GrayImage,
bounds: { x: number; y: number; width: number; height: number },
font: BdfFont,
bolusEvents: NightscoutState["boluses"],
nowMs: number,
): void {
const graphNowMs = minuteBucketTimestampMs(nowMs);
const windowStartMs = graphNowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
const topY = bounds.y + 1;
for (const event of bolusEvents) {
const eventTimestampMs = minuteBucketTimestampMs(event.timestampMs);
if (eventTimestampMs < windowStartMs || eventTimestampMs > graphNowMs) {
continue;
}
const x = timeToGraphX(bounds, windowStartMs, eventTimestampMs);
image.drawLine(x, topY, x, topY + 6, 144);
if (event.insulin >= 1) {
drawTextCentered(
image,
font,
x,
Math.min(bounds.y + bounds.height - font.lineHeight - 1, topY + 8),
formatBolusLabel(event.insulin),
144,
bounds,
);
}
}
}
function drawTextCentered(
image: GrayImage,
font: BdfFont,
centerX: number,
y: number,
text: string,
shade: number,
bounds: { x: number; y: number; width: number; height: number },
): void {
const textWidth = font.measureText(text);
const x = Math.max(bounds.x + 1, Math.min(bounds.x + bounds.width - textWidth - 1, centerX - Math.round(textWidth / 2)));
image.drawText(font, x, y, text, shade);
}
function timeToGraphX(
bounds: { x: number; y: number; width: number; height: number },
windowStartMs: number,
timestampMs: number,
): number {
const graphTimestampMs = minuteBucketTimestampMs(timestampMs);
return (
bounds.x +
Math.round(
((graphTimestampMs - windowStartMs) / Math.max(1, NIGHTSCOUT_GRAPH_WINDOW_MS)) * Math.max(1, bounds.width - 1),
)
);
}
function minuteBucketTimestampMs(timestampMs: number): number {
return Math.floor(timestampMs / NIGHTSCOUT_GRAPH_TIME_QUANTUM_MS) * NIGHTSCOUT_GRAPH_TIME_QUANTUM_MS;
}
function drawNightscoutReferenceLine(
image: GrayImage,
bounds: { x: number; y: number; width: number; height: number },
minValue: number,
maxValue: number,
value: number,
shade: number,
): void {
const y =
bounds.y +
bounds.height -
1 -
Math.round(((value - minValue) / Math.max(1, maxValue - minValue)) * Math.max(1, bounds.height - 1));
image.drawLine(bounds.x + 1, y, bounds.x + bounds.width - 2, y, shade);
}
export class NightscoutLayer implements Layer {
paint(ctx: LayerContext): GrayImage {
const font = getDefaultSmallFont();
// Sized to the hosting stack (the Nightscout app viewport).
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
const nightscout = nightscoutBridge.snapshot();
const nowMs = Date.now();
const footerY = height - 26;
image.drawText(font, 22, 16, "Nightscout", 220);
if (!isNightscoutSettingsConfigured() || nightscout.configurationMissing) {
image.drawText(font, 22, 44, "Nightscout needs configuration.", 180);
image.drawText(font, 22, 62, `Set the site URL and API token in ${GESTURE_CLICK} menu > Settings.`, 140);
image.drawText(font, 22, footerY, `${GESTURE_CLICK} menu ${GESTURE_DOUBLE_CLICK} back`, 110);
return image;
}
if (!nightscout.available || !nightscout.latest) {
image.drawText(font, 22, 44, "No Nightscout data available.", 180);
image.drawText(font, 22, 58, truncateLine(nightscout.status, 60), 140);
image.drawText(font, 22, footerY, `${GESTURE_CLICK} menu ${GESTURE_DOUBLE_CLICK} back`, 110);
return image;
}
const latest = nightscout.latest;
const glucoseText = `${latest.sgv}`;
const glucoseX = 22;
const glucoseWidth = nightscoutLargeFont.measureText(glucoseText);
image.drawText(nightscoutLargeFont, glucoseX, 28, glucoseText, 230);
if (isNightscoutPointStale(latest, nowMs)) {
drawNightscoutValueStrikeThrough(image, glucoseX, 40, glucoseWidth);
}
image.drawText(font, glucoseX + glucoseWidth + 8, 36, nightscout.units, 140);
const trendText = `Delta ${formatDelta(nightscout.delta)} Trend `;
image.drawText(font, 22, 62, trendText, 180);
drawDirectionIndicator(image, font, 22 + font.measureText(trendText), 62, nightscout.direction, 180);
image.drawText(
font,
22,
78,
`IOB ${nightscout.iob === null ? "--" : nightscout.iob.toFixed(2)} COB ${nightscout.cob === null ? "--" : formatWholeNumber(nightscout.cob)} Updated ${formatTimestamp(latest.timestampMs)}`,
160,
);
image.drawText(
font,
22,
94,
`CAGE ${formatAgeShortFromTimestamp(nightscout.cageTimestampMs, nowMs)} Loop ${nightscout.openapsStatusShort}`,
160,
);
image.drawText(font, 22, 110, `Pump ${truncateLine(nightscout.pumpStatus || "--", 56)}`, 150);
const graphHeight = Math.max(40, height - 128 - 48);
drawNightscoutGraph(image, { x: 22, y: 128, width: width - 44, height: graphHeight }, nightscout, nowMs, font);
image.drawText(font, 22, height - 42, "2-hour glucose history with basal / carbs / boluses", 130);
image.drawText(font, 22, footerY, `${GESTURE_CLICK} menu ${GESTURE_DOUBLE_CLICK} back`, 110);
return image;
}
async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> {
switch (event.type) {
case "click":
ctx.stack.push(createNightscoutMenu());
return;
case "double-click":
ctx.stack.pop();
return;
default:
return;
}
}
}
/** The app menu (opened with a click); MenuLayer self-closes on double-click. */
function createNightscoutMenu(): MenuLayer {
return new MenuLayer(
"Nightscout",
[
{
label: "Refresh",
onSelect: async (ctx) => {
ctx.stack.pop();
await nightscoutBridge.refreshNow();
},
},
{
label: "Settings",
onSelect: (ctx) => {
// Pop the menu first so closing the settings modal lands back on
// the glucose view, not this menu.
ctx.stack.pop();
openSettingsSubMenu(ctx, "Nightscout settings", [
textSettingMenuItem(nightscoutSiteUrlSetting),
textSettingMenuItem(nightscoutApiTokenSetting),
]);
},
},
],
{ x: 8, y: 8, width: 200, minHeight: 0 },
);
}
function isNightscoutPointStale(point: NightscoutState["latest"], nowMs: number): boolean {
return point !== null && nowMs - point.timestampMs > NIGHTSCOUT_STALE_MS;
}
function drawNightscoutValueStrikeThrough(image: GrayImage, x: number, y: number, width: number): void {
image.drawLine(x, y, x + width, y, 180);
}
-73
View File
@@ -1,73 +0,0 @@
import { getDefaultSmallFont } from "../../graphics/bdffont";
import { GrayImage } from "../../graphics/image";
import { Layer, type DashboardInputEvent, type LayerContext } from "../layers";
const COLOR_VALUE_COUNT = 256;
const COLOR_VALUE_STEP = 1;
const GRID_COLUMNS = 16;
const CELL_HEIGHT = 30;
const LABEL_Y_OFFSET = 0;
const SWATCH_Y_OFFSET = 12;
const SWATCH_WIDTH = 24;
const SWATCH_HEIGHT = 16;
export class ScreenTestLayer implements Layer {
paint(ctx: LayerContext): GrayImage {
// Sized to the hosting stack (the Debug tests app viewport).
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
const font = getDefaultSmallFont();
const cellWidth = Math.floor(width / GRID_COLUMNS);
const gridX = Math.floor((width - cellWidth * GRID_COLUMNS) / 2);
for (let value = 0; value < COLOR_VALUE_COUNT; value += COLOR_VALUE_STEP) {
const slot = value / COLOR_VALUE_STEP;
const col = slot % GRID_COLUMNS;
const row = Math.floor(slot / GRID_COLUMNS);
const cellX = gridX + col * cellWidth;
const cellY = row * CELL_HEIGHT;
const label = String(value);
const labelX = cellX + Math.max(0, Math.floor((cellWidth - font.measureText(label)) / 2));
const swatchX = cellX + Math.floor((cellWidth - SWATCH_WIDTH) / 2);
image.drawText(font, labelX, cellY + LABEL_Y_OFFSET, label, 185);
fillSwatch(image, swatchX, cellY + SWATCH_Y_OFFSET, SWATCH_WIDTH, SWATCH_HEIGHT, value);
}
return image;
}
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
if (event.type === "double-click") {
ctx.stack.pop();
}
}
}
function fillSwatch(image: GrayImage, x: number, y: number, width: number, height: number, value: number): void {
// Values will ultimately be rounded up to the nearest multiple of 16 (since they're transmitted as 4-bit)
// grayscale). So, for intermediate values, dither.
if (value % 16 !== 0) {
const baseValue = value & 0xf0;
const fillFraction = value & 0x0f;
for (let i = 0; i < height; i++) {
for (let j = 0; j < width; j++) {
const ditheredValue = ditherPattern(j, i, fillFraction)
image.setPixel(x + j, y + i, ditheredValue ? baseValue + 16 : baseValue);
}
}
} else {
image.fillRect(x, y, width, height, value);
}
}
function ditherPattern(x: number, y: number, fillFraction: number): number {
const pattern = [
[0, 8, 2, 10],
[12, 4, 14, 6],
[3, 11, 1, 9],
[15, 7, 13, 5],
];
const patternValue = pattern[y % 4][x % 4];
return (fillFraction > patternValue) ? 1 : 0;
}
-81
View File
@@ -1,81 +0,0 @@
import type { Terminal as XtermTerminal } from "@xterm/headless";
// xterm-headless expects a few browser globals (navigator for platform
// sniffing, window for timer/scheduling lookups) that the NativeScript
// runtime doesn't define. Provide minimal stand-ins before the library is
// evaluated (hence require, not a hoisted import).
const runtimeGlobal = globalThis as any;
if (typeof runtimeGlobal.navigator === "undefined") {
runtimeGlobal.navigator = {
userAgent: "NativeScript",
platform: "Android",
language: "en",
languages: ["en"],
};
}
if (typeof runtimeGlobal.window === "undefined") {
runtimeGlobal.window = runtimeGlobal;
}
if (typeof runtimeGlobal.self === "undefined") {
runtimeGlobal.self = runtimeGlobal;
}
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { Terminal } = require("@xterm/headless") as typeof import("@xterm/headless");
/**
* Headless terminal emulator for g2mirror streams: feed it the raw
* VT100/xterm bytes from snapshot/output messages and read back the visible
* text grid. Formatting (color/bold/inverse) is deliberately dropped for
* now — we only mirror the text.
*/
export class TerminalEmulator {
private readonly term: XtermTerminal;
constructor(
readonly cols: number,
readonly rows: number,
) {
this.term = new Terminal({
cols,
rows,
// Retain witnessed lines that scroll off the top; the archive covers
// everything before this. Matches the wrapper's default history cap.
scrollback: 10000,
allowProposedApi: true,
});
}
/**
* Apply terminal bytes. onProcessed fires once the emulator has actually
* parsed them (xterm buffers writes internally), so schedule repaints there.
*/
write(data: Uint8Array, onProcessed: () => void): void {
this.term.write(data, onProcessed);
}
/** Full reset; snapshots are defined as repainting from a cleared screen. */
reset(): void {
this.term.reset();
}
/** Total lines held (witnessed scrollback + the live screen). */
bufferLength(): number {
return this.term.buffer.active.length;
}
/** Text of buffer line `index` (0 = oldest retained), trailing space trimmed. */
lineAt(index: number): string {
const line = this.term.buffer.active.getLine(index);
return line ? line.translateToString(true) : "";
}
/** Cursor row as an absolute buffer index (baseY + cursorY). */
cursorRow(): number {
const buffer = this.term.buffer.active;
return buffer.baseY + buffer.cursorY;
}
cursorCol(): number {
return this.term.buffer.active.cursorX;
}
}
-96
View File
@@ -1,96 +0,0 @@
import { wrapText, truncateText } from "../../graphics/textwrap";
import { getDefaultSmallFont, type BdfFont } from "../../graphics/bdffont";
import { GrayImage } from "../../graphics/image";
import { Layer, type DashboardInputEvent, type LayerContext } from "../layers";
const MARGIN_X = 18;
const TITLE_Y = 16;
const BODY_X = 18;
const BODY_Y = 44;
const LINE_STEP = 14;
const FOOTER_MARGIN = 36;
/**
* Paged text viewer for a document. Sized to its hosting stack (a Files
* document window, or pushed over the file browser for view-in-place).
*/
export class TextViewerLayer implements Layer {
private lines: string[] | null = null;
private wrappedForWidth = 0;
private firstLine = 0;
private bodyLineCount = 14;
constructor(
private readonly documentText: string,
private readonly title = "Text",
) {}
paint(ctx: LayerContext): GrayImage {
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
const footerY = height - FOOTER_MARGIN;
this.bodyLineCount = Math.max(1, Math.floor((footerY - BODY_Y) / LINE_STEP));
image.drawText(font, MARGIN_X + 4, TITLE_Y, truncateText(font, this.title, width - 2 * MARGIN_X - 8), 220);
const lines = this.getLines(font, width);
const visibleLines = lines.slice(this.firstLine, this.firstLine + this.bodyLineCount);
for (let index = 0; index < visibleLines.length; index++) {
image.drawText(font, BODY_X, BODY_Y + index * LINE_STEP, visibleLines[index]!, 230);
}
const currentPage = Math.floor(this.firstLine / this.pageStep()) + 1;
image.drawText(font, BODY_X, footerY, `Page ${currentPage}/${this.totalPageCount(lines.length)}`, 110);
return image;
}
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
switch (event.type) {
case "scroll-down":
this.scrollBy(this.pageStep());
return;
case "scroll-up":
this.scrollBy(-this.pageStep());
return;
case "double-click":
ctx.stack.pop();
return;
default:
return;
}
}
private pageStep(): number {
return Math.max(1, this.bodyLineCount - 1);
}
private scrollBy(delta: number): void {
const lines = this.lines ?? [];
if (lines.length <= this.bodyLineCount) {
this.firstLine = 0;
return;
}
const maxFirstLine = Math.max(0, lines.length - 1);
this.firstLine = Math.max(0, Math.min(maxFirstLine, this.firstLine + delta));
}
private getLines(font: BdfFont, width: number): string[] {
if (this.lines === null || this.wrappedForWidth !== width) {
const normalized = this.documentText.replace(/\t/g, " ").replace(/\r/g, "");
this.lines = wrapText(font, normalized, width - BODY_X - 12, {
preserveLeadingWhitespace: true,
breakLongWords: true,
});
this.wrappedForWidth = width;
}
return this.lines;
}
private totalPageCount(lineCount: number): number {
if (lineCount <= this.bodyLineCount) {
return 1;
}
return Math.ceil((lineCount - this.bodyLineCount) / this.pageStep()) + 1;
}
}
-132
View File
@@ -1,132 +0,0 @@
import { GrayImage } from "../../graphics/image";
import { getDefaultSmallFont, type BdfFont } from "../../graphics/bdffont";
import { writeTextToDownloads } from "../../native/file-access";
import { voiceControlBridge, type VoiceTranscriptEvent } from "../../native/voice-control";
import { Layer, type DashboardInputEvent, type LayerContext } from "../layers";
/**
* Live transcription view. Continuous mic capture is owned by the app wrapper
* (createTranscribeAppWindow); this layer accumulates the transcript, shows
* it, and saves it to Downloads on click.
*/
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK } from "../gestures";
export class TranscribeLayer implements Layer {
private status = "Listening...";
// Finalized utterances, plus the live (replace-semantics) partial appended
// when painting.
private finalizedText = "";
private liveText = "";
private saveNotice = "";
private unsubscribeTranscript: (() => void) | null = null;
private unsubscribeStatus: (() => void) | null = null;
start(requestRender: () => void): void {
this.unsubscribeTranscript = voiceControlBridge.onTranscript((event) => {
this.onTranscript(event);
requestRender();
});
this.unsubscribeStatus = voiceControlBridge.onStatus((state) => {
this.status = state.status;
requestRender();
});
}
paint(ctx: LayerContext): GrayImage {
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
const text = this.displayText() || "Listening...";
const wrapped = wrapTranscribeText(font, text, width - 64);
image.drawText(font, 24, 20, "Transcribe", 200);
image.drawText(font, 24, 40, this.saveNotice || this.status, 110);
const bodyTop = 62;
const footerY = height - 18;
const bodyLines = Math.max(1, Math.floor((footerY - bodyTop) / 16));
const firstLine = Math.max(0, wrapped.length - bodyLines);
for (let index = firstLine; index < wrapped.length; index++) {
const y = bodyTop + (index - firstLine) * 16;
image.drawText(font, 32, y, wrapped[index]!, 230);
}
image.drawText(font, 24, footerY, `${GESTURE_CLICK} save ${GESTURE_DOUBLE_CLICK} back`, 110);
return image;
}
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
if (event.type === "click") {
this.saveTranscript();
ctx.actions.requestRender();
return;
}
if (event.type === "double-click") {
ctx.stack.pop();
}
}
onRemoved(): void {
this.unsubscribeTranscript?.();
this.unsubscribeTranscript = null;
this.unsubscribeStatus?.();
this.unsubscribeStatus = null;
}
private saveTranscript(): void {
const text = this.displayText().trim();
if (!text) {
this.saveNotice = "Nothing to save yet.";
return;
}
const filename = `transcript-${transcriptTimestamp()}.txt`;
const path = writeTextToDownloads(filename, `${text}\n`);
this.saveNotice = path ? `Saved ${filename}` : "Save failed (check file access).";
}
private displayText(): string {
if (!this.finalizedText) return this.liveText;
if (!this.liveText) return this.finalizedText;
return `${this.finalizedText} ${this.liveText}`;
}
private onTranscript(event: VoiceTranscriptEvent): void {
if (event.isFinal) {
const finalText = event.text.trim() || this.liveText.trim();
if (finalText) {
this.finalizedText = this.finalizedText ? `${this.finalizedText} ${finalText}` : finalText;
}
this.liveText = "";
} else {
// Replace semantics: the live partial is the whole current best transcript.
this.liveText = event.text.trim();
}
}
}
function transcriptTimestamp(): string {
const now = new Date();
const pad = (value: number) => String(value).padStart(2, "0");
return (
`${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}` +
`-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`
);
}
function wrapTranscribeText(font: BdfFont, text: string, maxWidth: number): string[] {
const words = text.split(/\s+/).filter(Boolean);
const lines: string[] = [];
let line = "";
for (const word of words) {
const candidate = line ? `${line} ${word}` : word;
if (line && font.measureText(candidate) > maxWidth) {
lines.push(line);
line = word;
} else {
line = candidate;
}
}
if (line) {
lines.push(line);
}
return lines.length ? lines : [""];
}
-191
View File
@@ -1,191 +0,0 @@
import { getDefaultLargeFont, getDefaultMediumFont, getDefaultSmallFont, type BdfFont } from "../../graphics/bdffont";
import { GrayImage } from "../../graphics/image";
import { wrapText, truncateText } from "../../graphics/textwrap";
import { clamp } from "../../util/numeric-util";
import { type ForecastPeriod, type WeatherState } from "../../native/weather";
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_SCROLL } from "../gestures";
import { type DashboardInputEvent, type Layer, type LayerContext } from "../layers";
import { drawSelectionHighlight, scrollToKeepSelectionVisible } from "../menu";
const PAGE_X = 18;
const HEADER_Y = 8;
const CURRENT_TOP = 34;
const CURRENT_TEXT_X = 112;
const FORECAST_HEADER_Y = 105;
const FORECAST_TOP = 124;
const FORECAST_ROW_HEIGHT = 23;
const FOOTER_HEIGHT = 18;
const FORECAST_NAME_WIDTH = 92;
const FORECAST_TEMP_X = 126;
const FORECAST_PRECIP_X = 184;
const FORECAST_SUMMARY_X = 244;
/** Weather's current-conditions summary and scrollable 12-hour forecast. */
export class WeatherLayer implements Layer {
private selectedIndex = 0;
private scrollRow = 0;
constructor(
private readonly state: () => WeatherState,
private readonly requestUpdate: () => void,
) {}
paint(ctx: LayerContext): GrayImage {
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
const weather = this.state();
image.drawText(font, PAGE_X, HEADER_Y, "Weather", 225);
if (weather.locationName) {
image.drawText(
font,
width - PAGE_X - font.measureText(truncateText(font, weather.locationName, 220)),
HEADER_Y,
truncateText(font, weather.locationName, 220),
150,
);
}
if (weather.phase === "permission-required") {
this.drawMessage(
image,
font,
width,
height,
"Allow approximate location on your phone to get local weather.",
`${GESTURE_CLICK} request ${GESTURE_DOUBLE_CLICK} back`,
);
return image;
}
if (weather.phase === "locating" || weather.phase === "loading") {
this.drawMessage(image, font, width, height, weather.status, `${GESTURE_DOUBLE_CLICK} back`);
return image;
}
if (weather.phase === "error") {
this.drawMessage(
image,
font,
width,
height,
weather.status,
`${GESTURE_CLICK} retry ${GESTURE_DOUBLE_CLICK} back`,
);
return image;
}
this.drawCurrent(image, weather, width);
this.drawForecast(image, weather.forecast, ctx, width, height);
return image;
}
handleInput(event: DashboardInputEvent): void {
const weather = this.state();
if (event.type === "click") {
this.requestUpdate();
return;
}
if (!weather.forecast.length || weather.phase !== "ready") return;
if (event.type === "scroll-up") {
this.selectedIndex = Math.max(0, this.selectedIndex - 1);
} else if (event.type === "scroll-down") {
this.selectedIndex = Math.min(weather.forecast.length - 1, this.selectedIndex + 1);
}
}
private drawCurrent(image: GrayImage, weather: WeatherState, width: number): void {
const current = weather.current;
if (!current) return;
const large = getDefaultLargeFont();
const medium = getDefaultMediumFont();
const small = getDefaultSmallFont();
const temperature = current.temperatureF === null ? "--°" : `${Math.round(current.temperatureF)}°F`;
image.drawText(large, PAGE_X, CURRENT_TOP + 8, temperature, 245);
image.drawText(
medium,
CURRENT_TEXT_X,
CURRENT_TOP + 5,
truncateText(medium, current.description || "Current conditions", width - CURRENT_TEXT_X - PAGE_X),
220,
);
const details: string[] = [];
if (current.humidityPercent !== null) details.push(`Humidity ${Math.round(current.humidityPercent)}%`);
if (current.windSpeedMph !== null) {
details.push(`Wind ${current.windDirection ? `${current.windDirection} ` : ""}${Math.round(current.windSpeedMph)} mph`);
}
image.drawText(small, CURRENT_TEXT_X, CURRENT_TOP + 35, details.join(" ") || "Current forecast", 170);
const source = current.observed ? "Observed" : "Forecast";
const age = current.timestampMs ? formatAge(Date.now() - current.timestampMs) : "";
image.drawText(small, CURRENT_TEXT_X, CURRENT_TOP + 54, `${source}${age ? ` ${age}` : ""}`, 105);
image.drawLine(PAGE_X, FORECAST_HEADER_Y - 7, width - PAGE_X, FORECAST_HEADER_Y - 7, 40);
}
private drawForecast(
image: GrayImage,
forecast: ForecastPeriod[],
ctx: LayerContext,
width: number,
height: number,
): void {
const font = getDefaultSmallFont();
if (!forecast.length) {
image.drawText(font, PAGE_X, FORECAST_TOP, "No upcoming forecast periods.", 160);
return;
}
this.selectedIndex = clamp(this.selectedIndex, 0, forecast.length - 1);
const visibleRows = Math.max(1, Math.floor((height - FOOTER_HEIGHT - FORECAST_TOP) / FORECAST_ROW_HEIGHT));
this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, this.selectedIndex, visibleRows, forecast.length);
image.drawText(font, PAGE_X, FORECAST_HEADER_Y, "Upcoming", 150);
image.drawText(font, FORECAST_TEMP_X, FORECAST_HEADER_Y, "Temp", 105);
image.drawText(font, FORECAST_PRECIP_X, FORECAST_HEADER_Y, "Rain", 105);
image.drawText(font, width - PAGE_X - font.measureText(`${this.selectedIndex + 1}/${forecast.length}`), FORECAST_HEADER_Y, `${this.selectedIndex + 1}/${forecast.length}`, 105);
const last = Math.min(forecast.length, this.scrollRow + visibleRows);
for (let index = this.scrollRow; index < last; index++) {
const period = forecast[index]!;
const y = FORECAST_TOP + (index - this.scrollRow) * FORECAST_ROW_HEIGHT;
const selected = index === this.selectedIndex;
if (selected) {
drawSelectionHighlight(image, PAGE_X - 7, y - 2, width - 2 * (PAGE_X - 7), FORECAST_ROW_HEIGHT - 2, ctx.stack.isFocused(), 5);
}
const shade = selected ? 245 : 190;
image.drawText(font, PAGE_X, y + 2, truncateText(font, period.name, FORECAST_NAME_WIDTH), shade);
image.drawText(font, FORECAST_TEMP_X, y + 2, period.temperatureF === null ? "--" : `${Math.round(period.temperatureF)}°F`, shade);
image.drawText(font, FORECAST_PRECIP_X, y + 2, period.precipitationPercent === null ? "--" : `${Math.round(period.precipitationPercent)}%`, selected ? 220 : 155);
image.drawText(font, FORECAST_SUMMARY_X, y + 2, truncateText(font, period.shortForecast, width - FORECAST_SUMMARY_X - PAGE_X), selected ? 220 : 165);
}
image.drawText(
font,
PAGE_X,
height - 15,
`${GESTURE_SCROLL} forecast ${GESTURE_CLICK} refresh ${GESTURE_DOUBLE_CLICK} back`,
105,
);
}
private drawMessage(
image: GrayImage,
font: BdfFont,
width: number,
height: number,
message: string,
footer: string,
): void {
const lines = wrapText(font, message, width - 2 * (PAGE_X + 6));
const top = Math.max(52, Math.round((height - lines.length * 15) / 2) - 8);
for (let index = 0; index < lines.length; index++) {
image.drawText(font, PAGE_X + 6, top + index * 15, lines[index]!, 185);
}
image.drawText(font, PAGE_X, height - 20, footer, 110);
}
}
function formatAge(ageMs: number): string {
const minutes = Math.max(0, Math.round(ageMs / 60_000));
if (minutes < 1) return "just now";
if (minutes < 60) return `${minutes}m ago`;
return `${Math.round(minutes / 60)}h ago`;
}
+1 -1
View File
@@ -3,7 +3,7 @@ import { getDefaultSmallFont } from "../../graphics/bdffont";
import type { GrayImage } from "../../graphics/image";
import { getDashboardLogo } from "../../graphics/logo";
import { wrapText } from "../../graphics/textwrap";
import { TextViewerLayer } from "../apps/text-viewer";
import { TextViewerLayer } from "../../apps/files/text-viewer";
import type { MenuItem } from "../menu";
import { shell } from "../shell/shell";
import {
@@ -4,7 +4,7 @@ import { GESTURE_DOUBLE_CLICK } from "../gestures";
import { drawSelectionHighlight } from "../menu";
import { Layer, type DashboardInputEvent, type LayerActions, type LayerContext } from "../layers";
import { wrapText, truncateText } from "../../graphics/textwrap";
import { MIN_WINDOW_HEIGHT, minWindowTop } from "../shell/geometry";
import { MIN_WINDOW_HEIGHT, minWindowTop } from "./geometry";
const DIALOG_X = 40;
const DIALOG_W = G2_LENS_WIDTH - 80;
-54
View File
@@ -1,54 +0,0 @@
import { ensureCalendarPermission, hasCalendarPermission } from "../../g2/android-permissions";
import { invalidateCalendarCache } from "../../native/calendar";
import { CalendarLayer } from "../apps/calendar";
import {
createInProcessWindow,
YieldAtRootLayer,
type InProcessAppOptions,
type InProcessWindow,
} from "./in-process-window";
export const CALENDAR_WINDOW_ID = "calendar";
export const CALENDAR_SURFACE_ID = "window:calendar";
/**
* The Calendar app: a single screen listing upcoming events from the Android
* Calendar provider. If calendar permission is missing it shows a prompt and
* fires the system permission dialog (on launch and on any tap); once granted
* it re-renders with the event list.
*/
export function createCalendarAppWindow(options: InProcessAppOptions): InProcessWindow {
let requesting = false;
let app: InProcessWindow;
const requestPermission = () => {
if (requesting || hasCalendarPermission()) return;
requesting = true;
void ensureCalendarPermission().then((granted) => {
requesting = false;
if (granted) {
invalidateCalendarCache();
app.requestRender();
}
});
};
app = createInProcessWindow({
appId: "calendar",
windowId: CALENDAR_WINDOW_ID,
title: "Calendar",
iconLetter: "Ca",
icon: "calendar",
closeable: true,
actions: options.actions,
baseLayer: new YieldAtRootLayer(new CalendarLayer(requestPermission)),
submitFrame: options.submitFrame,
setSurfaceVisible: options.setSurfaceVisible,
removeSurface: options.removeSurface,
onClosed: options.onClosed,
});
// Prompt immediately on launch so the user doesn't have to discover the tap.
requestPermission();
return app;
}
-62
View File
@@ -1,62 +0,0 @@
import { MenuLayer } from "../menu";
import { ScreenTestLayer } from "../apps/screen-test";
import { BuzzerDemoLayer } from "../apps/buzzer-demo";
import { AccelerometerDemoLayer } from "../apps/accelerometer-demo";
import { appViewportSize } from "./geometry";
import {
createInProcessWindow,
YieldAtRootLayer,
type InProcessAppOptions,
type InProcessWindow,
} from "./in-process-window";
export const DEBUG_TESTS_WINDOW_ID = "debug-tests";
export const DEBUG_TESTS_SURFACE_ID = "window:debug-tests";
/** Debug/diagnostic pages (screen test, buzzer demo) as an in-process app. */
export function createDebugTestsAppWindow(options: InProcessAppOptions): InProcessWindow {
const menu = new MenuLayer(
"Debug tests",
[
{
label: "Screen test",
onSelect: (ctx) => {
ctx.stack.push(new ScreenTestLayer());
},
},
{
label: "Buzzer demo",
onSelect: (ctx) => {
ctx.stack.push(new BuzzerDemoLayer());
},
},
{
label: "Accelerometer demo",
onSelect: (ctx) => {
ctx.stack.push(new AccelerometerDemoLayer(DEBUG_TESTS_WINDOW_ID, ctx.actions.requestRender));
},
},
],
{
x: 8,
y: 8,
width: 272,
minHeight: 0,
maxHeight: appViewportSize("min").height - 16,
},
);
return createInProcessWindow({
appId: "debug-tests",
windowId: DEBUG_TESTS_WINDOW_ID,
title: "Debug tests",
iconLetter: "Db",
icon: "flask-conical",
closeable: true,
actions: options.actions,
baseLayer: new YieldAtRootLayer(menu),
submitFrame: options.submitFrame,
setSurfaceVisible: options.setSurfaceVisible,
removeSurface: options.removeSurface,
onClosed: options.onClosed,
});
}
-153
View File
@@ -1,153 +0,0 @@
import { readTextFile, type DirectoryEntry } from "../../native/file-access";
import { isDecodableImageFile } from "../../native/image-files";
import { FileBrowserLayer } from "../apps/file-browser";
import { FileInfoDialogLayer, type FileInfoAction } from "../apps/file-info-dialog";
import { ImageViewerLayer } from "../apps/image-viewer";
import { TextViewerLayer } from "../apps/text-viewer";
import {
createInProcessWindow,
YieldAtRootLayer,
type InProcessAppOptions,
type InProcessWindow,
} from "./in-process-window";
import { shell } from "./shell";
export const FILES_WINDOW_ID = "files";
export const FILES_SURFACE_ID = "window:files";
const TEXT_FILE = /\.(txt|md|log)$/i;
export type FilesAppOptions = InProcessAppOptions & {
/** Open a text document as its own shell window (also used by the share intent). */
openDocumentWindow: (title: string, text: string) => void;
/** Open an image file as its own shell window. */
openImageWindow: (title: string, path: string) => void;
};
/**
* The Files app's launcher-opened window: a file browser over Places
* (bookmarks and storage roots). Picking any file opens an info dialog with
* metadata plus, for viewable types (text, images), the open actions.
*/
export function createFilesAppWindow(options: FilesAppOptions): InProcessWindow {
let created: InProcessWindow | null = null;
const browser = new FileBrowserLayer({
isSupportedFile: (name) => TEXT_FILE.test(name) || isDecodableImageFile(name),
// The browser handles double-click itself (up a level), so it is not
// wrapped in YieldAtRootLayer; it yields explicitly from the top level.
onLeave: () => shell.yieldFocusToSidebar(),
onFilePicked: (entry, ctx) => {
ctx.stack.push(new FileInfoDialogLayer(entry, fileOpenActions(entry, options)));
},
});
created = createInProcessWindow({
appId: "files",
windowId: FILES_WINDOW_ID,
title: "Files",
iconLetter: "F",
icon: "folder",
closeable: true,
// Browser actions (view switch, bookmarks) only apply while the browser
// itself is on top; a pushed viewer or dialog gets just the defaults.
menuItems: () => (created && !created.stack.isAtBase() ? [] : browser.buildMenuItems()),
actions: options.actions,
baseLayer: browser,
submitFrame: options.submitFrame,
setSurfaceVisible: options.setSurfaceVisible,
removeSurface: options.removeSurface,
onClosed: options.onClosed,
});
return created;
}
/** One opened text document as its own window (from the browser or a share intent). */
export function createTextDocumentWindow(
windowId: string,
title: string,
text: string,
options: InProcessAppOptions,
): InProcessWindow {
return createInProcessWindow({
appId: "files",
windowId,
title,
iconLetter: "F",
icon: "file-text",
closeable: true,
actions: options.actions,
baseLayer: new YieldAtRootLayer(new TextViewerLayer(text, title)),
submitFrame: options.submitFrame,
setSurfaceVisible: options.setSurfaceVisible,
removeSurface: options.removeSurface,
onClosed: options.onClosed,
});
}
/** One opened image file as its own window. */
export function createImageDocumentWindow(
windowId: string,
title: string,
path: string,
options: InProcessAppOptions,
): InProcessWindow {
return createInProcessWindow({
appId: "files",
windowId,
title,
iconLetter: "F",
icon: "image",
closeable: true,
actions: options.actions,
baseLayer: new YieldAtRootLayer(new ImageViewerLayer(path, title)),
submitFrame: options.submitFrame,
setSurfaceVisible: options.setSurfaceVisible,
removeSurface: options.removeSurface,
onClosed: options.onClosed,
});
}
/**
* The open actions for the picked-file dialog: View here / Open in new
* window for viewable types, empty for everything else (metadata only).
*/
function fileOpenActions(entry: DirectoryEntry, options: FilesAppOptions): FileInfoAction[] {
if (TEXT_FILE.test(entry.name)) {
return [
{
label: "View here",
onSelect: (ctx) => {
const text = readTextFile(entry.path);
ctx.stack.pop();
ctx.stack.push(new TextViewerLayer(text ?? "(could not read file)", entry.name));
},
},
{
label: "Open in new window",
onSelect: (ctx) => {
const text = readTextFile(entry.path);
ctx.stack.pop();
options.openDocumentWindow(entry.name, text ?? "(could not read file)");
},
},
];
}
if (isDecodableImageFile(entry.name)) {
return [
{
label: "View here",
onSelect: (ctx) => {
ctx.stack.pop();
ctx.stack.push(new ImageViewerLayer(entry.path, entry.name));
},
},
{
label: "Open in new window",
onSelect: (ctx) => {
ctx.stack.pop();
options.openImageWindow(entry.name, entry.path);
},
},
];
}
return [];
}
-300
View File
@@ -1,300 +0,0 @@
import { getDefaultSmallFont, type BdfFont } from "../../graphics/bdffont";
import { truncateText } from "../../graphics/textwrap";
import { GrayImage } from "../../graphics/image";
import { renderIcon, type IconName } from "../../graphics/icons";
import { clamp } from "../../util/numeric-util";
import {
GESTURE_CLICK,
GESTURE_DOUBLE_CLICK,
GESTURE_SCROLL,
} from "../gestures";
import { DashboardInputEvent, Layer, LayerActions, LayerContext } from "../layers";
import { drawSelectionHighlight, scrollToKeepSelectionVisible } from "../menu";
import { onAnySettingChanged } from "../dashboard-settings";
import { createInProcessWindow } from "./in-process-window";
import { getFolderAssignments, getFolders, getFolderStateFingerprint } from "./launcher-folders";
import { shell, type ShellWindow } from "./shell";
export type LauncherAppEntry = {
appId: string;
label: string;
icon: IconName;
};
export type LauncherOptions = {
actions: LayerActions;
apps: LauncherAppEntry[];
launchApp: (appId: string) => Promise<void> | void;
/** Submit a painted viewport-sized frame to this window's surface. */
submitFrame: (image: GrayImage, paintMs: number, frameId: number) => Promise<void>;
/** Flip the launcher's compositor surface visibility on foreground changes. */
setSurfaceVisible: (visible: boolean) => void;
};
export const LAUNCHER_WINDOW_ID = "launcher";
export const LAUNCHER_SURFACE_ID = "window:launcher";
const COLS = 5;
// Row height is sized so 3.5 rows fit the viewport: three full rows are
// always visible, and a fourth (half-clipped) row peeks in to signal that
// there are more apps to scroll to.
const VISIBLE_ROWS = 3.5;
const FULL_ROWS = Math.floor(VISIBLE_ROWS);
const GRID_TOP = 6;
const FOOTER_HEIGHT = 16;
const ICON_SIZE = 44;
const LABEL_GAP = 2;
/** Extra top inset for the folder-name header while inside a folder. */
const FOLDER_HEADER_HEIGHT = 16;
type LauncherMode = "row" | "item";
/** One cell of the grid: an app, or a folder holding some of the apps. */
type LauncherGridEntry =
| { kind: "app"; label: string; icon: IconName; appId: string }
| { kind: "folder"; label: string; name: string };
/**
* The launcher grid: app and folder icons with labels, arranged in a grid.
* Navigation has two levels so the max number of swipes to any app is halved:
* entering from the sidebar starts in "row" mode (scroll picks a row); a tap
* drops into "item" mode on that row, defaulting to the middle column (scroll
* picks the item); a tap launches an app or opens a folder (the same grid,
* restricted to that folder's apps). Double-click backs out one level (item →
* row, folder → top grid), and from the top level yields to the sidebar.
*
* The folder grouping lives in the settings store (see launcher-folders.ts)
* and is re-read every paint, so assistant folder tools take effect without
* the layer holding any copy of the state.
*/
class LauncherGridLayer implements Layer {
private mode: LauncherMode = "row";
private selectedRow = 0;
private selectedCol = 1;
private scrollRow = 0;
/** Folder whose contents the grid is showing, or null for the top grid. */
private currentFolder: string | null = null;
constructor(private readonly options: LauncherOptions) {}
/**
* The cells to show, computed fresh from the folder state. Self-heals
* currentFolder: if the open folder no longer exists (the assistant
* disbanded it), the view falls back to the top grid.
*/
private entries(): LauncherGridEntry[] {
const byAppId = new Map(this.options.apps.map((app) => [app.appId, app]));
if (this.currentFolder !== null) {
const members = (getFolders().get(this.currentFolder) ?? [])
.map((appId) => byAppId.get(appId))
.filter(Boolean) as LauncherAppEntry[];
if (members.length > 0) {
return members
.map((app): LauncherGridEntry => ({ kind: "app", label: app.label, icon: app.icon, appId: app.appId }))
.sort((a, b) => a.label.localeCompare(b.label));
}
this.currentFolder = null;
}
const assignments = getFolderAssignments();
const entries: LauncherGridEntry[] = [];
// A folder cell appears only when it holds at least one known app; stale
// assignments to removed apps are ignored.
for (const [name, members] of getFolders()) {
if (members.some((appId) => byAppId.has(appId))) {
entries.push({ kind: "folder", label: name, name });
}
}
for (const app of this.options.apps) {
if (!assignments[app.appId]) {
entries.push({ kind: "app", label: app.label, icon: app.icon, appId: app.appId });
}
}
return entries.sort((a, b) => a.label.localeCompare(b.label));
}
private rowCount(entryCount: number): number {
return Math.max(1, Math.ceil(entryCount / COLS));
}
private itemsInRow(entryCount: number, row: number): number {
return Math.max(0, Math.min(COLS, entryCount - row * COLS));
}
/** Leave the current folder, putting the selection back on its cell. */
private exitFolder(): void {
const folder = this.currentFolder;
this.currentFolder = null;
this.mode = "row";
const index = this.entries().findIndex((entry) => entry.kind === "folder" && entry.name === folder);
this.selectedRow = index >= 0 ? Math.floor(index / COLS) : 0;
}
paint(ctx: LayerContext): GrayImage {
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
const focused = ctx.stack.isFocused();
const entries = this.entries();
const rows = this.rowCount(entries.length);
this.selectedRow = clamp(this.selectedRow, 0, rows - 1);
this.selectedCol = clamp(
this.selectedCol,
0,
Math.max(0, this.itemsInRow(entries.length, this.selectedRow) - 1),
);
const gridTop = this.currentFolder !== null ? GRID_TOP + FOLDER_HEADER_HEIGHT : GRID_TOP;
if (this.currentFolder !== null) {
image.drawText(font, 8, GRID_TOP - 2, truncateText(font, this.currentFolder, width - 16), 160);
}
const gridBottom = height - FOOTER_HEIGHT;
const rowH = (gridBottom - gridTop) / VISIBLE_ROWS;
const colW = width / COLS;
// Scroll to keep the selected row among the fully-visible rows.
this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, this.selectedRow, FULL_ROWS, rows);
const rowY = (row: number) => gridTop + (row - this.scrollRow) * rowH;
// Selection highlight (row band, or a single cell in item mode).
const selY = rowY(this.selectedRow);
if (this.mode === "row") {
drawSelectionHighlight(image, 4, selY + 2, width - 8, rowH - 4, focused, 6);
} else {
drawSelectionHighlight(image, this.selectedCol * colW + 6, selY + 2, colW - 12, rowH - 4, focused, 6);
}
for (let index = 0; index < entries.length; index++) {
const entry = entries[index]!;
const row = Math.floor(index / COLS);
if (row < this.scrollRow) continue;
const blockTop = rowY(row) + Math.max(2, (rowH - ICON_SIZE - font.lineHeight - LABEL_GAP) / 2);
if (blockTop >= gridBottom) break; // fully below the grid
const centerX = (index % COLS) * colW + colW / 2;
const icon = renderIcon(entry.kind === "app" ? entry.icon : "folder-filled", ICON_SIZE);
if (icon) {
// Clip the icon at the grid bottom so a peeking row shows only its top.
const clipHeight = Math.min(icon.height, Math.floor(gridBottom - blockTop));
image.bitBlt(icon, Math.round(centerX - icon.width / 2), Math.round(blockTop), {
height: clipHeight,
transparentZero: true,
});
}
const labelY = Math.round(blockTop + ICON_SIZE + LABEL_GAP);
if (labelY + font.lineHeight <= gridBottom) {
const label = truncateText(font, entry.label, colW - 8);
image.drawText(font, Math.round(centerX - font.measureText(label) / 2), labelY, label, 210);
}
}
const selectedEntry = entries[this.selectedRow * COLS + this.selectedCol];
const pickVerb = selectedEntry?.kind === "folder" ? "open" : "launch";
const hint =
this.mode === "row"
? `${GESTURE_SCROLL} row ${GESTURE_CLICK} pick ${GESTURE_DOUBLE_CLICK} back`
: `${GESTURE_SCROLL} item ${GESTURE_CLICK} ${pickVerb} ${GESTURE_DOUBLE_CLICK} row`;
image.drawText(font, 8, height - 14, hint, 110);
return image;
}
async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> {
const entries = this.entries();
const rows = this.rowCount(entries.length);
switch (event.type) {
case "scroll-up":
case "scroll-down": {
const delta = event.type === "scroll-down" ? 1 : -1;
if (this.mode === "row") {
this.selectedRow = clamp(this.selectedRow + delta, 0, rows - 1);
} else {
// Item selection traverses the grid linearly: past a row's edge it
// continues onto the adjacent row (stopping at the grid's ends).
const itemCount = this.itemsInRow(entries.length, this.selectedRow);
const next = clamp(this.selectedCol, 0, itemCount - 1) + delta;
if (next >= 0 && next < itemCount) {
this.selectedCol = next;
} else if (next < 0 && this.selectedRow > 0) {
this.selectedRow--;
this.selectedCol = this.itemsInRow(entries.length, this.selectedRow) - 1;
} else if (next >= itemCount && this.selectedRow < rows - 1) {
this.selectedRow++;
this.selectedCol = 0;
}
}
return;
}
case "click": {
if (this.mode === "row") {
this.mode = "item";
// Default to the middle column (clamped to the row's item count).
this.selectedCol = Math.min(
Math.floor(COLS / 2),
this.itemsInRow(entries.length, this.selectedRow) - 1,
);
} else {
const entry = entries[this.selectedRow * COLS + this.selectedCol];
if (!entry) return;
if (entry.kind === "folder") {
this.currentFolder = entry.name;
this.mode = "row";
this.selectedRow = 0;
this.scrollRow = 0;
} else {
// Return to the top grid before launching, so the launcher never
// shows (even briefly) stale folder contents when re-entered.
if (this.currentFolder !== null) this.exitFolder();
this.mode = "row";
await this.options.launchApp(entry.appId);
}
}
return;
}
case "double-click":
if (this.mode === "item") {
this.mode = "row";
} else if (this.currentFolder !== null) {
this.exitFolder();
} else {
shell.yieldFocusToSidebar();
}
return;
default:
return;
}
}
}
/**
* The launcher: a pinned, uncloseable in-process window presenting the app
* grid. Selecting an app asks the controller to launch it and foregrounds the
* new window.
*/
export function createLauncherWindow(options: LauncherOptions): ShellWindow {
const created = createInProcessWindow({
appId: "launcher",
windowId: LAUNCHER_WINDOW_ID,
title: "Apps",
iconLetter: "A",
icon: "layout-grid",
closeable: false,
actions: options.actions,
// Not wrapped in YieldAtRootLayer: the grid handles double-click itself to
// back out of item selection before yielding to the sidebar.
baseLayer: new LauncherGridLayer(options),
submitFrame: options.submitFrame,
setSurfaceVisible: options.setSurfaceVisible,
});
// The assistant's folder tools change the grouping from outside the window;
// the settings broadcast is the change signal, and the fingerprint check
// keeps every unrelated setting change from repainting the launcher. The
// launcher is pinned for the app's lifetime, so the subscription never needs
// tearing down.
let lastFolderState = getFolderStateFingerprint();
onAnySettingChanged(() => {
const state = getFolderStateFingerprint();
if (state === lastFolderState) return;
lastFolderState = state;
created.requestRender();
});
return created.window;
}
-105
View File
@@ -1,105 +0,0 @@
/**
* Launcher folder state: which apps are grouped into which named folder.
* Stored as one JSON string (appId -> folder name) in the settings store, so
* it persists and its changes broadcast to every isolate. An unset value means
* the default grouping; any edit persists the whole map, so clearing out the
* defaults sticks. Folders exist only while at least one app is assigned to
* them — there is no separate create/delete step.
*/
import { getStringSetting, setStringSetting } from "../../native/settings-store";
const STORAGE_KEY = "launcher.folders";
/** The out-of-the-box grouping, applied only while the setting is unset. */
const DEFAULT_ASSIGNMENTS: Record<string, string> = {
blocks: "Games",
freecell: "Games",
minesweeper: "Games",
pinball: "Games",
};
export const FOLDER_NAME_MAX_LENGTH = 24;
/** appId -> folder name. Malformed stored JSON reads as "no folders". */
export function getFolderAssignments(): Record<string, string> {
const raw = getStringSetting(STORAGE_KEY, "");
if (!raw) return { ...DEFAULT_ASSIGNMENTS };
try {
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
const assignments: Record<string, string> = {};
for (const appId of Object.keys(parsed)) {
const folder = parsed[appId];
if (typeof folder === "string" && folder.trim()) {
assignments[appId] = folder.trim();
}
}
return assignments;
} catch {
return {};
}
}
/** folder name -> appIds (assignment order), folder names sorted. */
export function getFolders(): Map<string, string[]> {
const assignments = getFolderAssignments();
const unsorted = new Map<string, string[]>();
for (const appId of Object.keys(assignments)) {
const folder = assignments[appId]!;
const members = unsorted.get(folder);
if (members) {
members.push(appId);
} else {
unsorted.set(folder, [appId]);
}
}
const folders = new Map<string, string[]>();
for (const name of Array.from(unsorted.keys()).sort((a, b) => a.localeCompare(b))) {
folders.set(name, unsorted.get(name)!);
}
return folders;
}
/** Assign an app to a folder, or (with null) return it to the top level. */
export function setAppFolder(appId: string, folder: string | null): void {
const assignments = getFolderAssignments();
if (folder) {
assignments[appId] = folder;
} else {
delete assignments[appId];
}
setStringSetting(STORAGE_KEY, JSON.stringify(assignments));
}
/** Move every app out of a folder. Returns how many apps were moved. */
export function disbandFolder(folder: string): number {
const assignments = getFolderAssignments();
let moved = 0;
for (const appId of Object.keys(assignments)) {
if (assignments[appId] === folder) {
delete assignments[appId];
moved++;
}
}
if (moved > 0) {
setStringSetting(STORAGE_KEY, JSON.stringify(assignments));
}
return moved;
}
/**
* Match an existing folder name case-insensitively (so "games" reuses
* "Games" instead of creating a near-duplicate), else the trimmed input.
*/
export function resolveFolderName(input: string): string {
const trimmed = input.trim();
for (const name of getFolders().keys()) {
if (name.toLowerCase() === trimmed.toLowerCase()) return name;
}
return trimmed;
}
/** Raw stored value, for cheap change detection by the launcher window. */
export function getFolderStateFingerprint(): string {
return getStringSetting(STORAGE_KEY, "");
}
-494
View File
@@ -1,494 +0,0 @@
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.selectedActionIndex + 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")}`;
}
-103
View File
@@ -1,103 +0,0 @@
import { getDefaultSmallFont } from "../../graphics/bdffont";
import { GrayImage } from "../../graphics/image";
import { nightscoutBridge, type NightscoutState } from "../../native/nightscout-bridge";
import { NightscoutLayer } from "../apps/nightscout";
import {
createInProcessWindow,
YieldAtRootLayer,
type InProcessAppOptions,
type InProcessWindow,
} from "./in-process-window";
import { shell } from "./shell";
export const NIGHTSCOUT_WINDOW_ID = "nightscout";
export const NIGHTSCOUT_SURFACE_ID = "window:nightscout";
const TRAY_ICON_ID = "nightscout";
const TRAY_HEIGHT = 24;
const TRAY_GRAPH_WIDTH = 48;
const TRAY_STALE_MS = 15 * 60 * 1000;
const TRAY_GRAPH_WINDOW_MS = 2 * 60 * 60 * 1000;
/**
* The Nightscout app: the full-screen glucose view (previously reached via
* the dashboard card) in its own in-process window. While the app is running
* it also publishes a top-bar tray icon: the latest blood-glucose value
* (struck through when stale) plus a minimal 48px history graph.
*/
export function createNightscoutAppWindow(options: InProcessAppOptions): InProcessWindow {
let unsubscribe: (() => void) | null = null;
const app = createInProcessWindow({
appId: "nightscout",
windowId: NIGHTSCOUT_WINDOW_ID,
title: "Nightscout",
iconLetter: "Ns",
icon: "nightscout",
closeable: true,
actions: options.actions,
baseLayer: new YieldAtRootLayer(new NightscoutLayer()),
submitFrame: options.submitFrame,
setSurfaceVisible: options.setSurfaceVisible,
removeSurface: options.removeSurface,
onClosed: () => {
unsubscribe?.();
unsubscribe = null;
shell.setTrayIcon(TRAY_ICON_ID, null);
options.onClosed();
},
});
// onStateChange fires immediately with the current snapshot, so this also
// publishes the initial tray icon.
unsubscribe = nightscoutBridge.onStateChange((state) => {
shell.setTrayIcon(TRAY_ICON_ID, buildNightscoutTrayIcon(state));
app.requestRender();
});
return app;
}
/** BG value (struck through when stale) + minimal 2-hour line graph. */
function buildNightscoutTrayIcon(state: NightscoutState): GrayImage {
const font = getDefaultSmallFont();
const nowMs = Date.now();
const label = state.latest ? `${state.latest.sgv}` : "--";
const labelWidth = font.measureText(label);
const image = new GrayImage(labelWidth + 4 + TRAY_GRAPH_WIDTH, TRAY_HEIGHT, 0);
const textY = Math.max(0, ((TRAY_HEIGHT - font.lineHeight) / 2) | 0);
image.drawText(font, 0, textY, label, 220);
const stale = state.latest !== null && nowMs - state.latest.timestampMs > TRAY_STALE_MS;
if (stale) {
image.drawLine(0, TRAY_HEIGHT / 2, labelWidth, TRAY_HEIGHT / 2, 180);
}
drawTrayGraph(image, labelWidth + 4, state, nowMs);
return image;
}
function drawTrayGraph(image: GrayImage, x: number, state: NightscoutState, nowMs: number): void {
const windowStartMs = nowMs - TRAY_GRAPH_WINDOW_MS;
const points = state.history.filter(
(point) => point.timestampMs >= windowStartMs && point.timestampMs <= nowMs,
);
if (points.length === 0) return;
const values = points.map((point) => point.sgv);
const min = Math.min(...values, 60);
const max = Math.max(...values, 200);
const span = Math.max(20, max - min);
const plotted = points.map((point) => ({
timestampMs: point.timestampMs,
x: x + Math.round(((point.timestampMs - windowStartMs) / TRAY_GRAPH_WINDOW_MS) * (TRAY_GRAPH_WIDTH - 1)),
y: TRAY_HEIGHT - 1 - Math.round(((point.sgv - min) / span) * (TRAY_HEIGHT - 1)),
}));
for (let index = 1; index < plotted.length; index++) {
const previous = plotted[index - 1]!;
const current = plotted[index]!;
if (current.timestampMs - previous.timestampMs <= TRAY_STALE_MS) {
image.drawLine(previous.x, previous.y, current.x, current.y, 190);
} else {
image.fillRect(current.x, current.y, 1, 1, 190);
}
}
}
-32
View File
@@ -1,32 +0,0 @@
import { NotificationsListLayer } from "../notifications";
import {
createInProcessWindow,
YieldAtRootLayer,
type InProcessAppOptions,
type InProcessWindow,
} from "./in-process-window";
export const NOTIFICATIONS_WINDOW_ID = "notifications";
export const NOTIFICATIONS_SURFACE_ID = "window:notifications";
/**
* The Notifications app: the Android-notification list (previously a
* dashboard page) in its own in-process window; selecting a notification
* opens the detail view with its quick actions.
*/
export function createNotificationsAppWindow(options: InProcessAppOptions): InProcessWindow {
return createInProcessWindow({
appId: "notifications",
windowId: NOTIFICATIONS_WINDOW_ID,
title: "Notifications",
iconLetter: "N",
icon: "bell",
closeable: true,
actions: options.actions,
baseLayer: new YieldAtRootLayer(new NotificationsListLayer()),
submitFrame: options.submitFrame,
setSurfaceVisible: options.setSurfaceVisible,
removeSurface: options.removeSurface,
onClosed: options.onClosed,
});
}
-64
View File
@@ -1,64 +0,0 @@
import { GrayImage } from "../../graphics/image";
import { LayerActions } from "../layers";
import { EditTextSettingLayer } from "../dashboard-settings";
import { createSettingsPanelLayer } from "../dashboard/settings-menus";
import { createInProcessWindow } from "./in-process-window";
import { type ShellWindow } from "./shell";
export const SETTINGS_WINDOW_ID = "settings";
export const SETTINGS_SURFACE_ID = "window:settings";
export type SettingsAppOptions = {
actions: LayerActions;
submitFrame: (image: GrayImage, paintMs: number, frameId: number) => Promise<void>;
setSurfaceVisible: (visible: boolean) => void;
removeSurface: () => void;
onClosed: () => void;
};
export type SettingsAppWindow = {
window: ShellWindow;
requestRender: () => void;
/** Select a section in the left column by label (e.g. "Terminal"). */
focusSection: (label: string) => void;
/** Whether the glasses-side text-setting editor is the top layer. */
isTextEditorOnTop: () => boolean;
/** Pop the text-setting editor if it is on top; returns whether it was. */
closeTextEditor: () => boolean;
};
/**
* The Settings app: the settings menu tree (previously a dashboard submenu)
* hosted in its own in-process window. In-process because the text-setting
* editor is synchronized with the phone-side TextField through the
* controller, which lives on the main thread.
*/
export function createSettingsAppWindow(options: SettingsAppOptions): SettingsAppWindow {
const panel = createSettingsPanelLayer();
const { window, stack, requestRender } = createInProcessWindow({
appId: "settings",
windowId: SETTINGS_WINDOW_ID,
title: "Settings",
iconLetter: "Se",
icon: "settings",
closeable: true,
actions: options.actions,
// Not wrapped in YieldAtRootLayer: the panel routes double-click itself
// (right column -> left column, then left column -> sidebar).
baseLayer: panel,
submitFrame: options.submitFrame,
setSurfaceVisible: options.setSurfaceVisible,
removeSurface: options.removeSurface,
onClosed: options.onClosed,
});
return {
window,
requestRender,
focusSection: (label) => {
panel.focusSection(label);
requestRender();
},
isTextEditorOnTop: () => stack.topMatches((layer) => layer instanceof EditTextSettingLayer),
closeTextEditor: () => stack.popIfTop((layer) => layer instanceof EditTextSettingLayer),
};
}
+2 -2
View File
@@ -4,8 +4,8 @@ import { EvenAIStatus, EventSourceType, OsEventTypeList } from "../../g2/events"
import type { RawInputEvent } from "../../native/faceclaw-communicator";
import { DashboardInputEvent, Layer, LayerActions, LayerContext, LayerStack, noopLayerActions } from "../layers";
import { MenuLayer, type MenuItem } from "../menu";
import { VoiceInputLayer, type VoiceSendTarget } from "../apps/voice-input";
import { AssistantLayer } from "../apps/assistant";
import { VoiceInputLayer, type VoiceSendTarget } from "./voice-input";
import { AssistantLayer } from "./assistant";
import { AssistantSession, type AssistantBackendConfig } from "../../assistant/session";
import { resolveAssistantModel } from "../../assistant/models";
import type { AssistantContext } from "../../assistant/types";
-75
View File
@@ -1,75 +0,0 @@
import { imageFromAsciiArt } from "../../graphics/image";
import { TranscribeLayer } from "../apps/transcribe";
import {
createInProcessWindow,
YieldAtRootLayer,
type InProcessAppOptions,
type InProcessWindow,
} from "./in-process-window";
import { shell } from "./shell";
export const TRANSCRIBE_WINDOW_ID = "transcribe";
export const TRANSCRIBE_SURFACE_ID = "window:transcribe";
const TRAY_ICON_ID = "transcribe";
// 16x18 microphone glyph for the top-bar tray.
const MIC_ICON = imageFromAsciiArt(
[
" #### ",
" ###### ",
" # # ",
" # # ",
" # # ",
" # # ",
" # # ",
" # # # # ",
" # # # # ",
" # #### # ",
" # # ",
" ###### ",
" # ",
" # ",
" ###### ",
],
220,
);
export type TranscribeAppOptions = InProcessAppOptions & {
/** Begin continuous mic capture (kept on while the window is open). */
startContinuousVoiceCapture: () => void;
stopContinuousVoiceCapture: () => void;
};
/**
* The Transcribe app: live speech-to-text in its own window. While open it
* holds continuous mic capture (so push-to-talk can share the stream) and
* shows a microphone tray icon in the top bar.
*/
export function createTranscribeAppWindow(options: TranscribeAppOptions): InProcessWindow {
const layer = new TranscribeLayer();
const app = createInProcessWindow({
appId: "transcribe",
windowId: TRANSCRIBE_WINDOW_ID,
title: "Transcribe",
iconLetter: "Tr",
icon: "mic",
closeable: true,
actions: options.actions,
baseLayer: new YieldAtRootLayer(layer),
submitFrame: options.submitFrame,
setSurfaceVisible: options.setSurfaceVisible,
removeSurface: options.removeSurface,
onClosed: () => {
options.stopContinuousVoiceCapture();
shell.setTrayIcon(TRAY_ICON_ID, null);
options.onClosed();
},
});
// Wire async state changes to this window's renderer, rather than the
// controller action from which the window-specific actions were derived.
layer.start(app.requestRender);
options.startContinuousVoiceCapture();
shell.setTrayIcon(TRAY_ICON_ID, MIC_ICON);
return app;
}
@@ -7,7 +7,7 @@ import { anthropicApiKeySetting } from "../dashboard-settings";
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, gestureHints } from "../gestures";
import { drawSelectionHighlight } from "../menu";
import { Layer, type DashboardInputEvent, type LayerActions, type LayerContext } from "../layers";
import { MIN_WINDOW_HEIGHT, minWindowTop } from "../shell/geometry";
import { MIN_WINDOW_HEIGHT, minWindowTop } from "./geometry";
const DIALOG_X = 40;
const DIALOG_W = G2_LENS_WIDTH - 80;
-56
View File
@@ -1,56 +0,0 @@
import { ensureLocationPermission, hasLocationPermission } from "../../g2/android-permissions";
import { weatherBridge } from "../../native/weather";
import { WeatherLayer } from "../apps/weather";
import {
createInProcessWindow,
YieldAtRootLayer,
type InProcessAppOptions,
type InProcessWindow,
} from "./in-process-window";
export const WEATHER_WINDOW_ID = "weather";
export const WEATHER_SURFACE_ID = "window:weather";
/** Local current conditions and forecast from the National Weather Service. */
export function createWeatherAppWindow(options: InProcessAppOptions): InProcessWindow {
let requestingPermission = false;
let unsubscribe: (() => void) | null = null;
let app: InProcessWindow;
const requestUpdate = () => {
if (requestingPermission) return;
if (hasLocationPermission()) {
weatherBridge.start();
return;
}
requestingPermission = true;
void ensureLocationPermission().then((granted) => {
requestingPermission = false;
if (granted) weatherBridge.start();
app.requestRender();
});
};
app = createInProcessWindow({
appId: "weather",
windowId: WEATHER_WINDOW_ID,
title: "Weather",
iconLetter: "W",
icon: "cloud-sun",
closeable: true,
actions: options.actions,
baseLayer: new YieldAtRootLayer(new WeatherLayer(() => weatherBridge.snapshot(), requestUpdate)),
submitFrame: options.submitFrame,
setSurfaceVisible: options.setSurfaceVisible,
removeSurface: options.removeSurface,
onClosed: () => {
unsubscribe?.();
unsubscribe = null;
weatherBridge.stop();
options.onClosed();
},
});
unsubscribe = weatherBridge.onStateChange(() => app.requestRender());
requestUpdate();
return app;
}
File renamed without changes.