diff --git a/App_Resources/Android/src/main/AndroidManifest.xml b/App_Resources/Android/src/main/AndroidManifest.xml index 04caee59..222b4aa8 100644 --- a/App_Resources/Android/src/main/AndroidManifest.xml +++ b/App_Resources/Android/src/main/AndroidManifest.xml @@ -10,6 +10,9 @@ + + diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/util/BmpUtil.java b/App_Resources/Android/src/main/java/com/faceclaw/app/util/BmpUtil.java index 225888d7..c1879376 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/util/BmpUtil.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/util/BmpUtil.java @@ -91,7 +91,7 @@ public class BmpUtil { if (value <= 0) { return 0; } - return Math.min(15, value >> 4); + return Math.min(15, (value+8) >> 4); } private static void putUint16Le(byte[] buf, int offset, int value) { diff --git a/app/g2/dashboard-controller.ts b/app/g2/dashboard-controller.ts index 35924525..fa9c6a03 100644 --- a/app/g2/dashboard-controller.ts +++ b/app/g2/dashboard-controller.ts @@ -18,7 +18,6 @@ import { closeDashboardTextSettingEditor, drawDashboard, logToDashboard, - openTelepromptDocument, receiveDashboardWindowInput, resetDashboardSleepTimerAndWake, setDashboardBatteryLevels, @@ -39,7 +38,23 @@ import { NOTIFICATIONS_SURFACE_ID, NOTIFICATIONS_WINDOW_ID, } from "../ui/shell/notifications-app"; -import { type InProcessWindow } from "../ui/shell/in-process-window"; +import { + createDebugTestsAppWindow, + DEBUG_TESTS_SURFACE_ID, + DEBUG_TESTS_WINDOW_ID, +} from "../ui/shell/debug-tests-app"; +import { + createTelepromptBrowserWindow, + createTelepromptDocumentWindow, + TELEPROMPT_SURFACE_ID, + TELEPROMPT_WINDOW_ID, +} from "../ui/shell/teleprompt-app"; +import { + createNightscoutAppWindow, + NIGHTSCOUT_SURFACE_ID, + NIGHTSCOUT_WINDOW_ID, +} from "../ui/shell/nightscout-app"; +import { type InProcessAppOptions, type InProcessWindow } from "../ui/shell/in-process-window"; import { APP_VIEWPORT } from "../ui/shell/geometry"; import { type LayerActions } from "../ui/layers"; import { @@ -202,7 +217,8 @@ class DashboardController { // The Settings app is in-process (its text editor syncs with the phone UI // through this controller); tracked so edit flows reach its window. private settingsApp: SettingsAppWindow | null = null; - private notificationsApp: InProcessWindow | null = null; + // Other in-process singleton apps, keyed by windowId. + private readonly inProcessApps = new Map(); private sharedActions!: Omit; private lastForegroundNotificationUpdateAtMs = 0; private lastConnectedPreviewUpdateAtMs = 0; @@ -262,7 +278,10 @@ class DashboardController { apps: [ { appId: "stopwatch", label: "Stopwatch" }, { appId: "terminal", label: "Terminal" }, + { appId: "teleprompt", label: "Teleprompt" }, + { appId: "nightscout", label: "Nightscout" }, { appId: "notifications", label: "Notifications" }, + { appId: "debug-tests", label: "Debug tests" }, { appId: "settings", label: "Settings" }, ], launchApp: (appId) => this.launchApp(appId), @@ -703,16 +722,23 @@ class DashboardController { await this.handleInputEvent(event); } + /** A document arrived via Android's Share intent: open it as a new window. */ async openTelepromptDocument(text: string): Promise { - openTelepromptDocument(text); this.appendLog(`teleprompt document received (${text.length} chars)`); - if (this.phase === "connected" && this.communicator) { - this.requestShellRender(); - await this.requestRender("interval"); - return; + if (!shell.isScreenOn()) { + shell.wake("sidebar"); } - const image = drawDashboard(); - this.updateDisplayPreviewFromImage(image); + this.openTelepromptDocumentWindow("Shared text", text); + } + + /** Open a teleprompt document as its own (closeable, non-singleton) window. */ + private openTelepromptDocumentWindow(title: string, text: string): void { + const windowId = `teleprompt:doc:${this.nextWindowSerial++}`; + void this.launchInProcessApp(windowId, `window:${windowId}`, (options) => + createTelepromptDocumentWindow(windowId, title, text, options), + ).catch((error) => { + this.appendLog(`teleprompt window failed: ${this.formatError(error)}`); + }); } private startTextSettingEdit(setting: ConfigSettingString): void { @@ -1032,32 +1058,36 @@ class DashboardController { this.appendLog("launched settings"); } - /** Launch or focus the (in-process, singleton) Notifications app. */ - private async launchNotificationsApp(): Promise { - if (this.notificationsApp) { - shell.focusWindow(NOTIFICATIONS_WINDOW_ID); + /** Launch or focus an in-process singleton app (notifications, debug tests). */ + private async launchInProcessApp( + windowId: string, + surfaceId: string, + create: (options: InProcessAppOptions) => InProcessWindow, + ): Promise { + const existing = this.inProcessApps.get(windowId); + if (existing) { + shell.focusWindow(windowId); this.requestShellRender(); return; } - const notificationsApp = createNotificationsAppWindow({ + const app = create({ actions: { ...this.sharedActions, requestRender: () => {}, // rebound by createInProcessWindow }, - submitFrame: (image, paintMs, frameId) => - this.submitWindowFrame(NOTIFICATIONS_SURFACE_ID, image, paintMs, frameId), - setSurfaceVisible: (visible) => this.setWindowSurfaceVisible(NOTIFICATIONS_SURFACE_ID, visible), - removeSurface: () => this.removeWindowSurface(NOTIFICATIONS_SURFACE_ID), + submitFrame: (image, paintMs, frameId) => this.submitWindowFrame(surfaceId, image, paintMs, frameId), + setSurfaceVisible: (visible) => this.setWindowSurfaceVisible(surfaceId, visible), + removeSurface: () => this.removeWindowSurface(surfaceId), onClosed: () => { - this.notificationsApp = null; + this.inProcessApps.delete(windowId); }, }); - this.notificationsApp = notificationsApp; - shell.registerWindow(notificationsApp.window); - await this.configureWindowSurface(NOTIFICATIONS_SURFACE_ID, false); - shell.focusWindow(NOTIFICATIONS_WINDOW_ID); + this.inProcessApps.set(windowId, app); + shell.registerWindow(app.window); + await this.configureWindowSurface(surfaceId, false); + shell.focusWindow(windowId); this.requestShellRender(); - this.appendLog("launched notifications"); + this.appendLog(`launched ${windowId}`); } /** Get or spawn the worker host for an app. */ @@ -1097,7 +1127,24 @@ class DashboardController { return; } if (appId === "notifications") { - await this.launchNotificationsApp(); + await this.launchInProcessApp(NOTIFICATIONS_WINDOW_ID, NOTIFICATIONS_SURFACE_ID, createNotificationsAppWindow); + return; + } + if (appId === "debug-tests") { + await this.launchInProcessApp(DEBUG_TESTS_WINDOW_ID, DEBUG_TESTS_SURFACE_ID, createDebugTestsAppWindow); + return; + } + if (appId === "nightscout") { + await this.launchInProcessApp(NIGHTSCOUT_WINDOW_ID, NIGHTSCOUT_SURFACE_ID, createNightscoutAppWindow); + return; + } + if (appId === "teleprompt") { + await this.launchInProcessApp(TELEPROMPT_WINDOW_ID, TELEPROMPT_SURFACE_ID, (options) => + createTelepromptBrowserWindow({ + ...options, + openDocumentWindow: (title, text) => this.openTelepromptDocumentWindow(title, text), + }), + ); return; } const host = this.ensureAppHost(appId); @@ -1254,7 +1301,7 @@ class DashboardController { private async handleAndroidNotificationPosted(notificationKey: string): Promise { // Keep the Notifications app's list fresh if it is open. - this.notificationsApp?.requestRender(); + this.inProcessApps.get(NOTIFICATIONS_WINDOW_ID)?.requestRender(); if (!notificationKey) { this.requestShellRender(); return; diff --git a/app/native/file-access.ts b/app/native/file-access.ts new file mode 100644 index 00000000..fd7751b4 --- /dev/null +++ b/app/native/file-access.ts @@ -0,0 +1,91 @@ +/** + * Filesystem access for the on-glasses file browser. Arbitrary files outside + * app-specific directories require the "All files access" special permission + * on modern Android (MANAGE_EXTERNAL_STORAGE, granted via a Settings page, + * reasonable for a sideloaded personal tool). + */ +import { Utils } from "@nativescript/core"; + +declare const android: any; +declare const java: any; +declare const global: any; + +const MAX_TEXT_FILE_BYTES = 2_000_000; +const MAX_TEXT_CHARS = 500_000; + +export type DirectoryEntry = { + name: string; + path: string; + isDirectory: boolean; + sizeBytes: number; +}; + +export function hasAllFilesAccess(): boolean { + if (!global.isAndroid) return false; + try { + return Boolean(android.os.Environment.isExternalStorageManager()); + } catch { + // Pre-R devices have no such concept; the legacy permission suffices. + return true; + } +} + +/** Open the system Settings page where the user grants All files access. */ +export function requestAllFilesAccess(): void { + const context = Utils.android.getApplicationContext(); + const intent = new android.content.Intent( + android.provider.Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, + android.net.Uri.parse(`package:${context.getPackageName()}`), + ); + intent.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(intent); +} + +export function externalStorageRootPath(): string { + return String(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()); +} + +/** List a directory, directories first then by name; null when unreadable. */ +export function listDirectory(path: string): DirectoryEntry[] | null { + try { + const dir = new java.io.File(path); + if (!dir.isDirectory()) return null; + const files = dir.listFiles(); + if (files === null) return null; + const entries: DirectoryEntry[] = []; + for (let index = 0; index < files.length; index++) { + const file = files[index]; + entries.push({ + name: String(file.getName()), + path: String(file.getAbsolutePath()), + isDirectory: Boolean(file.isDirectory()), + sizeBytes: Number(file.length()), + }); + } + entries.sort((a, b) => { + if (a.isDirectory !== b.isDirectory) return a.isDirectory ? -1 : 1; + return a.name.toLowerCase() < b.name.toLowerCase() ? -1 : 1; + }); + return entries; + } catch (error) { + console.warn(`listDirectory failed for ${path}: ${error}`); + return null; + } +} + +/** Read a UTF-8 text file (size-capped); null when unreadable or too large. */ +export function readTextFile(path: string): string | null { + try { + const file = new java.io.File(path); + if (!file.isFile() || file.length() > MAX_TEXT_FILE_BYTES) return null; + // File.toPath() rather than Paths.get(path): NativeScript resolves the + // single-string Paths.get call to the (java.net.URI) overload, which + // aborts in JNI. + const bytes = java.nio.file.Files.readAllBytes(file.toPath()); + const text = String(new java.lang.String(bytes, "UTF-8")); + return text.length > MAX_TEXT_CHARS ? text.slice(0, MAX_TEXT_CHARS) : text; + } catch (error) { + console.warn(`readTextFile failed for ${path}: ${error}`); + return null; + } +} diff --git a/app/native/nightscout-bridge.ts b/app/native/nightscout-bridge.ts index 3b44518c..ab38aa52 100644 --- a/app/native/nightscout-bridge.ts +++ b/app/native/nightscout-bridge.ts @@ -121,7 +121,9 @@ const DEFAULT_NIGHTSCOUT_STATE: NightscoutState = { boluses: [], basal: [], lastUpdatedMs: null, - configurationMissing: true, + // Never assume unconfigured before a refresh has actually checked; UI that + // needs a live answer uses isNightscoutSettingsConfigured(). + configurationMissing: false, }; export class NightscoutBridge { @@ -261,10 +263,15 @@ export class NightscoutBridge { this.emit(); } catch (error) { const message = (error as Error)?.message ?? String(error); + console.warn(`nightscout refresh failed: ${message}`); this.state = { ...this.state, available: this.state.latest !== null, status: `Nightscout refresh failed: ${message}`, + // A fetch failure is not a configuration problem: the settings guard + // above already handled missing config, so a latched stale value here + // must not keep the UI on "Needs setup" (which hides the real error). + configurationMissing: false, }; this.emit(); } diff --git a/app/ui/apps/buzzer-demo.ts b/app/ui/apps/buzzer-demo.ts index 63f0307b..78b60259 100644 --- a/app/ui/apps/buzzer-demo.ts +++ b/app/ui/apps/buzzer-demo.ts @@ -1,5 +1,5 @@ import { getDefaultSmallFont } from "../../graphics/bdffont"; -import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage } from "../../graphics/image"; +import { GrayImage } from "../../graphics/image"; import { Layer, type DashboardInputEvent, type LayerContext } from "../layers"; const NOTE_NAMES = ["C", "D", "E", "F", "G", "A", "B"] as const; @@ -9,19 +9,21 @@ export class BuzzerDemoLayer implements Layer { private note = 1; private oct = 2; - paint(_ctx: LayerContext, _paintBelow: () => GrayImage): GrayImage { - const image = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0); + paint(ctx: LayerContext, _paintBelow: () => GrayImage): 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(); image.drawText(font, 24, 20, "Buzzer demo", 200); image.drawText(font, 24, 44, `Note: ${NOTE_NAMES[this.note - 1]} Octave: ${this.oct}`, 180); image.drawText(font, 24, 68, "Scroll: change note", 150); image.drawText(font, 24, 84, "Click: play note", 150); - image.drawText(font, 24, 252, "Double-click: back", 130); + image.drawText(font, 24, height - 24, "Double-click: back", 130); const keyWidth = 64; const keyY = 130; - const keyX = Math.floor((G2_LENS_WIDTH - keyWidth * NOTE_NAMES.length) / 2); + const keyX = Math.floor((width - keyWidth * NOTE_NAMES.length) / 2); for (let i = 0; i < NOTE_NAMES.length; i++) { const selected = i + 1 === this.note; const x = keyX + i * keyWidth; diff --git a/app/ui/apps/file-browser.ts b/app/ui/apps/file-browser.ts new file mode 100644 index 00000000..1d81542c --- /dev/null +++ b/app/ui/apps/file-browser.ts @@ -0,0 +1,181 @@ +import { getDefaultSmallFont, type BdfFont } from "../../graphics/bdffont"; +import { GrayImage } from "../../graphics/image"; +import { clamp } from "../../util/numeric-util"; +import { + hasAllFilesAccess, + listDirectory, + requestAllFilesAccess, + 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; + +export type FileBrowserOptions = { + startPath: string; + /** Files failing this are listed dimmed and cannot be picked. */ + isSupportedFile: (name: string) => boolean; + onFilePicked: (entry: DirectoryEntry, ctx: LayerContext) => void; + /** Double-click while already at startPath (leave the browser). */ + onLeave: () => void; +}; + +type BrowserRow = + | { kind: "grant"; label: string } + | { kind: "info"; label: string } + | { kind: "entry"; label: string; entry: DirectoryEntry; supported: boolean }; + +/** + * Minimal filesystem browser: scroll to select, click to descend into a + * directory or pick a supported file, double-click to go up (leaving the + * browser when already at the top). Sized to its hosting stack. + */ +export class FileBrowserLayer implements Layer { + private currentPath: string; + private entries: DirectoryEntry[] | null = null; + private listingFailed = false; + private selectedIndex = 0; + private scrollRow = 0; + + constructor(private readonly options: FileBrowserOptions) { + this.currentPath = options.startPath; + } + + paint(ctx: LayerContext): GrayImage { + const font = getDefaultSmallFont(); + const { width, height } = ctx.stack.getBaseSize(); + const image = new GrayImage(width, height, 0); + this.loadEntries(); + const rows = this.buildRows(); + this.selectedIndex = clamp(this.selectedIndex, 0, Math.max(0, rows.length - 1)); + + image.drawText(font, 20, 8, "Teleprompt files", 220); + image.drawText(font, 20, 22, truncateLeft(font, this.currentPath, width - 40), 130); + + const listHeight = height - HEADER_HEIGHT - FOOTER_HEIGHT; + const visibleRows = Math.max(1, (listHeight / ROW_HEIGHT) | 0); + if (this.selectedIndex < this.scrollRow) { + this.scrollRow = this.selectedIndex; + } else if (this.selectedIndex >= this.scrollRow + visibleRows) { + this.scrollRow = this.selectedIndex - visibleRows + 1; + } + this.scrollRow = clamp(this.scrollRow, 0, Math.max(0, rows.length - visibleRows)); + + 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.selectedIndex; + if (selected) { + image.fillRoundedRect(LIST_X - 6, y - 1, width - 2 * LIST_X + 12, ROW_HEIGHT - 1, 15, 4); + image.drawRoundedRect(LIST_X - 6, y - 1, width - 2 * LIST_X + 12, ROW_HEIGHT - 1, 45, 4); + } + const value = rowValue(row, selected); + image.drawText(font, LIST_X, y + 1, truncateRight(font, row.label, width - 2 * LIST_X), value); + } + + image.drawText(font, 20, height - 16, "Click: open Double-click: up / back", 110); + return image; + } + + async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise { + const rows = this.buildRows(); + switch (event.type) { + case "scroll-up": + this.selectedIndex = Math.max(0, this.selectedIndex - 1); + return; + case "scroll-down": + this.selectedIndex = Math.min(Math.max(0, rows.length - 1), this.selectedIndex + 1); + return; + case "click": { + const row = rows[clamp(this.selectedIndex, 0, Math.max(0, rows.length - 1))]; + if (!row) return; + if (row.kind === "grant") { + requestAllFilesAccess(); + this.entries = null; // re-list after the user returns from Settings + return; + } + if (row.kind !== "entry") return; + if (row.entry.isDirectory) { + this.navigateTo(row.entry.path); + } else if (row.supported) { + this.options.onFilePicked(row.entry, ctx); + } + return; + } + case "double-click": { + if (this.currentPath === this.options.startPath) { + this.options.onLeave(); + return; + } + const parent = this.currentPath.slice(0, this.currentPath.lastIndexOf("/")); + this.navigateTo(parent.length >= this.options.startPath.length ? parent : this.options.startPath); + return; + } + default: + return; + } + } + + private navigateTo(path: string): void { + this.currentPath = path; + this.entries = null; + this.selectedIndex = 0; + this.scrollRow = 0; + } + + private loadEntries(): void { + if (this.entries !== null) return; + const listing = listDirectory(this.currentPath); + this.listingFailed = listing === null; + this.entries = listing ?? []; + } + + private buildRows(): BrowserRow[] { + this.loadEntries(); + const rows: BrowserRow[] = []; + if (!hasAllFilesAccess()) { + rows.push({ kind: "grant", label: "Grant file access (opens phone Settings)" }); + } + for (const entry of this.entries ?? []) { + rows.push({ + kind: "entry", + entry, + supported: entry.isDirectory || this.options.isSupportedFile(entry.name), + label: entry.isDirectory ? `${entry.name}/` : entry.name, + }); + } + if (!rows.length || (this.listingFailed && rows.every((row) => row.kind !== "entry"))) { + rows.push({ kind: "info", label: this.listingFailed ? "(unreadable directory)" : "(empty directory)" }); + } + return rows; + } +} + +function rowValue(row: BrowserRow, selected: boolean): number { + if (row.kind === "info") return 120; + if (row.kind === "grant") return selected ? 255 : 210; + if (!row.supported) return selected ? 140 : 100; + return selected ? 255 : 200; +} + +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}`; +} diff --git a/app/ui/apps/nightscout.ts b/app/ui/apps/nightscout.ts index be6a3364..09a92098 100644 --- a/app/ui/apps/nightscout.ts +++ b/app/ui/apps/nightscout.ts @@ -72,9 +72,6 @@ export class NightscoutDashboardPlugin extends DashboardPlugin { ); } - override createFullscreenLayer(getState: () => DashboardPluginState): Layer { - return new NightscoutLayer(getState); - } } function drawNightscoutDelta( @@ -366,28 +363,30 @@ function drawNightscoutReferenceLine( } -class NightscoutLayer implements Layer { +export class NightscoutLayer implements Layer { constructor(private readonly getState: () => DashboardPluginState) {} paint(ctx: LayerContext): GrayImage { const font = getDefaultSmallFont(); - const image = new GrayImage(576, 288, 0); + // Sized to the hosting stack (the Nightscout app viewport). + const { width, height } = ctx.stack.getBaseSize(); + const image = new GrayImage(width, height, 0); const nightscout = this.getState().nightscout; const nowMs = Date.now(); - image.drawRect(12, 12, 552, 264, 52); + const footerY = height - 26; + image.drawRect(12, 12, width - 24, height - 24, 52); image.drawText(font, 22, 16, "Nightscout", 220); if (!this.getState().nightscoutConfigured || nightscout.configurationMissing) { image.drawText(font, 22, 44, "Nightscout needs configuration.", 180); - image.drawText(font, 22, 62, "Double-click and use Settings", 140); - image.drawText(font, 22, 78, "Integrations > Nightscout.", 140); + image.drawText(font, 22, 62, "Use Settings > Integrations > Nightscout.", 140); 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, 252, "Click: refresh Double-click: back", 110); + image.drawText(font, 22, footerY, "Click: refresh Double-click: back", 110); return image; } @@ -418,9 +417,10 @@ class NightscoutLayer implements Layer { 160, ); image.drawText(font, 22, 110, `Pump ${truncateLine(nightscout.pumpStatus || "--", 56)}`, 150); - drawNightscoutGraph(image, { x: 22, y: 128, width: 532, height: 96 }, nightscout, nowMs, font); - image.drawText(font, 22, 234, "2-hour glucose history with basal / carbs / boluses", 130); - image.drawText(font, 22, 252, "Click: refresh Double-click: back", 110); + 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, "Click: refresh Double-click: back", 110); return image; } diff --git a/app/ui/apps/screen-test.ts b/app/ui/apps/screen-test.ts index 266012f6..b51433bd 100644 --- a/app/ui/apps/screen-test.ts +++ b/app/ui/apps/screen-test.ts @@ -1,16 +1,11 @@ import { getDefaultSmallFont } from "../../graphics/bdffont"; -import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage } from "../../graphics/image"; +import { GrayImage } from "../../graphics/image"; import { Layer, type DashboardInputEvent, type LayerContext } from "../layers"; const COLOR_VALUE_COUNT = 256; const COLOR_VALUE_STEP = 1; -const SWATCH_COUNT = COLOR_VALUE_COUNT / COLOR_VALUE_STEP; const GRID_COLUMNS = 16; -const GRID_ROWS = Math.ceil(SWATCH_COUNT / GRID_COLUMNS); -const CELL_WIDTH = Math.floor(G2_LENS_WIDTH / GRID_COLUMNS); -//const CELL_HEIGHT = Math.floor(G2_LENS_HEIGHT / GRID_ROWS); const CELL_HEIGHT = 30; -const GRID_X = Math.floor((G2_LENS_WIDTH - CELL_WIDTH * GRID_COLUMNS) / 2); const LABEL_Y_OFFSET = 0; const SWATCH_Y_OFFSET = 12; const SWATCH_WIDTH = 24; @@ -18,18 +13,22 @@ const SWATCH_HEIGHT = 16; export class ScreenTestLayer implements Layer { paint(ctx: LayerContext): GrayImage { - const image = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0); + // 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 = GRID_X + col * CELL_WIDTH; + const cellX = gridX + col * cellWidth; const cellY = row * CELL_HEIGHT; const label = String(value); - const labelX = cellX + Math.max(0, Math.floor((CELL_WIDTH - font.measureText(label)) / 2)); - const swatchX = cellX + Math.floor((CELL_WIDTH - SWATCH_WIDTH) / 2); + 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); diff --git a/app/ui/apps/teleprompt.ts b/app/ui/apps/teleprompt.ts index abe83e4a..006b48bb 100644 --- a/app/ui/apps/teleprompt.ts +++ b/app/ui/apps/teleprompt.ts @@ -1,59 +1,57 @@ import { wrapText } from "../../graphics/textwrap"; import { getDefaultSmallFont, type BdfFont } from "../../graphics/bdffont"; -import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage } from "../../graphics/image"; +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 BODY_WIDTH = G2_LENS_WIDTH - BODY_X - 12; const LINE_STEP = 14; -const FOOTER_Y = 252; -const BODY_LINE_COUNT = Math.floor((FOOTER_Y - BODY_Y) / LINE_STEP); -const PAGE_STEP = Math.max(1, BODY_LINE_COUNT - 1); +const FOOTER_MARGIN = 36; +/** + * Paged text viewer for a document. Sized to its hosting stack (a teleprompt + * document window, or pushed over the file browser for view-in-place). + */ export class TelepromptLayer implements Layer { private lines: string[] | null = null; + private wrappedForWidth = 0; private firstLine = 0; + private bodyLineCount = 14; - constructor(private readonly documentText: string | null) {} + constructor( + private readonly documentText: string, + private readonly title = "Teleprompt", + ) {} paint(ctx: LayerContext): GrayImage { const font = getDefaultSmallFont(); - const image = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0); - image.drawRect(12, 12, G2_LENS_WIDTH - 24, G2_LENS_HEIGHT - 24, 52); - image.drawText(font, MARGIN_X + 4, TITLE_Y, "Teleprompt", 220); + 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.drawRect(12, 12, width - 24, height - 24, 52); + image.drawText(font, MARGIN_X + 4, TITLE_Y, truncateToWidth(font, this.title, width - 2 * MARGIN_X - 8), 220); - if (this.documentText === null) { - const message = [ - "Open a plain text document on your phone and Share it to Faceclaw.", - ]; - for (let index = 0; index < message.length; index++) { - image.drawText(font, BODY_X, BODY_Y + index * LINE_STEP, message[index]!, 200); - } - return image; - } - - const lines = this.getLines(font); - const visibleLines = lines.slice(this.firstLine, this.firstLine + BODY_LINE_COUNT); + 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 / PAGE_STEP) + 1; - const totalPages = totalPageCount(lines.length); - image.drawText(font, BODY_X, FOOTER_Y, `Page ${currentPage}/${totalPages}`, 110); + 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(PAGE_STEP); + this.scrollBy(this.pageStep()); return; case "scroll-up": - this.scrollBy(-PAGE_STEP); + this.scrollBy(-this.pageStep()); return; case "double-click": ctx.stack.pop(); @@ -63,9 +61,13 @@ export class TelepromptLayer implements Layer { } } + private pageStep(): number { + return Math.max(1, this.bodyLineCount - 1); + } + private scrollBy(delta: number): void { const lines = this.lines ?? []; - if (lines.length <= BODY_LINE_COUNT) { + if (lines.length <= this.bodyLineCount) { this.firstLine = 0; return; } @@ -73,25 +75,31 @@ export class TelepromptLayer implements Layer { this.firstLine = Math.max(0, Math.min(maxFirstLine, this.firstLine + delta)); } - private getLines(font: BdfFont): string[] { - if (this.lines === null) { - this.lines = wrapTextForTeleprompt(font, this.documentText ?? ""); + 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; } -} -function wrapTextForTeleprompt(font: BdfFont, text: string): string[] { - const normalized = text.replace(/\t/g, " ").replace(/\r/g, ""); - return wrapText(font, normalized, BODY_WIDTH, { - preserveLeadingWhitespace: true, - breakLongWords: true, - }); -} - -function totalPageCount(lineCount: number): number { - if (lineCount <= BODY_LINE_COUNT) { - return 1; + private totalPageCount(lineCount: number): number { + if (lineCount <= this.bodyLineCount) { + return 1; + } + return Math.ceil((lineCount - this.bodyLineCount) / this.pageStep()) + 1; } - return Math.ceil((lineCount - BODY_LINE_COUNT) / PAGE_STEP) + 1; +} + +function truncateToWidth(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}...`; } diff --git a/app/ui/dashboard.ts b/app/ui/dashboard.ts index 648643bd..fb03cda8 100644 --- a/app/ui/dashboard.ts +++ b/app/ui/dashboard.ts @@ -4,7 +4,6 @@ import { nightscoutBridge } from "../native/nightscout-bridge"; import { getDashboardPlugin, type DashboardPluginCardBounds, type DashboardPluginState } from "./dashboard-plugins"; import { EditTextSettingLayer, isNightscoutSettingsConfigured, type DashboardSlotId, DashboardPluginId, bottomRightSlotSetting, bottomLeftSlotSetting, dashboardSlotIds } from "./dashboard-settings"; import { Layer, LayerActions, LayerStack, type DashboardInputEvent } from "./layers"; -import { TelepromptLayer } from "./apps/teleprompt"; import { drawSystemCard } from "./dashboard/system-card"; import { createRootMenuLayer } from "./dashboard/root-menu"; import { inputEventToString, shell } from "./shell/shell"; @@ -18,13 +17,11 @@ export type DashboardBatteryLevels = { type DashboardState = { logLines: string[]; - telepromptDocumentText: string | null; battery: DashboardBatteryLevels; }; export let dashboardState: DashboardState = { logLines: [] as string[], - telepromptDocumentText: null as string | null, battery: { headset: null, headsetCharging: null, @@ -76,16 +73,6 @@ export function drawDashboard(): GrayImage { return dashboardLayers.paint(); } -export function openTelepromptDocument(text?: string): void { - if (text !== undefined) { - dashboardState.telepromptDocumentText = text; - } - shell.wake("window"); - dashboardLayers.clearToBase(); - dashboardLayers.push(createRootMenuLayer()); - dashboardLayers.push(new TelepromptLayer(dashboardState.telepromptDocumentText)); -} - export function resetDashboardSleepTimerAndWake(nowMs = Date.now()): boolean { if (!shell.wake("sidebar", nowMs)) return false; dashboardLayers.clearToBase(); diff --git a/app/ui/dashboard/root-menu.ts b/app/ui/dashboard/root-menu.ts index ae69d8ba..ce975e2c 100644 --- a/app/ui/dashboard/root-menu.ts +++ b/app/ui/dashboard/root-menu.ts @@ -1,14 +1,11 @@ import { getDefaultSmallFont } from "~/graphics/bdffont"; -import { dashboardState, getPluginIdForSlot, getPluginState, TOP_LEFT_MENU_LAYOUT } from "../dashboard"; +import { getPluginIdForSlot, getPluginState, TOP_LEFT_MENU_LAYOUT } from "../dashboard"; import { getDashboardPlugin, isBlankDashboardPlugin } from "../dashboard-plugins"; import { DashboardSlotId, dashboardSlotIds, isNightscoutSettingsConfigured } from "../dashboard-settings"; import { DashboardInputEvent, LayerContext } from "../layers"; import { MenuLayer } from "../menu"; import { createNightscoutSettingsMenuLayer } from "./settings-menus"; -import { TelepromptLayer } from "../apps/teleprompt"; import { TranscribeLayer } from "../apps/transcribe"; -import { ScreenTestLayer } from "../apps/screen-test"; -import { BuzzerDemoLayer } from "../apps/buzzer-demo"; import { GrayImage } from "~/graphics/image"; import { shell } from "../shell/shell"; @@ -55,12 +52,6 @@ function createAppsMenuLayer(): MenuLayer { return new MenuLayer( "Apps", [ - { - label: "Teleprompt", - onSelect: (ctx) => { - ctx.stack.push(new TelepromptLayer(dashboardState.telepromptDocumentText)); - }, - }, { label: "Transcribe", onSelect: (ctx) => { @@ -69,18 +60,6 @@ function createAppsMenuLayer(): MenuLayer { layer.start(ctx); }, }, - { - label: "Screen test", - onSelect: (ctx) => { - ctx.stack.push(new ScreenTestLayer()); - }, - }, - { - label: "Buzzer demo", - onSelect: (ctx) => { - ctx.stack.push(new BuzzerDemoLayer()); - }, - }, ], TOP_LEFT_MENU_LAYOUT, ); diff --git a/app/ui/shell/chrome-layer.ts b/app/ui/shell/chrome-layer.ts index db20986b..2efaf714 100644 --- a/app/ui/shell/chrome-layer.ts +++ b/app/ui/shell/chrome-layer.ts @@ -1,8 +1,11 @@ import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage } from "../../graphics/image"; -import { getDefaultMediumFont } from "../../graphics/bdffont"; -import { drawBattery } from "../../graphics/battery"; +import { getDefaultMediumFont, getDefaultSmallFont } from "../../graphics/bdffont"; +import { BATTERY_ICON_WIDTH, drawBattery } from "../../graphics/battery"; import { readActiveNotificationIcons } from "../../native/notification-icons"; +import { readPhoneBatteryState } from "../../native/phone-battery"; import { noteStaleDataUsed, renderPassAllowsStaleData } from "../../util/render-freshness"; +import { clamp } from "../../util/numeric-util"; +import { batteryDisplayModeSetting } from "../dashboard-settings"; import { Layer } from "../layers"; import { SHELL_OPAQUE_BLACK, SIDEBAR_WIDTH, TOP_BAR_HEIGHT } from "./geometry"; @@ -26,6 +29,8 @@ export type ShellChromeState = { selectedIndex: number; focus: "sidebar" | "window"; battery: { headset: number | null; headsetCharging: boolean | null }; + /** App-provided tray images, drawn between notification icons and batteries. */ + trayIcons: GrayImage[]; }; /** Reusable placeholder window icon: rounded outline with a single letter. */ @@ -45,6 +50,9 @@ export function makeLetterWindowIcon(letter: string): ShellChromeWindow["drawIco * the color-key shell surface), so the app viewport shows through. */ export class ShellChromeLayer implements Layer { + // First sidebar row shown; adjusted each paint to keep the selection visible. + private scrollRow = 0; + constructor(private readonly getState: () => ShellChromeState) {} paint(): GrayImage { @@ -63,10 +71,25 @@ export class ShellChromeLayer implements Layer { private drawSidebar(image: GrayImage, state: ShellChromeState): void { image.fillRect(0, 0, SIDEBAR_WIDTH, G2_LENS_HEIGHT, SHELL_OPAQUE_BLACK); image.drawLine(SIDEBAR_WIDTH - 1, 0, SIDEBAR_WIDTH - 1, G2_LENS_HEIGHT - 1, BORDER_VALUE); - for (let index = 0; index < state.windows.length; index++) { + + // Scroll the icon list to keep the selection visible; chevrons mark + // windows off-screen above/below. + const listTop = TOP_BAR_HEIGHT + 10; + const itemStride = ICON_SIZE + ICON_SPACING; + const listHeight = G2_LENS_HEIGHT - listTop - 10; + const visibleCount = Math.max(1, ((listHeight + ICON_SPACING) / itemStride) | 0); + const count = state.windows.length; + if (state.selectedIndex < this.scrollRow) { + this.scrollRow = state.selectedIndex; + } else if (state.selectedIndex >= this.scrollRow + visibleCount) { + this.scrollRow = state.selectedIndex - visibleCount + 1; + } + this.scrollRow = clamp(this.scrollRow, 0, Math.max(0, count - visibleCount)); + const lastVisible = Math.min(count, this.scrollRow + visibleCount); + + for (let index = this.scrollRow; index < lastVisible; index++) { const window = state.windows[index]!; - const y = TOP_BAR_HEIGHT + 6 + index * (ICON_SIZE + ICON_SPACING); - if (y + ICON_SIZE > G2_LENS_HEIGHT) break; + const y = listTop + (index - this.scrollRow) * itemStride; if (index === state.selectedIndex) { const highlight = state.focus === "sidebar" ? 200 : 70; image.drawRoundedRect(0, y - 2, SIDEBAR_WIDTH - 3, ICON_SIZE + 4, highlight, 6); @@ -76,6 +99,13 @@ export class ShellChromeLayer implements Layer { image.fillRoundedRect(ICON_MARGIN_X + ICON_SIZE - 7, y - 1, 8, 8, 255, 4); } } + + if (this.scrollRow > 0) { + drawChevron(image, SIDEBAR_WIDTH / 2, TOP_BAR_HEIGHT + 6, -1); + } + if (lastVisible < count) { + drawChevron(image, SIDEBAR_WIDTH / 2, G2_LENS_HEIGHT - 6, 1); + } } private drawTopBar(image: GrayImage, state: ShellChromeState): void { @@ -90,17 +120,11 @@ export class ShellChromeLayer implements Layer { const textY = Math.max(0, ((TOP_BAR_HEIGHT - font.lineHeight) / 2) | 0); image.drawText(font, clockX, textY, clock, 210); - let batteryLeft = G2_LENS_WIDTH; - if (state.battery.headset !== null) { - const battery = drawBattery(state.battery.headset, Boolean(state.battery.headsetCharging)); - batteryLeft = G2_LENS_WIDTH - battery.width - 8; - image.bitBlt(battery, batteryLeft, Math.max(0, ((TOP_BAR_HEIGHT - battery.height) / 2) | 0), { - transparentZero: true, - }); - } + const batteryLeft = this.drawTopBarBatteries(image, state); + const trayLeft = drawTrayIcons(image, state.trayIcons, batteryLeft); const iconsX = clockX + font.measureText(clock) + 16; - const maxIcons = Math.max(0, ((batteryLeft - 8 - iconsX) / (NOTIFICATION_ICON_SIZE + 4)) | 0); + const maxIcons = Math.max(0, ((trayLeft - 8 - iconsX) / (NOTIFICATION_ICON_SIZE + 4)) | 0); if (maxIcons > 0) { const { icons, stale } = readActiveNotificationIcons(maxIcons, renderPassAllowsStaleData()); if (stale) { @@ -114,4 +138,78 @@ export class ShellChromeLayer implements Layer { } } } + + /** + * Labelled battery indicators for the phone and the G2, right-aligned in + * the top bar, following the dashboard card's icon/percentage setting. + * Returns the left edge of the battery block. + */ + private drawTopBarBatteries(image: GrayImage, state: ShellChromeState): number { + const font = getDefaultSmallFont(); + const percentageMode = batteryDisplayModeSetting.get() === "percentage"; + type BatteryItem = { label: string; percent: number; charging: boolean }; + const items: BatteryItem[] = []; + const phone = readPhoneBatteryState(); + if (phone.battery !== null && Number.isFinite(phone.battery)) { + items.push({ label: "Phone", percent: phone.battery, charging: Boolean(phone.charging) }); + } + if (state.battery.headset !== null && Number.isFinite(state.battery.headset)) { + items.push({ label: "G2", percent: state.battery.headset, charging: Boolean(state.battery.headsetCharging) }); + } + if (!items.length) return G2_LENS_WIDTH; + + const labelGap = 5; + const itemGap = 12; + const textY = Math.max(0, ((TOP_BAR_HEIGHT - font.lineHeight) / 2) | 0); + let x = G2_LENS_WIDTH - 8; + for (let index = items.length - 1; index >= 0; index--) { + const item = items[index]!; + const percentText = `${Math.max(0, Math.min(100, Math.round(item.percent)))}%`; + const valueWidth = percentageMode ? font.measureText(percentText) : BATTERY_ICON_WIDTH; + const labelWidth = font.measureText(item.label); + x -= labelWidth + labelGap + valueWidth; + image.drawText(font, x, textY, item.label, 150); + const valueX = x + labelWidth + labelGap; + if (percentageMode) { + if (item.charging) { + // Inverted text marks charging, matching the dashboard card. + image.fillRect(valueX - 2, textY - 1, valueWidth + 4, font.lineHeight + 2, 255); + image.drawText(font, valueX, textY, percentText, 1); + } else { + image.drawText(font, valueX, textY, percentText, 200); + } + } else { + const icon = drawBattery(item.percent, item.charging); + image.bitBlt(icon, valueX, Math.max(0, ((TOP_BAR_HEIGHT - icon.height) / 2) | 0), { + transparentZero: true, + }); + } + x -= itemGap; + } + return x + itemGap; + } +} + +/** + * Draw app tray icons right-to-left, ending just left of the battery block; + * returns the left edge of the tray region. + */ +function drawTrayIcons(image: GrayImage, trayIcons: GrayImage[], rightEdge: number): number { + let x = rightEdge; + for (let index = trayIcons.length - 1; index >= 0; index--) { + const icon = trayIcons[index]!; + x -= icon.width + 10; + image.bitBlt(icon, x, Math.max(0, ((TOP_BAR_HEIGHT - icon.height) / 2) | 0), { + transparentZero: true, + }); + } + return x; +} + +/** Small triangle marker for sidebar overflow; direction -1 = up, 1 = down. */ +function drawChevron(image: GrayImage, centerX: number, y: number, direction: -1 | 1): void { + const half = 5; + const tipY = direction < 0 ? y - 3 : y + 3; + image.drawLine(centerX - half, y, centerX, tipY, 140); + image.drawLine(centerX, tipY, centerX + half, y, 140); } diff --git a/app/ui/shell/debug-tests-app.ts b/app/ui/shell/debug-tests-app.ts new file mode 100644 index 00000000..5e032864 --- /dev/null +++ b/app/ui/shell/debug-tests-app.ts @@ -0,0 +1,54 @@ +import { MenuLayer } from "../menu"; +import { ScreenTestLayer } from "../apps/screen-test"; +import { BuzzerDemoLayer } from "../apps/buzzer-demo"; +import { APP_VIEWPORT } 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()); + }, + }, + ], + { + x: 8, + y: 8, + width: 272, + minHeight: 0, + maxHeight: APP_VIEWPORT.height - 16, + }, + ); + return createInProcessWindow({ + appId: "debug-tests", + windowId: DEBUG_TESTS_WINDOW_ID, + title: "Debug tests", + iconLetter: "Db", + closeable: true, + actions: options.actions, + baseLayer: new YieldAtRootLayer(menu), + submitFrame: options.submitFrame, + setSurfaceVisible: options.setSurfaceVisible, + removeSurface: options.removeSurface, + onClosed: options.onClosed, + }); +} diff --git a/app/ui/shell/in-process-window.ts b/app/ui/shell/in-process-window.ts index 27a04b64..98078332 100644 --- a/app/ui/shell/in-process-window.ts +++ b/app/ui/shell/in-process-window.ts @@ -33,6 +33,15 @@ export type InProcessWindow = { requestRender: () => void; }; +/** The controller-provided plumbing common to every in-process app window. */ +export type InProcessAppOptions = { + actions: LayerActions; + submitFrame: (image: GrayImage, paintMs: number, frameId: number) => Promise; + setSurfaceVisible: (visible: boolean) => void; + removeSurface: () => void; + onClosed: () => void; +}; + export function createInProcessWindow(options: InProcessWindowOptions): InProcessWindow { const requestRender = () => { void render(0).catch((error) => { diff --git a/app/ui/shell/nightscout-app.ts b/app/ui/shell/nightscout-app.ts new file mode 100644 index 00000000..abd649d1 --- /dev/null +++ b/app/ui/shell/nightscout-app.ts @@ -0,0 +1,103 @@ +import { getDefaultSmallFont } from "../../graphics/bdffont"; +import { GrayImage } from "../../graphics/image"; +import { nightscoutBridge, type NightscoutState } from "../../native/nightscout-bridge"; +import { getPluginState } from "../dashboard"; +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", + closeable: true, + actions: options.actions, + baseLayer: new YieldAtRootLayer(new NightscoutLayer(getPluginState)), + 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); + } + } +} diff --git a/app/ui/shell/notifications-app.ts b/app/ui/shell/notifications-app.ts index 654104cb..837b2f3c 100644 --- a/app/ui/shell/notifications-app.ts +++ b/app/ui/shell/notifications-app.ts @@ -1,25 +1,20 @@ -import { GrayImage } from "../../graphics/image"; -import { LayerActions } from "../layers"; import { NotificationsListLayer } from "../notifications"; -import { createInProcessWindow, YieldAtRootLayer, type InProcessWindow } from "./in-process-window"; +import { + createInProcessWindow, + YieldAtRootLayer, + type InProcessAppOptions, + type InProcessWindow, +} from "./in-process-window"; export const NOTIFICATIONS_WINDOW_ID = "notifications"; export const NOTIFICATIONS_SURFACE_ID = "window:notifications"; -export type NotificationsAppOptions = { - actions: LayerActions; - submitFrame: (image: GrayImage, paintMs: number, frameId: number) => Promise; - setSurfaceVisible: (visible: boolean) => void; - removeSurface: () => void; - onClosed: () => void; -}; - /** * 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: NotificationsAppOptions): InProcessWindow { +export function createNotificationsAppWindow(options: InProcessAppOptions): InProcessWindow { return createInProcessWindow({ appId: "notifications", windowId: NOTIFICATIONS_WINDOW_ID, diff --git a/app/ui/shell/shell.ts b/app/ui/shell/shell.ts index 68a52028..7d5338ca 100644 --- a/app/ui/shell/shell.ts +++ b/app/ui/shell/shell.ts @@ -96,6 +96,9 @@ class Shell { private lastInputAtMs = Date.now(); private battery: ShellChromeState["battery"] = { headset: null, headsetCharging: null }; private attention = new Map(); + // App-provided top-bar tray icons, keyed by owner id; drawn between the + // notification icons and the battery indicators. + private readonly trayIcons = new Map(); private activeVoiceLayer: VoiceInputLayer | null = null; private readonly actions: LayerActions = { ...noopActions }; private config: ShellConfig = { @@ -173,6 +176,20 @@ class Shell { this.battery = { ...this.battery, ...levels }; } + /** + * Set or clear an app's top-bar tray icon (a small grayscale image, drawn + * between the notification icons and the battery indicators). Small and + * infrequently updated by design; not a framebuffer. + */ + setTrayIcon(ownerId: string, icon: GrayImage | null): void { + if (icon) { + this.trayIcons.set(ownerId, icon); + } else if (!this.trayIcons.delete(ownerId)) { + return; + } + this.config.requestShellRender(); + } + isScreenOn(): boolean { return this.screenOn; } @@ -400,6 +417,9 @@ class Shell { selectedIndex: this.selectedIndex, focus: this.focus, battery: this.battery, + trayIcons: Array.from(this.trayIcons.keys()) + .sort() + .map((key) => this.trayIcons.get(key)!), }; } } diff --git a/app/ui/shell/teleprompt-app.ts b/app/ui/shell/teleprompt-app.ts new file mode 100644 index 00000000..0fb12bb4 --- /dev/null +++ b/app/ui/shell/teleprompt-app.ts @@ -0,0 +1,109 @@ +import { externalStorageRootPath, readTextFile, type DirectoryEntry } from "../../native/file-access"; +import { FileBrowserLayer } from "../apps/file-browser"; +import { TelepromptLayer } from "../apps/teleprompt"; +import { MenuLayer } from "../menu"; +import { APP_VIEWPORT } from "./geometry"; +import { + createInProcessWindow, + YieldAtRootLayer, + type InProcessAppOptions, + type InProcessWindow, +} from "./in-process-window"; +import { shell } from "./shell"; + +export const TELEPROMPT_WINDOW_ID = "teleprompt"; +export const TELEPROMPT_SURFACE_ID = "window:teleprompt"; + +const SUPPORTED_FILE = /\.(txt|md|log)$/i; + +export type TelepromptBrowserOptions = InProcessAppOptions & { + /** Open a document as its own shell window (also used by the share intent). */ + openDocumentWindow: (title: string, text: string) => void; +}; + +/** + * The Teleprompt app's launcher-opened window: a file browser over external + * storage. Picking a supported (text) file offers viewing it in this window + * or opening it as a new window. + */ +export function createTelepromptBrowserWindow(options: TelepromptBrowserOptions): InProcessWindow { + const browser = new FileBrowserLayer({ + startPath: externalStorageRootPath(), + isSupportedFile: (name) => SUPPORTED_FILE.test(name), + // The browser handles double-click itself (up a directory), so it is not + // wrapped in YieldAtRootLayer; it yields explicitly from the top level. + onLeave: () => shell.yieldFocusToSidebar(), + onFilePicked: (entry, ctx) => { + ctx.stack.push(createFilePickedMenu(entry, options.openDocumentWindow)); + }, + }); + return createInProcessWindow({ + appId: "teleprompt", + windowId: TELEPROMPT_WINDOW_ID, + title: "Teleprompt", + iconLetter: "Tp", + closeable: true, + actions: options.actions, + baseLayer: browser, + submitFrame: options.submitFrame, + setSurfaceVisible: options.setSurfaceVisible, + removeSurface: options.removeSurface, + onClosed: options.onClosed, + }); +} + +/** One opened document as its own window (from the browser or a share intent). */ +export function createTelepromptDocumentWindow( + windowId: string, + title: string, + text: string, + options: InProcessAppOptions, +): InProcessWindow { + return createInProcessWindow({ + appId: "teleprompt", + windowId, + title, + iconLetter: "Tp", + closeable: true, + actions: options.actions, + baseLayer: new YieldAtRootLayer(new TelepromptLayer(text, title)), + submitFrame: options.submitFrame, + setSurfaceVisible: options.setSurfaceVisible, + removeSurface: options.removeSurface, + onClosed: options.onClosed, + }); +} + +function createFilePickedMenu( + entry: DirectoryEntry, + openDocumentWindow: (title: string, text: string) => void, +): MenuLayer { + return new MenuLayer( + entry.name, + [ + { + label: "View here", + onSelect: (ctx) => { + const text = readTextFile(entry.path); + ctx.stack.pop(); + ctx.stack.push(new TelepromptLayer(text ?? "(could not read file)", entry.name)); + }, + }, + { + label: "Open in new window", + onSelect: (ctx) => { + const text = readTextFile(entry.path); + ctx.stack.pop(); + openDocumentWindow(entry.name, text ?? "(could not read file)"); + }, + }, + ], + { + x: 8, + y: 8, + width: 272, + minHeight: 0, + maxHeight: APP_VIEWPORT.height - 16, + }, + ); +} diff --git a/app/ui/shell/worker-window.ts b/app/ui/shell/worker-window.ts index cc260c7a..7f221f90 100644 --- a/app/ui/shell/worker-window.ts +++ b/app/ui/shell/worker-window.ts @@ -1,3 +1,4 @@ +import { GrayImage } from "../../graphics/image"; import { makeLetterWindowIcon } from "./chrome-layer"; import { shell, type ShellWindow } from "./shell"; @@ -26,7 +27,16 @@ export type WorkerAppReply = focus?: boolean; } | { type: "set-title"; windowId: string; title: string } - | { type: "set-attention"; windowId: string; attention: boolean }; + | { type: "set-attention"; windowId: string; attention: boolean } + | { + /** + * Set or clear the app's top-bar tray icon. Pixels ride the JSON + * postMessage roundtrip — acceptable because tray icons are small and + * infrequently updated. + */ + type: "set-tray-icon"; + icon: { width: number; height: number; pixels: number[] } | null; + }; export type WorkerWindowSpec = { /** Unique across the shell; namespace with the appId (e.g. "terminal:view:3"). */ @@ -80,6 +90,15 @@ export class WorkerAppHost { case "set-attention": shell.setWindowAttention(message.windowId, message.attention); break; + case "set-tray-icon": { + let icon: GrayImage | null = null; + if (message.icon) { + icon = new GrayImage(message.icon.width, message.icon.height, 0); + icon.pixels.set(message.icon.pixels.slice(0, icon.pixels.length)); + } + shell.setTrayIcon(this.options.appId, icon); + break; + } case "set-title": // Titles are informational for now (sidebar shows icons only). break;