Borderless modes have different padding inside the builtin apps

Most of the builtin apps had some padding between the window edge and
their content, because they expect to be displayed with a line border on
their edge. We added a customization option to remove the border, so,
that padding is not always necessary. Make the layouts dynamically
adjust, to omit the padding when it isn't needed.
This commit is contained in:
James Babcock committed 2026-11-11 15:19:29 -08:00
1 parent e158452ba4
commit a02b849200
115 files changed
+3600 -1583

No files matched your search

+13 -10
View File
@@ -1797,26 +1797,29 @@ export class EditTextSettingLayer implements Layer {
const font = getDefaultSmallFont();
// Sized to the hosting stack (full lens in the dashboard window, app
// viewport in the settings app).
const { width, height } = ctx.stack.getBaseSize();
const { width, height, padding } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
const step = lineStep(font);
image.drawText(font, 22, 16, this.setting.glassesEditTitle, 220);
const messageTop = 24 + 2 * font.lineHeight;
const message = wrapText(font, "Look at the phone app to type a value.", width - 48);
// A text column inside the padding suggested for each window edge.
const x = padding.left;
const textWidth = width - padding.left - padding.right;
image.drawText(font, x, padding.top, this.setting.glassesEditTitle, 220);
const messageTop = padding.top + 8 + 2 * font.lineHeight;
const message = wrapText(font, "Look at the phone app to type a value.", textWidth);
for (let index = 0; index < message.length; index++) {
image.drawText(font, 22, messageTop + index * step, message[index]!, 200);
image.drawText(font, x, messageTop + index * step, message[index]!, 200);
}
const valueY = messageTop + (message.length + 2) * step;
image.drawText(font, 22, valueY, truncateSetting(this.setting.get(), 52), 220);
image.drawText(font, x, valueY, truncateSetting(this.setting.get(), 52), 220);
const error = this.setting.validationError();
const errorLines = error ? wrapText(font, error, width - 48) : [];
const errorLines = error ? wrapText(font, error, textWidth) : [];
errorLines.forEach((line, index) =>
image.drawText(font, 22, messageTop + (message.length + 4 + index) * step, line, 180));
image.drawText(font, x, messageTop + (message.length + 4 + index) * step, line, 180));
// The back hint at the bottom, unless a short window (the RayNeo iO's)
// leaves it no room under the value and error.
const contentBottom = errorLines.length ? messageTop + (message.length + 4 + errorLines.length) * step : valueY + step;
const hintY = height - 24 - font.lineHeight;
if (hintY >= contentBottom) image.drawText(font, 22, hintY, `${GESTURE_DOUBLE_CLICK} back`, 110);
const hintY = height - padding.bottom - font.lineHeight;
if (hintY >= contentBottom) image.drawText(font, x, hintY, `${GESTURE_DOUBLE_CLICK} back`, 110);
return image;
}
+39 -16
View File
@@ -7,6 +7,7 @@ import { isMenuItemDisabled, MenuItem, MenuLayer, openModalMenu } from "../menu"
import { Menu } from "../menu-core";
import { LIST_ROW_TEXT_INSET, lineStep, listRowHeight } from "../metrics";
import { shell } from "../shell/shell";
import type { Viewport } from "../viewport";
/**
* One left-column entry. `items` are the right-column rows (reusing the shared
@@ -29,8 +30,12 @@ export type SettingsSection = {
}) => number | void;
};
const PAD = 8;
const LEFT_W = 150;
/** Between the left column's rows and the divider, and between the divider and the right column's content. */
const DIVIDER_GAP_LEFT = 8;
const DIVIDER_GAP_RIGHT = 14;
/** How far a right-column row's selection box overhangs the column's content on the left. */
const RIGHT_ROW_OVERHANG = 2;
/** Gap between a row's selection box and the next row. */
const ROW_GAP = 2;
/** Horizontal inset of row text (and custom row content) from its selection box. */
@@ -114,27 +119,27 @@ export class SettingsPanelLayer implements Layer {
paint(ctx: LayerContext): GrayImage {
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const viewport = ctx.stack.getBaseSize();
const { width, height, padding } = viewport;
const image = new GrayImage(width, height, 0);
const appFocused = ctx.stack.isFocused();
const section = this.section();
const rightItems = section.items;
this.rightMenu.setItems(rightItems);
const top = PAD;
const listBottom = height - PAD;
// Fixed content keeps the padding suggested for the window's edges. The
// two lists scroll, so they run to the top and bottom edges themselves,
// with that padding inside them (before the first row, after the last).
const { top, bottom: listBottom, divX, rightX, rightW } = panelColumns(viewport);
// Left column: section labels.
this.leftMenu.paint(image, { x: PAD - 2, y: top, width: LEFT_W, height: listBottom - top },
this.leftMenu.paint(image, { x: padding.left, y: 0, width: LEFT_W, height, padTop: padding.top, padBottom: padding.bottom },
appFocused && this.focus === "left");
// Column divider (a light rule, not a full border).
const divX = PAD + LEFT_W + 6;
image.drawLine(divX, top, divX, listBottom, 40);
// Right column: the highlighted section's contents.
const rightX = divX + 14;
const rightW = width - rightX - PAD;
let rightTop = top;
if (section.renderDetail && !this.detailCrowdsList(section, ctx, font, { x: rightX, y: top, width: rightW, height: listBottom - top })) {
const used = section.renderDetail({ image, x: rightX, y: top, width: rightW, height: listBottom - top, ctx });
@@ -144,12 +149,20 @@ export class SettingsPanelLayer implements Layer {
// Once focus is in the right column, the selected item's extended
// description (when it has one) is drawn over the bottom of the pane by
// the companion SettingsDescriptionOverlayLayer. The list stops above
// that band, so the selected row always stays clear of it.
const listHeight = listBottom - this.descriptionHeight(font, rightW) - rightTop;
if (listHeight > 0) {
// that band, so the selected row always stays clear of it. Under a
// detail, and above that band, the list ends short of the window's
// edge, where it needs no padding of its own.
const description = this.descriptionHeight(font, rightW);
const fromEdge = rightTop === top;
const listTop = fromEdge ? 0 : rightTop;
const listEnd = description ? listBottom - description : height;
if (listEnd > rightTop) {
this.paintCtx = ctx;
try {
this.rightMenu.paint(image, { x: rightX - 2, y: rightTop, width: rightW + 2, height: listHeight }, appFocused);
this.rightMenu.paint(image, {
x: rightX - RIGHT_ROW_OVERHANG, y: listTop, width: rightW + RIGHT_ROW_OVERHANG, height: listEnd - listTop,
padTop: fromEdge ? padding.top : 0, padBottom: description ? 0 : padding.bottom,
}, appFocused);
} finally {
this.paintCtx = null;
}
@@ -202,10 +215,7 @@ export class SettingsPanelLayer implements Layer {
*/
paintDescriptionOverlay(image: GrayImage, ctx: LayerContext): void {
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const listBottom = height - PAD;
const rightX = PAD + LEFT_W + 6 + 14;
const rightW = width - rightX - PAD;
const { bottom: listBottom, rightX, rightW } = panelColumns(ctx.stack.getBaseSize());
const lines = this.descriptionLines(font, rightW);
if (!lines.length) return;
const top = listBottom - (lines.length * lineStep(font) + 10);
@@ -273,6 +283,19 @@ export class SettingsPanelLayer implements Layer {
}
}
/**
* The panel's fixed geometry in a viewport: the rows fixed content spans
* (inside the padding suggested for the top and bottom edges), the divider's
* x, and the right column's content span. The left column's rows start at
* the left edge's padding; the right column ends at the right edge's.
*/
function panelColumns(viewport: Viewport): { top: number; bottom: number; divX: number; rightX: number; rightW: number } {
const { width, height, padding } = viewport;
const divX = padding.left + LEFT_W + DIVIDER_GAP_LEFT;
const rightX = divX + DIVIDER_GAP_RIGHT;
return { top: padding.top, bottom: height - padding.bottom, divX, rightX, rightW: width - rightX - padding.right };
}
/** Scroll and watch swipe-up/down both move a column's selection. */
function scrollEventFor(event: InputEvent): InputEvent | null {
if (event.type === "scroll-up" || event.type === "swipe-up") return { ...event, type: "scroll-up" } as InputEvent;
+65 -16
View File
@@ -3,7 +3,9 @@
* region: nested nodes indent, todo nodes get checkboxes, links underline,
* code blocks get a shaded box. Selection moves over nodes (a node's wrapped
* lines highlight as one unit) and the scroll position follows it, matching
* the house list style in ui/menu.ts.
* the house list style in ui/menu.ts. Scrolling is by whole lines: the
* region's top always shows the start of a line (or the padding before the
* first one), and a line that would be cut off at its bottom is left out.
*/
import { GrayImage, type UiFont } from "../../graphics/image";
import { getDefaultMediumFont, getDefaultSmallFont } from "../../graphics/ui-fonts";
@@ -22,6 +24,16 @@ const MARKER_GUTTER = 16;
const RIGHT_PAD = 10;
const CODE_INSET = 6;
/**
* The size of the region a DocumentView scrolls in. padTop and padBottom are
* blank space inside the scrolled content, before the first line and after
* the last (default none), which scrolls away with the lines. A view whose
* region runs to a window's top or bottom edge passes the padding suggested
* for that edge (viewport.ts): its end lines then keep clear of a border
* line there, while lines scrolled past them use the room up to the edge.
*/
export type DocumentViewSize = { width: number; height: number; padTop?: number; padBottom?: number };
type SegmentStyle = "plain" | "link" | "code";
type Segment = { text: string; x: number; style: SegmentStyle };
@@ -46,18 +58,29 @@ export class DocumentView {
private lines: LayoutLine[] = [];
private selectable: DocNode[] = [];
private selectedIndex = 0;
/** Index of the line at the region's top; at 0 the top padding shows above it. */
private scrollLine = 0;
private width: number;
private height: number;
private padTop: number;
private padBottom: number;
constructor(
private width: number,
private height: number,
) {}
constructor(size: DocumentViewSize) {
this.width = size.width;
this.height = size.height;
this.padTop = size.padTop ?? 0;
this.padBottom = size.padBottom ?? 0;
}
/** 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;
resize(size: DocumentViewSize): void {
const padTop = size.padTop ?? 0;
const padBottom = size.padBottom ?? 0;
if (size.width === this.width && size.height === this.height && padTop === this.padTop && padBottom === this.padBottom) return;
this.width = size.width;
this.height = size.height;
this.padTop = padTop;
this.padBottom = padBottom;
if (this.root) this.setDocument(this.root);
}
@@ -101,6 +124,7 @@ export class DocumentView {
paint(target: GrayImage, x: number, y: number, focused: boolean): void {
const image = new GrayImage(this.width, this.height, 0);
const selected = this.selectedNode();
const firstLineY = this.leadAt(this.scrollLine);
const visibleCount = this.visibleCountFrom(this.scrollLine);
const lastVisible = Math.min(this.lines.length, this.scrollLine + visibleCount);
@@ -109,7 +133,7 @@ export class DocumentView {
let top: number | null = null;
let bottom = 0;
let indentX = 0;
let lineY = 0;
let lineY = firstLineY;
for (let index = this.scrollLine; index < lastVisible; index++) {
const line = this.lines[index]!;
if (line.node === selected) {
@@ -127,7 +151,7 @@ export class DocumentView {
}
}
let lineY = 0;
let lineY = firstLineY;
for (let index = this.scrollLine; index < lastVisible; index++) {
const line = this.lines[index]!;
const isSelected = line.node === selected;
@@ -143,7 +167,9 @@ export class DocumentView {
}
if (this.lines.length > visibleCount) {
drawListScrollbar(image, this.width - 3, 0, this.height, this.scrollLine, visibleCount, this.lines.length);
// The track keeps inside the padding, as the document's end lines do.
const trackHeight = Math.max(0, this.height - this.padTop - this.padBottom);
drawListScrollbar(image, this.width - 3, this.padTop, trackHeight, this.scrollLine, visibleCount, this.lines.length);
}
target.bitBlt(image, x, y);
}
@@ -257,8 +283,14 @@ export class DocumentView {
// -------------------------------------------------------------------------
// Scrolling
/** Blank space above the line at the region's top: the top padding, until it scrolls away. */
private leadAt(scrollLine: number): number {
return scrollLine === 0 ? this.padTop : 0;
}
/** How many whole lines the region shows when scrolled to `start` (never fewer than one). */
private visibleCountFrom(start: number): number {
let used = 0;
let used = this.leadAt(start);
let count = 0;
for (let index = start; index < this.lines.length; index++) {
used += this.lines[index]!.height;
@@ -268,11 +300,22 @@ export class DocumentView {
return Math.max(1, count);
}
/**
* Whether the region, scrolled to `start`, shows the lines through `end`
* whole, and after the document's last line the bottom padding too.
*/
private showsThrough(start: number, end: number): boolean {
let used = this.leadAt(start) + (end === this.lines.length - 1 ? this.padBottom : 0);
for (let index = start; index <= end && used <= this.height; index++) used += this.lines[index]!.height;
return used <= this.height;
}
/** The furthest the view scrolls: the first line from which the rest fits, bottom padding included. */
private maxScrollLine(): number {
let used = 0;
let used = this.padBottom;
for (let index = this.lines.length - 1; index >= 0; index--) {
used += this.lines[index]!.height;
if (used > this.height) return index + 1;
if (used + this.leadAt(index) > this.height) return Math.min(index + 1, this.lines.length - 1);
}
return 0;
}
@@ -289,9 +332,15 @@ export class DocumentView {
}
}
if (first < 0) return;
// Lines no selection reaches belong with the end node next to them:
// selecting the first node shows the document's start, and the last its
// end, with the padding there, when that fits along with the node.
const end = this.lines.length - 1;
if (this.selectedIndex === 0 && this.showsThrough(0, last)) first = 0;
if (this.selectedIndex === this.selectable.length - 1 && this.showsThrough(first, end)) last = end;
let scroll = this.scrollLine;
// Scroll down the minimum needed; a node taller than the view pins its top.
while (last >= scroll + this.visibleCountFrom(scroll) && scroll < first) scroll++;
while (scroll < first && !this.showsThrough(scroll, last)) scroll++;
if (first < scroll) scroll = first;
this.scrollLine = clamp(scroll, 0, this.maxScrollLine());
}
+24 -16
View File
@@ -35,6 +35,11 @@ import type { Layer, LayerContext } from "./layers";
/** Pixel sizes offered for TTF faces (also by the onboarding's text-size page). */
export const FONT_SIZE_CHOICES = [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 24, 26, 28] as const;
const DEFAULT_TTF_SIZE = 16;
/** Row text (and the title, in line with it) from the rows' highlight boxes. */
const ROW_TEXT_INSET = 10;
/** The title: below the window's top padding, and the gap under its line. */
const TITLE_OFFSET_Y = 2;
const TITLE_GAP = 10;
const PREVIEW_TEXT = "The quick brown fox jumps over 0123456789";
const INHERIT_UI_FONT_LABEL = "Same as UI font";
const UI_BITMAP_FACES: FontPickerOptions["bitmapFaces"] = [
@@ -132,27 +137,31 @@ export class FontPickerLayer implements Layer {
paint(ctx: LayerContext): GrayImage {
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const { width, height, padding } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
const focused = ctx.stack.isFocused();
image.drawText(font, 22, 14, this.options.title, 220);
// The rows' highlight boxes span the window inside the padding suggested
// for its sides; the title and the rows' text sit ROW_TEXT_INSET in.
const rowX = padding.left + ROW_TEXT_INSET;
const rowWidth = width - padding.left - padding.right - 2 * ROW_TEXT_INSET;
const titleY = padding.top + TITLE_OFFSET_Y;
image.drawText(font, rowX, titleY, this.options.title, 220);
const rowX = 22;
const rowWidth = width - 2 * rowX;
const rowHeight = listRowHeight(font);
const rowsTop = 24 + font.lineHeight;
const rowsTop = titleY + font.lineHeight + TITLE_GAP;
const rowsHeight = ROWS.length * rowHeight;
const bottom = height - padding.bottom;
const preview = this.previewFont();
const info = `Line height: ${preview.lineHeight}px`;
// Preview under the rows, where its sample line and the info line fit
// (the G2's window): a separator, then the sample line in the draft font.
const previewTop = rowsTop + rowsHeight + 10;
if (previewTop + 8 + preview.lineHeight + 6 + font.lineHeight <= height) {
this.menu.paint(image, { x: rowX - 10, y: rowsTop, width: rowWidth + 20, height: rowsHeight }, focused);
image.drawLine(rowX - 10, previewTop, rowX + rowWidth + 10, previewTop, 60);
if (previewTop + 8 + preview.lineHeight + 6 + font.lineHeight <= bottom) {
this.menu.paint(image, { x: rowX - ROW_TEXT_INSET, y: rowsTop, width: rowWidth + 2 * ROW_TEXT_INSET, height: rowsHeight }, focused);
image.drawLine(rowX - ROW_TEXT_INSET, previewTop, rowX + rowWidth + ROW_TEXT_INSET, previewTop, 60);
const sample =
preview.measureText(PREVIEW_TEXT) <= rowWidth + 20 ? PREVIEW_TEXT : "The quick brown fox 0123";
preview.measureText(PREVIEW_TEXT) <= rowWidth + 2 * ROW_TEXT_INSET ? PREVIEW_TEXT : "The quick brown fox 0123";
preview.drawText(image, rowX - 4, previewTop + 8, sample, 230);
image.drawText(font, rowX - 4, previewTop + 8 + preview.lineHeight + 6, info, 110);
return image;
@@ -161,12 +170,11 @@ export class FontPickerLayer implements Layer {
// Else beside them (a short window, as on the RayNeo iO), the sample
// wrapped to the column, as many lines as fit above the info line.
const columnWidth = Math.round(rowWidth / 2);
const bottom = height - 8;
this.menu.paint(image, { x: rowX - 10, y: rowsTop, width: columnWidth + 20, height: Math.min(rowsHeight, bottom - rowsTop) }, focused);
const dividerX = rowX + columnWidth + 20;
this.menu.paint(image, { x: rowX - ROW_TEXT_INSET, y: rowsTop, width: columnWidth + 2 * ROW_TEXT_INSET, height: Math.min(rowsHeight, bottom - rowsTop) }, focused);
const dividerX = rowX + columnWidth + 2 * ROW_TEXT_INSET;
image.drawLine(dividerX, rowsTop, dividerX, Math.min(rowsTop + rowsHeight, bottom), 60);
const previewX = dividerX + 12;
const lines = wrapText(preview, PREVIEW_TEXT, width - previewX - 12);
const lines = wrapText(preview, PREVIEW_TEXT, width - padding.right - previewX);
const infoY = bottom - font.lineHeight;
let y = rowsTop + 4;
for (const line of lines) {
@@ -178,11 +186,11 @@ export class FontPickerLayer implements Layer {
return image;
}
/** Row box = highlight box; text sits 10px in from its left edge and 10px from its right. */
/** Row box = highlight box; text sits ROW_TEXT_INSET in from its left and right edges. */
private drawRow({ image, item: row, x, y, width, selected }: MenuDrawArgs<RowId>): void {
const font = getDefaultSmallFont();
const textX = x + 10;
const textWidth = width - 20;
const textX = x + ROW_TEXT_INSET;
const textWidth = width - 2 * ROW_TEXT_INSET;
if (row === "save") {
image.drawText(font, textX, y + LIST_ROW_TEXT_INSET, "Save", selected ? 255 : 200);
return;
+73 -29
View File
@@ -22,12 +22,11 @@ const DEFAULT_COLUMNS = 5;
const DEFAULT_LABEL_VALUE = 210;
/** Wide rows: text inset from the grid's left and right edges. */
const WIDE_TEXT_X = 20;
/** The scrollbar's columns at the right edge, which animations leave alone. */
/** Columns a grid with a scrollbar keeps for it at the box's right edge, clear of its rows. */
const SCROLLBAR_GUTTER = 5;
/** How far a row-mode highlight band is inset from the box's left and right edges. */
export const ICON_GRID_BAND_INSET_X = 4;
const SCROLLBAR_WIDTH = 3;
/** How far a grid row's highlight (band or cell) is inset from the row's top and bottom. */
export const ICON_GRID_HIGHLIGHT_INSET_Y = 2;
const HIGHLIGHT_INSET_Y = 2;
export type IconGridCell = {
label: string;
@@ -69,7 +68,10 @@ export type IconGridOptions<T> = {
* always uses), even if the host reset the selection while navigating.
*/
onBack: (ctx: LayerContext) => boolean | void;
/** Draw a scrollbar at the right edge when rows overflow. Default false. */
/**
* Draw a scrollbar at the box's right edge when rows overflow; the rows
* then always keep its few columns free. Default false.
*/
scrollbar?: boolean;
};
@@ -79,7 +81,16 @@ type GridRow<T> =
type GridMode = "row" | "item";
type GridLayout = { box: MenuBox; rowH: number; colW: number };
/**
* `lead` is the blank space before the first row, inside the scrolled
* content (see paint); `scrollOffset` is the content offset of the box's top.
*/
type GridLayout = { box: MenuBox; rowH: number; colW: number; lead: number; scrollOffset: number };
/** The part of a grid's box its rows take: all of it, less a scrollbar's gutter. */
function rowsBox(box: MenuBox, scrollbar: boolean): MenuBox {
return scrollbar ? { ...box, width: Math.max(0, box.width - SCROLLBAR_GUTTER) } : box;
}
/**
* The selection highlight in image coordinates. `key` names what is
@@ -101,6 +112,12 @@ type Highlight = { key: number; x: number; y: number; width: number; height: num
* many rows fit. Space left below the last full row shows the top of the
* next row, cut off at the box's edge, as a hint that there is more to scroll to.
*
* The box is the scroll viewport, and a row-mode highlight band spans its
* width: a host insets it from a window's sides by the padding suggested
* for them (viewport.ts), and runs it to the window's top and bottom edges,
* giving their padding as the box's padTop and padBottom, which the grid
* keeps inside the scrolled content.
*
* Ring input navigates on two levels, halving the scrolls to reach an item:
* in row mode scroll picks a row and a click drops into item mode on it,
* defaulting to the middle column; in item mode scroll traverses items
@@ -196,21 +213,34 @@ export class IconGrid<T> {
}
}
paint(image: GrayImage, box: MenuBox, focused: boolean): void {
/**
* Paint the grid into `box`, its scroll viewport. The box's padTop keeps
* the first row's highlight that far below the box's top while the grid
* is scrolled to its start, and padBottom keeps the last row's that far
* above its bottom at the end; rows scrolled past either are cut off at
* the box's edge itself.
*/
paint(image: GrayImage, viewportBox: MenuBox, focused: boolean): void {
const font = getDefaultSmallFont();
const rows = this.buildRows();
this.clampSelection(rows);
const box = rowsBox(viewportBox, !!this.options.scrollbar);
const rowH = iconGridMinRowHeight(font, ICON_GRID_ICON_SIZE, LABEL_GAP);
const fullRows = Math.max(1, Math.floor(box.height / rowH));
// A row's highlight already sits HIGHLIGHT_INSET_Y inside it.
const lead = Math.max(0, (box.padTop ?? 0) - HIGHLIGHT_INSET_Y);
const tail = Math.max(0, (box.padBottom ?? 0) - HIGHLIGHT_INSET_Y);
// Rows that fit whole wherever the grid is scrolled to: the rest of the
// box shows the next row cut off.
const fullRows = Math.max(1, Math.floor((box.height - lead - tail) / rowH));
// Scroll to keep the selected row among the fully-visible rows.
this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, this.selectedRow, fullRows, rows.length);
const layout: GridLayout = { box, rowH, colW: box.width / this.columns };
const layout: GridLayout = { box, rowH, colW: box.width / this.columns, lead, scrollOffset: scrollOffsetFor(this.scrollRow, rowH, lead) };
this.layout = layout;
const highlight = this.highlight(rows, layout, font, focused);
const bottom = box.y + box.height;
for (let rowIndex = this.scrollRow; rowIndex < rows.length; rowIndex++) {
const y = box.y + (rowIndex - this.scrollRow) * rowH;
const y = rowTop(layout, rowIndex);
if (y >= bottom) break;
if (highlight && rowIndex === this.selectedRow) {
drawSelectionHighlight(image, highlight.x, highlight.y, highlight.width, highlight.height, focused, highlight.radius);
@@ -218,11 +248,13 @@ export class IconGrid<T> {
this.drawRow(image, rows[rowIndex]!, rowIndex, box.x, y, layout, font, bottom);
}
const scrollbar = !!this.options.scrollbar && rows.length > fullRows;
if (scrollbar) {
drawListScrollbar(image, box.x + box.width - SCROLLBAR_GUTTER, box.y, box.height, this.scrollRow, fullRows, rows.length);
if (this.options.scrollbar && rows.length > fullRows) {
// Fixed, unlike the rows: it keeps inside the box's padding.
const trackTop = box.y + (box.padTop ?? 0);
const trackHeight = box.height - (box.padTop ?? 0) - (box.padBottom ?? 0);
drawListScrollbar(image, viewportBox.x + viewportBox.width - SCROLLBAR_WIDTH, trackTop, trackHeight, this.scrollRow, fullRows, rows.length);
}
this.paintMotion(image, rows, layout, font, focused, highlight, scrollbar);
this.paintMotion(image, rows, layout, font, focused, highlight);
}
async handleInput(event: InputEvent, ctx: LayerContext): Promise<void> {
@@ -240,10 +272,10 @@ export class IconGrid<T> {
*/
async hitTest(x: number, y: number, ctx: LayerContext): Promise<boolean> {
if (!this.layout) return false;
const { box, rowH, colW } = this.layout;
const { box, rowH, colW, lead, scrollOffset } = this.layout;
if (x < box.x || x >= box.x + box.width || y < box.y || y >= box.y + box.height) return false;
const rowIndex = this.scrollRow + Math.floor((y - box.y) / rowH);
const row = this.buildRows()[rowIndex];
const rowIndex = Math.floor((y - box.y + scrollOffset - lead) / rowH);
const row = rowIndex >= 0 ? this.buildRows()[rowIndex] : undefined;
if (!row) return false;
if (row.kind === "cells") {
const col = Math.floor((x - box.x) / colW);
@@ -269,19 +301,18 @@ export class IconGrid<T> {
const row = rows[this.selectedRow];
if (!row) return null;
const { box, rowH, colW } = layout;
const y = box.y + (this.selectedRow - this.scrollRow) * rowH;
const y = rowTop(layout, this.selectedRow);
if (row.kind === "wide") {
const textY = y + wideTextOffset(rowH, font);
return { key: row.firstIndex, x: box.x + WIDE_TEXT_X - 6, y: textY - 2,
width: box.width - 2 * WIDE_TEXT_X + 12, height: font.lineHeight + 4, radius: 4 };
}
const insetY = ICON_GRID_HIGHLIGHT_INSET_Y;
const insetY = HIGHLIGHT_INSET_Y;
if (this.mode === "item" || (!focused && shell.lastInputWasWatch())) {
return { key: row.firstIndex + this.selectedCol, x: Math.round(box.x + this.selectedCol * colW) + 6, y: y + insetY,
width: Math.round(colW) - 12, height: rowH - 2 * insetY, radius: 6 };
}
return { key: -1 - this.selectedRow, x: box.x + ICON_GRID_BAND_INSET_X, y: y + insetY,
width: box.width - 2 * ICON_GRID_BAND_INSET_X, height: rowH - 2 * insetY, radius: 6 };
return { key: -1 - this.selectedRow, x: box.x, y: y + insetY, width: box.width, height: rowH - 2 * insetY, radius: 6 };
}
/**
@@ -325,16 +356,16 @@ export class IconGrid<T> {
* moving, retain the display list that animates them over the static paint.
*/
private paintMotion(image: GrayImage, rows: readonly GridRow<T>[], layout: GridLayout, font: UiFont,
focused: boolean, highlight: Highlight | null, scrollbar: boolean): void {
focused: boolean, highlight: Highlight | null): void {
const now = Date.now();
const scrollOffset = this.scrollRow * layout.rowH;
const { scrollOffset } = layout;
const scroll = this.scrollMotion.paint(scrollOffset, layout.box, now);
const slide = highlight
? this.highlightMotion.paint(highlight.key, scrollOffset, highlight.x, highlight.y, highlight.width, highlight.height, now, !!scroll)
: undefined;
if (!scroll && !slide) return;
const { box } = layout;
const clip: ListClip = { x: 0, y: 0, width: box.width - (scrollbar ? SCROLLBAR_GUTTER : 0), height: box.height };
const clip: ListClip = { x: 0, y: 0, width: box.width, height: box.height };
const list = this.motionList(rows, layout, font, focused, highlight, clip, scroll, slide);
if (!list) {
this.scrollMotion.cancel();
@@ -353,11 +384,10 @@ export class IconGrid<T> {
private motionList(rows: readonly GridRow<T>[], layout: GridLayout, font: UiFont, focused: boolean,
highlight: Highlight | null, clip: ListClip, scroll: MenuScrollAnimation | undefined,
slide: MenuHighlightAnimation | undefined): DisplayList | null {
const { box, rowH } = layout;
const scrollOffset = this.scrollRow * rowH;
const { box, rowH, lead, scrollOffset } = layout;
const offsets = scroll ? [scroll.from, scroll.to, scroll.peak ?? scroll.to] : [scrollOffset];
const firstRow = Math.max(0, Math.floor(Math.min(...offsets) / rowH));
const lastRow = Math.min(rows.length, Math.ceil((Math.max(...offsets) + box.height) / rowH));
const firstRow = Math.max(0, Math.floor((Math.min(...offsets) - lead) / rowH));
const lastRow = Math.min(rows.length, Math.ceil((Math.max(...offsets) + box.height - lead) / rowH));
const content = new GrayImage(box.width, Math.max(1, (lastRow - firstRow) * rowH));
for (let rowIndex = firstRow; rowIndex < lastRow; rowIndex++) {
this.drawRow(content, rows[rowIndex]!, rowIndex, 0, (rowIndex - firstRow) * rowH, layout, font);
@@ -380,7 +410,7 @@ export class IconGrid<T> {
background: focused ? q(MENU_HIGHLIGHT_FILL) : 0, border: q(MENU_HIGHLIGHT_STROKE), clip });
}
// Without a scroll the rows stay put; a literal keeps every compiled call small.
const rowsY = scroll ? E.i32(firstRow * rowH).sub(offset) : (firstRow - this.scrollRow) * rowH;
const rowsY = scroll ? E.i32(lead + firstRow * rowH).sub(offset) : lead + firstRow * rowH - scrollOffset;
calls.push({ op: DrawOp.DRAWS, x: 0, y: rowsY, records: replay.records, count: replay.count, source: content, clip });
return { resources: [], timeline: { token: timeline.token, startedAt: timeline.startedAt }, calls };
}
@@ -569,6 +599,20 @@ export class IconGrid<T> {
}
}
/**
* Content offset of the box's top with `scrollRow` as the first row shown:
* that row's top, or for the first row the content's, so the space before
* it shows too.
*/
function scrollOffsetFor(scrollRow: number, rowH: number, lead: number): number {
return scrollRow === 0 ? 0 : lead + scrollRow * rowH;
}
/** Image y of a row's top in the layout's box as scrolled. */
function rowTop(layout: GridLayout, rowIndex: number): number {
return layout.box.y + layout.lead + rowIndex * layout.rowH - layout.scrollOffset;
}
function rowLength<T>(row: GridRow<T>): number {
return row.kind === "wide" ? 1 : row.items.length;
}
+21 -10
View File
@@ -4,6 +4,7 @@ import { dimPlanes, type Plane } from "../graphics/plane";
import { spanCurrent } from "../native/frame-timings";
import { type ConfigSettingBoolean, type ConfigSettingString, type VoiceProvider } from "./dashboard-settings";
import { directionalFallback, isDirectionalInput, type InputEvent } from "./gestures";
import { toViewport, type Viewport, type ViewportSize } from "./viewport";
export type TextSettingsEditToggle = {
setting: ConfigSettingBoolean;
@@ -155,18 +156,19 @@ export class LayerStack {
private readonly shellKeys = new WeakMap<Layer, number>();
private readonly ctx: LayerContext;
/**
* The base viewport's size, or null to follow the paired glasses' screen
* as it is now: the shell's own stack lives for the whole process, and
* The base viewport, or null to follow the paired glasses' screen as it
* is now: the shell's own stack lives for the whole process, and
* re-pairing with the other glasses type changes the screen under it.
*/
private baseSize: { width: number; height: number } | null;
private baseSize: Viewport | null;
private readonly focusedFn: () => boolean;
private lastBaseDim: number | false = 1;
constructor(
baseLayer: Layer,
actions: LayerActions,
baseSize?: { width: number; height: number },
// A bare size is a viewport nothing borders (see toViewport).
baseSize?: ViewportSize | Viewport,
// Whether this stack is the current input target; drives the strength of
// selection highlights (a visible-but-unfocused window dims its selection).
// Defaults to always-focused for shell overlays and standalone stacks.
@@ -177,7 +179,7 @@ export class LayerStack {
stack: this,
actions,
};
this.baseSize = baseSize ? { width: baseSize.width, height: baseSize.height } : null;
this.baseSize = baseSize ? toViewport(baseSize) : null;
this.focusedFn = isFocused;
}
@@ -247,13 +249,22 @@ export class LayerStack {
return this.layers.length === 1;
}
getBaseSize(): { width: number; height: number } {
return this.baseSize ? { ...this.baseSize } : { width: screenWidth(), height: screenHeight() };
/**
* The viewport layers lay out in: its size, what each of its edges
* touches, and the padding suggested for them (see viewport.ts). A host
* that gave only a size, and the shell's own screen-sized stack, have
* edges nothing borders and no padding.
*/
getBaseSize(): Viewport {
return toViewport(this.baseSize ?? { width: screenWidth(), height: screenHeight() });
}
/** Resize the base viewport (e.g. an EvenHub window switching to the tall canvas). */
setBaseSize(size: { width: number; height: number }): void {
this.baseSize = { width: size.width, height: size.height };
/**
* Resize the base viewport (e.g. an EvenHub window switching to the tall
* canvas), or change what its edges touch.
*/
setBaseSize(size: ViewportSize | Viewport): void {
this.baseSize = toViewport(size);
}
setActions(actions: Partial<LayerActions>): void {
+12 -10
View File
@@ -2,9 +2,8 @@ import { type GrayImage, type UiFont } from "../graphics/image";
import { truncateText } from "../graphics/textwrap";
import { voiceControlBridge } from "../native/voice-control";
import { lineStep } from "./metrics";
import type { Edges } from "./viewport";
const HEADER_X = 24;
const HEADER_Y = 20;
const TITLE_GRAY = 200;
const STATUS_GRAY = 110;
@@ -66,8 +65,9 @@ export class MicLevelMeter {
/**
* The one-line header of the listening views (Transcribe, Translate):
* "Title · status", the status truncated to fit, then the mic level meter at
* the line's end when one is given (while listening). Returns the y at which
* the view's body starts.
* the line's end when one is given (while listening). It spans the image
* inside `padding`, the padding suggested for the window's edges
* (viewport.ts). Returns the y at which the view's body starts.
*/
export function paintListeningHeader(
image: GrayImage,
@@ -75,18 +75,20 @@ export function paintListeningHeader(
title: string,
status: string,
meter: MicLevelMeter | null,
padding: Edges<number>,
): number {
let textRight = image.width - HEADER_X;
const x = padding.left, y = padding.top;
let textRight = image.width - padding.right;
if (meter) {
const meterX = textRight - meter.width;
// Roughly cap height, sitting on the text's baseline.
meter.paint(image, meterX, HEADER_Y + font.ascent, Math.max(4, Math.round(font.ascent * 0.6)));
meter.paint(image, meterX, y + font.ascent, Math.max(4, Math.round(font.ascent * 0.6)));
textRight = meterX - METER_GAP;
}
image.drawText(font, HEADER_X, HEADER_Y, title, TITLE_GRAY);
image.drawText(font, x, y, title, TITLE_GRAY);
if (status) {
const statusX = HEADER_X + Math.ceil(font.measureText(title));
image.drawText(font, statusX, HEADER_Y, truncateText(font, ` · ${status}`, textRight - statusX), STATUS_GRAY);
const statusX = x + Math.ceil(font.measureText(title));
image.drawText(font, statusX, y, truncateText(font, ` · ${status}`, textRight - statusX), STATUS_GRAY);
}
return HEADER_Y + lineStep(font) + 2;
return y + lineStep(font) + 2;
}
+51 -27
View File
@@ -18,8 +18,15 @@ const MAX_SCROLL_STRIP_BYTES = 65536;
export const BOUNCE_FRACTION = 0.4;
export const MAX_BOUNCE = 24;
/** A rectangle in image coordinates. */
export type MenuBox = { x: number; y: number; width: number; height: number };
/**
* A rectangle in image coordinates. padTop and padBottom are blank rows
* inside the scrolled content, before the first row and after the last
* (default none): they scroll away with the rows. A list whose box runs to
* a window's top or bottom edge passes the padding suggested for that edge
* (viewport.ts), so its end rows keep clear of a border line there while
* rows scrolled past them are cut off right at the edge.
*/
export type MenuBox = { x: number; y: number; width: number; height: number; padTop?: number; padBottom?: number };
export type MenuDrawArgs<T> = {
/**
@@ -73,6 +80,7 @@ export type MenuOptions<T> = {
highlight?: MenuHighlightStyle | false;
};
/** Row tops and pitches in content coordinates; `total` includes the box's padTop and padBottom. */
type MenuLayout = { tops: number[]; heights: number[]; total: number };
/**
@@ -144,7 +152,7 @@ export class Menu<T> {
/** True when the content did not fit the box given to the last paint. */
get overflows(): boolean {
if (!this.lastBox) return false;
return this.layout(this.lastBox.width).total > this.lastBox.height;
return this.layout(this.lastBox).total > this.lastBox.height;
}
/**
@@ -154,15 +162,15 @@ export class Menu<T> {
* viewport keeps the selected row at the same on-screen position when it can.
*/
setItems(items: readonly T[], selectedIndex?: number | null): void {
const width = this.lastBox?.width;
const before = this.selected !== null && width !== undefined
? this.layout(width).tops[this.selected]! - this.scrollY
const box = this.lastBox;
const before = this.selected !== null && box
? this.layout(box).tops[this.selected]! - this.scrollY
: null;
this.itemList = items;
if (selectedIndex !== undefined) this.deselected = selectedIndex === null;
this.selected = this.settle(selectedIndex === undefined ? this.selected : selectedIndex);
if (before !== null && this.selected !== null && width !== undefined) {
this.scrollY = Math.max(0, this.layout(width).tops[this.selected]! - before);
if (before !== null && this.selected !== null && box) {
this.scrollY = Math.max(0, this.layout(box).tops[this.selected]! - before);
}
}
@@ -197,7 +205,7 @@ export class Menu<T> {
this.selected = wrapped;
this.deselected = false;
} else if (from === null && this.lastBox) {
this.scrollY = delta > 0 ? 0 : this.maxScroll(this.layout(this.lastBox.width), this.lastBox.height);
this.scrollY = delta > 0 ? 0 : this.maxScroll(this.layout(this.lastBox), this.lastBox.height);
}
return;
}
@@ -234,7 +242,7 @@ export class Menu<T> {
indexAt(y: number): number | null {
const box = this.lastBox;
if (!box || y < box.y || y >= box.y + box.height) return null;
const layout = this.layout(box.width);
const layout = this.layout(box);
const contentY = y - box.y + this.scrollY;
for (let index = 0; index < this.itemList.length; index++) {
if (contentY >= layout.tops[index]! && contentY < layout.tops[index]! + layout.heights[index]!) {
@@ -247,7 +255,7 @@ export class Menu<T> {
paint(image: GrayImage, box: MenuBox, focused: boolean): void {
this.lastBox = box;
this.reconcile();
const layout = this.layout(box.width);
const layout = this.layout(box);
this.ensureVisible(layout, box.height);
const now = Date.now();
const scroll = this.scrollMotion.paint(this.scrollY, box, now);
@@ -297,7 +305,7 @@ export class Menu<T> {
drawScrollbar(image: GrayImage, x: number, y: number, height: number): void {
const box = this.lastBox;
if (!box) return;
const layout = this.layout(box.width);
const layout = this.layout(box);
if (layout.total <= box.height) return;
const maxScroll = this.maxScroll(layout, box.height);
const thumbHeight = Math.max(SCROLLBAR_MIN_THUMB, (height * box.height / layout.total) | 0);
@@ -378,7 +386,7 @@ export class Menu<T> {
private bounce(delta: -1 | 1): void {
const count = this.itemList.length;
if (!this.lastBox || !count) return;
const layout = this.layout(this.lastBox.width);
const layout = this.layout(this.lastBox);
const pitch = layout.heights[delta > 0 ? count - 1 : 0]!;
const amount = Math.min(MAX_BOUNCE, Math.round(pitch * BOUNCE_FRACTION));
if (amount > 0) this.scrollMotion.bounce(delta * amount);
@@ -417,20 +425,30 @@ export class Menu<T> {
this.selected = this.settle(this.selected);
}
private layout(width: number): MenuLayout {
private layout(box: MenuBox): MenuLayout {
const tops: number[] = [];
const heights: number[] = [];
let total = 0;
let total = Math.max(0, (box.padTop ?? 0) | 0);
for (const item of this.itemList) {
const height = Math.max(0, this.options.getHeight(item, width) | 0);
const height = Math.max(0, this.options.getHeight(item, box.width) | 0);
tops.push(total);
heights.push(height);
total += height;
}
if (this.itemList.length) total -= this.options.rowGap ?? 0;
total += Math.max(0, (box.padBottom ?? 0) | 0);
return { tops, heights, total };
}
/**
* Where the viewport's top rests to show row `index` from its start: the
* row's top, or for the first row the content's, so the padding above it
* shows too.
*/
private restTop(layout: MenuLayout, index: number): number {
return index === 0 ? 0 : layout.tops[index]!;
}
private maxScroll(layout: MenuLayout, viewportHeight: number): number {
return Math.max(0, layout.total - viewportHeight);
}
@@ -443,16 +461,21 @@ export class Menu<T> {
}
const gap = this.options.rowGap ?? 0;
const selected = this.selected;
const last = this.itemList.length - 1;
const top = layout.tops[selected]!;
const bottom = top + layout.heights[selected]! - gap;
// The content's padding counts as part of its end rows: showing the
// first row shows the padding above it, and the last the padding below.
const startOf = (index: number) => this.restTop(layout, index);
const endOf = (index: number) => index === last ? layout.total : layout.tops[index]! + layout.heights[index]! - gap;
// Keep the neighbors in view too when all three fit, so the user sees
// what the next step will reach.
const contextTop = selected > 0 ? layout.tops[selected - 1]! : top;
const contextBottom = selected + 1 < this.itemList.length
? layout.tops[selected + 1]! + layout.heights[selected + 1]! - gap : bottom;
const contextTop = startOf(Math.max(0, selected - 1));
const contextBottom = endOf(Math.min(last, selected + 1));
const paddedFits = endOf(selected) - startOf(selected) <= viewportHeight;
const fits = contextBottom - contextTop <= viewportHeight;
const wantTop = fits ? contextTop : top;
const wantBottom = fits ? contextBottom : bottom;
const wantTop = fits ? contextTop : paddedFits ? startOf(selected) : top;
const wantBottom = fits ? contextBottom : paddedFits ? endOf(selected) : bottom;
let target = this.scrollY;
if (wantTop < target) {
target = wantTop;
@@ -462,8 +485,8 @@ export class Menu<T> {
// Snap to the first row that starts inside the viewport: the wanted
// rows still fit (their bottom is within viewportHeight of that top).
for (let index = 0; index <= selected; index++) {
if (layout.tops[index]! >= target) {
target = layout.tops[index]!;
if (startOf(index) >= target) {
target = startOf(index);
break;
}
}
@@ -474,7 +497,7 @@ export class Menu<T> {
// the list. The selected row stays visible, since it ends by the list's end.
const maxScroll = this.maxScroll(layout, viewportHeight);
if (target > maxScroll) {
const aligned = layout.tops.find((rowTop) => rowTop >= maxScroll);
const aligned = layout.tops.map((_, index) => startOf(index)).find((rowTop) => rowTop >= maxScroll);
target = aligned !== undefined && aligned <= target ? aligned : maxScroll;
}
this.scrollY = Math.max(0, target);
@@ -483,16 +506,17 @@ export class Menu<T> {
/** With nothing selectable, up/down page the content by rows. Returns false at the end being scrolled past. */
private scrollContent(delta: -1 | 1): boolean {
if (!this.lastBox) return false;
const layout = this.layout(this.lastBox.width);
const layout = this.layout(this.lastBox);
const maxScroll = this.maxScroll(layout, this.lastBox.height);
const stops = layout.tops.map((_, index) => this.restTop(layout, index));
if (delta > 0) {
if (this.scrollY >= maxScroll) return false;
const next = layout.tops.find((top) => top > this.scrollY);
const next = stops.find((top) => top > this.scrollY);
this.scrollY = Math.min(maxScroll, next ?? maxScroll);
} else {
if (this.scrollY <= 0) return false;
let previous = 0;
for (const top of layout.tops) if (top < this.scrollY) previous = top;
for (const top of stops) if (top < this.scrollY) previous = top;
this.scrollY = Math.max(0, previous);
}
return true;
+86 -23
View File
@@ -34,6 +34,11 @@ const MENU_FOOTER_GAP = 8;
const MENU_ROW_INSET = 12;
/** Horizontal inset of row text from the row box. */
const MENU_ROW_TEXT_INSET = 10;
/** A page menu's title: how far below the window's top padding, and the gap under its band. */
const PAGE_TITLE_OFFSET_Y = 2;
const PAGE_TITLE_GAP = 4;
/** Room a page menu keeps right of its rows for the scrollbar. */
const PAGE_SCROLLBAR_GUTTER = 6;
export type MenuLayout = {
/** Stereo depth of the menu surface, including the selected row. */
@@ -64,6 +69,23 @@ export type MenuLayout = {
squareCorners?: boolean;
};
/**
* A menu laid out as a page of its window rather than a box floating over
* it (an app's root menu, a settings sub-screen): opaque, with no outline.
* Its rows start at the padding suggested for the window's left edge
* (viewport.ts) and its title lines up with their text. The title and a
* footer stay put, inside the top and bottom padding; the rows scroll
* between them, or right to the window's top or bottom edge where there is
* none, with that edge's padding inside the list.
*/
export type MenuPageLayout = {
page: true;
/** Width of the rows. Default (and at most): the window's, inside its side padding. */
width?: number;
/** Dim hint line pinned above the window's bottom padding, below the rows. */
footer?: string;
};
export type MenuItemRenderArgs = {
image: GrayImage;
x: number;
@@ -231,16 +253,16 @@ export class MenuLayer implements Layer {
/** The context of the paint in progress, handed to item render callbacks. */
private paintCtx: LayerContext | null = null;
get depth(): number { return this.layout.depth ?? 0; }
get depth(): number { return "page" in this.layout ? 0 : this.layout.depth ?? 0; }
get dimUnderneath(): false | number {
return this.layout.dimUnderneath ?? false;
return "page" in this.layout ? false : this.layout.dimUnderneath ?? false;
}
constructor(
private readonly title: string | null,
private items: MenuItem[],
private readonly layout: MenuLayout = {
private readonly layout: MenuLayout | MenuPageLayout = {
x: DEFAULT_MENU_X,
y: DEFAULT_MENU_Y,
width: DEFAULT_MENU_WIDTH,
@@ -301,22 +323,24 @@ export class MenuLayer implements Layer {
}
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
if ("page" in this.layout) return this.paintPage(ctx, this.layout);
const layout = this.layout;
const font = getDefaultSmallFont();
const rowHeight = listRowHeight(font);
const base = ctx.stack.getBaseSize();
const image = this.layout.opaque ? new GrayImage(base.width, base.height, 0) : paintBelow();
const { y, width } = this.layout;
const x = this.layout.x === "center" ? ((image.width - width) / 2) | 0 : this.layout.x;
const image = layout.opaque ? new GrayImage(base.width, base.height, 0) : paintBelow();
const { y, width } = layout;
const x = layout.x === "center" ? ((image.width - width) / 2) | 0 : layout.x;
const chromeTop = (this.title ? menuTitleHeight(font) : 0) + MENU_BODY_PADDING;
const minHeight = this.layout.minHeight ?? defaultMenuMinHeight();
const minHeight = layout.minHeight ?? defaultMenuMinHeight();
// Cap to the surface being painted on: a window's stack image may be much
// shorter than the full screen (min-height windows).
const maxHeight = Math.min(
this.layout.maxHeight ?? image.height - y - DEFAULT_MENU_Y,
layout.maxHeight ?? image.height - y - DEFAULT_MENU_Y,
image.height - y,
(this.layout.squareCorners || this.depth !== 0) ? Math.floor(65530 / Math.ceil(width / 2)) : Infinity,
(layout.squareCorners || this.depth !== 0) ? Math.floor(65530 / Math.ceil(width / 2)) : Infinity,
);
const footerHeight = this.layout.footer ? MENU_FOOTER_GAP + lineStep(font) : 0;
const footerHeight = layout.footer ? MENU_FOOTER_GAP + lineStep(font) : 0;
const contentHeight = chromeTop + this.items.length * rowHeight + footerHeight + MENU_BODY_PADDING;
const height = clamp(contentHeight, Math.min(minHeight, maxHeight), maxHeight);
const visibleRowCount = Math.max(
@@ -326,17 +350,17 @@ export class MenuLayer implements Layer {
// Fill 1, not 0: identical after 4bpp quantization, but 0 is the
// transparent color key when a menu paints on the shell surface.
if (this.layout.squareCorners) image.fillRect(x, y, width, height, 1);
if (layout.squareCorners) image.fillRect(x, y, width, height, 1);
else image.fillRoundedRect(x, y, width, height, 1);
if (this.layout.showBorder !== false) {
if (this.layout.squareCorners) image.drawRect(x, y, width, height, 72);
if (layout.showBorder !== false) {
if (layout.squareCorners) image.drawRect(x, y, width, height, 72);
else image.drawRoundedRect(x, y, width, height, 72);
}
if (this.title) {
image.drawText(font, x + 12, y + 8, this.title, 220);
}
if (this.layout.footer) {
image.drawText(font, x + 22, y + height - MENU_BODY_PADDING - font.lineHeight, this.layout.footer, 110);
if (layout.footer) {
image.drawText(font, x + 22, y + height - MENU_BODY_PADDING - font.lineHeight, layout.footer, 110);
}
const bodyY = y + chromeTop;
@@ -352,6 +376,42 @@ export class MenuLayer implements Layer {
return image;
}
/** Paint as a page of the window (see MenuPageLayout). */
private paintPage(ctx: LayerContext, layout: MenuPageLayout): GrayImage {
const font = getDefaultSmallFont();
const { width, height, padding } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
const x = padding.left;
const available = Math.max(0, width - padding.left - padding.right - PAGE_SCROLLBAR_GUTTER);
const rowsWidth = Math.min(layout.width ?? available, available);
// Fixed parts keep inside the window's padding; the list's box runs to
// an edge nothing fixed stands before, taking that edge's padding as its own.
let top = 0;
let fixedTop = padding.top;
if (this.title) {
const titleY = padding.top + PAGE_TITLE_OFFSET_Y;
image.drawText(font, x + MENU_ROW_TEXT_INSET, titleY, this.title, 220);
top = fixedTop = titleY + menuTitleHeight(font) + PAGE_TITLE_GAP;
}
let bottom = height;
let fixedBottom = height - padding.bottom;
if (layout.footer) {
const footerY = height - padding.bottom - font.lineHeight;
image.drawText(font, x + MENU_ROW_TEXT_INSET, footerY, layout.footer, 110);
bottom = fixedBottom = footerY - MENU_FOOTER_GAP;
}
if (bottom <= top) return image;
this.paintCtx = ctx;
try {
this.menu.paint(image, { x, y: top, width: rowsWidth, height: bottom - top, padTop: fixedTop - top, padBottom: bottom - fixedBottom },
ctx.stack.isFocused());
} finally {
this.paintCtx = null;
}
this.menu.drawScrollbar(image, x + rowsWidth + PAGE_SCROLLBAR_GUTTER - 3, fixedTop, Math.max(0, fixedBottom - fixedTop));
return image;
}
async handleInput(event: InputEvent, ctx: LayerContext): Promise<void> {
switch (event.type) {
case "double-click":
@@ -413,20 +473,23 @@ export class TextPageLayer implements Layer {
// Size to the stack, not the lens: in an app window the stack is the
// window's viewport, and the compositor rejects a frame larger than its
// surface (leaving the previous frame on screen).
const { width, height } = ctx.stack.getBaseSize();
const { width, height, padding } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
image.drawText(font, 18, 14, this.title, 220);
image.drawRect(12, 12, width - 24, height - 24, 52);
// The page's own outline sits at the padding suggested for each window
// edge; everything else is placed from it.
const box = { x: padding.left, y: padding.top, width: width - padding.left - padding.right, height: height - padding.top - padding.bottom };
image.drawText(font, box.x + 6, box.y + 2, this.title, 220);
image.drawRect(box.x, box.y, box.width, box.height, 52);
const wrapped = wrapText(font, this.body, width - 60);
const wrapped = wrapText(font, this.body, box.width - 36);
const step = lineStep(font);
const bodyTop = 28 + font.lineHeight;
const footerY = height - 48;
const bodyTop = box.y + 16 + font.lineHeight;
const footerY = box.y + box.height - 36;
const maxBodyLines = Math.max(0, Math.floor((footerY - bodyTop - 8) / step));
for (let index = 0; index < Math.min(wrapped.length, maxBodyLines); index++) {
image.drawText(font, 24, bodyTop + index * step, wrapped[index]!, 190);
image.drawText(font, box.x + 12, bodyTop + index * step, wrapped[index]!, 190);
}
image.drawText(font, 24, footerY, `${GESTURE_DOUBLE_CLICK} back`, 110);
image.drawText(font, box.x + 12, footerY, `${GESTURE_DOUBLE_CLICK} back`, 110);
return image;
}
+5 -12
View File
@@ -10,11 +10,10 @@ import { drawToggleMenuItem, MenuLayer, type MenuItem } from "./menu";
/** Refresh rows as new sources arrive, keeping the current selection by package. */
export class NotificationFilterLayer implements Layer {
private menu: MenuLayer | null = null;
private menuWidth = 0;
/** The package behind each current row, parallel to the menu's items. */
private packages: string[] = [];
private currentMenu(ctx: LayerContext): MenuLayer {
private currentMenu(): MenuLayer {
readActiveNotifications(ALL_NOTIFICATIONS);
const sources = readNotificationSources().sort((a, b) =>
a.appName.localeCompare(b.appName) || a.packageName.localeCompare(b.packageName));
@@ -32,14 +31,8 @@ export class NotificationFilterLayer implements Layer {
const index = sources.findIndex((source) => source.packageName === selectedPackage);
this.packages = sources.map((source) => source.packageName);
const width = ctx.stack.getBaseSize().width;
if (!this.menu || width !== this.menuWidth) {
this.menuWidth = width;
this.menu = new MenuLayer("Notification filter", items, {
x: 8, y: 8, width: width - 16,
opaque: true, showBorder: false,
footer: "On = show popups on glasses",
}).selectItem(Math.max(0, index));
if (!this.menu) {
this.menu = new MenuLayer("Notification filter", items, { page: true, footer: "On = show popups on glasses" }).selectItem(Math.max(0, index));
} else {
this.menu.setItems(items, index >= 0 ? index : undefined);
}
@@ -47,10 +40,10 @@ export class NotificationFilterLayer implements Layer {
}
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
return this.currentMenu(ctx).paint(ctx, paintBelow);
return this.currentMenu().paint(ctx, paintBelow);
}
async handleInput(event: InputEvent, ctx: LayerContext): Promise<void> {
await this.currentMenu(ctx).handleInput(event, ctx);
await this.currentMenu().handleInput(event, ctx);
}
}
+97 -71
View File
@@ -24,12 +24,17 @@ import { noteStaleDataUsed, renderPassAllowsStaleData } from "../util/render-fre
import { type InputEvent } from "./gestures";
import { type Layer, type LayerContext, type PaintBelow } from "./layers";
import { Menu, type MenuBox } from "./menu-core";
import type { Viewport } from "./viewport";
// Title position, shared with the other list apps (terminal, calendar).
const TITLE_X = 18;
const TITLE_Y = 10;
const LIST_TOP = 38;
const CARD_X = 20;
// The list's title, as in the other list apps (terminal, calendar): this far
// in from the cards' left edge (in line with their icons) and below the
// window's top padding; the first card starts LIST_TOP_GAP under its top.
const TITLE_INSET_X = 10;
const TITLE_OFFSET_Y = 2;
const LIST_TOP_GAP = 28;
/** The empty-list message: indented from the title, and this far under its top. */
const EMPTY_MESSAGE_INDENT = 6;
const EMPTY_MESSAGE_GAP = 62;
const ICON_SIZE = NOTIFICATION_ICON_SIZE;
const ICON_TEXT_GAP = 8;
const CARD_TEXT_X = 10 + ICON_SIZE + ICON_TEXT_GAP;
@@ -37,23 +42,19 @@ const CARD_GAP = 6;
const MAX_NOTIFICATIONS = 50;
// Right-hand action menu of the detail view.
const DETAIL_MENU_WIDTH = 148;
/** Top of the action menu's first row box, and the space kept below its last. */
const DETAIL_MENU_TOP = 22;
const DETAIL_MENU_BOTTOM_MARGIN = 17;
/** Gap between the content column and the action menu's row boxes. */
const DETAIL_MENU_GAP = 12;
const DETAIL_MENU_ROW_GAP = 3;
/** Row text inset from the row box: horizontal, then vertical. */
const DETAIL_MENU_TEXT_X = 8;
const DETAIL_MENU_TEXT_Y = 4;
const DETAIL_CONTENT_X = 24;
const DETAIL_TITLE_Y = 21;
/** Gaps below the title's line box and below the icon/app-name header row. */
const DETAIL_HEADER_GAP = 3;
const DETAIL_BODY_GAP = 4;
/** Untitled text lines that attached images (custom layout, picture) leave room for above them, when there are that many; they take the rest. */
const DETAIL_PICTURE_TEXT_LINES = 2;
/** Gap between the text and an attached picture, and the space kept below the picture. */
/** Gap between the text and an attached picture. */
const DETAIL_PICTURE_GAP = 6;
const DETAIL_PICTURE_BOTTOM_MARGIN = 12;
/** An attached picture with less height than this to fit in (a large UI font) is left out. */
const DETAIL_PICTURE_MIN_HEIGHT = 32;
/** Likewise a custom layout; Dexcom's reading is about 40 high. */
@@ -62,8 +63,6 @@ const DETAIL_CUSTOM_VIEW_MIN_HEIGHT = 16;
const LARGE_ICON_SIZE = 32;
const LARGE_ICON_GAP = 8;
// Disable-source confirmation: actions on top, the explanation below them.
const CONFIRM_X = 24;
const CONFIRM_Y = 8;
const CONFIRM_TEXT_X = 10;
const CONFIRM_PROMPT_GAP = 16;
@@ -137,10 +136,14 @@ export class NotificationsListLayer implements Layer {
paint(ctx: LayerContext): GrayImage {
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const { width, height, padding } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
const cardWidth = width - 2 * CARD_X;
// Cards span the window between the padding suggested for its sides.
const cardX = padding.left;
const cardWidth = width - padding.left - padding.right;
const cardTextWidth = cardWidth - CARD_TEXT_X - 14;
const titleX = cardX + TITLE_INSET_X;
const titleY = padding.top + TITLE_OFFSET_Y;
const notifications = readActiveNotifications(MAX_NOTIFICATIONS);
const selectedIndex = this.resolveSelectedIndex(notifications);
const layouts = notifications.map((notification, index) =>
@@ -148,37 +151,41 @@ export class NotificationsListLayer implements Layer {
);
if (!notifications.length) {
image.drawText(font, TITLE_X, TITLE_Y, "Notifications", 220);
image.drawText(font, titleX, titleY, "Notifications", 220);
const message = notificationEmptyMessage();
const messageLines = wrapText(font, message, width - 48);
const messageX = titleX + EMPTY_MESSAGE_INDENT;
const messageLines = wrapText(font, message, width - padding.right - messageX);
for (let index = 0; index < messageLines.length; index++) {
image.drawText(font, 24, 72 + index * lineStep(font), messageLines[index]!, 190);
image.drawText(font, messageX, titleY + EMPTY_MESSAGE_GAP + index * lineStep(font), messageLines[index]!, 190);
}
return image;
}
const focused = ctx.stack.isFocused();
const listBottom = height;
const scrollY = scrollForSelected(layouts, selectedIndex, listBottom - LIST_TOP);
// The title scrolls away with the list. Card text is drawn as deferred
// glyphs (always composited above raster fills), so a fixed title would
// show through cards scrolled over it; moving it with the content keeps
// it above the first card instead.
if (TITLE_Y - scrollY + font.lineHeight > 0) {
image.drawText(font, TITLE_X, TITLE_Y - scrollY, "Notifications", 220);
// The whole window scrolls, title and all, so cards scrolled past either
// end are cut off at the window's own edges; the padding suggested for
// the top and bottom edges lies inside the scrolled content, above the
// title and below the last card.
const listTop = titleY + LIST_TOP_GAP;
const scrollY = scrollForSelected(layouts, selectedIndex, height - listTop, padding.bottom);
// Card text is drawn as deferred glyphs (always composited above raster
// fills), so a fixed title would show through cards scrolled over it;
// moving it with the content keeps it above the first card instead.
if (titleY - scrollY + font.lineHeight > 0) {
image.drawText(font, titleX, titleY - scrollY, "Notifications", 220);
}
let cursorY = LIST_TOP - scrollY;
let cursorY = listTop - scrollY;
for (let index = 0; index < layouts.length; index++) {
const layout = layouts[index]!;
if (cursorY + layout.height >= LIST_TOP && cursorY <= listBottom) {
if (cursorY + layout.height > 0 && cursorY < height) {
// Icons are only resolved for cards actually drawn, so a long list
// does not fetch icons for everything below the fold.
const icon = iconForNotification(layout.notification.key);
const largeIcon = largeIconForNotification(layout.notification);
drawNotificationCard(image, font, layout, CARD_X, cursorY, cardWidth, index === selectedIndex, focused, icon, largeIcon);
drawNotificationCard(image, font, layout, cardX, cursorY, cardWidth, index === selectedIndex, focused, icon, largeIcon);
}
cursorY += layout.height + CARD_GAP;
if (cursorY > listBottom + 80) break;
if (cursorY > height + 80) break;
}
return image;
@@ -250,8 +257,8 @@ export class SingleNotificationLayer implements Layer {
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
if (this.confirmation) return this.paintConfirmation(ctx);
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
const viewport = ctx.stack.getBaseSize();
const image = new GrayImage(viewport.width, viewport.height, 0);
const notification = readActiveNotifications(ALL_NOTIFICATIONS).find((item) => item.key === this.notificationKey);
if (!notification) {
@@ -259,8 +266,9 @@ export class SingleNotificationLayer implements Layer {
}
this.detailMenu.setItems(buildDetailMenu(notification, this.options.origin));
drawDetailContent(image, font, notification, iconForNotification(notification.key), width, height);
this.detailMenu.paint(image, notificationActionMenuBox(width, height), ctx.stack.isFocused());
const layout = notificationDetailLayout(viewport);
drawDetailContent(image, font, notification, iconForNotification(notification.key), layout);
this.detailMenu.paint(image, layout.menuBox, ctx.stack.isFocused());
this.lastImage = image;
return image;
}
@@ -330,24 +338,28 @@ export class SingleNotificationLayer implements Layer {
private paintConfirmation(ctx: LayerContext): GrayImage {
const { source, menu } = this.confirmation!;
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const { width, height, padding } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
const contentWidth = width - padding.left - padding.right;
// Put actions first so they remain reachable even with a large UI font.
const menuBox: MenuBox = {
x: CONFIRM_X,
y: CONFIRM_Y,
width: width - 2 * CONFIRM_X,
height: Math.min(menu.items.length * listRowHeight(font), height - CONFIRM_Y),
x: padding.left,
y: padding.top,
width: contentWidth,
height: Math.min(menu.items.length * listRowHeight(font), height - padding.top),
};
menu.paint(image, menuBox, ctx.stack.isFocused());
const top = menuBox.y + menuBox.height + CONFIRM_PROMPT_GAP;
const prompt = `Turn off notification popups from ${source.appName || source.packageName}? You can turn them back on in the Notifications app's Notification filter.`;
const lines = wrapText(font, prompt, width - 2 * CONFIRM_X);
const maxLines = Math.max(1, Math.floor((height - top - 12) / lineStep(font)));
// In line with the actions' labels.
const promptX = menuBox.x + CONFIRM_TEXT_X;
const promptWidth = contentWidth - 2 * CONFIRM_TEXT_X;
const lines = wrapText(font, prompt, promptWidth);
const maxLines = Math.max(1, Math.floor((height - padding.bottom - top) / lineStep(font)));
for (let index = 0; index < Math.min(lines.length, maxLines); index++) {
const text = index === maxLines - 1 && lines.length > maxLines
? truncateText(font, lines[index] + "...", width - 2 * CONFIRM_X) : lines[index]!;
image.drawText(font, CONFIRM_X, top + index * lineStep(font), text, 210);
? truncateText(font, lines[index] + "...", promptWidth) : lines[index]!;
image.drawText(font, promptX, top + index * lineStep(font), text, 210);
}
return image;
}
@@ -443,14 +455,20 @@ function drawNotificationCard(
}
}
function scrollForSelected(layouts: CardLayout[], selectedIndex: number, viewportHeight: number): number {
/**
* How far the list is scrolled to centre the selected card in the rows from
* the first card's resting top to the window's bottom (`viewportHeight` of
* them), without scrolling past the last card and the `bottomPadding` kept
* under it.
*/
function scrollForSelected(layouts: CardLayout[], selectedIndex: number, viewportHeight: number, bottomPadding: number): number {
if (selectedIndex < 0) return 0;
let selectedTop = 0;
for (let index = 0; index < selectedIndex; index++) {
selectedTop += layouts[index]!.height + CARD_GAP;
}
const selectedBottom = selectedTop + layouts[selectedIndex]!.height;
const contentHeight = layouts.reduce((sum, layout) => sum + layout.height + CARD_GAP, 0);
const contentHeight = layouts.reduce((sum, layout) => sum + layout.height + CARD_GAP, -CARD_GAP) + bottomPadding;
const maxScroll = Math.max(0, contentHeight - viewportHeight);
const centered = selectedTop - Math.max(0, (viewportHeight - (selectedBottom - selectedTop)) / 2);
return clamp(centered | 0, 0, maxScroll);
@@ -461,14 +479,12 @@ function drawDetailContent(
font: UiFont,
notification: AndroidNotification,
icon: GrayImage | null,
width: number,
height: number,
layout: NotificationDetailLayout,
): void {
const contentX = NOTIFICATION_CONTENT_X;
const contentWidth = notificationContentWidth(width);
const { contentX, contentWidth, bottom } = layout;
const step = lineStep(font);
const bottom = height - DETAIL_PICTURE_BOTTOM_MARGIN;
let top = drawNotificationHeader(image, font, icon, `${notification.appName || notification.packageName} ${formatRelativeTime(notification.postTime)}`);
let top = drawNotificationHeader(image, font, icon,
`${notification.appName || notification.packageName} ${formatRelativeTime(notification.postTime)}`, layout);
// The title, beside the large icon (a sender's avatar, a site's logo) when
// there is one. A picture or custom layout can be the whole notification
@@ -561,24 +577,44 @@ function drawClippedLines(
return shown;
}
/** Left edge of a notification detail view's content column. */
export const NOTIFICATION_CONTENT_X = DETAIL_CONTENT_X;
/**
* Where a notification detail view's parts go in its viewport: a content
* column from the padding suggested for the left edge, and an action column
* of DETAIL_MENU_WIDTH ending at the right edge's. The content keeps inside
* the top and bottom padding (`top`, `bottom`). The action menu scrolls, so
* its box runs to the top and bottom edges with their padding inside it.
*/
export type NotificationDetailLayout = {
contentX: number;
contentWidth: number;
top: number;
bottom: number;
menuBox: MenuBox;
};
/** Width of a notification detail view's content column, left of the action column. */
export function notificationContentWidth(width: number): number {
return width - DETAIL_MENU_WIDTH - 24 - NOTIFICATION_CONTENT_X - 20;
export function notificationDetailLayout(viewport: Viewport): NotificationDetailLayout {
const { width, height, padding } = viewport;
const menuX = width - padding.right - DETAIL_MENU_WIDTH;
return {
contentX: padding.left,
contentWidth: menuX - DETAIL_MENU_GAP - padding.left,
top: padding.top,
bottom: height - padding.bottom,
menuBox: { x: menuX, y: 0, width: DETAIL_MENU_WIDTH, height, padTop: padding.top, padBottom: padding.bottom },
};
}
/**
* The top of a notification detail view: the "Notification" title, then the
* source's icon and label. Returns the y where the body starts.
*/
export function drawNotificationHeader(image: GrayImage, font: UiFont, icon: GrayImage | null, sourceLabel: string): number {
const contentX = NOTIFICATION_CONTENT_X;
image.drawText(font, contentX, DETAIL_TITLE_Y, "Notification", 220);
export function drawNotificationHeader(image: GrayImage, font: UiFont, icon: GrayImage | null, sourceLabel: string,
layout: NotificationDetailLayout): number {
const { contentX, top } = layout;
image.drawText(font, contentX, top, "Notification", 220);
// The header row (icon + app name) and the body stack below the title's
// line box, so a large UI font pushes them down instead of overlapping.
const headerTop = DETAIL_TITLE_Y + font.lineHeight + DETAIL_HEADER_GAP;
const headerTop = top + font.lineHeight + DETAIL_HEADER_GAP;
const headerHeight = Math.max(ICON_SIZE, font.lineHeight);
let sourceX = contentX;
if (icon) {
@@ -616,16 +652,6 @@ export function createNotificationActionMenu<T extends { label: string }>(wraps:
});
}
/** The action column's row boxes: right of the content, from DETAIL_MENU_TOP to the bottom margin. */
export function notificationActionMenuBox(width: number, height: number): MenuBox {
return {
x: width - DETAIL_MENU_WIDTH - 32,
y: DETAIL_MENU_TOP,
width: DETAIL_MENU_WIDTH,
height: height - DETAIL_MENU_TOP - DETAIL_MENU_BOTTOM_MARGIN,
};
}
function buildDetailMenu(notification: AndroidNotification, origin: SingleNotificationLayerOrigin): DetailMenuItem[] {
return [
{ kind: "back", label: "Back" },
+32
View File
@@ -12,6 +12,7 @@ import {
type WindowBorder,
windowBorderSetting,
} from "../dashboard-settings";
import { type EdgeKind, type Edges, uniformEdges, type Viewport, viewportWith } from "../viewport";
/** The paired glasses' screen, which the shell lays out in (graphics/screen-size.ts). */
export { screenHeight, screenWidth };
@@ -481,6 +482,37 @@ export function appViewportSize(mode: WindowHeightMode, appId?: string): { width
};
}
/**
* What each edge of an app's windows touches (see viewport.ts EdgeKind): a
* line the chrome draws right outside it, or nothing. A framed window has a
* line on every side. Otherwise the top or bottom has one where a status bar
* with rows of its own, or a bottom switcher row, lies past it and the
* Border setting divides the two; a side has one only beside a side strip,
* whose separator it is. An immersive window has the whole panel, and so
* none.
*/
export function windowEdges(appId?: string): Edges<EdgeKind> {
if (isImmersive(appId)) return uniformEdges("offscreen");
if (windowFramed(appId)) return uniformEdges("border");
const position = switcherPosition();
const line = (drawn: boolean): EdgeKind => (drawn ? "border" : "offscreen");
const statusLine = (edge: "top" | "bottom") => windowEdgeHeight(edge, appId) === TOP_BAR_HEIGHT && statusBarDivider();
return {
top: line(statusLine("top")),
right: line(position === "right"),
bottom: line(position === "bottom" ? switcherRowHeight(appId) > 0 && switcherRowDivider(appId) : statusLine("bottom")),
left: line(position === "left"),
};
}
/**
* A window's viewport as its layouts get it: the app-content size for its
* height mode, what its edges touch, and the padding suggested for them.
*/
export function appViewport(mode: WindowHeightMode, appId?: string): Viewport {
return viewportWith(appViewportSize(mode, appId), windowEdges(appId));
}
/** Screen rect of a window's app-content viewport (between its header and footer). */
export function appViewportRect(mode: WindowHeightMode, appId?: string): {
x: number;
+2 -2
View File
@@ -8,7 +8,7 @@ import { type MenuItem } from "../menu";
import { WindowMenuLayer } from "../window-menu";
import { windowIcon } from "./chrome-layer";
import { type IconName } from "../../graphics/icons";
import { appViewportSize, setAppImmersive, type WindowHeightMode } from "./geometry";
import { appViewport, setAppImmersive, type WindowHeightMode } from "./geometry";
import { shell, type ShellWindow } from "./shell";
/**
@@ -111,7 +111,7 @@ export function createInProcessWindow(options: InProcessWindowOptions): InProces
const requestRender = () => renderInNewFrame(0);
let heightMode = options.heightMode ?? "min";
setAppImmersive(options.appId, options.immersive ?? false);
const viewportSize = () => appViewportSize(heightMode, options.appId);
const viewportSize = () => appViewport(heightMode, options.appId);
const stack = new LayerStack(
options.baseLayer,
{ ...options.actions, requestRender },
+8 -4
View File
@@ -3,6 +3,7 @@ import { flattenPlanes } from "../../graphics/plane";
import { InputEvent } from "../gestures";
import { Layer, LayerActions, LayerContext, LayerStack, PaintBelow } from "../layers";
import { appViewportRect, appViewportSize, SHELL_OPAQUE_BLACK } from "./geometry";
import { uniformEdges, type Viewport, viewportWith } from "../viewport";
// The modal covers most of the min-height app viewport, leaving a little of
// the foreground app visible around the edges. Both its size and position are
@@ -11,13 +12,16 @@ import { appViewportRect, appViewportSize, SHELL_OPAQUE_BLACK } from "./geometry
const MODAL_MARGIN = 14;
const MODAL_PADDING = 4;
/** Content (inner layer stack) size of the modal box. */
function modalInterior(): { width: number; height: number } {
/**
* The modal box's content (inner layer stack) viewport: every edge is just
* inside the box's border.
*/
function modalInterior(): Viewport {
const viewport = appViewportSize("min");
return {
return viewportWith({
width: viewport.width - 2 * MODAL_MARGIN - 2 * MODAL_PADDING,
height: Math.min(viewport.height - 2 * MODAL_MARGIN, Math.floor(65530 / Math.ceil((viewport.width - 2 * MODAL_MARGIN) / 2))) - 2 * MODAL_PADDING,
};
}, uniformEdges("border"));
}
/** Screen rect of the modal box, aligned to the min-height window band. */
+5 -4
View File
@@ -89,6 +89,7 @@ import {
screenWidth,
} from "./geometry";
import type { AppSwitcherPosition } from "../dashboard-settings";
import type { Viewport } from "../viewport";
/**
* The shell: owns the window registry, focus, screen on/off, and the shell
@@ -169,11 +170,11 @@ export type ShellWindow = {
*/
relayout?: () => void;
/**
* The viewport size the window is laid out at (it changes on relayout), so
* the controller can tell a window whose size fell behind the geometry from
* one whose surface merely moved.
* The viewport the window is laid out at (it changes on relayout), so the
* controller can tell a window whose size, or whose edges, fell behind the
* geometry from one whose surface merely moved.
*/
layoutSize?: () => { width: number; height: number };
layoutSize?: () => Viewport;
/**
* A touch from the phone's mirror at (x, y) in app-viewport coordinates.
* True if the window acted on it; otherwise the controller sends a select.
+8 -5
View File
@@ -3,7 +3,8 @@ import { GrayImage } from "../../graphics/image";
import { windowIcon } from "./chrome-layer";
import { type IconActivity, type IconName } from "../../graphics/icons";
import { toolRegistry, type ToolResult, type ToolSpec } from "../../assistant/tool-registry";
import { appViewportSize, type WindowHeightMode } from "./geometry";
import { appViewport, type WindowHeightMode } from "./geometry";
import { type Viewport } from "../viewport";
import * as frameTimings from "../../native/frame-timings";
import { shell, type ShellWindow } from "./shell";
import { publishWorkerState } from "./worker-state";
@@ -20,8 +21,10 @@ export type WorkerAppMessage =
/** Release app-wide resources, then acknowledge with worker-stopped. */
| { type: "shutdown" }
| { type: "navigation-sensors"; event: NavigationSensorEvent }
| { type: "open-window"; windowId: string; surfaceId: string; title: string; viewport: { width: number; height: number } }
| { type: "resize-window"; windowId: string; viewport: { width: number; height: number } }
/** `viewport` carries what the window's edges touch and the padding suggested for them (viewport.ts). */
| { type: "open-window"; windowId: string; surfaceId: string; title: string; viewport: Viewport }
/** The window's size changed, or what its edges touch did (so its padding). */
| { type: "resize-window"; windowId: string; viewport: Viewport }
| { type: "close-window"; windowId: string }
| { type: "input"; windowId: string; event: unknown; frameId: number; focused: boolean }
| { type: "text-input"; windowId: string; text: string; submit?: boolean }
@@ -462,7 +465,7 @@ export class WorkerAppHost {
const surfaceId = `window:${spec.windowId}`;
const heightMode = spec.heightMode ?? "min";
this.openWindows.add(spec.windowId);
let viewport = appViewportSize(heightMode, this.options.appId);
let viewport = appViewport(heightMode, this.options.appId);
this.post({
type: "open-window",
windowId: spec.windowId,
@@ -482,7 +485,7 @@ export class WorkerAppHost {
// (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: () => {
viewport = appViewportSize(window.heightMode, this.options.appId);
viewport = appViewport(window.heightMode, this.options.appId);
this.post({ type: "resize-window", windowId: spec.windowId, viewport });
},
layoutSize: () => viewport,
+82
View File
@@ -0,0 +1,82 @@
/**
* A window's viewport as its layouts see it: its size, what lies past each
* of its edges, and how much padding to leave at each because of that. Pure
* data, so it crosses to app workers in their open/resize messages.
*/
/**
* What a viewport edge touches: a line the shell draws right outside it
* ("border": a side of the window frame, the status bar's divider, the app
* switcher's separator), or nothing ("offscreen": the end of the screen, or
* space the shell leaves blank, which looks the same on the glasses; chrome
* with no line before it, a status bar or switcher row, counts too).
*/
export type EdgeKind = "border" | "offscreen";
export type Edges<T> = { top: T; right: T; bottom: T; left: T };
export type ViewportSize = { width: number; height: number };
export type Viewport = ViewportSize & {
edges: Edges<EdgeKind>;
/**
* Suggested distance to keep between each edge and the content nearest it
* (see suggestedPadding). A layout puts its outermost element this far in,
* rather than hard-coding a margin, so it has room beside a border line
* and wastes none beside blank space. A vertical scroll container is the
* exception: its viewport runs to the top and bottom edges whatever they
* touch, and the padding goes inside the scrolled content, before the
* first element and after the last.
*/
padding: Edges<number>;
};
/** Suggested padding between a border line and the content beside it. */
export const BORDER_EDGE_PADDING = 8;
/** Suggested content padding for each edge: room beside a border, none beside blank space. */
export function suggestedPadding(edges: Edges<EdgeKind>): Edges<number> {
const pad = (edge: EdgeKind) => (edge === "border" ? BORDER_EDGE_PADDING : 0);
return { top: pad(edges.top), right: pad(edges.right), bottom: pad(edges.bottom), left: pad(edges.left) };
}
export function uniformEdges(kind: EdgeKind): Edges<EdgeKind> {
return { top: kind, right: kind, bottom: kind, left: kind };
}
/** A viewport of the given size and edges, with the padding suggested for them. */
export function viewportWith(size: ViewportSize, edges: Edges<EdgeKind>): Viewport {
return { width: size.width, height: size.height, edges: { ...edges }, padding: suggestedPadding(edges) };
}
/**
* Complete a bare size as a viewport nothing borders (no padding); one that
* already says what its edges touch is copied as it is.
*/
export function toViewport(size: ViewportSize | Viewport): Viewport {
if ("edges" in size && "padding" in size) {
return { width: size.width, height: size.height, edges: { ...size.edges }, padding: { ...size.padding } };
}
return viewportWith(size, uniformEdges("offscreen"));
}
export function sameEdges(a: Edges<EdgeKind>, b: Edges<EdgeKind>): boolean {
return a.top === b.top && a.right === b.right && a.bottom === b.bottom && a.left === b.left;
}
export function sameViewport(a: Viewport, b: Viewport): boolean {
return a.width === b.width && a.height === b.height && sameEdges(a.edges, b.edges)
&& a.padding.top === b.padding.top && a.padding.right === b.padding.right
&& a.padding.bottom === b.padding.bottom && a.padding.left === b.padding.left;
}
/** The rect inside a viewport's suggested padding, in its own coordinates. */
export function paddedRect(viewport: Viewport): { x: number; y: number; width: number; height: number } {
const { padding } = viewport;
return {
x: padding.left,
y: padding.top,
width: Math.max(0, viewport.width - padding.left - padding.right),
height: Math.max(0, viewport.height - padding.top - padding.bottom),
};
}
+4 -2
View File
@@ -4,6 +4,7 @@ import { GESTURE_LONG_PRESS, GESTURE_SHORT_THEN_LONG_PRESS, gestureHints, type I
import { type Layer, type LayerActions, LayerStack, noopLayerActions } from "./layers";
import { CONTEXT_MENU_DIM, MenuLayer, type MenuItem, type MenuLayout } from "./menu";
import type { WorkerAppReply } from "./shell/worker-window";
import type { Viewport, ViewportSize } from "./viewport";
/**
* The window context menu, opened by tap-then-hold: an app's own menu,
@@ -65,7 +66,8 @@ export type WindowMenuOptions = {
claimsLongPress?: () => boolean;
/** Paint the window content the menu draws over (a fresh, mutable image). */
paintBase: () => GrayImage;
size: { width: number; height: number };
/** The window's viewport; a bare size will do, as the menu itself floats clear of the edges. */
size: ViewportSize | Viewport;
isFocused: () => boolean;
};
@@ -92,7 +94,7 @@ export class WindowMenu {
constructor(private readonly options: WindowMenuOptions) {}
resize(size: { width: number; height: number }): void {
resize(size: ViewportSize | Viewport): void {
this.options.size = size;
this.stack?.setBaseSize(size);
}