Multi-row status/app-switcher bar layouts

This commit is contained in:
James Babcock committed 2026-10-13 00:21:01 -07:00
1 parent f6201d8e41
commit 26e4396972
14 files changed
+706 -229

No files matched your search

+10 -1
View File
@@ -290,8 +290,17 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
updateTickTimer(window); updateTickTimer(window);
} }
break; 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 "navigation-sensors":
case "resize-window":
case "text-input": case "text-input":
case "tool-call": case "tool-call":
break; break;
+10 -1
View File
@@ -205,9 +205,18 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
if (window.foreground) renderAndSubmit(window, 0); if (window.foreground) renderAndSubmit(window, 0);
break; 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 "input-focus":
case "navigation-sensors": case "navigation-sensors":
case "resize-window":
case "screen": case "screen":
case "text-input": case "text-input":
case "tool-call": case "tool-call":
+10 -1
View File
@@ -250,8 +250,17 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
syncClock(window); syncClock(window);
} }
break; 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 "navigation-sensors":
case "resize-window":
case "text-input": case "text-input":
case "tool-call": case "tool-call":
break; break;
+10 -1
View File
@@ -411,8 +411,17 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
syncTickTimer(window); syncTickTimer(window);
} }
break; 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 "navigation-sensors":
case "resize-window":
case "text-input": case "text-input":
case "tool-call": case "tool-call":
break; break;
+9 -1
View File
@@ -251,9 +251,17 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
); );
break; 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 "input-focus":
case "navigation-sensors": case "navigation-sensors":
case "resize-window":
break; break;
} }
}; };
+31 -5
View File
@@ -423,6 +423,7 @@ class DashboardController {
}, },
openNotificationsWindow: () => openNotificationsWindow: () =>
this.openInProcessAppInBackground(NOTIFICATIONS_WINDOW_ID, NOTIFICATIONS_SURFACE_ID, createNotificationsAppWindow), this.openInProcessAppInBackground(NOTIFICATIONS_WINDOW_ID, NOTIFICATIONS_SURFACE_ID, createNotificationsAppWindow),
onSwitcherBarHeightChanged: () => this.applySwitcherBarHeight(),
onScreenStateChanged: (on) => { onScreenStateChanged: (on) => {
// Any wake of the regular UI replaces a showing Glanceboard. // Any wake of the regular UI replaces a showing Glanceboard.
if (on) this.glance.dismiss(); 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 lastAppLayouts = this.appLayouts();
private appLayouts(): Record<string, string> { private appLayouts(): Record<string, string> {
@@ -2565,20 +2589,22 @@ class DashboardController {
target: DisplayTarget | null = this.display, target: DisplayTarget | null = this.display,
): Promise<void> { ): Promise<void> {
if (!target) return; if (!target) return;
await target.configureSurface(surfaceId, { const rect = appViewportRect(heightMode, shell.getWindows().find((window) => window.surfaceId === surfaceId)?.appId);
...appViewportRect(heightMode, shell.getWindows().find((window) => window.surfaceId === surfaceId)?.appId), this.windowSurfaceRects.set(surfaceId, JSON.stringify(rect));
zOrder: 0, await target.configureSurface(surfaceId, { ...rect, zOrder: 0, transparency: "opaque" });
transparency: "opaque",
});
await target.setSurfaceVisible(surfaceId, typeof visible === "function" ? visible() : visible); 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<string, string>();
/** A late answer to "is this window in front?", for configureWindowSurface. */ /** A late answer to "is this window in front?", for configureWindowSurface. */
private isForegroundWindow(windowId: string): () => boolean { private isForegroundWindow(windowId: string): () => boolean {
return () => shell.foregroundWindow()?.windowId === windowId; return () => shell.foregroundWindow()?.windowId === windowId;
} }
private removeWindowSurface(surfaceId: string): void { private removeWindowSurface(surfaceId: string): void {
this.windowSurfaceRects.delete(surfaceId);
const display = this.display; const display = this.display;
if (!display) return; if (!display) return;
void display.removeSurface(surfaceId).catch((error) => { void display.removeSurface(surfaceId).catch((error) => {
+5
View File
@@ -181,6 +181,11 @@ export class IosPreviewController {
getScreenTimeoutMs: () => null, getScreenTimeoutMs: () => null,
requestShellRender: () => this.requestShellRender(), requestShellRender: () => this.requestShellRender(),
onWindowsChanged: () => { this.requestShellRender(); this.syncEvenHubPhoneUi() }, onWindowsChanged: () => { this.requestShellRender(); this.syncEvenHubPhoneUi() },
onSwitcherBarHeightChanged: () => {
this.relayout()
shell.foregroundWindow()?.requestRender()
this.requestShellRender()
},
onScreenStateChanged: on => { onScreenStateChanged: on => {
if (on) this.glance.dismiss() if (on) this.glance.dismiss()
void this.display?.setScreenBlanked(!on).catch(error => this.fail(error)) void this.display?.setScreenBlanked(!on).catch(error => this.fail(error))
+11 -4
View File
@@ -58,19 +58,21 @@ export function readActiveNotificationIcons(maxIcons: number, allowStale: boolea
const now = Date.now(); const now = Date.now();
if (cachedAtMs > 0 && now - cachedAtMs < ICON_CACHE_MS) { if (cachedAtMs > 0 && now - cachedAtMs < ICON_CACHE_MS) {
logCurrent("notification icons served from cache"); logCurrent("notification icons served from cache");
return { icons: cachedIcons.map(icon => icon.clone()), keys: cachedKeys.slice(), stale: false }; return cachedIconsResult(maxIcons, false);
} }
if (allowStale) { if (allowStale) {
logCurrent("notification icons served stale"); 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 keyList = new java.util.ArrayList();
const bytes = spanCurrent("fetch-notification-icons", () => const bytes = spanCurrent("fetch-notification-icons", () =>
toUint8Array( toUint8Array(
com.faceclaw.app.FaceclawMediaNotificationListenerService.getActiveNotificationIconGrays( com.faceclaw.app.FaceclawMediaNotificationListenerService.getActiveNotificationIconGrays(
ICON_SIZE, ICON_SIZE,
maxIcons, ALL_NOTIFICATIONS,
keyList, keyList,
), ),
), ),
@@ -91,7 +93,12 @@ export function readActiveNotificationIcons(maxIcons: number, allowStale: boolea
cachedIcons = icons; cachedIcons = icons;
cachedKeys = keys; cachedKeys = keys;
cachedAtMs = now; 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 = { export type NotificationIconResult = {
+10 -2
View File
@@ -49,10 +49,18 @@ export class DocumentView {
private scrollLine = 0; private scrollLine = 0;
constructor( constructor(
private readonly width: number, private width: number,
private readonly height: 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 { setDocument(root: DocumentRoot): void {
const previousId = this.selectedNode()?.id; const previousId = this.selectedNode()?.id;
this.root = root; this.root = root;
+353 -157
View File
@@ -6,7 +6,7 @@ import { getDefaultMediumFont, getDefaultSmallFont } from "../../graphics/ui-fon
import { truncateText } from "../../graphics/textwrap"; import { truncateText } from "../../graphics/textwrap";
import { activeAmbientCards } from "./ambient-cards"; import { activeAmbientCards } from "./ambient-cards";
import { BATTERY_ICON_WIDTH, DENSE_BATTERY_BLOCK_HEIGHT, drawBattery, drawDenseBatteries, type BatteryDevice } from "../../graphics/battery"; 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 { readPhoneBatteryState } from "../../native/phone-battery";
import { noteStaleDataUsed, renderPassAllowsStaleData } from "../../util/render-freshness"; import { noteStaleDataUsed, renderPassAllowsStaleData } from "../../util/render-freshness";
import { renderIcon, renderIconWithGlyph, type IconActivity, type IconName } from "../../graphics/icons"; import { renderIcon, renderIconWithGlyph, type IconActivity, type IconName } from "../../graphics/icons";
@@ -30,6 +30,7 @@ import {
isImmersive, isImmersive,
MIN_WINDOW_HEIGHT, MIN_WINDOW_HEIGHT,
minWindowTop, minWindowTop,
setSwitcherBarHeight,
SHELL_OPAQUE_BLACK, SHELL_OPAQUE_BLACK,
SIDEBAR_WIDTH, SIDEBAR_WIDTH,
sidebarStripVisible, sidebarStripVisible,
@@ -56,7 +57,8 @@ import {
* sidebar. In the two-column variant the column against the app area fills * 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 * 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 * 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 }; type SidebarVariant = { columns: number; columnWidth: number; iconSize: number };
const ONE_COLUMN: SidebarVariant = { columns: 1, columnWidth: 36, iconSize: 32 }; 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 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 // 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 // (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); 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 // 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; const ROW_CLOCK_GAP = 16;
// Between the windows' end of the row (its scroll chevron) and the status. // Between the windows' end of the row (its scroll chevron) and the status.
const ROW_STATUS_GAP = 8; const ROW_STATUS_GAP = 8;
// Notification icons stop short of room for this many windows' slots (or // When the windows have to scroll anyway (planBottomBar's last layout),
// all of them, when there are fewer); the windows take whatever is left. // 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; 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 // The popup switcher (geometry.ts "popup"): a box centred over the
// foreground window's content, holding a row of window icons above 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). * 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 * A bottom switcher's window icons take `bar`'s slots (planBottomBar), the
* the status bar when it shares the row. `scrollRow` is the first visible * row against the window first, then the one under it. `scrollRow` is the
* window's index. * 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(); const position = switcherPosition();
if (position === "bottom") { if (position === "bottom") {
const row = switcherRect(heightMode, appId); 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 // 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 // at the frame's left side, one pixel outside the window, so a selection
// tab there carries the side straight down (drawWindowFrame squares that // tab there carries the side straight down (drawWindowFrame squares that
// corner for it). Scrolled past it, the cells keep the margin the left // 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; const first = windowFramed(appId) && scrollRow === 0 ? row.x - 1 : row.x + LIST_MARGIN - 2;
return { return {
position, position,
iconSize: ROW_ICON_SIZE, iconSize: ROW_ICON_SIZE,
visibleCount: Math.max(1, ((width - 2 * LIST_MARGIN + ICON_SPACING) / ROW_STEP) | 0), visibleCount: columns * windowRows,
cell: (slot) => ({ cell: (slot) => {
x: first + slot * ROW_STEP, y: row.y, width: ROW_ICON_SIZE + 4, height: SWITCHER_ROW_HEIGHT, const line = (slot / columns) | 0;
atSeparator: true, 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 // 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<T extends RowStatusSize = RowStatusSize> = {
/** 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<T extends RowStatusSize>(width: number, windowCount: number, status: T[]): BottomBarPlan<T> {
const plan = (level: number, windowRows: number, statusRows: T[][]): BottomBarPlan<T> => {
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<T extends RowStatusSize>(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 * Popup switcher geometry for the foreground window: its box, centred over
* the window's content (geometry.ts switcherRect), as wide as the icons * 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_SIZE = 24;
const NOTIFICATION_ICON_STEP = NOTIFICATION_ICON_SIZE + 4; 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 // 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. // side, and by 1px above and below, all a top bar leaves above its divider.
const NOTIFICATION_BOX_MARGIN_X = 2; const NOTIFICATION_BOX_MARGIN_X = 2;
@@ -416,8 +554,8 @@ export class ShellChromeLayer implements Layer {
private scrollRow = 0; private scrollRow = 0;
// The popup switcher's shell surface. // The popup switcher's shell surface.
private popupKey: number | undefined; private popupKey: number | undefined;
// Where the last paint ended a bottom row's window icons, for hit testing. // The bottom switcher's layout as the last paint planned it, for hit testing.
private rowWindowsRight: number | undefined; private bottomBar: BottomBarPlan<RowStatusItem> | null = null;
// Whether the last paint's selection tab carries the window frame's left // Whether the last paint's selection tab carries the window frame's left
// side down, so the frame's bottom-left corner is square. // side down, so the frame's bottom-left corner is square.
private frameCornerSquare = false; private frameCornerSquare = false;
@@ -425,12 +563,21 @@ export class ShellChromeLayer implements Layer {
// switcher's selection can move onto, and mirror touches hit. // switcher's selection can move onto, and mirror touches hit.
private notificationEntries: NotificationEntry[] = []; 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 { paint(): GrayImage {
const image = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0); const image = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0);
const state = this.getState(); const state = this.getState();
this.notificationEntries = []; this.notificationEntries = [];
this.bottomBar = this.layoutBottomBar(state);
const statusInRow = statusInSwitcherRow(state.foregroundAppId); const statusInRow = statusInSwitcherRow(state.foregroundAppId);
const popup = switcherPosition() === "popup"; const popup = switcherPosition() === "popup";
// Over an immersive window the strip is an overlay, present only while // Over an immersive window the strip is an overlay, present only while
@@ -452,6 +599,7 @@ export class ShellChromeLayer implements Layer {
paintParts(): Plane[] { paintParts(): Plane[] {
const state = this.getState(), parts: Plane[] = []; const state = this.getState(), parts: Plane[] = [];
this.notificationEntries = []; this.notificationEntries = [];
this.bottomBar = this.layoutBottomBar(state);
const statusInRow = statusInSwitcherRow(state.foregroundAppId); const statusInRow = statusInSwitcherRow(state.foregroundAppId);
const canvas = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0); const canvas = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0);
const span = topBarSpan(state); const span = topBarSpan(state);
@@ -534,7 +682,7 @@ export class ShellChromeLayer implements Layer {
if (windowCount === 0) return null; if (windowCount === 0) return null;
const state = this.getState(); const state = this.getState();
const layout = switcherPosition() === "popup" ? popupLayout(windowCount, state) 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); const lastVisible = Math.min(windowCount, this.scrollRow + layout.visibleCount);
for (let index = this.scrollRow; index < lastVisible; index++) { for (let index = this.scrollRow; index < lastVisible; index++) {
const cell = layout.cell(index - this.scrollRow); 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 * Draw the switcher strip or row. Given `statusImage`, a bottom switcher
* its right end with the status bar, drawn there (into that image, which * shares its right end with the status bar, drawn there (into that image,
* may be this one) first, and the window icons take what it leaves. * 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. * (see planBottomBar). Returns the status bar's left edge, or null without
* one.
*/ */
private drawSidebar(image: GrayImage, state: ShellChromeState, statusImage?: GrayImage): number | null { private drawSidebar(image: GrayImage, state: ShellChromeState, statusImage?: GrayImage): number | null {
// A side strip aligns with the app's preferred band (legacy tall // 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 // windows off-screen before/after. Sidebar icons fill the column against
// the separator top to bottom, then overflow into the outer one, so a // 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 // 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 count = state.windows.length;
const statusLeft = statusImage && switcherPosition() === "bottom" const bar = this.bottomBar;
? this.drawRowStatus(statusImage, state, strip, count) : null; const statusLeft = statusImage && bar?.statusRows.length ? this.drawRowStatus(statusImage, strip, bar) : null;
const windowsRight = statusLeft === null ? strip.x + strip.width : statusLeft - ROW_STATUS_GAP; const windowsRight = statusLeft === null ? strip.x + strip.width : statusLeft - ROW_STATUS_GAP;
this.rowWindowsRight = windowsRight; const visibleCount = switcherLayout(count, state.foregroundHeightMode, state.foregroundAppId, bar).visibleCount;
const visibleCount = switcherLayout(count, state.foregroundHeightMode, state.foregroundAppId, windowsRight).visibleCount;
// With the selection out on a notification, the windows stay scrolled as they were. // With the selection out on a notification, the windows stay scrolled as they were.
this.scrollRow = state.selectedIndex >= 0 this.scrollRow = state.selectedIndex >= 0
? scrollToKeepSelectionVisible(this.scrollRow, state.selectedIndex, visibleCount, count) ? scrollToKeepSelectionVisible(this.scrollRow, state.selectedIndex, visibleCount, count)
: Math.min(this.scrollRow, Math.max(0, count - visibleCount)); : 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 { iconSize, position } = layout;
const lastVisible = Math.min(count, this.scrollRow + layout.visibleCount); const lastVisible = Math.min(count, this.scrollRow + layout.visibleCount);
const cellOf = (index: number) => layout.cell(index - this.scrollRow); 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; const selCell = selVisible ? cellOf(state.selectedIndex) : null;
drawSeparator(image, state, strip, selCell?.atSeparator ? selCell : null); drawSeparator(image, state, strip, selCell?.atSeparator ? selCell : null);
const frame = position === "bottom" ? windowFrameRect(state) : 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++) { for (let index = this.scrollRow; index < lastVisible; index++) {
const window = state.windows[index]!; const window = state.windows[index]!;
@@ -630,13 +778,14 @@ export class ShellChromeLayer implements Layer {
} }
if (position === "bottom") { if (position === "bottom") {
// Chevrons sit in the margins at either end of the icons, pointing off them. // Chevrons sit in the margins at either end of the icons, pointing off
const chevronY = strip.y + ((strip.height / 2) | 0); // 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) { if (this.scrollRow > 0) {
drawChevron(image, strip.x + 6, chevronY, "left"); drawChevron(image, strip.x + 6, rowMiddle(0), "left");
} }
if (lastVisible < count) { if (lastVisible < count) {
drawChevron(image, windowsRight - 6, chevronY, "right"); drawChevron(image, windowsRight - 6, rowMiddle((bar?.windowRows ?? 1) - 1), "right");
} }
return statusLeft; 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: * Lay out the bottom switcher for this paint (planBottomBar) under the
* date and time, batteries, app widgets, then notification icons, each as * foreground window, with the status bar's items when it shares the
* it sits in the top bar (see ROW_STATUS_TOP). Notification icons stop * switcher, and record its height in geometry.ts, telling the shell when
* short of room for a few window slots; the windows get the rest, and * that moves or resizes windows. Null for the other switcher positions.
* whatever they leave over is free space between the two. Returns the
* left edge of what it drew.
*/ */
private drawRowStatus(image: GrayImage, state: ShellChromeState, row: Rect, windowCount: number): number { private layoutBottomBar(state: ShellChromeState): BottomBarPlan<RowStatusItem> | null {
image.fillRect(row.x, row.y + 1, row.width, row.height - 1, SHELL_OPAQUE_BLACK); if (switcherPosition() !== "bottom") return null;
const top = row.y + ROW_STATUS_TOP; const appId = state.foregroundAppId;
const font = getDefaultMediumFont(); const status = statusInSwitcherRow(appId) ? this.rowStatusItems(state) : [];
const clock = clockText(); const plan = planBottomBar(switcherRect(state.foregroundHeightMode, appId).width, state.windows.length, status);
// A TTF face measures fractionally; the status surface's crop edges need whole pixels. if (setSwitcherBarHeight(plan.height, appId)) this.onBottomBarHeightChanged();
const clockX = row.x + row.width - Math.ceil(font.measureText(clock)); return plan;
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);
// Right-aligned against the widgets, with the top bar's spacing. /**
const slots = Math.min(windowCount, ROW_MIN_WINDOW_SLOTS); * The status bar's items for the bottom switcher, left to right: every
const windowsFloor = row.x + 2 * LIST_MARGIN + Math.max(0, slots * ROW_STEP - ICON_SPACING) + ROW_STATUS_GAP; * notification icon, the app widgets, the battery block, and the date and
const iconsRight = trayLeft - 8, step = NOTIFICATION_ICON_STEP; * time, each to draw as it sits in the top bar.
const maxIcons = Math.max(0, ((iconsRight - windowsFloor + 4) / step) | 0); */
if (maxIcons === 0) return trayLeft; private rowStatusItems(state: ShellChromeState): RowStatusItem[] {
const { icons, keys, stale } = readActiveNotificationIcons(maxIcons, renderPassAllowsStaleData()); const items: RowStatusItem[] = [];
const { icons, keys, stale } = readActiveNotificationIcons(ALL_NOTIFICATIONS, renderPassAllowsStaleData());
if (stale) { if (stale) {
noteStaleDataUsed(); noteStaleDataUsed();
} }
if (!icons.length) return trayLeft; icons.forEach((icon, index) => items.push({
const iconsLeft = iconsRight - icons.length * step + 4; kind: "notification", width: NOTIFICATION_ICON_SIZE,
this.drawNotificationIcons(image, state, icons, keys, iconsLeft, top + (((TOP_BAR_HEIGHT - NOTIFICATION_ICON_SIZE) / 2) | 0)); draw: (image, x, top) => this.drawNotificationIcon(image, state, icon, keys[index], x, top + NOTIFICATION_ICON_TOP),
return iconsLeft; }));
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<RowStatusItem>): 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); const textY = barTop + Math.max(0, ((TOP_BAR_HEIGHT - font.lineHeight) / 2) | 0);
image.drawText(font, clockX, textY, clock, 210); 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 trayLeft = drawTrayIcons(image, state.trayIcons, batteryLeft, barTop);
const iconsX = clockX + Math.ceil(font.measureText(clock)) + 16; 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) { if (maxIcons > 0) {
const { icons, keys, stale } = readActiveNotificationIcons(maxIcons, renderPassAllowsStaleData()); const { icons, keys, stale } = readActiveNotificationIcons(maxIcons, renderPassAllowsStaleData());
if (stale) { if (stale) {
noteStaleDataUsed(); 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 * Draw a notification icon at (x, iconY), noting it as a notification
* notification entry. The one the switcher's selection is on * entry. The one the switcher's selection is on
* (state.selectedNotificationKey) sits in a rounded box like a sidebar * (state.selectedNotificationKey) sits in a rounded box like a sidebar
* overflow icon's: filled, with the icon inverted, while the switcher has * overflow icon's: filled, with the icon inverted, while the switcher has
* focus, and outlined while its detail view in the foreground window 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 { private drawNotificationIcon(image: GrayImage, state: ShellChromeState, icon: GrayImage, key: string | undefined, x: number, iconY: number): void {
for (let index = 0; index < icons.length; index++) { const box = {
const x = left + index * NOTIFICATION_ICON_STEP; x: x - NOTIFICATION_BOX_MARGIN_X, y: iconY - NOTIFICATION_BOX_MARGIN_Y,
const key = keys[index]; width: NOTIFICATION_ICON_SIZE + 2 * NOTIFICATION_BOX_MARGIN_X, height: NOTIFICATION_ICON_SIZE + 2 * NOTIFICATION_BOX_MARGIN_Y,
const box = { };
x: x - NOTIFICATION_BOX_MARGIN_X, y: iconY - NOTIFICATION_BOX_MARGIN_Y, if (key) this.notificationEntries.push({ key, ...box });
width: NOTIFICATION_ICON_SIZE + 2 * NOTIFICATION_BOX_MARGIN_X, height: NOTIFICATION_ICON_SIZE + 2 * NOTIFICATION_BOX_MARGIN_Y, const selected = !!key && key === state.selectedNotificationKey;
}; const focused = selected && state.focus === "sidebar";
if (key) this.notificationEntries.push({ key, ...box }); if (selected) drawSelectionBox(image, box.x, box.y, box.width, box.height, focused);
const selected = !!key && key === state.selectedNotificationKey; image.drawImage(focused ? invertedIcon(icon) : icon, x, iconY);
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;
} }
} }
type BatteryItem = { label: string; device: BatteryDevice; percent: number; charging: boolean }; 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. */ /** The status bar's date and time. */
function clockText(): string { function clockText(): string {
const now = new Date(); const now = new Date();
@@ -1009,12 +1200,17 @@ function drawTrayIcons(image: GrayImage, trayIcons: GrayImage[], rightEdge: numb
let x = rightEdge; let x = rightEdge;
for (let index = trayIcons.length - 1; index >= 0; index--) { for (let index = trayIcons.length - 1; index >= 0; index--) {
const icon = trayIcons[index]!; const icon = trayIcons[index]!;
x -= icon.width + 10; x -= icon.width + TRAY_ICON_GAP;
image.drawImage(icon, x, barTop + Math.max(0, ((TOP_BAR_HEIGHT - icon.height) / 2) | 0)); drawTrayIcon(image, icon, x, barTop);
} }
return x; 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). */ /** The sidebar attention marker, cached per fill value (deferred-image source). */
const attentionDots = new Map<number, GrayImage>(); const attentionDots = new Map<number, GrayImage>();
function attentionDot(value: number): GrayImage { function attentionDot(value: number): GrayImage {
+49 -20
View File
@@ -26,17 +26,38 @@ export const TOP_BAR_HEIGHT = 28;
export const SIDEBAR_WIDTH = 64; 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. * 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 * 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 * 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 * 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 * 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 * 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; 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). */ /** Which edge the app switcher is on, or a popup (Settings > Customization). */
export function switcherPosition(): AppSwitcherPosition { export function switcherPosition(): AppSwitcherPosition {
return appSwitcherPositionSetting.get(); 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 * How much of the screen's height a bottom switcher takes away from app
* windows: the row, or nothing beside a side strip or under an immersive * windows: its rows (one, or two when the layout needs them), or nothing
* window (where the row overlays the window's bottom edge while it has * beside a side strip or under an immersive window (where the switcher
* focus). * overlays the window's bottom edge while it has focus).
*/ */
export function switcherRowHeight(appId?: string): number { 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 * (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 * 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 * 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 * the row overlays the bottom edge of the screen. Either way it is as tall
* centres in, the foreground window's content (the chrome layer sizes the * as its layout (setSwitcherBarHeight). A popup's is the area it centres
* box itself). * 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 } { export function switcherRect(heightMode: WindowHeightMode, appId?: string): { x: number; y: number; width: number; height: number } {
switch (switcherPosition()) { switch (switcherPosition()) {
case "popup": case "popup":
return appViewportRect(heightMode, appId); return appViewportRect(heightMode, appId);
case "bottom": case "bottom": {
const reserved = switcherRowHeight(appId);
const height = reserved || switcherBarHeights.overlay;
return { return {
x: appViewportLeft(appId), x: appViewportLeft(appId),
y: switcherRowHeight(appId) > 0 y: reserved > 0 ? windowTop(heightMode, appId) + windowBandHeight(heightMode, appId) : G2_LENS_HEIGHT - height,
? windowTop(heightMode, appId) + windowBandHeight(heightMode, appId)
: G2_LENS_HEIGHT - SWITCHER_ROW_HEIGHT,
width: appViewportWidth(appId), width: appViewportWidth(appId),
height: SWITCHER_ROW_HEIGHT, height,
}; };
}
case "right": case "right":
return { x: G2_LENS_WIDTH - SIDEBAR_WIDTH, y: minWindowTop(appId), width: SIDEBAR_WIDTH, height: MIN_WINDOW_HEIGHT }; return { x: G2_LENS_WIDTH - SIDEBAR_WIDTH, y: minWindowTop(appId), width: SIDEBAR_WIDTH, height: MIN_WINDOW_HEIGHT };
default: default:
@@ -345,7 +368,7 @@ export const SHELL_OPAQUE_BLACK = 1;
* firmware uses, leaving most of the field of view clear; "medium" is one * 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 * 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 * 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 * shell draws at the window's top edge (windowHeaderHeight) and any footer
* at its bottom (windowFooterHeight). * 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 * 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 { function windowAreaHeight(appId?: string): number {
return G2_LENS_HEIGHT - switcherRowHeight(appId); 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 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 * top. A bottom switcher row hangs under the band, so the band and a
* together distribute the screen's slack. * 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 { 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). */ /** App-content viewport size for a height mode (independent of vertical position). */
+27 -4
View File
@@ -143,9 +143,10 @@ export type ShellWindow = {
/** Repaint and resubmit this window's surface. */ /** Repaint and resubmit this window's surface. */
requestRender: () => void; requestRender: () => void;
/** /**
* Re-measure against the current display mode (viewport size / band) and * Re-measure against the current display mode and app switcher (viewport
* repaint. Windows without it (workers with a canvas fixed at open) are * size / band) and repaint. Windows without it are closed and relaunched
* closed and relaunched by the controller instead. * 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; relayout?: () => void;
/** /**
@@ -201,6 +202,12 @@ export type ShellConfig = {
onScreenStateChanged: (on: boolean) => void; onScreenStateChanged: (on: boolean) => void;
/** Window registered/removed or foreground changed (persists the open-app list). */ /** Window registered/removed or foreground changed (persists the open-app list). */
onWindowsChanged?: () => void; 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 * The Notifications app's window, opened in the background (neither
* foregrounded nor focused) unless it is open already, for the switcher * foregrounded nor focused) unless it is open already, for the switcher
@@ -445,8 +452,9 @@ class Shell {
requestShellRender: () => {}, requestShellRender: () => {},
onScreenStateChanged: () => {}, 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 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 // 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. // 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). */ /** Add a window (or replace one with the same windowId, keeping its slot). */
registerWindow(window: ShellWindow): void { registerWindow(window: ShellWindow): void {
const existing = this.windows.findIndex((w) => w.windowId === window.windowId); const existing = this.windows.findIndex((w) => w.windowId === window.windowId);
+4 -4
View File
@@ -460,10 +460,10 @@ export class WorkerAppHost {
closeable: true, closeable: true,
acceptsDirectional: spec.acceptsDirectional, acceptsDirectional: spec.acceptsDirectional,
heightMode, heightMode,
// These apps can resize their live content without losing route/session state. // Every app worker resizes its live content in place, keeping its state
relayout: this.options.appId === "navigate" || this.options.appId === "terminal" // (a game in progress, a route): the bottom switcher's height changes
? () => this.post({ type: "resize-window", windowId: spec.windowId, viewport: appViewportSize(heightMode, this.options.appId) }) // with what it holds, and full-height windows give way to it.
: undefined, relayout: () => this.post({ type: "resize-window", windowId: spec.windowId, viewport: appViewportSize(heightMode, this.options.appId) }),
hasAppMenu: () => this.windowGestures.get(spec.windowId)?.hasAppMenu ?? false, hasAppMenu: () => this.windowGestures.get(spec.windowId)?.hasAppMenu ?? false,
claimsLongPress: () => this.windowGestures.get(spec.windowId)?.claimsLongPress ?? false, claimsLongPress: () => this.windowGestures.get(spec.windowId)?.claimsLongPress ?? false,
close: () => { close: () => {
+167 -28
View File
@@ -282,7 +282,7 @@ function chromeLayer(g, { notifications = 0, phoneBattery = null, windows = 1, t
'../../graphics/textwrap': require('../.test-build/app/graphics/textwrap.js'), '../../graphics/textwrap': require('../.test-build/app/graphics/textwrap.js'),
'../../graphics/battery': require('../.test-build/app/graphics/battery.js'), '../../graphics/battery': require('../.test-build/app/graphics/battery.js'),
'./ambient-cards': { activeAmbientCards: () => [] }, './ambient-cards': { activeAmbientCards: () => [] },
'../../native/notification-icons': { readActiveNotificationIcons: (max) => { '../../native/notification-icons': { ALL_NOTIFICATIONS: 0x7fffffff, readActiveNotificationIcons: (max) => {
requested.push(max); requested.push(max);
const count = Math.min(max, notifications); const count = Math.min(max, notifications);
return { icons: Array.from({ length: count }, () => new graphics.GrayImage(24, 24, 200)), 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', selectedIndex: 0, focus: 'window', foregroundHeightMode: 'min',
battery: { headset: null, ring: null, watch: null }, trayIcons, 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', () => { 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)); ({ px, at } = paint(chrome));
assert.deepEqual([px(31, 365), px(32, 365), at(35, 366), at(36, 366)], [0, 0, 1, 40]); 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); assert.equal(chrome.windowIndexAt(31, 380, 3), 0);
// Scrolled past the launcher, the cells keep the left chevron's margin. // Scrolled past the launcher (more windows than two rows of 14 hold), the
const scrolled = chromeLayer(g, { windows: 20 }); // cells keep the left chevron's margin.
scrolled.state.selectedIndex = 19; const scrolled = chromeLayer(g, { windows: 40 });
scrolled.state.selectedIndex = 39;
({ px } = paint(scrolled.chrome)); ({ px } = paint(scrolled.chrome));
assert.equal(scrolled.chrome.windowIndexAt(35, 380, 20), null); assert.equal(scrolled.chrome.windowIndexAt(35, 380, 40), null);
assert.notEqual(scrolled.chrome.windowIndexAt(41, 380, 20), null); assert.notEqual(scrolled.chrome.windowIndexAt(41, 380, 40), null);
assert.equal(px(31, 365), 0); 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(at(row, 40 + 2, 366 + 2), 120, 'first window icon');
assert.equal(chrome.windowIndexAt(45, 380, 1), 0); assert.equal(chrome.windowIndexAt(45, 380, 1), 0);
assert.equal(chrome.windowIndexAt(iconsLeft + 2, 380, 1), null); assert.equal(chrome.windowIndexAt(iconsLeft + 2, 380, 1), null);
// Notification icons stop short of the one window slot's room (with the // The row asks for every notification icon, to lay itself out round them all.
// row's margins and the gap to the status bar). assert.equal(requested.at(-1), 0x7fffffff);
assert.equal(requested.at(-1), Math.floor((trayLeft - 8 - (32 + 20 + 40 - 8 + 8) + 4) / 28));
// No top bar, but the frame is still there, its top one row above the content. // 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); 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]); assert.deepEqual([row.x + frame.x, row.y + frame.y, frame.source.height], [31, 78, 289]);
shellScene.encodeShellScene(parts, g.uiDepth()); 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(); const g = geometry();
g.settings.appSwitcherPositionSetting.value = 'bottom'; g.settings.appSwitcherPositionSetting.value = 'bottom';
g.settings.statusBarPositionSetting.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(); const [row, status] = chrome.paintParts();
// Clock only (no batteries or widgets): notifications end 8px before its assert.equal(requested.at(-1), 0x7fffffff);
// 8px lead-in, and stop where three window slots plus margins remain. // The last layout: two rows of each, 72px tall, under the unmoved band.
const trayLeft = 608 - 56 - 8, floor = 32 + 20 + 3 * 40 - 8 + 8; assert.equal(g.switcherRowHeight(), 72);
const max = Math.floor((trayLeft - 8 - floor + 4) / 28); assert.equal(heightChanges(), 1);
assert.equal(requested.at(-1), max); assert.deepEqual([row.y, row.image.height], [366, 72]);
const iconsLeft = trayLeft - 8 - max * 28 + 4; // Notification icons drop from the end until the two status rows leave
assert.equal(status.x, iconsLeft - 2); // three window slots a row (32 + 20 + 3 * 40 - 8, and the gap): 28 stay,
// Three windows fit before the status bar's gap; the rest scroll, with the // 15 in the first row (416px) and 13 with the clock in the second (432px).
// chevron at the end of the windows rather than of the row. 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 + 2 * 40 + 4, 380, 12), 2);
assert.equal(chrome.windowIndexAt(32 + 10 + 3 * 40 + 4, 380, 12), null); assert.equal(chrome.windowIndexAt(32 + 10 + 3 * 40 + 4, 380, 12), null);
const windowsRight = iconsLeft - 8; assert.equal(chrome.windowIndexAt(32 + 10 + 2 * 40 + 4, 420, 12), 5);
const chevron = row.image.pixels.findIndex((v, i) => v === 140); const windowsRight = 608 - 432 - 8;
assert.equal(chevron % row.image.width + row.x, windowsRight - 6); 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', () => { 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', () => { test('with the selection out on a notification, the windows stay scrolled as they were', () => {
const g = geometry(); const g = geometry();
g.settings.appSwitcherPositionSetting.value = 'bottom'; g.settings.appSwitcherPositionSetting.value = 'bottom';
const { chrome, state } = chromeLayer(g, { notifications: 2, windows: 20 }); const { chrome, state } = chromeLayer(g, { notifications: 2, windows: 40 });
state.selectedIndex = 19; state.selectedIndex = 39;
chrome.paintParts(); chrome.paintParts();
const last = 32 + 10 + 2 * 40 + 4; 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); assert.ok(before > 2);
Object.assign(state, { selectedIndex: -1, selectedNotificationKey: 'n0' }); Object.assign(state, { selectedIndex: -1, selectedNotificationKey: 'n0' });
chrome.paintParts(); 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. // 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); 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', () => { test('resizing a terminal reconnects with the new grid and ignores callbacks from the old socket', () => {
const sockets = []; const sockets = [];
const context = { const context = {