From 132b90c21dbf8bcb8ae3244d832c4120931bebd6 Mon Sep 17 00:00:00 2001 From: James Babcock Date: Wed, 14 Oct 2026 01:31:10 -0700 Subject: [PATCH] Status bar widgets are selectable --- CHANGELOG | 1 + app/apps/app-definition.ts | 34 ++- app/apps/nightscout/index.ts | 7 +- app/apps/nightscout/nightscout-app.ts | 13 +- app/apps/weather/index.ts | 7 +- app/apps/weather/weather-indicators.ts | 11 +- app/g2/dashboard-controller.ts | 8 +- app/ui/shell/chrome-layer.ts | 145 ++++++++----- app/ui/shell/shell.ts | 283 +++++++++++++++---------- tests/app-layout.test.cjs | 69 +++++- 10 files changed, 383 insertions(+), 195 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 9a4f8afa..da397e0c 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -8,6 +8,7 @@ * T3 Code client: Add options (worktree, host, etc) when creating threads * Add configuration options to the glanceboard system card and music player * Glanceboard compass shows calibration-accuracy indicator +* Status-bar widgets (nightscout, weather) are selectable ### Bug fixes diff --git a/app/apps/app-definition.ts b/app/apps/app-definition.ts index b2e69a01..e586336a 100644 --- a/app/apps/app-definition.ts +++ b/app/apps/app-definition.ts @@ -4,7 +4,7 @@ import { type IconName } from "../graphics/icons"; import { type LayerActions } from "../ui/layers"; import { type InProcessAppOptions, type InProcessWindow } from "../ui/shell/in-process-window"; import { WorkerAppHost } from "../ui/shell/worker-window"; -import { shell } from "../ui/shell/shell"; +import { shell, type TrayWidget } from "../ui/shell/shell"; /** * An app, as seen from outside while it isn't running. Each app directory's @@ -96,6 +96,17 @@ export type AppContext = { surfaceId: string, create: (options: InProcessAppOptions) => InProcessWindow, ) => Promise; + /** + * Open a main-thread singleton window in the background (neither + * foregrounded nor focused) unless it is open already; `opened` says this + * call opened it. For windows the shell brings forward itself, such as an + * app widget's (see inProcessTrayWidget). Hosts that leave it out can't. + */ + openInProcessAppInBackground?: ( + windowId: string, + surfaceId: string, + create: (options: InProcessAppOptions) => InProcessWindow, + ) => { window: InProcessWindow; opened: boolean }; /** Get this app's shared worker host, spawning the worker on first use. */ ensureWorkerHost: (createWorker: () => Worker) => WorkerAppHost; /** Submit a window surface's painted frame, as planes (windows created outside launchInProcessApp). */ @@ -120,6 +131,27 @@ export type TextEditorHost = { requestRender: () => void; }; +/** + * A tray widget (see Shell.setTrayIcon) whose window is a main-thread + * singleton app window, opened in the background while the switcher's + * selection is on it; undefined on hosts that can't do that. + */ +export function inProcessTrayWidget( + ctx: AppContext, + windowId: string, + surfaceId: string, + create: (options: InProcessAppOptions) => InProcessWindow, +): TrayWidget | undefined { + const open = ctx.openInProcessAppInBackground; + if (!open) return undefined; + return { + openWindow: () => { + const { window, opened } = open(windowId, surfaceId, create); + return { window: window.window, opened }; + }, + }; +} + /** * Launch-or-focus flow shared by the worker-hosted apps: focus the app's * existing window if one is open, otherwise open a window in the app's shared diff --git a/app/apps/nightscout/index.ts b/app/apps/nightscout/index.ts index 6f5f59ad..3d30251c 100644 --- a/app/apps/nightscout/index.ts +++ b/app/apps/nightscout/index.ts @@ -1,11 +1,14 @@ -import { type AppDefinition } from "../app-definition"; +import { inProcessTrayWidget, type AppDefinition } from "../app-definition"; import { createNightscoutAppWindow, startNightscoutTrayIcon, NIGHTSCOUT_SURFACE_ID, NIGHTSCOUT_WINDOW_ID } from "./nightscout-app"; const nightscoutApp: AppDefinition = { appId: "nightscout", title: "Nightscout", icon: "nightscout", - boot: () => startNightscoutTrayIcon(), + // Selected in the switcher, the tray readout shows the app's window. + boot: (ctx) => startNightscoutTrayIcon( + inProcessTrayWidget(ctx, NIGHTSCOUT_WINDOW_ID, NIGHTSCOUT_SURFACE_ID, createNightscoutAppWindow), + ), launch: (ctx) => ctx.launchInProcessApp(NIGHTSCOUT_WINDOW_ID, NIGHTSCOUT_SURFACE_ID, createNightscoutAppWindow), }; diff --git a/app/apps/nightscout/nightscout-app.ts b/app/apps/nightscout/nightscout-app.ts index 2f6c536e..6458541a 100644 --- a/app/apps/nightscout/nightscout-app.ts +++ b/app/apps/nightscout/nightscout-app.ts @@ -10,7 +10,7 @@ import { } from "../../ui/shell/in-process-window"; import { evaluateNightscoutAlerts } from "./nightscout-alerts"; import { loadNightscoutThresholds, nightscoutAlwaysShowInTopBarSetting, onAnySettingChanged } from "../../ui/dashboard-settings"; -import { shell } from "../../ui/shell/shell"; +import { shell, type TrayWidget } from "../../ui/shell/shell"; export const NIGHTSCOUT_WINDOW_ID = "nightscout"; export const NIGHTSCOUT_SURFACE_ID = "window:nightscout"; @@ -23,11 +23,12 @@ const TRAY_GRAPH_WINDOW_MS = 2 * 60 * 60 * 1000; const windowRenders = new Set<() => void>(); let trayStarted = false; +let trayWidget: TrayWidget | undefined; let trayTick: ReturnType | null = null; function syncNightscout(): void { const visible = windowRenders.size > 0 || nightscoutAlwaysShowInTopBarSetting.get(); - shell.setTrayIcon(TRAY_ICON_ID, visible ? buildNightscoutTrayIcon(nightscoutBridge.snapshot()) : null); + shell.setTrayIcon(TRAY_ICON_ID, visible ? buildNightscoutTrayIcon(nightscoutBridge.snapshot()) : null, trayWidget); for (const render of windowRenders) render(); // Age warnings and stale glucose must advance even during a stalled fetch. if (visible && trayTick === null) trayTick = setInterval(syncNightscout, 60_000); @@ -37,8 +38,12 @@ function syncNightscout(): void { } } -/** Shell-lifetime subscription so the tray can be enabled before any window opens. */ -export function startNightscoutTrayIcon(): void { +/** + * Shell-lifetime subscription so the tray can be enabled before any window + * opens; `widget` makes it selectable in the switcher. + */ +export function startNightscoutTrayIcon(widget?: TrayWidget): void { + trayWidget ??= widget; if (trayStarted) return; trayStarted = true; nightscoutBridge.onStateChange(syncNightscout); diff --git a/app/apps/weather/index.ts b/app/apps/weather/index.ts index 73f12e7d..50410ce6 100644 --- a/app/apps/weather/index.ts +++ b/app/apps/weather/index.ts @@ -1,4 +1,4 @@ -import { type AppDefinition } from "../app-definition"; +import { inProcessTrayWidget, type AppDefinition } from "../app-definition"; import { createWeatherAppWindow, WEATHER_SURFACE_ID, WEATHER_WINDOW_ID } from "./weather-app"; import { startWeatherIndicators } from "./weather-indicators"; @@ -6,7 +6,10 @@ const weatherApp: AppDefinition = { appId: "weather", title: "Weather", icon: "cloud-sun", - boot: () => startWeatherIndicators(), + // Selected in the switcher, the status-bar indicator shows the app's window. + boot: (ctx) => startWeatherIndicators( + inProcessTrayWidget(ctx, WEATHER_WINDOW_ID, WEATHER_SURFACE_ID, createWeatherAppWindow), + ), launch: (ctx) => ctx.launchInProcessApp(WEATHER_WINDOW_ID, WEATHER_SURFACE_ID, createWeatherAppWindow), }; diff --git a/app/apps/weather/weather-indicators.ts b/app/apps/weather/weather-indicators.ts index 109f65ee..0e2be397 100644 --- a/app/apps/weather/weather-indicators.ts +++ b/app/apps/weather/weather-indicators.ts @@ -2,7 +2,7 @@ import { GrayImage, type UiFont } from "../../graphics/image"; import { getDefaultSmallFont } from "../../graphics/ui-fonts"; import { weatherBridge } from "../../native/weather"; import { onAnySettingChanged } from "../../ui/dashboard-settings"; -import { shell } from "../../ui/shell/shell"; +import { shell, type TrayWidget } from "../../ui/shell/shell"; import { isSystemCardWidgetInUse } from "../glanceboard/configuration"; import { drawWeatherReading, measureWeatherReading, weatherReading, type WeatherReading } from "./weather-icons"; import { weatherShowInStatusBarSetting, weatherShowOnSystemCardSetting } from "./weather-settings"; @@ -12,6 +12,7 @@ const TRAY_HEIGHT = 24; const TRAY_ICON_SIZE = 20; let started = false; +let trayWidget: TrayWidget | undefined; /** What the tray currently shows, to skip rebuilding an unchanged icon. */ let trayShown: { key: string; font: UiFont } | null = null; @@ -19,11 +20,13 @@ let trayShown: { key: string; font: UiFont } | null = null; * Shell-lifetime subscription: keeps the hourly background refresh running * while the status-bar indicator is enabled, or the system-card one is and * the system card is on an enabled Glanceboard, and the tray icon in sync. - * The system card reads the bridge itself while it shows. + * The system card reads the bridge itself while it shows. `widget` makes + * the tray icon selectable in the switcher. */ -export function startWeatherIndicators(): void { +export function startWeatherIndicators(widget?: TrayWidget): void { if (started) return; started = true; + trayWidget = widget; weatherBridge.onStateChange(syncWeatherIndicators); onAnySettingChanged(syncWeatherIndicators); } @@ -37,7 +40,7 @@ function syncWeatherIndicators(): void { const key = reading ? `${reading.condition}|${reading.isDaytime}|${reading.temperature}` : null; if (key === (trayShown?.key ?? null) && (!trayShown || trayShown.font === font)) return; trayShown = key === null ? null : { key, font }; - shell.setTrayIcon(TRAY_ICON_ID, reading ? buildWeatherTrayIcon(reading, font) : null); + shell.setTrayIcon(TRAY_ICON_ID, reading ? buildWeatherTrayIcon(reading, font) : null, trayWidget); } /** Condition icon and temperature, baked to a raster so the tray keeps one stable image. */ diff --git a/app/g2/dashboard-controller.ts b/app/g2/dashboard-controller.ts index ec80503f..49e0ac8d 100644 --- a/app/g2/dashboard-controller.ts +++ b/app/g2/dashboard-controller.ts @@ -1974,8 +1974,8 @@ class DashboardController { const foreground = shell.foregroundWindow(); const stripShown = sidebarStripVisible(shell.getFocus(), foreground?.appId); this.appendLog(`mirror tap at ${x},${y}`); - if (!shell.hasOverlay() && shell.focusNotificationAt(x, y)) { - this.appendLog("mirror tap: notification icon"); + if (!shell.hasOverlay() && shell.focusStatusItemAt(x, y)) { + this.appendLog("mirror tap: status bar item"); this.requestShellRender(); return; } @@ -2397,7 +2397,7 @@ class DashboardController { * An in-process singleton app's window, opened in the background (neither * foregrounded nor focused) unless it is open already: for the shell to * bring forward itself (the Notifications window under a notification - * selected in the switcher). The bridge runs calls in order, so the + * selected in the switcher, or an app widget's window under the widget). The bridge runs calls in order, so the * shell may foreground it at once: its surface's visibility is settled * when the configure call is queued, ahead of any frame. */ @@ -2486,6 +2486,8 @@ class DashboardController { launchApp: (appId, params) => this.launchApp(appId, params), uninstallApp: (appId) => this.uninstallApp(appId), launchInProcessApp: (windowId, surfaceId, create) => this.launchInProcessApp(windowId, surfaceId, create), + openInProcessAppInBackground: (windowId, surfaceId, create) => + this.openInProcessAppInBackground(windowId, surfaceId, create), ensureWorkerHost: (createWorker) => this.ensureWorkerHost(app.appId, createWorker), submitWindowFrame: (surfaceId, planes, paintMs, frameId) => this.submitWindowFrame(surfaceId, planes, paintMs, frameId), diff --git a/app/ui/shell/chrome-layer.ts b/app/ui/shell/chrome-layer.ts index c7c85179..f7e5f723 100644 --- a/app/ui/shell/chrome-layer.ts +++ b/app/ui/shell/chrome-layer.ts @@ -432,7 +432,8 @@ function statusBarPlacement(state: ShellChromeState): StatusBarPlacement | null const NOTIFICATION_ICON_SIZE = 24; const NOTIFICATION_ICON_STEP = NOTIFICATION_ICON_SIZE + 4; -// Notification icons' top, in the top bar's layout. +// Notification icons' top, in the top bar's layout (where any status icon's +// selection box starts, a row above). const NOTIFICATION_ICON_TOP = ((TOP_BAR_HEIGHT - NOTIFICATION_ICON_SIZE) / 2) | 0; // The box round a selected notification icon: clear of it by 2px either // side, and by 1px above and below, all a top bar leaves above its divider. @@ -448,15 +449,31 @@ export type ShellChromeWindow = { drawIcon: (image: GrayImage, x: number, y: number, size: number, inverted?: boolean) => void; }; +/** + * A status bar item the app switcher's selection can move onto (see + * Shell.moveSelection): a notification's icon, by notification key, or an + * app widget (a tray icon), by its owner's id. + */ +export type StatusItem = { kind: "notification" | "widget"; key: string }; + +/** Whether two status bar items are the same one. */ +export function sameStatusItem(a: StatusItem | null | undefined, b: StatusItem | null | undefined): boolean { + return !!a && !!b && a.kind === b.kind && a.key === b.key; +} + +/** An app's tray icon, by its owner's id (see Shell.setTrayIcon). */ +export type ShellChromeTrayIcon = { ownerId: string; icon: GrayImage }; + export type ShellChromeState = { windows: ShellChromeWindow[]; - /** The selected window's index, or -1 while the selection is on a notification. */ + /** The selected window's index, or -1 while the selection is on a status bar item. */ selectedIndex: number; /** - * The notification (by key) whose icon the switcher's selection is on - * instead of a window, if any (see Shell.moveSelection). + * The status bar item (a notification's icon or an app widget) the + * switcher's selection is on instead of a window, if any (see + * Shell.moveSelection). */ - selectedNotificationKey?: string | null; + selectedStatusItem?: StatusItem | null; focus: "sidebar" | "window"; /** Height mode of the foreground window; decides where its top bar sits. */ foregroundHeightMode: WindowHeightMode; @@ -471,7 +488,7 @@ export type ShellChromeState = { watchCharging: boolean | null; }; /** App-provided tray images, drawn between notification icons and batteries. */ - trayIcons: GrayImage[]; + trayIcons: ShellChromeTrayIcon[]; }; /** Placeholder window icon: rounded outline with a single letter. */ @@ -493,15 +510,17 @@ export function makeLetterWindowIcon(letter: string): ShellChromeWindow["drawIco * (1) rather than 0, since 0 is the surface's transparent color key. Memoized * per source object so the variant is a stable image the texture cache can * key on (mode-13's inverse LUT can't reproduce this mapping exactly, so it - * is simply a separate cached image). + * is simply a separate cached image). Deferred draws (an app widget's text) + * are baked in first, to be inverted with the rest. */ const invertedIconCache = new WeakMap(); function invertedIcon(icon: GrayImage): GrayImage { let inverted = invertedIconCache.get(icon); if (!inverted) { + const flat = icon.withDrawsBaked(); inverted = new GrayImage(icon.width, icon.height, 0); - for (let i = 0; i < icon.pixels.length; i++) { - const coverage = icon.pixels[i]!; + for (let i = 0; i < flat.pixels.length; i++) { + const coverage = flat.pixels[i]!; if (coverage > 0) { inverted.pixels[i] = Math.max(SHELL_OPAQUE_BLACK, 255 - coverage); } @@ -559,9 +578,9 @@ export class ShellChromeLayer implements Layer { // Whether the last paint's selection tab carries the window frame's left // side down, so the frame's bottom-left corner is square. private frameCornerSquare = false; - // The notification icons the last paint drew, left to right: what the - // switcher's selection can move onto, and mirror touches hit. - private notificationEntries: NotificationEntry[] = []; + // The status bar icons (notifications' and app widgets') the last paint + // drew: what the switcher's selection can move onto, and mirror touches hit. + private statusEntries: StatusEntry[] = []; /** * `onBottomBarHeightChanged` is called, during a paint, when the bottom @@ -576,7 +595,7 @@ export class ShellChromeLayer implements Layer { paint(): GrayImage { const image = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0); const state = this.getState(); - this.notificationEntries = []; + this.statusEntries = []; this.bottomBar = this.layoutBottomBar(state); const statusInRow = statusInSwitcherRow(state.foregroundAppId); const popup = switcherPosition() === "popup"; @@ -598,7 +617,7 @@ export class ShellChromeLayer implements Layer { paintParts(): Plane[] { const state = this.getState(), parts: Plane[] = []; - this.notificationEntries = []; + this.statusEntries = []; this.bottomBar = this.layoutBottomBar(state); const statusInRow = statusInSwitcherRow(state.foregroundAppId); const canvas = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0); @@ -693,15 +712,19 @@ export class ShellChromeLayer implements Layer { return null; } - /** Keys of the notifications whose icons the last paint drew, left to right. */ - notificationKeys(): string[] { - return this.notificationEntries.map((entry) => entry.key); + /** + * The status bar items whose icons the last paint drew, in reading order: + * left to right, then a second row's. Notifications come before app + * widgets wherever the status bar is. + */ + statusItems(): StatusItem[] { + return [...this.statusEntries].sort((a, b) => a.y - b.y || a.x - b.x).map(({ kind, key }) => ({ kind, key })); } - /** Which notification's icon is under (x, y) on screen, if any (mirror touches). */ - notificationKeyAt(x: number, y: number): string | null { - const entry = this.notificationEntries.find((e) => x >= e.x && x < e.x + e.width && y >= e.y && y < e.y + e.height); - return entry?.key ?? null; + /** Which status bar item's icon is under (x, y) on screen, if any (mirror touches). */ + statusItemAt(x: number, y: number): StatusItem | null { + const entry = this.statusEntries.find((e) => x >= e.x && x < e.x + e.width && y >= e.y && y < e.y + e.height); + return entry ? { kind: entry.kind, key: entry.key } : null; } /** @@ -830,10 +853,10 @@ export class ShellChromeLayer implements Layer { } icons.forEach((icon, index) => items.push({ kind: "notification", width: NOTIFICATION_ICON_SIZE, - draw: (image, x, top) => this.drawNotificationIcon(image, state, icon, keys[index], x, top + NOTIFICATION_ICON_TOP), + draw: (image, x, top) => this.drawStatusIcon(image, state, notificationItem(keys[index]), icon, x, top), })); - for (const icon of state.trayIcons) { - items.push({ kind: "tray", width: icon.width, draw: (image, x, top) => drawTrayIcon(image, icon, x, top) }); + for (const tray of state.trayIcons) { + items.push({ kind: "tray", width: tray.icon.width, draw: (image, x, top) => this.drawTrayIcon(image, state, tray, x, top) }); } const batteries = batteryItems(state); if (batteries.length) { @@ -945,7 +968,7 @@ export class ShellChromeLayer implements Layer { image.drawText(font, clockX, textY, clock, 210); const batteryLeft = drawBatteryBlock(image, batteryItems(state), barTop, barRight); - const trayLeft = drawTrayIcons(image, state.trayIcons, batteryLeft, barTop); + const trayLeft = this.drawTrayIcons(image, state, batteryLeft, barTop); const iconsX = clockX + Math.ceil(font.measureText(clock)) + 16; const maxIcons = Math.max(0, ((trayLeft - NOTIFICATIONS_GAP - iconsX) / NOTIFICATION_ICON_STEP) | 0); @@ -955,25 +978,47 @@ export class ShellChromeLayer implements Layer { noteStaleDataUsed(); } for (let index = 0; index < icons.length; index++) { - this.drawNotificationIcon(image, state, icons[index]!, keys[index], iconsX + index * NOTIFICATION_ICON_STEP, barTop + NOTIFICATION_ICON_TOP); + this.drawStatusIcon(image, state, notificationItem(keys[index]), icons[index]!, iconsX + index * NOTIFICATION_ICON_STEP, barTop); } } } /** - * Draw a notification icon at (x, iconY), noting it as a notification - * entry. The one the switcher's selection is on - * (state.selectedNotificationKey) sits in a rounded box like a sidebar - * overflow icon's: filled, with the icon inverted, while the switcher has - * focus, and outlined while its detail view in the foreground window has. + * Draw app tray icons right-to-left, ending just left of the battery + * block; returns the left edge of the tray region. */ - private drawNotificationIcon(image: GrayImage, state: ShellChromeState, icon: GrayImage, key: string | undefined, x: number, iconY: number): void { + private drawTrayIcons(image: GrayImage, state: ShellChromeState, rightEdge: number, barTop: number): number { + let x = rightEdge; + for (let index = state.trayIcons.length - 1; index >= 0; index--) { + const tray = state.trayIcons[index]!; + x -= tray.icon.width + TRAY_ICON_GAP; + this.drawTrayIcon(image, state, tray, x, barTop); + } + return x; + } + + /** Draw an app tray icon (an app widget's) with its left edge at x, as drawStatusIcon does. */ + private drawTrayIcon(image: GrayImage, state: ShellChromeState, tray: ShellChromeTrayIcon, x: number, barTop: number): void { + this.drawStatusIcon(image, state, { kind: "widget", key: tray.ownerId }, tray.icon, x, barTop); + } + + /** + * Draw a status bar item's icon with its left edge at x, centred in the + * top bar's layout from `barTop`, noting it as a status entry (unless + * `item` is null). The one the switcher's selection is on + * (state.selectedStatusItem) sits in a rounded box like a sidebar + * overflow icon's: filled, with the icon inverted, while the switcher has + * focus, and outlined while its window has. The box is a notification + * icon's height whatever the icon's, clear of the top bar's divider. + */ + private drawStatusIcon(image: GrayImage, state: ShellChromeState, item: StatusItem | null, icon: GrayImage, x: number, barTop: number): void { + const iconY = barTop + Math.max(0, ((TOP_BAR_HEIGHT - icon.height) / 2) | 0); const box = { - x: x - NOTIFICATION_BOX_MARGIN_X, y: iconY - NOTIFICATION_BOX_MARGIN_Y, - width: NOTIFICATION_ICON_SIZE + 2 * NOTIFICATION_BOX_MARGIN_X, height: NOTIFICATION_ICON_SIZE + 2 * NOTIFICATION_BOX_MARGIN_Y, + x: x - NOTIFICATION_BOX_MARGIN_X, y: barTop + NOTIFICATION_ICON_TOP - NOTIFICATION_BOX_MARGIN_Y, + width: icon.width + 2 * NOTIFICATION_BOX_MARGIN_X, height: NOTIFICATION_ICON_SIZE + 2 * NOTIFICATION_BOX_MARGIN_Y, }; - if (key) this.notificationEntries.push({ key, ...box }); - const selected = !!key && key === state.selectedNotificationKey; + if (item) this.statusEntries.push({ ...item, ...box }); + const selected = sameStatusItem(item, state.selectedStatusItem); const focused = selected && state.focus === "sidebar"; if (selected) drawSelectionBox(image, box.x, box.y, box.width, box.height, focused); image.drawImage(focused ? invertedIcon(icon) : icon, x, iconY); @@ -1192,25 +1237,6 @@ function drawAmbientCards(image: GrayImage, right: number, parts?: Plane[]): voi } } -/** - * 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, barTop: number): number { - let x = rightEdge; - for (let index = trayIcons.length - 1; index >= 0; index--) { - const icon = trayIcons[index]!; - x -= icon.width + TRAY_ICON_GAP; - drawTrayIcon(image, icon, x, barTop); - } - return x; -} - -/** An app tray icon with its left edge at x, centred in the top bar's layout from `barTop`. */ -function drawTrayIcon(image: GrayImage, icon: GrayImage, x: number, barTop: number): void { - image.drawImage(icon, x, barTop + Math.max(0, ((TOP_BAR_HEIGHT - icon.height) / 2) | 0)); -} - /** The sidebar attention marker, cached per fill value (deferred-image source). */ const attentionDots = new Map(); function attentionDot(value: number): GrayImage { @@ -1225,8 +1251,13 @@ function attentionDot(value: number): GrayImage { type Rect = { x: number; y: number; width: number; height: number }; -/** A notification icon as drawn: its notification's key, and its selection box. */ -type NotificationEntry = Rect & { key: string }; +/** A status bar item's icon as drawn: the item, and its selection box. */ +type StatusEntry = Rect & StatusItem; + +/** A notification's status item, if its icon came with a key. */ +function notificationItem(key: string | undefined): StatusItem | null { + return key ? { kind: "notification", key } : null; +} /** Corner radius of the foreground window's frame. */ const FRAME_RADIUS = 8; diff --git a/app/ui/shell/shell.ts b/app/ui/shell/shell.ts index 38447cd9..5285ce5b 100644 --- a/app/ui/shell/shell.ts +++ b/app/ui/shell/shell.ts @@ -48,7 +48,14 @@ import { windowBorderSetting, } from "../dashboard-settings"; import { onAmbientCardsChanged } from "./ambient-cards"; -import { ShellChromeLayer, sidebarContentSpan, type ShellChromeState, type ShellChromeWindow } from "./chrome-layer"; +import { + sameStatusItem, + ShellChromeLayer, + sidebarContentSpan, + type ShellChromeState, + type ShellChromeWindow, + type StatusItem, +} from "./chrome-layer"; import { ShellModalLayer } from "./modal-layer"; import { NotificationModalQueue } from "./notification-modal-queue"; import { ALL_NOTIFICATIONS, readActiveNotifications } from "../../native/notification-icons"; @@ -218,21 +225,38 @@ export type ShellConfig = { }; /** - * The app switcher's selection while it is on a notification's icon rather - * than a window's (bottom switcher only; see Shell.moveSelection). The - * Notifications app's window is the foreground window meanwhile, with the - * notification's detail view on top of its stack. + * What makes an app's tray icon (see Shell.setTrayIcon) a widget the app + * switcher's selection can move onto, as it can onto a notification's icon + * (bottom switcher only; see Shell.moveSelection). */ -type NotificationSelection = { - key: string; - /** Where the notification's icon sat among them, for once it has gone. */ - index: number; - host: InProcessWindow; - layer: SingleNotificationLayer; +export type TrayWidget = { /** - * The Notifications window was opened for the selection: it has no - * switcher icon of its own, and closes once the selection moves off the - * notifications. + * The window to show while the selection is on the widget, opened in the + * background (neither foregrounded nor focused) unless it is open + * already; `opened` says this call opened it, and the shell closes it + * again once the selection moves on. Null when it can't be opened. + */ + openWindow: () => { window: ShellWindow; opened: boolean } | null; +}; + +/** + * The app switcher's selection while it is on a status bar item rather than + * a window's icon (bottom switcher only; see Shell.moveSelection): a + * notification's icon or an app widget. The item's window is the + * foreground window meanwhile: a notification's is the Notifications app's, + * with the notification's detail view on top of its stack; a widget's is + * whatever window it gives (TrayWidget.openWindow). + */ +type StatusSelection = { + item: StatusItem; + /** Where the item sat among the selectable ones, for once it has gone. */ + index: number; + host: ShellWindow; + /** A notification's detail view, and the host's stack it is on. */ + detail: { stack: LayerStack; layer: SingleNotificationLayer } | null; + /** + * The host window was opened for the selection: it has no switcher icon + * of its own, and closes once the selection moves off it. */ transient: boolean; /** The window selected before, to go back to when the screen sleeps. */ @@ -403,11 +427,11 @@ class Shell { }; private readonly batteryListeners = new Set<() => void>(); private attention = new Map(); - /** Set while the switcher's selection is on a notification (see NotificationSelection). */ - private selectedNotification: NotificationSelection | null = null; + /** Set while the switcher's selection is on a status bar item (see StatusSelection). */ + private selectedStatus: StatusSelection | null = null; // 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 readonly trayIcons = new Map(); private activeVoiceLayer: VoiceInputLayer | null = null; private activeKeyboardLayer: KeyboardInputLayer | null = null; private readonly notificationModals = new NotificationModalQueue({ @@ -548,9 +572,9 @@ class Shell { removeWindow(windowId: string): void { const index = this.windows.findIndex((w) => w.windowId === windowId); if (index < 0) return; - // Closing the Notifications window under a selected notification (from - // the system menu) takes the selection with it. - if (this.selectedNotification?.host.window.windowId === windowId) this.selectedNotification = null; + // Closing the window under a selected status bar item (from the system + // menu) takes the selection with it. + if (this.selectedStatus?.host.windowId === windowId) this.selectedStatus = null; const wasSelected = index === this.selectedIndex; this.windows.splice(index, 1); this.attention.delete(windowId); @@ -626,14 +650,20 @@ class Shell { /** * 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. + * infrequently updated by design; not a framebuffer. With `widget`, the + * switcher's selection can move onto it. A widget that goes, or stops + * being one, while the selection is on it leaves the selection on its + * window, as an ordinary window. */ - setTrayIcon(ownerId: string, icon: GrayImage | null): void { + setTrayIcon(ownerId: string, icon: GrayImage | null, widget?: TrayWidget): void { if (icon) { - this.trayIcons.set(ownerId, icon); + this.trayIcons.set(ownerId, { icon, widget }); } else if (!this.trayIcons.delete(ownerId)) { return; } + if ((!icon || !widget) && sameStatusItem(this.selectedStatus?.item, { kind: "widget", key: ownerId })) { + this.endStatusSelection(true); + } this.config.requestShellRender(); } @@ -678,16 +708,19 @@ class Shell { } /** - * A touch from the phone's mirror on a selectable notification's icon: - * select it and go into its detail view, as a touch on a window's icon - * focuses that window. False when there is no such icon at (x, y). + * A touch from the phone's mirror on a selectable status bar item's icon + * (a notification's or an app widget's): select it and go into its + * window, as a touch on a window's icon focuses that window. False when + * there is no such icon at (x, y). */ - focusNotificationAt(x: number, y: number): boolean { - const keys = this.selectableNotificationKeys(); - const key = this.chrome.notificationKeyAt(x, y); - if (!key || !keys.includes(key)) return false; - this.selectNotification(key, keys.indexOf(key)); - const host = this.selectedNotification?.key === key ? this.selectedNotification.host.window : null; + focusStatusItemAt(x: number, y: number): boolean { + const items = this.selectableStatusItems(); + const touched = this.chrome.statusItemAt(x, y); + const index = items.findIndex((item) => sameStatusItem(item, touched)); + if (index < 0) return false; + this.selectStatusItem(items[index]!, index); + const selected = this.selectedStatus; + const host = selected && sameStatusItem(selected.item, touched) ? selected.host : null; if (!host) return false; const alreadyFocused = this.isFocusTarget(host); this.focus = "window"; @@ -755,11 +788,11 @@ class Shell { /** * Turn the screen off, closing any shell overlays. Sidebar selection is - * kept, except that one on a notification goes back to its window. + * kept, except that one on a status bar item goes back to its window. */ sleep(): void { if (!this.screenOn) return; - this.returnFromNotification(); + this.returnFromStatusItem(); this.cancelEscapeMenuTimer(); this.screenOn = false; this.stack.clearToBase(); @@ -777,9 +810,9 @@ class Shell { const target = this.windows[index]; const alreadyFocused = this.isFocusTarget(target); this.setSelectedIndex(index); - // Asked for by id, the Notifications window stays, whether or not it - // was opened for a selected notification. - this.endNotificationSelection(target === this.selectedNotification?.host.window); + // Asked for by id, a status bar item's window stays, whether or not it + // was opened for the selection. + this.endStatusSelection(target === this.selectedStatus?.host); this.focus = "window"; if (!alreadyFocused) target?.onFocus?.(this.lastInput); this.syncInputFocus(); @@ -1164,115 +1197,143 @@ class Shell { /** * Step the switcher's selection through the windows and then, with a - * bottom switcher, on through the notifications whose icons are showing, - * wrapping round at either end. + * bottom switcher, on through the status bar's selectable items whose + * icons are showing (notifications, then app widgets), wrapping round at + * either end. */ private moveSelection(delta: number): void { const windows = this.switcherWindows(); - const keys = this.selectableNotificationKeys(); - const count = windows.length + keys.length; + const items = this.selectableStatusItems(); + const count = windows.length + items.length; if (!count) return; let current = this.selectedIndex; - const selected = this.selectedNotification; + const selected = this.selectedStatus; if (selected) { - // Once its notification has gone, the selection stands between the + // Once its item has gone, the selection stands between the // neighbours it left. - const at = keys.indexOf(selected.key); - current = windows.length + (at >= 0 ? at : Math.min(selected.index, keys.length) - (delta > 0 ? 1 : 0)); + const at = items.findIndex((item) => sameStatusItem(item, selected.item)); + current = windows.length + (at >= 0 ? at : Math.min(selected.index, items.length) - (delta > 0 ? 1 : 0)); } const next = (((current + delta) % count) + count) % count; if (next < windows.length) { this.selectSwitcherWindow(windows[next]!); } else { - this.selectNotification(keys[next - windows.length]!, next - windows.length); + this.selectStatusItem(items[next - windows.length]!, next - windows.length); } } /** - * Windows with an icon in the switcher: all of them, except a - * Notifications window opened just to show a selected notification. + * Windows with an icon in the switcher: all of them, except a window + * opened just to show a selected status bar item. */ private switcherWindows(): ShellWindow[] { - const hidden = this.selectedNotification?.transient ? this.selectedNotification.host.window : null; + const hidden = this.selectedStatus?.transient ? this.selectedStatus.host : null; return hidden ? this.windows.filter((window) => window !== hidden) : this.windows; } /** - * Keys of the notifications the switcher's selection can move onto, left - * to right: those whose icons are showing, with a bottom switcher (the - * selection reaches them past the last window). + * The status bar items the switcher's selection can move onto, in order: + * with a bottom switcher (the selection reaches them past the last + * window), those whose icons are showing that have a window to show, + * which notifications have where the host gives the Notifications window, + * and app widgets always do. */ - private selectableNotificationKeys(): string[] { - return this.config.openNotificationsWindow && switcherPosition() === "bottom" ? this.chrome.notificationKeys() : []; + private selectableStatusItems(): StatusItem[] { + if (switcherPosition() !== "bottom") return []; + return this.chrome.statusItems().filter((item) => item.kind === "notification" + ? !!this.config.openNotificationsWindow + : !!this.trayIcons.get(item.key)?.widget); } - /** Move the switcher's selection onto a window, off a notification if it was on one. */ + /** Move the switcher's selection onto a window, off a status bar item if it was on one. */ private selectSwitcherWindow(window: ShellWindow): void { - // Foreground first, so a Notifications window closing with the - // notification selection can't hand the foreground elsewhere first. + // Foreground first, so a status bar item's window closing with its + // selection can't hand the foreground elsewhere first. this.setSelectedIndex(this.windows.indexOf(window)); - this.endNotificationSelection(window === this.selectedNotification?.host.window); + this.endStatusSelection(window === this.selectedStatus?.host); } /** - * Move the switcher's selection onto a notification: the Notifications - * window (opened in the background first, if need be) comes to the - * foreground showing its detail view. + * Move the switcher's selection onto a status bar item: its window + * (opened in the background first, if need be) comes to the foreground, + * a notification's showing its detail view. The window the selection was + * on before is left as endStatusSelection leaves it, unless it is this + * one too. */ - private selectNotification(key: string, index: number): void { - const selected = this.selectedNotification; - if (selected) { - selected.index = index; - if (selected.key === key) return; - selected.host.stack.popThrough(selected.layer); - selected.key = key; - selected.layer = this.notificationDetailLayer(key); - selected.host.stack.push(selected.layer); - selected.host.requestRender(); + private selectStatusItem(item: StatusItem, index: number): void { + const previous = this.selectedStatus; + if (previous && sameStatusItem(previous.item, item)) { + previous.index = index; return; } - const returnWindowId = this.foregroundWindow()?.windowId ?? null; - const opened = this.config.openNotificationsWindow?.(); - const hostIndex = opened ? this.windows.indexOf(opened.window.window) : -1; + const returnWindowId = previous ? previous.returnWindowId : (this.foregroundWindow()?.windowId ?? null); + const opened = this.openStatusItemWindow(item); + const hostIndex = opened ? this.windows.indexOf(opened.window) : -1; if (!opened || hostIndex < 0) return; const host = opened.window; - const layer = this.notificationDetailLayer(key); - host.stack.push(layer); - this.selectedNotification = { key, index, host, layer, transient: opened.opened, returnWindowId }; + const sameHost = previous?.host === host; + if (sameHost && previous.detail) previous.detail.stack.popThrough(previous.detail.layer); + const detail = item.kind === "notification" && opened.stack + ? { stack: opened.stack, layer: this.notificationDetailLayer(item.key) } : null; + if (detail) detail.stack.push(detail.layer); + this.selectedStatus = { + item, index, host, detail, returnWindowId, + transient: sameHost ? previous.transient : opened.opened, + }; if (hostIndex === this.selectedIndex) { host.requestRender(); } else { this.setSelectedIndex(hostIndex); } + if (previous && !sameHost) this.releaseStatusWindow(previous, false); } /** - * Take the switcher's selection off its notification: the Notifications - * window drops the detail view (and anything opened over it), and closes - * if it was opened for the selection, unless `keepWindow` (it is the - * window being selected instead). + * The window a status bar item shows in, opened in the background unless + * it is open already (`opened` says this call opened it), and for a + * notification, the stack its detail view goes on. */ - private endNotificationSelection(keepWindow = false): void { - const selected = this.selectedNotification; - if (!selected) return; - this.selectedNotification = null; - selected.host.stack.popThrough(selected.layer); - if (selected.transient && !keepWindow) { - this.closeWindow(selected.host.window.windowId); - return; - } - selected.host.requestRender(); - // A window opened for the selection is now one with an icon of its own. - if (selected.transient) this.config.onWindowsChanged?.(); + private openStatusItemWindow(item: StatusItem): { window: ShellWindow; opened: boolean; stack?: LayerStack } | null { + if (item.kind === "widget") return this.trayIcons.get(item.key)?.widget?.openWindow() ?? null; + const opened = this.config.openNotificationsWindow?.(); + return opened ? { window: opened.window.window, opened: opened.opened, stack: opened.window.stack } : null; } - /** End a notification selection by going back to the window selected before it. */ - private returnFromNotification(): void { - const selected = this.selectedNotification; + /** + * Take the switcher's selection off its status bar item, leaving its + * window as releaseStatusWindow does. + */ + private endStatusSelection(keepWindow = false): void { + const selected = this.selectedStatus; + if (!selected) return; + this.selectedStatus = null; + this.releaseStatusWindow(selected, keepWindow); + } + + /** + * A status bar item's window, once the selection has left the item: it + * drops a notification's detail view (and anything opened over it), and + * closes if it was opened for the selection, unless `keepWindow` (it is + * the window being selected instead). + */ + private releaseStatusWindow(selection: StatusSelection, keepWindow: boolean): void { + if (selection.detail) selection.detail.stack.popThrough(selection.detail.layer); + if (selection.transient && !keepWindow) { + this.closeWindow(selection.host.windowId); + return; + } + selection.host.requestRender(); + // A window opened for the selection is now one with an icon of its own. + if (selection.transient) this.config.onWindowsChanged?.(); + } + + /** End a status bar item selection by going back to the window selected before it. */ + private returnFromStatusItem(): void { + const selected = this.selectedStatus; if (!selected) return; const back = this.windows.find((window) => window.windowId === selected.returnWindowId); if (back) this.setSelectedIndex(this.windows.indexOf(back)); - this.endNotificationSelection(back === selected.host.window); + this.endStatusSelection(back === selected.host); } private notificationDetailLayer(key: string): SingleNotificationLayer { @@ -1287,25 +1348,25 @@ class Shell { * A selected notification's detail view asked to close. Back (or a * double-tap) hands focus back to the switcher, its selection still on * the notification. Once the notification is gone (dismissed, or removed - * by an action), the selection also moves on to the one that took its - * place, or back to the windows when there are none left; that waits for - * the current paint to finish, since a vanished notification closes its - * view from inside its paint. + * by an action), the selection also moves on to the status bar item that + * took its place, or back to the windows when there are none left; that + * waits for the current paint to finish, since a vanished notification + * closes its view from inside its paint. */ private notificationDetailClosed(layer: SingleNotificationLayer, gone: boolean): void { if (!gone) { - if (this.selectedNotification?.layer === layer) this.yieldFocusToSidebar(); + if (this.selectedStatus?.detail?.layer === layer) this.yieldFocusToSidebar(); return; } setTimeout(() => { - const selected = this.selectedNotification; - if (selected?.layer !== layer) return; + const selected = this.selectedStatus; + if (selected?.detail?.layer !== layer) return; this.focus = "sidebar"; - const keys = this.selectableNotificationKeys().filter((key) => key !== selected.key); + const items = this.selectableStatusItems().filter((item) => !sameStatusItem(item, selected.item)); const windows = this.switcherWindows(); - if (keys.length) { - const index = Math.min(selected.index, keys.length - 1); - this.selectNotification(keys[index]!, index); + if (items.length) { + const index = Math.min(selected.index, items.length - 1); + this.selectStatusItem(items[index]!, index); } else if (windows.length) { this.selectSwitcherWindow(windows[windows.length - 1]!); } @@ -1849,15 +1910,15 @@ class Shell { attention: Boolean(this.attention.get(window.windowId)), drawIcon: window.drawIcon, })), - selectedIndex: this.selectedNotification ? -1 : this.selectedIndex, - selectedNotificationKey: this.selectedNotification?.key ?? null, + selectedIndex: this.selectedStatus ? -1 : this.selectedIndex, + selectedStatusItem: this.selectedStatus?.item ?? null, focus: this.focus, foregroundHeightMode: this.foregroundWindow()?.heightMode ?? "min", foregroundAppId: this.foregroundWindow()?.appId, battery: this.battery, trayIcons: Array.from(this.trayIcons.keys()) .sort() - .map((key) => this.trayIcons.get(key)!), + .map((ownerId) => ({ ownerId, icon: this.trayIcons.get(ownerId)!.icon })), }; } } diff --git a/tests/app-layout.test.cjs b/tests/app-layout.test.cjs index 5fa117ce..3ca09abe 100644 --- a/tests/app-layout.test.cjs +++ b/tests/app-layout.test.cjs @@ -395,6 +395,8 @@ function chromeLayer(g, { notifications = 0, phoneBattery = null, windows = 1, t const chrome = new context.exports.ShellChromeLayer(() => state, () => heightChanges++); return { chrome, state, requested, planBottomBar: context.exports.planBottomBar, heightChanges: () => heightChanges }; } +const notification = (key) => ({ kind: 'notification', key }); +const keysOf = (items) => Array.from(items, (item) => item.key); test('a bottom app switcher frames the foreground window\'s content in a rounded border', () => { const g = geometry(); @@ -526,7 +528,7 @@ test('the switcher row lays out windows, free space, notifications, widgets, bat g.settings.appSwitcherPositionSetting.value = 'bottom'; g.settings.statusBarPositionSetting.value = 'bottom'; const tray = new graphics.GrayImage(30, 20, 180); - const { chrome, requested } = chromeLayer(g, { notifications: 2, phoneBattery: 80, trayIcons: [tray] }); + const { chrome, requested } = chromeLayer(g, { notifications: 2, phoneBattery: 80, trayIcons: [{ ownerId: 'w', icon: tray }] }); const parts = chrome.paintParts(); // No top bar: the row, then the status bar on the top bar's surface and depth. assert.deepEqual(Array.from(parts, (p) => [p.shellKey, p.depth ?? 0]), [[1, 0], [2, -2]]); @@ -568,7 +570,7 @@ test('past two rows of windows, they scroll, and notification icons give way to // Notification icons drop from the end until the two status rows leave // three window slots a row (32 + 20 + 3 * 40 - 8, and the gap): 28 stay, // 15 in the first row (416px) and 13 with the clock in the second (432px). - assert.equal(chrome.notificationKeys().length, 28); + assert.equal(chrome.statusItems().length, 28); assert.deepEqual([status.x, status.y, status.image.height], [608 - 432 - 2, 367, 71]); const at = (p, x, y) => p.image.withDrawsBaked().pixels[(y - p.y) * p.image.width + x - p.x]; assert.deepEqual([at(status, 608 - 416, 366 + 5 + 2), at(status, 608 - 432, 366 + 36 + 5 + 2)], [200, 200]); @@ -659,7 +661,7 @@ test('the status bar takes a second row of its own before the windows do', () => const at = (p, x, y) => p.image.withDrawsBaked().pixels[(y - p.y) * p.image.width + x - p.x]; assert.deepEqual([at(status, 608 - 220, 371 + 2), at(status, 608 - 236, 371 + 28 + 2), at(status, 608 - 56, 371 + 28 + 8 + 2)], [200, 200, 210]); - assert.deepEqual(Array.from(chrome.notificationKeys()), Array.from({ length: 14 }, (_, i) => `n${i}`)); + assert.deepEqual(keysOf(chrome.statusItems()), Array.from({ length: 14 }, (_, i) => `n${i}`)); // The windows keep one row, against the window. assert.equal(chrome.windowIndexAt(45, 380, 3), 0); assert.equal(chrome.windowIndexAt(45, 410, 3), null); @@ -772,9 +774,9 @@ test('a notification the switcher selects sits in a box, filled with its icon in g.settings.appSwitcherPositionSetting.value = 'bottom'; g.settings.statusBarPositionSetting.value = 'bottom'; const { chrome, state } = chromeLayer(g, { notifications: 3, windows: 2 }); - Object.assign(state, { selectedIndex: -1, selectedNotificationKey: 'n1', focus: 'sidebar' }); + Object.assign(state, { selectedIndex: -1, selectedStatusItem: notification('n1'), focus: 'sidebar' }); let [row, status] = chrome.paintParts(); - assert.deepEqual(Array.from(chrome.notificationKeys()), ['n0', 'n1', 'n2']); + assert.deepEqual(keysOf(chrome.statusItems()), ['n0', 'n1', 'n2']); // Clock only: the icons end 8px before its 8px lead-in, 28px apart, each // 7 rows into the row (the top bar's layout, 5 rows down). const iconsLeft = 608 - 56 - 8 - 8 - 3 * 28 + 4, iconY = 366 + 7, n1 = iconsLeft + 28; @@ -787,23 +789,68 @@ test('a notification the switcher selects sits in a box, filled with its icon in // No window is selected: the separator runs unbroken over the windows. assert.equal(at(row, 50, 366), 40); // Mirror touches find the icons by their boxes, which tile the icons' run. - assert.deepEqual([chrome.notificationKeyAt(n1 + 5, 380), chrome.notificationKeyAt(n1 - 3, 380), - chrome.notificationKeyAt(iconsLeft - 3, 380), chrome.notificationKeyAt(n1 + 5, 400)], ['n1', 'n0', null, null]); + const keyAt = (x, y) => chrome.statusItemAt(x, y)?.key ?? null; + assert.deepEqual([keyAt(n1 + 5, 380), keyAt(n1 - 3, 380), keyAt(iconsLeft - 3, 380), keyAt(n1 + 5, 400)], ['n1', 'n0', null, null]); // With its detail view focused instead, the box is an outline round the plain icon. state.focus = 'window'; [, status] = chrome.paintParts(); assert.deepEqual([at(status, n1 - 2, iconY + 12), at(status, n1 - 1, iconY + 12), at(status, n1 + 5, iconY + 5)], [150, 1, 200]); // The first icon's box fits the status bar's surface. - state.selectedNotificationKey = 'n0'; + state.selectedStatusItem = notification('n0'); [, status] = chrome.paintParts(); assert.equal(at(status, iconsLeft - 2, iconY + 12), 150); // In the top bar (the status bar's default place) likewise; barTop=78. g.settings.statusBarPositionSetting.value = 'top'; const [bar] = chrome.paintParts(); const barIconsLeft = 32 + 10 + 56 + 16; - assert.deepEqual(Array.from(chrome.notificationKeys()), ['n0', 'n1', 'n2']); + assert.deepEqual(keysOf(chrome.statusItems()), ['n0', 'n1', 'n2']); assert.deepEqual([at(bar, barIconsLeft - 2, 78 + 14), at(bar, barIconsLeft + 5, 78 + 7)], [150, 200]); - assert.equal(chrome.notificationKeyAt(barIconsLeft + 30, 78 + 10), 'n1'); + assert.equal(keyAt(barIconsLeft + 30, 78 + 10), 'n1'); +}); + +test('an app widget the switcher selects sits in a box as a notification does, after the notifications', () => { + const g = geometry(); + g.settings.appSwitcherPositionSetting.value = 'bottom'; + g.settings.statusBarPositionSetting.value = 'bottom'; + // A 30x20 widget, its text a deferred draw, and a 12x16 one. + const wide = new graphics.GrayImage(30, 20, 0); + wide.fillRect(0, 0, 30, 20, 180); + wide.drawImage(new graphics.GrayImage(4, 4, 220), 10, 8); + const small = new graphics.GrayImage(12, 16, 160); + const { chrome, state } = chromeLayer(g, { notifications: 2, windows: 2, + trayIcons: [{ ownerId: 'nightscout', icon: wide }, { ownerId: 'timer', icon: small }] }); + Object.assign(state, { selectedIndex: -1, selectedStatusItem: { kind: 'widget', key: 'nightscout' }, focus: 'sidebar' }); + let [, status] = chrome.paintParts(); + // Notifications first, then the widgets, as they sit left to right. + assert.deepEqual(Array.from(chrome.statusItems(), (item) => `${item.kind}:${item.key}`), + ['notification:n0', 'notification:n1', 'widget:nightscout', 'widget:timer']); + // Right to left from the row's end: the clock (56px), its 16px lead-in, + // the small widget, 10px, the wide one. Each centred in the top bar's + // layout, 5 rows into the row. + const smallLeft = 608 - 56 - 16 - 12, wideLeft = smallLeft - 10 - 30, wideTop = 366 + 5 + 4; + const at = (p, x, y) => p.image.withDrawsBaked().pixels[(y - p.y) * p.image.width + x - p.x]; + // The box: 2px either side, as tall as a notification's (rows 1..26 of + // the layout) whatever the widget's height; white, with the widget + // inverted inside it, its deferred draw too. + assert.deepEqual([at(status, wideLeft - 2, 366 + 5 + 14), at(status, wideLeft + 31, 366 + 5 + 14), + at(status, wideLeft + 15, 366 + 5 + 1), at(status, wideLeft + 15, 366 + 5 + 26)], [255, 255, 255, 255]); + assert.equal(at(status, wideLeft + 15, 366 + 5 + 27), 1); + assert.deepEqual([at(status, wideLeft + 2, wideTop + 2), at(status, wideLeft + 11, wideTop + 9)], [75, 35]); + assert.equal(at(status, smallLeft + 2, 366 + 5 + 8), 160); + // Mirror touches find widgets by their boxes too. + assert.deepEqual({ ...chrome.statusItemAt(wideLeft - 1, 380) }, { kind: 'widget', key: 'nightscout' }); + assert.deepEqual({ ...chrome.statusItemAt(smallLeft + 13, 380) }, { kind: 'widget', key: 'timer' }); + // With its window focused instead, an outline round the plain widget. + state.focus = 'window'; + [, status] = chrome.paintParts(); + assert.deepEqual([at(status, wideLeft - 2, 366 + 5 + 14), at(status, wideLeft + 2, wideTop + 2)], [150, 180]); + // In the top bar likewise, the notifications still before the widgets + // though drawn after them; barTop=78. + g.settings.statusBarPositionSetting.value = 'top'; + const [bar] = chrome.paintParts(); + assert.deepEqual(Array.from(chrome.statusItems(), (item) => item.key), ['n0', 'n1', 'nightscout', 'timer']); + const barWideLeft = 608 - 10 - 12 - 10 - 30; + assert.deepEqual([at(bar, barWideLeft - 2, 78 + 14), at(bar, barWideLeft + 2, 78 + 6)], [150, 180]); }); test('with the selection out on a notification, the windows stay scrolled as they were', () => { @@ -815,7 +862,7 @@ test('with the selection out on a notification, the windows stay scrolled as the const last = 32 + 10 + 2 * 40 + 4; const before = chrome.windowIndexAt(last, 380, 40); assert.ok(before > 2); - Object.assign(state, { selectedIndex: -1, selectedNotificationKey: 'n0' }); + Object.assign(state, { selectedIndex: -1, selectedStatusItem: notification('n0') }); chrome.paintParts(); assert.equal(chrome.windowIndexAt(last, 380, 40), before); });