diff --git a/app/apps/blocks/blocks-app.worker.ts b/app/apps/blocks/blocks-app.worker.ts index 239a3366..7ab33372 100644 --- a/app/apps/blocks/blocks-app.worker.ts +++ b/app/apps/blocks/blocks-app.worker.ts @@ -290,8 +290,17 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { updateTickTimer(window); } break; + case "resize-window": { + const window = windows.get(message.windowId); + if (!window) break; + window.viewportWidth = message.viewport.width; + window.viewportHeight = message.viewport.height; + window.menu?.resize({ width: window.viewportWidth, height: window.viewportHeight }); + window.lastSubmittedFingerprint = ""; + if (window.foreground) renderAndSubmit(window, 0); + break; + } case "navigation-sensors": - case "resize-window": case "text-input": case "tool-call": break; diff --git a/app/apps/freecell/freecell-app.worker.ts b/app/apps/freecell/freecell-app.worker.ts index fb939857..bd611a44 100644 --- a/app/apps/freecell/freecell-app.worker.ts +++ b/app/apps/freecell/freecell-app.worker.ts @@ -205,9 +205,18 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { if (window.foreground) renderAndSubmit(window, 0); break; } + case "resize-window": { + const window = windows.get(message.windowId); + if (!window) break; + window.viewportWidth = message.viewport.width; + window.viewportHeight = message.viewport.height; + window.menu?.resize({ width: window.viewportWidth, height: window.viewportHeight }); + window.lastSubmittedFingerprint = ""; + if (window.foreground) renderAndSubmit(window, 0); + break; + } case "input-focus": case "navigation-sensors": - case "resize-window": case "screen": case "text-input": case "tool-call": diff --git a/app/apps/minesweeper/minesweeper-app.worker.ts b/app/apps/minesweeper/minesweeper-app.worker.ts index a4320d83..3cd49ee9 100644 --- a/app/apps/minesweeper/minesweeper-app.worker.ts +++ b/app/apps/minesweeper/minesweeper-app.worker.ts @@ -250,8 +250,17 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { syncClock(window); } break; + case "resize-window": { + const window = windows.get(message.windowId); + if (!window) break; + window.viewportWidth = message.viewport.width; + window.viewportHeight = message.viewport.height; + window.menu?.resize({ width: window.viewportWidth, height: window.viewportHeight }); + window.lastSubmittedFingerprint = ""; + if (window.foreground) renderAndSubmit(window, 0); + break; + } case "navigation-sensors": - case "resize-window": case "text-input": case "tool-call": break; diff --git a/app/apps/pinball/pinball-app.worker.ts b/app/apps/pinball/pinball-app.worker.ts index 13d5242e..8ff5a1bb 100644 --- a/app/apps/pinball/pinball-app.worker.ts +++ b/app/apps/pinball/pinball-app.worker.ts @@ -411,8 +411,17 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { syncTickTimer(window); } break; + case "resize-window": { + const window = windows.get(message.windowId); + if (!window) break; + window.viewportWidth = message.viewport.width; + window.viewportHeight = message.viewport.height; + window.menu?.resize({ width: window.viewportWidth, height: window.viewportHeight }); + window.lastSubmittedFingerprint = ""; + if (window.foreground) renderAndSubmit(window, 0); + break; + } case "navigation-sensors": - case "resize-window": case "text-input": case "tool-call": break; diff --git a/app/apps/roam/roam-app.worker.ts b/app/apps/roam/roam-app.worker.ts index 5575154b..a26cb5e9 100644 --- a/app/apps/roam/roam-app.worker.ts +++ b/app/apps/roam/roam-app.worker.ts @@ -251,9 +251,17 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { ); break; } + case "resize-window": + if (!window || window.windowId !== message.windowId) break; + window.viewportWidth = message.viewport.width; + window.viewportHeight = message.viewport.height; + window.view.resize(message.viewport.width - DOC_MARGIN * 2, message.viewport.height - HEADER_HEIGHT - BOTTOM_MARGIN); + window.menu?.resize(message.viewport); + window.lastSubmittedFingerprint = ""; + render(); + break; case "input-focus": case "navigation-sensors": - case "resize-window": break; } }; diff --git a/app/g2/dashboard-controller.ts b/app/g2/dashboard-controller.ts index 53ce6cb8..103135ce 100644 --- a/app/g2/dashboard-controller.ts +++ b/app/g2/dashboard-controller.ts @@ -423,6 +423,7 @@ class DashboardController { }, openNotificationsWindow: () => this.openInProcessAppInBackground(NOTIFICATIONS_WINDOW_ID, NOTIFICATIONS_SURFACE_ID, createNotificationsAppWindow), + onSwitcherBarHeightChanged: () => this.applySwitcherBarHeight(), onScreenStateChanged: (on) => { // Any wake of the regular UI replaces a showing Glanceboard. if (on) this.glance.dismiss(); @@ -584,6 +585,29 @@ class DashboardController { }); } + /** + * The bottom switcher's layout changed its height (shell.ts + * onSwitcherBarHeightChanged): window bands move where the slack under + * them runs out, and full-height windows resize; the rest stay as they + * are. Windows that can't resize keep the surface they have, the switcher + * covering any of it that it now overlaps, rather than being relaunched + * for it. + */ + private applySwitcherBarHeight(): void { + void (async () => { + for (const window of Array.from(shell.getWindows())) { + const rect = JSON.stringify(appViewportRect(window.heightMode, window.appId)); + if (!window.relayout || this.windowSurfaceRects.get(window.surfaceId) === rect) continue; + window.relayout(); + await this.configureWindowSurface(window.surfaceId, this.isForegroundWindow(window.windowId), window.heightMode); + } + shell.foregroundWindow()?.requestRender(); + this.requestShellRender(); + })().catch((error) => { + this.appendLog(`switcher height change failed: ${this.formatError(error)}`); + }); + } + private lastAppLayouts = this.appLayouts(); private appLayouts(): Record { @@ -2565,20 +2589,22 @@ class DashboardController { target: DisplayTarget | null = this.display, ): Promise { if (!target) return; - await target.configureSurface(surfaceId, { - ...appViewportRect(heightMode, shell.getWindows().find((window) => window.surfaceId === surfaceId)?.appId), - zOrder: 0, - transparency: "opaque", - }); + const rect = appViewportRect(heightMode, shell.getWindows().find((window) => window.surfaceId === surfaceId)?.appId); + this.windowSurfaceRects.set(surfaceId, JSON.stringify(rect)); + await target.configureSurface(surfaceId, { ...rect, zOrder: 0, transparency: "opaque" }); await target.setSurfaceVisible(surfaceId, typeof visible === "function" ? visible() : visible); } + /** Each window surface's rect as last configured (applySwitcherBarHeight skips those that stay). */ + private readonly windowSurfaceRects = new Map(); + /** A late answer to "is this window in front?", for configureWindowSurface. */ private isForegroundWindow(windowId: string): () => boolean { return () => shell.foregroundWindow()?.windowId === windowId; } private removeWindowSurface(surfaceId: string): void { + this.windowSurfaceRects.delete(surfaceId); const display = this.display; if (!display) return; void display.removeSurface(surfaceId).catch((error) => { diff --git a/app/g2/ios-preview-controller.ts b/app/g2/ios-preview-controller.ts index f59de83b..70f29a7e 100644 --- a/app/g2/ios-preview-controller.ts +++ b/app/g2/ios-preview-controller.ts @@ -181,6 +181,11 @@ export class IosPreviewController { getScreenTimeoutMs: () => null, requestShellRender: () => this.requestShellRender(), onWindowsChanged: () => { this.requestShellRender(); this.syncEvenHubPhoneUi() }, + onSwitcherBarHeightChanged: () => { + this.relayout() + shell.foregroundWindow()?.requestRender() + this.requestShellRender() + }, onScreenStateChanged: on => { if (on) this.glance.dismiss() void this.display?.setScreenBlanked(!on).catch(error => this.fail(error)) diff --git a/app/native/notification-icons.ts b/app/native/notification-icons.ts index 7620ab24..242e12e8 100644 --- a/app/native/notification-icons.ts +++ b/app/native/notification-icons.ts @@ -58,19 +58,21 @@ export function readActiveNotificationIcons(maxIcons: number, allowStale: boolea const now = Date.now(); if (cachedAtMs > 0 && now - cachedAtMs < ICON_CACHE_MS) { logCurrent("notification icons served from cache"); - return { icons: cachedIcons.map(icon => icon.clone()), keys: cachedKeys.slice(), stale: false }; + return cachedIconsResult(maxIcons, false); } if (allowStale) { logCurrent("notification icons served stale"); - return { icons: cachedIcons.map(icon => icon.clone()), keys: cachedKeys.slice(), stale: true }; + return cachedIconsResult(maxIcons, true); } + // Every icon, whatever this caller wants: the cache serves callers asking + // for different counts (the switcher row needs them all to lay itself out). const keyList = new java.util.ArrayList(); const bytes = spanCurrent("fetch-notification-icons", () => toUint8Array( com.faceclaw.app.FaceclawMediaNotificationListenerService.getActiveNotificationIconGrays( ICON_SIZE, - maxIcons, + ALL_NOTIFICATIONS, keyList, ), ), @@ -91,7 +93,12 @@ export function readActiveNotificationIcons(maxIcons: number, allowStale: boolea cachedIcons = icons; cachedKeys = keys; cachedAtMs = now; - return { icons: icons.map(icon => icon.clone()), keys: keys.slice(), stale: false }; + return cachedIconsResult(maxIcons, false); +} + +/** Copies of the first maxIcons cached icons, with their keys. */ +function cachedIconsResult(maxIcons: number, stale: boolean): NotificationIconsResult { + return { icons: cachedIcons.slice(0, maxIcons).map(icon => icon.clone()), keys: cachedKeys.slice(0, maxIcons), stale }; } export type NotificationIconResult = { diff --git a/app/ui/document/document-view.ts b/app/ui/document/document-view.ts index e9300d62..c4d5813d 100644 --- a/app/ui/document/document-view.ts +++ b/app/ui/document/document-view.ts @@ -49,10 +49,18 @@ export class DocumentView { private scrollLine = 0; constructor( - private readonly width: number, - private readonly height: number, + private width: number, + private height: number, ) {} + /** Re-wrap the document for a region of a new size, keeping the selection in view. */ + resize(width: number, height: number): void { + if (width === this.width && height === this.height) return; + this.width = width; + this.height = height; + if (this.root) this.setDocument(this.root); + } + setDocument(root: DocumentRoot): void { const previousId = this.selectedNode()?.id; this.root = root; diff --git a/app/ui/shell/chrome-layer.ts b/app/ui/shell/chrome-layer.ts index 53a04776..c7c85179 100644 --- a/app/ui/shell/chrome-layer.ts +++ b/app/ui/shell/chrome-layer.ts @@ -6,7 +6,7 @@ import { getDefaultMediumFont, getDefaultSmallFont } from "../../graphics/ui-fon import { truncateText } from "../../graphics/textwrap"; import { activeAmbientCards } from "./ambient-cards"; import { BATTERY_ICON_WIDTH, DENSE_BATTERY_BLOCK_HEIGHT, drawBattery, drawDenseBatteries, type BatteryDevice } from "../../graphics/battery"; -import { readActiveNotificationIcons } from "../../native/notification-icons"; +import { ALL_NOTIFICATIONS, readActiveNotificationIcons } from "../../native/notification-icons"; import { readPhoneBatteryState } from "../../native/phone-battery"; import { noteStaleDataUsed, renderPassAllowsStaleData } from "../../util/render-freshness"; import { renderIcon, renderIconWithGlyph, type IconActivity, type IconName } from "../../graphics/icons"; @@ -30,6 +30,7 @@ import { isImmersive, MIN_WINDOW_HEIGHT, minWindowTop, + setSwitcherBarHeight, SHELL_OPAQUE_BLACK, SIDEBAR_WIDTH, sidebarStripVisible, @@ -56,7 +57,8 @@ import { * sidebar. In the two-column variant the column against the app area fills * first and windows past that overflow into the outer column, so the common * case keeps every icon next to the content it belongs to. A bottom row - * always uses the roomy slots, laid out left to right. + * always uses the roomy slots, laid out left to right, and when they don't + * fit beside the status bar, in a second row (see planBottomBar). */ type SidebarVariant = { columns: number; columnWidth: number; iconSize: number }; const ONE_COLUMN: SidebarVariant = { columns: 1, columnWidth: 36, iconSize: 32 }; @@ -74,16 +76,25 @@ const ROW_STEP = ROW_ICON_SIZE + ICON_SPACING; // The status bar in the switcher row (geometry.ts statusInSwitcherRow) keeps // the top bar's layout, so every element sits as it does there: its 28 rows // (whose last is the divider, which the row has no use for) centred in the -// row below its separator line. +// row below its separator line. A second row of status items sits a top +// bar's height under the first, or, beside two rows of windows, a row's +// height under it, level with the second row of windows. const ROW_STATUS_TOP = 1 + ((SWITCHER_ROW_HEIGHT - TOP_BAR_HEIGHT) >> 1); // Its clock ends flush with the row's right end, which is the window's -// right edge; batteries keep the top bar's clock-to-icons gap from it. +// right edge; batteries keep the top bar's clock-to-icons gap from it, as +// does whatever else comes right before the clock. const ROW_CLOCK_GAP = 16; // Between the windows' end of the row (its scroll chevron) and the status. const ROW_STATUS_GAP = 8; -// Notification icons stop short of room for this many windows' slots (or -// all of them, when there are fewer); the windows take whatever is left. +// When the windows have to scroll anyway (planBottomBar's last layout), +// notification icons stop short of room for this many windows' slots in a +// row (or all of them, when there are fewer); the windows take whatever is +// left. const ROW_MIN_WINDOW_SLOTS = 3; +// After an app widget (tray icon), and between the last notification icon +// and what follows it, as in the top bar. +const TRAY_ICON_GAP = 10; +const NOTIFICATIONS_GAP = 8; // The popup switcher (geometry.ts "popup"): a box centred over the // foreground window's content, holding a row of window icons above the @@ -155,29 +166,34 @@ type SwitcherLayout = { /** * Switcher geometry for the foreground window (a bottom row sits under it). - * `windowsRight` is where a bottom row's window icons must end: short of - * the status bar when it shares the row. `scrollRow` is the first visible - * window's index. + * A bottom switcher's window icons take `bar`'s slots (planBottomBar), the + * row against the window first, then the one under it. `scrollRow` is the + * first visible window's index. */ -function switcherLayout(windowCount: number, heightMode: WindowHeightMode, appId?: string, windowsRight?: number, scrollRow = 0): SwitcherLayout { +function switcherLayout(windowCount: number, heightMode: WindowHeightMode, appId: string | undefined, bar: BottomBarPlan | null, scrollRow = 0): SwitcherLayout { const position = switcherPosition(); if (position === "bottom") { const row = switcherRect(heightMode, appId); - const width = (windowsRight ?? row.x + row.width) - row.x; + const { windowColumns, windowRows } = bar ?? planBottomBar(row.width, windowCount, []); + const columns = Math.max(1, windowColumns); // Under a framed window the first window's cell (the launcher's) starts // at the frame's left side, one pixel outside the window, so a selection // tab there carries the side straight down (drawWindowFrame squares that // corner for it). Scrolled past it, the cells keep the margin the left - // chevron needs. The count of slots stays the same either way. + // chevron needs. The count of slots stays the same either way. Only the + // first row's cells touch the separator; a second row's lines up under it. const first = windowFramed(appId) && scrollRow === 0 ? row.x - 1 : row.x + LIST_MARGIN - 2; return { position, iconSize: ROW_ICON_SIZE, - visibleCount: Math.max(1, ((width - 2 * LIST_MARGIN + ICON_SPACING) / ROW_STEP) | 0), - cell: (slot) => ({ - x: first + slot * ROW_STEP, y: row.y, width: ROW_ICON_SIZE + 4, height: SWITCHER_ROW_HEIGHT, - atSeparator: true, - }), + visibleCount: columns * windowRows, + cell: (slot) => { + const line = (slot / columns) | 0; + return { + x: first + (slot % columns) * ROW_STEP, y: row.y + line * SWITCHER_ROW_HEIGHT, + width: ROW_ICON_SIZE + 4, height: SWITCHER_ROW_HEIGHT, atSeparator: line === 0, + }; + }, }; } // Slots fill the column against the separator top to bottom, then @@ -202,6 +218,126 @@ function switcherLayout(windowCount: number, heightMode: WindowHeightMode, appId }; } +/** + * One of the status bar's items as the bottom switcher lays it out (see + * planBottomBar): left to right, the notification icons, app widgets (tray + * icons), the battery block and the clock. + */ +type RowStatusSize = { kind: "notification" | "tray" | "batteries" | "clock"; width: number }; + +/** A status item ready to draw with its left edge at x, in the top bar's layout from `top`. */ +type RowStatusItem = RowStatusSize & { draw: (image: GrayImage, x: number, top: number) => void }; + +/** + * A layout of the bottom switcher (planBottomBar): its window icons in + * `windowRows` rows of `windowColumns` slots, scrolling when there are more + * windows than that; the status bar's items in `statusRows` (top first), + * each right-aligned against the switcher's end, `statusPitch` apart; and + * the height it all takes. + */ +export type BottomBarPlan = { + /** Which of planBottomBar's layouts this is, 1 (the roomiest) to 4. */ + level: number; + height: number; + windowRows: number; + windowColumns: number; + statusRows: T[][]; + /** Width of the widest status row; the windows take what it leaves. */ + statusWidth: number; + statusPitch: number; +}; + +/** + * Lay out the bottom switcher, `width` wide, for `windowCount` windows and + * the status bar's items (none unless it shares the switcher; notification + * icons first), trying denser layouts in turn until one fits: + * + * 1. One row: the windows, then the status bar's items. + * 2. The status bar's items in two rows, broken where the two come nearest + * the same width, beside the one row of windows. The extra height comes + * out of the slack under a window band, or a full-height window's height + * (geometry.ts windowTop). + * 3. The windows in two rows too. + * 4. As 3, but with only as many windows showing as fit, scrolling to the + * rest, and notification icons dropped from the end as need be to leave + * the windows room for a few slots a row. + * + * A layout fails when its windows don't all fit beside its status rows; the + * last can't fail. + */ +export function planBottomBar(width: number, windowCount: number, status: T[]): BottomBarPlan { + const plan = (level: number, windowRows: number, statusRows: T[][]): BottomBarPlan => { + const statusWidth = Math.max(0, ...statusRows.map(statusRowWidth)); + return { + level, + height: windowRows > 1 ? windowRows * SWITCHER_ROW_HEIGHT + : SWITCHER_ROW_HEIGHT + Math.max(0, statusRows.length - 1) * TOP_BAR_HEIGHT, + windowRows, + windowColumns: rowWindowColumns(width - (statusWidth > 0 ? statusWidth + ROW_STATUS_GAP : 0)), + statusRows, + statusWidth, + statusPitch: windowRows > 1 ? SWITCHER_ROW_HEIGHT : TOP_BAR_HEIGHT, + }; + }; + const twoRows = splitStatusRows(status); + for (const candidate of [plan(1, 1, status.length ? [status] : []), plan(2, 1, twoRows), plan(3, 2, twoRows)]) { + if (candidate.windowColumns * candidate.windowRows >= windowCount && candidate.statusWidth <= width) return candidate; + } + const notifications = status.filter((item) => item.kind === "notification").length; + const room = width - ROW_STATUS_GAP - rowWindowsWidth(Math.min(Math.ceil(windowCount / 2), ROW_MIN_WINDOW_SLOTS)); + let last = plan(4, 2, twoRows); + for (let kept = notifications - 1; kept >= 0 && last.statusWidth > room; kept--) { + last = plan(4, 2, splitStatusRows([...status.slice(0, kept), ...status.slice(notifications)])); + } + return { ...last, windowColumns: Math.max(1, last.windowColumns) }; +} + +/** Width `columns` window slots take in the bottom switcher, with its end margins. */ +function rowWindowsWidth(columns: number): number { + return columns > 0 ? 2 * LIST_MARGIN + columns * ROW_STEP - ICON_SPACING : 0; +} + +/** How many window slots fit across `width` of the bottom switcher. */ +function rowWindowColumns(width: number): number { + return Math.max(0, ((width - 2 * LIST_MARGIN + ICON_SPACING) / ROW_STEP) | 0); +} + +/** Space between two neighbouring status items, as the top bar spaces them. */ +function statusGap(left: RowStatusSize, right: RowStatusSize): number { + if (right.kind === "clock" || left.kind === "batteries") return ROW_CLOCK_GAP; + if (left.kind === "tray") return TRAY_ICON_GAP; + return right.kind === "notification" ? NOTIFICATION_ICON_STEP - NOTIFICATION_ICON_SIZE : NOTIFICATIONS_GAP; +} + +/** Width of a row of status items, from the first's left edge to the last's right. */ +function statusRowWidth(items: readonly RowStatusSize[]): number { + let width = 0; + for (let index = 0; index < items.length; index++) { + width += items[index]!.width + (index > 0 ? statusGap(items[index - 1]!, items[index]!) : 0); + } + return width; +} + +/** + * Status items in two rows (one when there are fewer than two), broken + * where the wider row is narrowest, so the two come out about as wide. + */ +function splitStatusRows(items: T[]): T[][] { + if (items.length < 2) return items.length ? [items] : []; + const total = statusRowWidth(items); + let best = 1, bestWidth = Infinity, before = 0; + for (let index = 1; index < items.length; index++) { + // Items before `index` take the first row; the gap at the break goes. + before += items[index - 1]!.width + (index > 1 ? statusGap(items[index - 2]!, items[index - 1]!) : 0); + const widest = Math.max(before, total - before - statusGap(items[index - 1]!, items[index]!)); + if (widest < bestWidth) { + best = index; + bestWidth = widest; + } + } + return [items.slice(0, best), items.slice(best)]; +} + /** * Popup switcher geometry for the foreground window: its box, centred over * the window's content (geometry.ts switcherRect), as wide as the icons @@ -296,6 +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. +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. const NOTIFICATION_BOX_MARGIN_X = 2; @@ -416,8 +554,8 @@ export class ShellChromeLayer implements Layer { private scrollRow = 0; // The popup switcher's shell surface. private popupKey: number | undefined; - // Where the last paint ended a bottom row's window icons, for hit testing. - private rowWindowsRight: number | undefined; + // The bottom switcher's layout as the last paint planned it, for hit testing. + private bottomBar: BottomBarPlan | null = null; // 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; @@ -425,12 +563,21 @@ export class ShellChromeLayer implements Layer { // switcher's selection can move onto, and mirror touches hit. private notificationEntries: NotificationEntry[] = []; - constructor(private readonly getState: () => ShellChromeState) {} + /** + * `onBottomBarHeightChanged` is called, during a paint, when the bottom + * switcher's layout changes its height so that windows have to move or + * resize (see layoutBottomBar). + */ + constructor( + private readonly getState: () => ShellChromeState, + private readonly onBottomBarHeightChanged: () => void = () => {}, + ) {} paint(): GrayImage { const image = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0); const state = this.getState(); this.notificationEntries = []; + this.bottomBar = this.layoutBottomBar(state); const statusInRow = statusInSwitcherRow(state.foregroundAppId); const popup = switcherPosition() === "popup"; // Over an immersive window the strip is an overlay, present only while @@ -452,6 +599,7 @@ export class ShellChromeLayer implements Layer { paintParts(): Plane[] { const state = this.getState(), parts: Plane[] = []; this.notificationEntries = []; + this.bottomBar = this.layoutBottomBar(state); const statusInRow = statusInSwitcherRow(state.foregroundAppId); const canvas = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0); const span = topBarSpan(state); @@ -534,7 +682,7 @@ export class ShellChromeLayer implements Layer { if (windowCount === 0) return null; const state = this.getState(); const layout = switcherPosition() === "popup" ? popupLayout(windowCount, state) - : switcherLayout(windowCount, state.foregroundHeightMode, state.foregroundAppId, this.rowWindowsRight, this.scrollRow); + : switcherLayout(windowCount, state.foregroundHeightMode, state.foregroundAppId, this.bottomBar, this.scrollRow); const lastVisible = Math.min(windowCount, this.scrollRow + layout.visibleCount); for (let index = this.scrollRow; index < lastVisible; index++) { const cell = layout.cell(index - this.scrollRow); @@ -557,10 +705,11 @@ export class ShellChromeLayer implements Layer { } /** - * Draw the switcher strip or row. Given `statusImage`, a bottom row shares - * its right end with the status bar, drawn there (into that image, which - * may be this one) first, and the window icons take what it leaves. - * Returns the status bar's left edge, or null without one. + * Draw the switcher strip or row. Given `statusImage`, a bottom switcher + * shares its right end with the status bar, drawn there (into that image, + * which may be this one) first, and the window icons take what it leaves + * (see planBottomBar). Returns the status bar's left edge, or null without + * one. */ private drawSidebar(image: GrayImage, state: ShellChromeState, statusImage?: GrayImage): number | null { // A side strip aligns with the app's preferred band (legacy tall @@ -573,18 +722,17 @@ export class ShellChromeLayer implements Layer { // windows off-screen before/after. Sidebar icons fill the column against // the separator top to bottom, then overflow into the outer one, so a // visible slot's column is decided by its position within the scrolled - // window. + // window; a bottom switcher's two rows likewise fill the top one first. const count = state.windows.length; - const statusLeft = statusImage && switcherPosition() === "bottom" - ? this.drawRowStatus(statusImage, state, strip, count) : null; + const bar = this.bottomBar; + const statusLeft = statusImage && bar?.statusRows.length ? this.drawRowStatus(statusImage, strip, bar) : null; const windowsRight = statusLeft === null ? strip.x + strip.width : statusLeft - ROW_STATUS_GAP; - this.rowWindowsRight = windowsRight; - const visibleCount = switcherLayout(count, state.foregroundHeightMode, state.foregroundAppId, windowsRight).visibleCount; + const visibleCount = switcherLayout(count, state.foregroundHeightMode, state.foregroundAppId, bar).visibleCount; // With the selection out on a notification, the windows stay scrolled as they were. this.scrollRow = state.selectedIndex >= 0 ? scrollToKeepSelectionVisible(this.scrollRow, state.selectedIndex, visibleCount, count) : Math.min(this.scrollRow, Math.max(0, count - visibleCount)); - const layout = switcherLayout(count, state.foregroundHeightMode, state.foregroundAppId, windowsRight, this.scrollRow); + const layout = switcherLayout(count, state.foregroundHeightMode, state.foregroundAppId, bar, this.scrollRow); const { iconSize, position } = layout; const lastVisible = Math.min(count, this.scrollRow + layout.visibleCount); const cellOf = (index: number) => layout.cell(index - this.scrollRow); @@ -600,7 +748,7 @@ export class ShellChromeLayer implements Layer { const selCell = selVisible ? cellOf(state.selectedIndex) : null; drawSeparator(image, state, strip, selCell?.atSeparator ? selCell : null); const frame = position === "bottom" ? windowFrameRect(state) : null; - this.frameCornerSquare = !!frame && selCell?.x === frame.x; + this.frameCornerSquare = !!frame && !!selCell?.atSeparator && selCell.x === frame.x; for (let index = this.scrollRow; index < lastVisible; index++) { const window = state.windows[index]!; @@ -630,13 +778,14 @@ export class ShellChromeLayer implements Layer { } if (position === "bottom") { - // Chevrons sit in the margins at either end of the icons, pointing off them. - const chevronY = strip.y + ((strip.height / 2) | 0); + // Chevrons sit in the margins at either end of the icons, pointing off + // them: before the first row's, and after the last row's. + const rowMiddle = (line: number) => strip.y + line * SWITCHER_ROW_HEIGHT + (SWITCHER_ROW_HEIGHT >> 1); if (this.scrollRow > 0) { - drawChevron(image, strip.x + 6, chevronY, "left"); + drawChevron(image, strip.x + 6, rowMiddle(0), "left"); } if (lastVisible < count) { - drawChevron(image, windowsRight - 6, chevronY, "right"); + drawChevron(image, windowsRight - 6, rowMiddle((bar?.windowRows ?? 1) - 1), "right"); } return statusLeft; } @@ -654,39 +803,75 @@ export class ShellChromeLayer implements Layer { } /** - * The status bar at the right end of the switcher row, right to left: - * date and time, batteries, app widgets, then notification icons, each as - * it sits in the top bar (see ROW_STATUS_TOP). Notification icons stop - * short of room for a few window slots; the windows get the rest, and - * whatever they leave over is free space between the two. Returns the - * left edge of what it drew. + * Lay out the bottom switcher for this paint (planBottomBar) under the + * foreground window, with the status bar's items when it shares the + * switcher, and record its height in geometry.ts, telling the shell when + * that moves or resizes windows. Null for the other switcher positions. */ - private drawRowStatus(image: GrayImage, state: ShellChromeState, row: Rect, windowCount: number): number { - image.fillRect(row.x, row.y + 1, row.width, row.height - 1, SHELL_OPAQUE_BLACK); - const top = row.y + ROW_STATUS_TOP; - const font = getDefaultMediumFont(); - const clock = clockText(); - // A TTF face measures fractionally; the status surface's crop edges need whole pixels. - const clockX = row.x + row.width - Math.ceil(font.measureText(clock)); - image.drawText(font, clockX, top + Math.max(0, ((TOP_BAR_HEIGHT - font.lineHeight) / 2) | 0), clock, 210); - // The battery block keeps its usual right margin inside the edge it's given. - const batteryLeft = this.drawTopBarBatteries(image, state, top, clockX - ROW_CLOCK_GAP + BATTERY_BLOCK_RIGHT_MARGIN); - const trayLeft = drawTrayIcons(image, state.trayIcons, batteryLeft, top); + private layoutBottomBar(state: ShellChromeState): BottomBarPlan | null { + if (switcherPosition() !== "bottom") return null; + const appId = state.foregroundAppId; + const status = statusInSwitcherRow(appId) ? this.rowStatusItems(state) : []; + const plan = planBottomBar(switcherRect(state.foregroundHeightMode, appId).width, state.windows.length, status); + if (setSwitcherBarHeight(plan.height, appId)) this.onBottomBarHeightChanged(); + return plan; + } - // Right-aligned against the widgets, with the top bar's spacing. - const slots = Math.min(windowCount, ROW_MIN_WINDOW_SLOTS); - const windowsFloor = row.x + 2 * LIST_MARGIN + Math.max(0, slots * ROW_STEP - ICON_SPACING) + ROW_STATUS_GAP; - const iconsRight = trayLeft - 8, step = NOTIFICATION_ICON_STEP; - const maxIcons = Math.max(0, ((iconsRight - windowsFloor + 4) / step) | 0); - if (maxIcons === 0) return trayLeft; - const { icons, keys, stale } = readActiveNotificationIcons(maxIcons, renderPassAllowsStaleData()); + /** + * The status bar's items for the bottom switcher, left to right: every + * notification icon, the app widgets, the battery block, and the date and + * time, each to draw as it sits in the top bar. + */ + private rowStatusItems(state: ShellChromeState): RowStatusItem[] { + const items: RowStatusItem[] = []; + const { icons, keys, stale } = readActiveNotificationIcons(ALL_NOTIFICATIONS, renderPassAllowsStaleData()); if (stale) { noteStaleDataUsed(); } - if (!icons.length) return trayLeft; - const iconsLeft = iconsRight - icons.length * step + 4; - this.drawNotificationIcons(image, state, icons, keys, iconsLeft, top + (((TOP_BAR_HEIGHT - NOTIFICATION_ICON_SIZE) / 2) | 0)); - return iconsLeft; + 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), + })); + for (const icon of state.trayIcons) { + items.push({ kind: "tray", width: icon.width, draw: (image, x, top) => drawTrayIcon(image, icon, x, top) }); + } + const batteries = batteryItems(state); + if (batteries.length) { + // Measured by drawing it: each battery style lays itself out as it draws. + const scratch = new GrayImage(G2_LENS_WIDTH, TOP_BAR_HEIGHT, 0); + const width = G2_LENS_WIDTH - BATTERY_BLOCK_RIGHT_MARGIN - drawBatteryBlock(scratch, batteries, 0, G2_LENS_WIDTH); + // The block keeps its usual right margin inside the edge it's given. + items.push({ kind: "batteries", width, + draw: (image, x, top) => drawBatteryBlock(image, batteries, top, x + width + BATTERY_BLOCK_RIGHT_MARGIN) }); + } + const font = getDefaultMediumFont(); + const clock = clockText(); + // A TTF face measures fractionally; the status surface's crop edges need whole pixels. + items.push({ kind: "clock", width: Math.ceil(font.measureText(clock)), + draw: (image, x, top) => image.drawText(font, x, top + Math.max(0, ((TOP_BAR_HEIGHT - font.lineHeight) / 2) | 0), clock, 210) }); + return items; + } + + /** + * The status bar at the right end of the bottom switcher: its rows as + * planned (planBottomBar), each right-aligned against the switcher's end, + * the first row ROW_STATUS_TOP under its top. Whatever the windows leave + * over is free space between the two. Returns the left edge of the widest + * row. + */ + private drawRowStatus(image: GrayImage, row: Rect, bar: BottomBarPlan): number { + image.fillRect(row.x, row.y + 1, row.width, row.height - 1, SHELL_OPAQUE_BLACK); + const right = row.x + row.width; + bar.statusRows.forEach((items, line) => { + const top = row.y + ROW_STATUS_TOP + line * bar.statusPitch; + let x = right - statusRowWidth(items); + items.forEach((item, index) => { + if (index > 0) x += statusGap(items[index - 1]!, item); + item.draw(image, x, top); + x += item.width; + }); + }); + return right - bar.statusWidth; } /** @@ -759,118 +944,124 @@ export class ShellChromeLayer implements Layer { const textY = barTop + Math.max(0, ((TOP_BAR_HEIGHT - font.lineHeight) / 2) | 0); image.drawText(font, clockX, textY, clock, 210); - const batteryLeft = this.drawTopBarBatteries(image, state, barTop, barRight); + const batteryLeft = drawBatteryBlock(image, batteryItems(state), barTop, barRight); const trayLeft = drawTrayIcons(image, state.trayIcons, batteryLeft, barTop); const iconsX = clockX + Math.ceil(font.measureText(clock)) + 16; - const maxIcons = Math.max(0, ((trayLeft - 8 - iconsX) / NOTIFICATION_ICON_STEP) | 0); + const maxIcons = Math.max(0, ((trayLeft - NOTIFICATIONS_GAP - iconsX) / NOTIFICATION_ICON_STEP) | 0); if (maxIcons > 0) { const { icons, keys, stale } = readActiveNotificationIcons(maxIcons, renderPassAllowsStaleData()); if (stale) { noteStaleDataUsed(); } - this.drawNotificationIcons(image, state, icons, keys, iconsX, barTop + (((TOP_BAR_HEIGHT - NOTIFICATION_ICON_SIZE) / 2) | 0)); + 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); + } } } /** - * Draw the notification icons left to right from `left`, noting each as a - * notification entry. The one the switcher's selection is on + * 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. */ - private drawNotificationIcons(image: GrayImage, state: ShellChromeState, icons: GrayImage[], keys: string[], left: number, iconY: number): void { - for (let index = 0; index < icons.length; index++) { - const x = left + index * NOTIFICATION_ICON_STEP; - const key = keys[index]; - 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, - }; - if (key) this.notificationEntries.push({ key, ...box }); - const selected = !!key && key === state.selectedNotificationKey; - const focused = selected && state.focus === "sidebar"; - if (selected) drawSelectionBox(image, box.x, box.y, box.width, box.height, focused); - image.drawImage(focused ? invertedIcon(icons[index]!) : icons[index]!, x, iconY); - } - } - - /** - * Labelled battery indicators for the phone, Wear OS watch, G2, and R1, - * right-aligned in the top bar. The watch one exists only while a watch - * running the Faceclaw watch app is reachable (no placeholder otherwise). - * The Settings > Customization > Battery indicators submenu picks the - * style (label beside a gauge icon or percentage, stacked above either, or - * dense: device icons beside gauges, two per column) and, per device, - * whether the indicator shows always, only below 50%, or never. `barRight` - * is the bar's right edge (short of a right-hand sidebar). Returns the left - * edge of the battery block. - */ - private drawTopBarBatteries(image: GrayImage, state: ShellChromeState, barTop: number, barRight: number): number { - const mode = batteryDisplayModeSetting.get(); - const items: BatteryItem[] = []; - const phone = readPhoneBatteryState(); - if (phone.battery !== null && Number.isFinite(phone.battery)) { - pushBatteryItem(items, phoneBatteryVisibilitySetting.get(), "Phone", "phone", phone.battery, Boolean(phone.charging)); - } - if (state.battery.watch !== null && Number.isFinite(state.battery.watch)) { - pushBatteryItem(items, watchBatteryVisibilitySetting.get(), "Watch", "watch", state.battery.watch, - Boolean(state.battery.watchCharging)); - } - if (state.battery.headset !== null && Number.isFinite(state.battery.headset)) { - pushBatteryItem(items, glassesBatteryVisibilitySetting.get(), "G2", "glasses", state.battery.headset, - Boolean(state.battery.headsetCharging)); - } - if (state.battery.ring !== null && Number.isInteger(state.battery.ring) - && state.battery.ring >= 0 && state.battery.ring <= 100) { - pushBatteryItem(items, ringBatteryVisibilitySetting.get(), "R1", "ring", state.battery.ring, - Boolean(state.battery.ringCharging)); - } - if (!items.length) return barRight; - if (mode === "stacked" || mode === "stacked-percentage") { - return drawStackedBatteries(image, items, barTop, barRight, mode === "stacked-percentage"); - } - if (mode === "dense") { - return drawDenseBatteries(image, items, barRight - BATTERY_BLOCK_RIGHT_MARGIN, barTop + DENSE_TOP); - } - - const font = getDefaultSmallFont(); - const percentageMode = mode === "percentage"; - const labelGap = 5; - const itemGap = 12; - const textY = barTop + Math.max(0, ((TOP_BAR_HEIGHT - font.lineHeight) / 2) | 0); - let x = barRight - BATTERY_BLOCK_RIGHT_MARGIN; - for (let index = items.length - 1; index >= 0; index--) { - const item = items[index]!; - const percentText = `${item.percent}%`; - const valueWidth = percentageMode ? Math.ceil(font.measureText(percentText)) : BATTERY_ICON_WIDTH; - const labelWidth = Math.ceil(font.measureText(item.label)); - x -= labelWidth + labelGap + valueWidth; - image.drawText(font, x, textY, item.label, BATTERY_LABEL_VALUE); - 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, barTop + Math.max(0, ((TOP_BAR_HEIGHT - icon.height) / 2) | 0), { - transparentZero: true, - }); - } - x -= itemGap; - } - return x + itemGap; + private drawNotificationIcon(image: GrayImage, state: ShellChromeState, icon: GrayImage, key: string | undefined, x: number, iconY: number): void { + 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, + }; + if (key) this.notificationEntries.push({ key, ...box }); + const selected = !!key && key === state.selectedNotificationKey; + 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); } } type BatteryItem = { label: string; device: BatteryDevice; percent: number; charging: boolean }; +/** + * Labelled battery indicators for the phone, Wear OS watch, G2, and R1. The + * watch one exists only while a watch running the Faceclaw watch app is + * reachable (no placeholder otherwise). The Settings > Customization > + * Battery indicators submenu picks, per device, whether the indicator shows + * always, only below 50%, or never. + */ +function batteryItems(state: ShellChromeState): BatteryItem[] { + const items: BatteryItem[] = []; + const phone = readPhoneBatteryState(); + if (phone.battery !== null && Number.isFinite(phone.battery)) { + pushBatteryItem(items, phoneBatteryVisibilitySetting.get(), "Phone", "phone", phone.battery, Boolean(phone.charging)); + } + if (state.battery.watch !== null && Number.isFinite(state.battery.watch)) { + pushBatteryItem(items, watchBatteryVisibilitySetting.get(), "Watch", "watch", state.battery.watch, + Boolean(state.battery.watchCharging)); + } + if (state.battery.headset !== null && Number.isFinite(state.battery.headset)) { + pushBatteryItem(items, glassesBatteryVisibilitySetting.get(), "G2", "glasses", state.battery.headset, + Boolean(state.battery.headsetCharging)); + } + if (state.battery.ring !== null && Number.isInteger(state.battery.ring) + && state.battery.ring >= 0 && state.battery.ring <= 100) { + pushBatteryItem(items, ringBatteryVisibilitySetting.get(), "R1", "ring", state.battery.ring, + Boolean(state.battery.ringCharging)); + } + return items; +} + +/** + * The battery indicators (batteryItems), right-aligned in the top bar's + * layout from `barTop`, in the style the Battery indicators submenu picks: + * label beside a gauge icon or percentage, stacked above either, or dense + * (device icons beside gauges, two per column). `barRight` is the bar's + * right edge (short of a right-hand sidebar). Returns the left edge of the + * battery block, or `barRight` with no indicators. + */ +function drawBatteryBlock(image: GrayImage, items: BatteryItem[], barTop: number, barRight: number): number { + const mode = batteryDisplayModeSetting.get(); + if (!items.length) return barRight; + if (mode === "stacked" || mode === "stacked-percentage") { + return drawStackedBatteries(image, items, barTop, barRight, mode === "stacked-percentage"); + } + if (mode === "dense") { + return drawDenseBatteries(image, items, barRight - BATTERY_BLOCK_RIGHT_MARGIN, barTop + DENSE_TOP); + } + + const font = getDefaultSmallFont(); + const percentageMode = mode === "percentage"; + const labelGap = 5; + const itemGap = 12; + const textY = barTop + Math.max(0, ((TOP_BAR_HEIGHT - font.lineHeight) / 2) | 0); + let x = barRight - BATTERY_BLOCK_RIGHT_MARGIN; + for (let index = items.length - 1; index >= 0; index--) { + const item = items[index]!; + const percentText = `${item.percent}%`; + const valueWidth = percentageMode ? Math.ceil(font.measureText(percentText)) : BATTERY_ICON_WIDTH; + const labelWidth = Math.ceil(font.measureText(item.label)); + x -= labelWidth + labelGap + valueWidth; + image.drawText(font, x, textY, item.label, BATTERY_LABEL_VALUE); + 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, barTop + Math.max(0, ((TOP_BAR_HEIGHT - icon.height) / 2) | 0), { + transparentZero: true, + }); + } + x -= itemGap; + } + return x + itemGap; +} + /** The status bar's date and time. */ function clockText(): string { const now = new Date(); @@ -1009,12 +1200,17 @@ function drawTrayIcons(image: GrayImage, trayIcons: GrayImage[], rightEdge: numb let x = rightEdge; for (let index = trayIcons.length - 1; index >= 0; index--) { const icon = trayIcons[index]!; - x -= icon.width + 10; - image.drawImage(icon, x, barTop + Math.max(0, ((TOP_BAR_HEIGHT - icon.height) / 2) | 0)); + 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 { diff --git a/app/ui/shell/geometry.ts b/app/ui/shell/geometry.ts index 5be3bfbb..ec8abc62 100644 --- a/app/ui/shell/geometry.ts +++ b/app/ui/shell/geometry.ts @@ -26,17 +26,38 @@ export const TOP_BAR_HEIGHT = 28; export const SIDEBAR_WIDTH = 64; /** - * Height of the app switcher as a row under the window: one tall tab, the + * Height of one row of the app switcher under the window: one tall tab, the * same 36px (a 32px icon plus 2px either side) as a one-column sidebar slot. * The row is wide enough that it never needs the sidebar's smaller * two-column icons. It comes out of the height available to windows; their * width stays 576, centred, leaving SIDEBAR_WIDTH / 2 at each side: one * pixel for the side of the window's frame (windowFramed), the rest for the * whole display's stereo shift (uiDepth). Full Screen windows take those - * margins too, giving up both. + * margins too, giving up both. When the row's contents don't fit, the + * switcher grows a second row (see setSwitcherBarHeight). */ export const SWITCHER_ROW_HEIGHT = 36; +/** + * Height of the bottom switcher as its contents last laid out (chrome-layer.ts + * planBottomBar): SWITCHER_ROW_HEIGHT, or more once the status bar's items + * or the window icons take a second row. One for the switcher reserved + * under windows, one for the switcher overlaying an immersive window. + */ +const switcherBarHeights = { reserved: SWITCHER_ROW_HEIGHT, overlay: SWITCHER_ROW_HEIGHT }; + +/** + * Set the bottom switcher's height for its current layout under the given + * (foreground) app's window: the overlay's over an immersive window, else + * the row reserved under windows. True if that moves or resizes windows. + */ +export function setSwitcherBarHeight(height: number, appId?: string): boolean { + const which = isImmersive(appId) ? "overlay" : "reserved"; + if (switcherBarHeights[which] === height) return false; + switcherBarHeights[which] = height; + return which === "reserved"; +} + /** Which edge the app switcher is on, or a popup (Settings > Customization). */ export function switcherPosition(): AppSwitcherPosition { return appSwitcherPositionSetting.get(); @@ -116,13 +137,13 @@ export function sidebarWidth(appId?: string): number { } /** - * How much of the screen's height a bottom switcher row takes away from app - * windows: the row, or nothing beside a side strip or under an immersive - * window (where the row overlays the window's bottom edge while it has - * focus). + * How much of the screen's height a bottom switcher takes away from app + * windows: its rows (one, or two when the layout needs them), or nothing + * beside a side strip or under an immersive window (where the switcher + * overlays the window's bottom edge while it has focus). */ export function switcherRowHeight(appId?: string): number { - return !isImmersive(appId) && switcherPosition() === "bottom" ? SWITCHER_ROW_HEIGHT : 0; + return !isImmersive(appId) && switcherPosition() === "bottom" ? switcherBarHeights.reserved : 0; } /** @@ -139,23 +160,25 @@ export function sidebarStripVisible(focus: "sidebar" | "window", appId?: string) * (foreground) window and spans its width, so a band shorter than the * screen has no gap below it; it moves when the foreground switches to a * window of another height, as the top bar does. Over an immersive window - * the row overlays the bottom edge of the screen. A popup's is the area it - * centres in, the foreground window's content (the chrome layer sizes the - * box itself). + * the row overlays the bottom edge of the screen. Either way it is as tall + * as its layout (setSwitcherBarHeight). A popup's is the area it centres + * in, the foreground window's content (the chrome layer sizes the box + * itself). */ export function switcherRect(heightMode: WindowHeightMode, appId?: string): { x: number; y: number; width: number; height: number } { switch (switcherPosition()) { case "popup": return appViewportRect(heightMode, appId); - case "bottom": + case "bottom": { + const reserved = switcherRowHeight(appId); + const height = reserved || switcherBarHeights.overlay; return { x: appViewportLeft(appId), - y: switcherRowHeight(appId) > 0 - ? windowTop(heightMode, appId) + windowBandHeight(heightMode, appId) - : G2_LENS_HEIGHT - SWITCHER_ROW_HEIGHT, + y: reserved > 0 ? windowTop(heightMode, appId) + windowBandHeight(heightMode, appId) : G2_LENS_HEIGHT - height, width: appViewportWidth(appId), - height: SWITCHER_ROW_HEIGHT, + height, }; + } case "right": return { x: G2_LENS_WIDTH - SIDEBAR_WIDTH, y: minWindowTop(appId), width: SIDEBAR_WIDTH, height: MIN_WINDOW_HEIGHT }; default: @@ -345,7 +368,7 @@ export const SHELL_OPAQUE_BLACK = 1; * firmware uses, leaving most of the field of view clear; "medium" is one * header (and footer) taller, so the content area between them is a full * 288px (the EvenHub app surface height); "max" uses the whole 480px screen - * (terminal views), less a bottom switcher row. All include the header the + * (terminal views), less a bottom switcher's rows. All include the header the * shell draws at the window's top edge (windowHeaderHeight) and any footer * at its bottom (windowFooterHeight). */ @@ -356,7 +379,7 @@ export const MIN_WINDOW_HEIGHT = 288; /** * Height of the screen area windows are placed in: the whole screen, less - * a bottom switcher row's height. + * a bottom switcher's height. */ function windowAreaHeight(appId?: string): number { return G2_LENS_HEIGHT - switcherRowHeight(appId); @@ -394,11 +417,17 @@ export function minWindowTop(appId?: string): number { /** * Top edge (y) of a window's header; max-height windows pin to the screen - * top. A bottom switcher row hangs under the band, so the band and row - * together distribute the screen's slack. + * top. A bottom switcher row hangs under the band, so the band and a + * one-row switcher together distribute the screen's slack. A switcher of + * more rows takes its extra height out of the slack under it, pushing the + * band up only as far as there is too little, so the band doesn't move as + * the switcher's layout changes unless it has to. */ export function windowTop(mode: WindowHeightMode, appId?: string): number { - return Math.round((windowAreaHeight(appId) - windowBandHeight(mode, appId)) * verticalPositionFraction(appId)); + const band = windowBandHeight(mode, appId); + const oneRowArea = G2_LENS_HEIGHT - (switcherRowHeight(appId) > 0 ? SWITCHER_ROW_HEIGHT : 0); + const top = Math.round((oneRowArea - band) * verticalPositionFraction(appId)); + return Math.min(top, windowAreaHeight(appId) - band); } /** App-content viewport size for a height mode (independent of vertical position). */ diff --git a/app/ui/shell/shell.ts b/app/ui/shell/shell.ts index 19bc40a4..38447cd9 100644 --- a/app/ui/shell/shell.ts +++ b/app/ui/shell/shell.ts @@ -143,9 +143,10 @@ export type ShellWindow = { /** Repaint and resubmit this window's surface. */ requestRender: () => void; /** - * Re-measure against the current display mode (viewport size / band) and - * repaint. Windows without it (workers with a canvas fixed at open) are - * closed and relaunched by the controller instead. + * Re-measure against the current display mode and app switcher (viewport + * size / band) and repaint. Windows without it are closed and relaunched + * by the controller instead on a display mode change, and left at the size + * they opened with when the bottom switcher changes height. */ relayout?: () => void; /** @@ -201,6 +202,12 @@ export type ShellConfig = { onScreenStateChanged: (on: boolean) => void; /** Window registered/removed or foreground changed (persists the open-app list). */ onWindowsChanged?: () => void; + /** + * The bottom switcher's layout changed its height (geometry.ts + * setSwitcherBarHeight): windows have to move, or resize, to suit. Called + * after the shell paint that found it. + */ + onSwitcherBarHeightChanged?: () => void; /** * The Notifications app's window, opened in the background (neither * foregrounded nor focused) unless it is open already, for the switcher @@ -445,8 +452,9 @@ class Shell { requestShellRender: () => {}, onScreenStateChanged: () => {}, }; - private readonly chrome = new ShellChromeLayer(() => this.chromeState()); + private readonly chrome = new ShellChromeLayer(() => this.chromeState(), () => this.switcherBarHeightChanged()); private readonly stack = new LayerStack(this.chrome, this.actions); + private switcherBarChangePending = false; // Top-bar settings we mirror into the chrome; a change to any of them // repaints the shell surface so the top bar reflects it immediately. @@ -494,6 +502,21 @@ class Shell { }); } + /** + * The chrome found, mid-paint, that the bottom switcher's height changed. + * The controller moves or resizes windows once the paint is over: a + * window's relayout repaints it, which mustn't happen inside the shell's + * own paint. + */ + private switcherBarHeightChanged(): void { + if (this.switcherBarChangePending) return; + this.switcherBarChangePending = true; + setTimeout(() => { + this.switcherBarChangePending = false; + this.config.onSwitcherBarHeightChanged?.(); + }, 0); + } + /** Add a window (or replace one with the same windowId, keeping its slot). */ registerWindow(window: ShellWindow): void { const existing = this.windows.findIndex((w) => w.windowId === window.windowId); diff --git a/app/ui/shell/worker-window.ts b/app/ui/shell/worker-window.ts index 3ef4685b..79cb3799 100644 --- a/app/ui/shell/worker-window.ts +++ b/app/ui/shell/worker-window.ts @@ -460,10 +460,10 @@ export class WorkerAppHost { closeable: true, acceptsDirectional: spec.acceptsDirectional, heightMode, - // These apps can resize their live content without losing route/session state. - relayout: this.options.appId === "navigate" || this.options.appId === "terminal" - ? () => this.post({ type: "resize-window", windowId: spec.windowId, viewport: appViewportSize(heightMode, this.options.appId) }) - : undefined, + // Every app worker resizes its live content in place, keeping its state + // (a game in progress, a route): the bottom switcher's height changes + // with what it holds, and full-height windows give way to it. + relayout: () => this.post({ type: "resize-window", windowId: spec.windowId, viewport: appViewportSize(heightMode, this.options.appId) }), hasAppMenu: () => this.windowGestures.get(spec.windowId)?.hasAppMenu ?? false, claimsLongPress: () => this.windowGestures.get(spec.windowId)?.claimsLongPress ?? false, close: () => { diff --git a/tests/app-layout.test.cjs b/tests/app-layout.test.cjs index cc31f474..785fa756 100644 --- a/tests/app-layout.test.cjs +++ b/tests/app-layout.test.cjs @@ -282,7 +282,7 @@ function chromeLayer(g, { notifications = 0, phoneBattery = null, windows = 1, t '../../graphics/textwrap': require('../.test-build/app/graphics/textwrap.js'), '../../graphics/battery': require('../.test-build/app/graphics/battery.js'), './ambient-cards': { activeAmbientCards: () => [] }, - '../../native/notification-icons': { readActiveNotificationIcons: (max) => { + '../../native/notification-icons': { ALL_NOTIFICATIONS: 0x7fffffff, readActiveNotificationIcons: (max) => { requested.push(max); const count = Math.min(max, notifications); return { icons: Array.from({ length: count }, () => new graphics.GrayImage(24, 24, 200)), @@ -307,7 +307,9 @@ function chromeLayer(g, { notifications = 0, phoneBattery = null, windows = 1, t selectedIndex: 0, focus: 'window', foregroundHeightMode: 'min', battery: { headset: null, ring: null, watch: null }, trayIcons, }; - return { chrome: new context.exports.ShellChromeLayer(() => state), state, requested }; + let heightChanges = 0; + const chrome = new context.exports.ShellChromeLayer(() => state, () => heightChanges++); + return { chrome, state, requested, planBottomBar: context.exports.planBottomBar, heightChanges: () => heightChanges }; } test('a bottom app switcher frames the foreground window\'s content in a rounded border', () => { @@ -405,12 +407,13 @@ test('the launcher\'s tab lines up with the window frame, whose corner squares t ({ px, at } = paint(chrome)); assert.deepEqual([px(31, 365), px(32, 365), at(35, 366), at(36, 366)], [0, 0, 1, 40]); assert.equal(chrome.windowIndexAt(31, 380, 3), 0); - // Scrolled past the launcher, the cells keep the left chevron's margin. - const scrolled = chromeLayer(g, { windows: 20 }); - scrolled.state.selectedIndex = 19; + // Scrolled past the launcher (more windows than two rows of 14 hold), the + // cells keep the left chevron's margin. + const scrolled = chromeLayer(g, { windows: 40 }); + scrolled.state.selectedIndex = 39; ({ px } = paint(scrolled.chrome)); - assert.equal(scrolled.chrome.windowIndexAt(35, 380, 20), null); - assert.notEqual(scrolled.chrome.windowIndexAt(41, 380, 20), null); + assert.equal(scrolled.chrome.windowIndexAt(35, 380, 40), null); + assert.notEqual(scrolled.chrome.windowIndexAt(41, 380, 40), null); assert.equal(px(31, 365), 0); }); @@ -459,35 +462,144 @@ test('the switcher row lays out windows, free space, notifications, widgets, bat assert.equal(at(row, 40 + 2, 366 + 2), 120, 'first window icon'); assert.equal(chrome.windowIndexAt(45, 380, 1), 0); assert.equal(chrome.windowIndexAt(iconsLeft + 2, 380, 1), null); - // Notification icons stop short of the one window slot's room (with the - // row's margins and the gap to the status bar). - assert.equal(requested.at(-1), Math.floor((trayLeft - 8 - (32 + 20 + 40 - 8 + 8) + 4) / 28)); + // The row asks for every notification icon, to lay itself out round them all. + assert.equal(requested.at(-1), 0x7fffffff); // No top bar, but the frame is still there, its top one row above the content. const [frame] = row.image.draws.filter((d) => d.presentation?.displayList); assert.deepEqual([row.x + frame.x, row.y + frame.y, frame.source.height], [31, 78, 289]); shellScene.encodeShellScene(parts, g.uiDepth()); }); -test('many windows scroll in what the notification icons leave them', () => { +test('past two rows of windows, they scroll, and notification icons give way to a few slots a row', () => { const g = geometry(); g.settings.appSwitcherPositionSetting.value = 'bottom'; g.settings.statusBarPositionSetting.value = 'bottom'; - const { chrome, requested } = chromeLayer(g, { notifications: 40, windows: 12 }); + const { chrome, requested, heightChanges } = chromeLayer(g, { notifications: 40, windows: 12 }); const [row, status] = chrome.paintParts(); - // Clock only (no batteries or widgets): notifications end 8px before its - // 8px lead-in, and stop where three window slots plus margins remain. - const trayLeft = 608 - 56 - 8, floor = 32 + 20 + 3 * 40 - 8 + 8; - const max = Math.floor((trayLeft - 8 - floor + 4) / 28); - assert.equal(requested.at(-1), max); - const iconsLeft = trayLeft - 8 - max * 28 + 4; - assert.equal(status.x, iconsLeft - 2); - // Three windows fit before the status bar's gap; the rest scroll, with the - // chevron at the end of the windows rather than of the row. + assert.equal(requested.at(-1), 0x7fffffff); + // The last layout: two rows of each, 72px tall, under the unmoved band. + assert.equal(g.switcherRowHeight(), 72); + assert.equal(heightChanges(), 1); + assert.deepEqual([row.y, row.image.height], [366, 72]); + // 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.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]); + // Three windows a row; the rest scroll, with the chevron after the second + // row's, at the end of the windows rather than of the row. assert.equal(chrome.windowIndexAt(32 + 10 + 2 * 40 + 4, 380, 12), 2); assert.equal(chrome.windowIndexAt(32 + 10 + 3 * 40 + 4, 380, 12), null); - const windowsRight = iconsLeft - 8; - const chevron = row.image.pixels.findIndex((v, i) => v === 140); - assert.equal(chevron % row.image.width + row.x, windowsRight - 6); + assert.equal(chrome.windowIndexAt(32 + 10 + 2 * 40 + 4, 420, 12), 5); + const windowsRight = 608 - 432 - 8; + const chevron = row.image.pixels.findIndex((v) => v === 140); + assert.deepEqual([chevron % row.image.width + row.x, Math.floor(chevron / row.image.width) + row.y], [windowsRight - 6, 366 + 36 + 18 - 5]); +}); + +test('the bottom switcher falls back to denser layouts as what it holds outgrows it', () => { + const { planBottomBar } = chromeLayer(geometry()); + const notifications = (count) => Array.from({ length: count }, () => ({ kind: 'notification', width: 24 })); + const clock = { kind: 'clock', width: 56 }; + const summary = (plan) => [plan.level, plan.height, plan.windowRows, plan.windowColumns, + Array.from(plan.statusRows, (items) => items.length), plan.statusWidth, plan.statusPitch]; + // Three windows (132px with margins) and five icons and the clock fit one row. + assert.deepEqual(summary(planBottomBar(576, 3, [...notifications(5), clock])), [1, 36, 1, 8, [6], 208, 28]); + // Fourteen icons don't (28 * 14 - 4 + 16 + 56 > 576 - 132 - 8), so the + // status bar takes two rows, broken where they come nearest the same + // width: 8 icons (220px) over 6 and the clock (236px), a top bar apart. + const many = [...notifications(14), clock]; + assert.deepEqual(summary(planBottomBar(576, 3, many)), [2, 64, 1, 8, [8, 7], 236, 28]); + // Nine windows don't fit the one row of 8 slots that leaves: two rows of + // windows, the status rows level with them. + assert.deepEqual(summary(planBottomBar(576, 9, many)), [3, 72, 2, 8, [8, 7], 236, 36]); + // Seventeen don't fit those 16 slots: the last layout scrolls them. + assert.deepEqual(summary(planBottomBar(576, 17, many)), [4, 72, 2, 8, [8, 7], 236, 36]); + // Without the status bar, the windows alone: 14 a row. + assert.deepEqual(summary(planBottomBar(576, 14, [])), [1, 36, 1, 14, [], 0, 28]); + assert.deepEqual(summary(planBottomBar(576, 15, [])), [3, 72, 2, 14, [], 0, 36]); + assert.deepEqual(summary(planBottomBar(576, 29, [])), [4, 72, 2, 14, [], 0, 36]); + // A full-width (640) row has room for more. + assert.equal(planBottomBar(640, 3, many).level, 1); +}); + +test('a taller bottom switcher takes its room from the slack under a band, or from full-height windows', () => { + const g = geometry(); + g.settings.appSwitcherPositionSetting.value = 'bottom'; + g.settings.statusBarPositionSetting.value = 'bottom'; + const before = g.rect('min'); + assert.equal(g.setSwitcherBarHeight(64), true); + assert.equal(g.setSwitcherBarHeight(64), false); + // The band stays put, the switcher growing down into the slack under it... + assert.deepEqual(g.rect('min'), before); + assert.deepEqual({ ...g.switcherRect('min') }, { x: 32, y: 366, width: 576, height: 64 }); + assert.equal(g.isOnSwitcherEdge(10, 420, 'min'), true); + // ...pushing it up only where there's too little. + g.settings.displayLayoutSetting.value = 'band-low'; + assert.equal(g.windowTop('min'), 117); + g.settings.displayLayoutSetting.value = 'band-bottom'; + assert.equal(g.windowTop('min'), 480 - 64 - 288); + assert.equal(g.switcherRect('min').y + 64, 480); + // Tall windows give up the height. + g.settings.displayLayoutSetting.value = 'tall'; + assert.deepEqual(g.rect('max'), { x: 32, y: 1, width: 576, height: 415 }); + g.settings.displayLayoutSetting.value = 'band-middle'; + assert.deepEqual(g.rect('max', 'terminal'), { x: 32, y: 1, width: 576, height: 415 }); + // Over an immersive window the switcher is an overlay of its own height, + // which moves no window. + g.setAppImmersive('onboarding', true); + assert.equal(g.setSwitcherBarHeight(72, 'onboarding'), false); + assert.deepEqual({ ...g.switcherRect('min', 'onboarding') }, { x: 0, y: 408, width: 640, height: 72 }); + assert.equal(g.switcherRowHeight(), 64); + // Beside a side strip it takes nothing. + g.settings.appSwitcherPositionSetting.value = 'left'; + assert.equal(g.switcherRowHeight(), 0); +}); + +test('the status bar takes a second row of its own before the windows do', () => { + const g = geometry(); + g.settings.appSwitcherPositionSetting.value = 'bottom'; + g.settings.statusBarPositionSetting.value = 'bottom'; + const { chrome, heightChanges } = chromeLayer(g, { notifications: 14, windows: 3 }); + const before = g.rect('min'); + const [row, status] = chrome.paintParts(); + assert.equal(g.switcherRowHeight(), 64); + assert.equal(heightChanges(), 1); + chrome.paintParts(); + assert.equal(heightChanges(), 1, 'reported once'); + assert.deepEqual(g.rect('min'), before); + // Both rows right-aligned against the row's end: 8 icons (220px) over 6 + // and the clock (236px), a top bar's height apart. + assert.deepEqual([status.x, status.y, status.image.height], [608 - 236 - 2, 367, 63]); + 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}`)); + // The windows keep one row, against the window. + assert.equal(chrome.windowIndexAt(45, 380, 3), 0); + assert.equal(chrome.windowIndexAt(45, 410, 3), null); + assert.equal(row.image.height, 64); +}); + +test('windows past one row take a second, where a selected one sits in a box', () => { + const g = geometry(); + g.settings.appSwitcherPositionSetting.value = 'bottom'; + g.settings.statusBarPositionSetting.value = 'bottom'; + const { chrome, state } = chromeLayer(g, { notifications: 14, windows: 9 }); + state.selectedIndex = 8; + const [row, status] = chrome.paintParts(); + assert.equal(g.switcherRowHeight(), 72); + // Eight slots a row (what the 236px status rows leave); the ninth window + // starts the second row, under the first. + assert.deepEqual([chrome.windowIndexAt(31 + 7 * 40, 380, 9), chrome.windowIndexAt(31, 410, 9), chrome.windowIndexAt(71, 410, 9)], [7, 8, null]); + const at = (p, x, y) => p.image.pixels[(y - p.y) * p.image.width + x - p.x]; + // Its selection is a box (as for a sidebar overflow column), and the + // separator runs unbroken over the first row. + assert.deepEqual([at(row, 31, 402 + 18), at(row, 31 + 5, 402 + 7)], [150, 120]); + assert.equal(at(row, 50, 366), 40); + // The status rows line up with the window rows. + assert.equal(status.image.withDrawsBaked().pixels[(366 + 36 + 5 + 2 - status.y) * status.image.width + 608 - 236 - status.x], 200); }); test('a popup app switcher shows a box of window icons over the dimmed window while focused', () => { @@ -613,15 +725,15 @@ test('a notification the switcher selects sits in a box, filled with its icon in test('with the selection out on a notification, the windows stay scrolled as they were', () => { const g = geometry(); g.settings.appSwitcherPositionSetting.value = 'bottom'; - const { chrome, state } = chromeLayer(g, { notifications: 2, windows: 20 }); - state.selectedIndex = 19; + const { chrome, state } = chromeLayer(g, { notifications: 2, windows: 40 }); + state.selectedIndex = 39; chrome.paintParts(); const last = 32 + 10 + 2 * 40 + 4; - const before = chrome.windowIndexAt(last, 380, 20); + const before = chrome.windowIndexAt(last, 380, 40); assert.ok(before > 2); Object.assign(state, { selectedIndex: -1, selectedNotificationKey: 'n0' }); chrome.paintParts(); - assert.equal(chrome.windowIndexAt(last, 380, 20), before); + assert.equal(chrome.windowIndexAt(last, 380, 40), before); }); // Exercise the real worker message handler with platform work stubbed out. @@ -677,6 +789,33 @@ test('Terminal resize keeps the view identity, negotiates its grid and skips pos assert.equal(calls.length, 6); }); +test('the games and Roam resize in place, keeping their state, and repaint when in front', () => { + for (const app of ['blocks', 'freecell', 'minesweeper', 'pinball']) { + let paints = 0, menuSize; + const window = { windowId: 'test', viewportWidth: 576, viewportHeight: 443, foreground: true, phase: 'playing', + menu: { resize: (size) => { menuSize = size; } }, lastSubmittedFingerprint: 'old' }; + const resize = resizeHandler(`app/apps/${app}/${app}-app.worker.ts`, { + windows: new Map([['test', window]]), renderAndSubmit: () => paints++, + }); + resize({ width: 576, height: 415 }); + assert.deepEqual([window.viewportWidth, window.viewportHeight, window.phase, window.lastSubmittedFingerprint, paints], + [576, 415, 'playing', '', 1], app); + assert.deepEqual({ ...menuSize }, { width: 576, height: 415 }, app); + window.foreground = false; + resize({ width: 576, height: 443 }); + assert.deepEqual([window.viewportHeight, paints], [443, 1], app); + } + let paints = 0, viewSize; + const window = { windowId: 'test', viewportWidth: 576, viewportHeight: 443, menu: null, lastSubmittedFingerprint: 'old', + view: { resize: (...size) => { viewSize = size; } } }; + const resize = resizeHandler('app/apps/roam/roam-app.worker.ts', { + window, render: () => paints++, DOC_MARGIN: 6, HEADER_HEIGHT: 30, BOTTOM_MARGIN: 6, + }); + resize({ width: 576, height: 415 }); + // The document re-wraps for the region under its header. + assert.deepEqual([window.viewportHeight, viewSize, window.lastSubmittedFingerprint, paints], [415, [564, 379], '', 1]); +}); + test('resizing a terminal reconnects with the new grid and ignores callbacks from the old socket', () => { const sockets = []; const context = {