Add a minesweeper game, a freecell game, and some voice assistant tools for window management

This commit is contained in:
James Babcock committed 2026-07-26 19:45:14 -07:00
1 parent dcf68cb09a
commit 434419c8e4
11 files changed
+2231 -67

No files matched your search

+5 -5
View File
@@ -4,7 +4,7 @@ import { BATTERY_ICON_WIDTH, drawBattery } from "../../graphics/battery";
import { readActiveNotificationIcons } from "../../native/notification-icons";
import { readPhoneBatteryState } from "../../native/phone-battery";
import { noteStaleDataUsed, renderPassAllowsStaleData } from "../../util/render-freshness";
import { renderIcon, type IconName } from "../../graphics/icons";
import { renderIcon, renderIconWithGlyph, type IconName } from "../../graphics/icons";
import { batteryDisplayModeSetting, timeFormatSetting } from "../dashboard-settings";
import { Layer } from "../layers";
import { scrollToKeepSelectionVisible } from "../menu";
@@ -49,9 +49,9 @@ export function makeLetterWindowIcon(letter: string): ShellChromeWindow["drawIco
}
/** Window icon rendered from an SVG (Lucide), rendered once per size and cached. */
export function makeSvgWindowIcon(name: IconName): ShellChromeWindow["drawIcon"] {
export function makeSvgWindowIcon(name: IconName, glyph?: string): ShellChromeWindow["drawIcon"] {
return (image, x, y, size, inverted) => {
const icon = renderIcon(name, size);
const icon = glyph ? renderIconWithGlyph(name, glyph, size) : renderIcon(name, size);
if (!icon) return;
const dx = x + Math.max(0, ((size - icon.width) / 2) | 0);
const dy = y + Math.max(0, ((size - icon.height) / 2) | 0);
@@ -74,8 +74,8 @@ export function makeSvgWindowIcon(name: IconName): ShellChromeWindow["drawIcon"]
}
/** SVG icon when a name is given, else the letter placeholder. */
export function windowIcon(icon: IconName | undefined, letter: string): ShellChromeWindow["drawIcon"] {
return icon ? makeSvgWindowIcon(icon) : makeLetterWindowIcon(letter);
export function windowIcon(icon: IconName | undefined, letter: string, glyph?: string): ShellChromeWindow["drawIcon"] {
return icon ? makeSvgWindowIcon(icon, glyph) : makeLetterWindowIcon(letter);
}
/**
+130 -32
View File
@@ -10,7 +10,9 @@ import {
} from "../gestures";
import { DashboardInputEvent, Layer, LayerActions, LayerContext } from "../layers";
import { drawSelectionHighlight, scrollToKeepSelectionVisible } from "../menu";
import { onAnySettingChanged } from "../dashboard-settings";
import { createInProcessWindow } from "./in-process-window";
import { getFolderAssignments, getFolders, getFolderStateFingerprint } from "./launcher-folders";
import { shell, type ShellWindow } from "./shell";
export type LauncherAppEntry = {
@@ -42,16 +44,28 @@ const GRID_TOP = 6;
const FOOTER_HEIGHT = 16;
const ICON_SIZE = 44;
const LABEL_GAP = 2;
/** Extra top inset for the folder-name header while inside a folder. */
const FOLDER_HEADER_HEIGHT = 16;
type LauncherMode = "row" | "item";
/** One cell of the grid: an app, or a folder holding some of the apps. */
type LauncherGridEntry =
| { kind: "app"; label: string; icon: IconName; appId: string }
| { kind: "folder"; label: string; name: string };
/**
* The launcher grid: app icons with labels, arranged in a 3-column grid.
* The launcher grid: app and folder icons with labels, arranged in a grid.
* Navigation has two levels so the max number of swipes to any app is halved:
* entering from the sidebar starts in "row" mode (scroll picks a row); a tap
* drops into "item" mode on that row, defaulting to the middle column (scroll
* picks the app); a tap launches it. Double-click backs out one level (item →
* row), and from the top level yields to the sidebar.
* picks the item); a tap launches an app or opens a folder (the same grid,
* restricted to that folder's apps). Double-click backs out one level (item →
* row, folder → top grid), and from the top level yields to the sidebar.
*
* The folder grouping lives in the settings store (see launcher-folders.ts)
* and is re-read every paint, so assistant folder tools take effect without
* the layer holding any copy of the state.
*/
class LauncherGridLayer implements Layer {
private mode: LauncherMode = "row";
@@ -59,15 +73,61 @@ class LauncherGridLayer implements Layer {
private selectedCol = 1;
private scrollRow = 0;
private wasFocused = false;
/** Folder whose contents the grid is showing, or null for the top grid. */
private currentFolder: string | null = null;
constructor(private readonly options: LauncherOptions) {}
private rowCount(): number {
return Math.max(1, Math.ceil(this.options.apps.length / COLS));
/**
* The cells to show, computed fresh from the folder state. Self-heals
* currentFolder: if the open folder no longer exists (the assistant
* disbanded it), the view falls back to the top grid.
*/
private entries(): LauncherGridEntry[] {
const byAppId = new Map(this.options.apps.map((app) => [app.appId, app]));
if (this.currentFolder !== null) {
const members = (getFolders().get(this.currentFolder) ?? [])
.map((appId) => byAppId.get(appId))
.filter(Boolean) as LauncherAppEntry[];
if (members.length > 0) {
return members
.map((app): LauncherGridEntry => ({ kind: "app", label: app.label, icon: app.icon, appId: app.appId }))
.sort((a, b) => a.label.localeCompare(b.label));
}
this.currentFolder = null;
}
const assignments = getFolderAssignments();
const entries: LauncherGridEntry[] = [];
// A folder cell appears only when it holds at least one known app; stale
// assignments to removed apps are ignored.
for (const [name, members] of getFolders()) {
if (members.some((appId) => byAppId.has(appId))) {
entries.push({ kind: "folder", label: name, name });
}
}
for (const app of this.options.apps) {
if (!assignments[app.appId]) {
entries.push({ kind: "app", label: app.label, icon: app.icon, appId: app.appId });
}
}
return entries.sort((a, b) => a.label.localeCompare(b.label));
}
private itemsInRow(row: number): number {
return Math.max(0, Math.min(COLS, this.options.apps.length - row * COLS));
private rowCount(entryCount: number): number {
return Math.max(1, Math.ceil(entryCount / COLS));
}
private itemsInRow(entryCount: number, row: number): number {
return Math.max(0, Math.min(COLS, entryCount - row * COLS));
}
/** Leave the current folder, putting the selection back on its cell. */
private exitFolder(): void {
const folder = this.currentFolder;
this.currentFolder = null;
this.mode = "row";
const index = this.entries().findIndex((entry) => entry.kind === "folder" && entry.name === folder);
this.selectedRow = index >= 0 ? Math.floor(index / COLS) : 0;
}
paint(ctx: LayerContext): GrayImage {
@@ -75,24 +135,35 @@ class LauncherGridLayer implements Layer {
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
const focused = ctx.stack.isFocused();
// Re-entering the launcher (focus gained) resets to row selection.
// Re-entering the launcher (focus gained) resets to the top grid's row
// selection, so the view never resumes inside a stale folder.
if (focused && !this.wasFocused) {
this.mode = "row";
this.currentFolder = null;
}
this.wasFocused = focused;
const rows = this.rowCount();
const entries = this.entries();
const rows = this.rowCount(entries.length);
this.selectedRow = clamp(this.selectedRow, 0, rows - 1);
this.selectedCol = clamp(this.selectedCol, 0, Math.max(0, this.itemsInRow(this.selectedRow) - 1));
this.selectedCol = clamp(
this.selectedCol,
0,
Math.max(0, this.itemsInRow(entries.length, this.selectedRow) - 1),
);
const gridTop = this.currentFolder !== null ? GRID_TOP + FOLDER_HEADER_HEIGHT : GRID_TOP;
if (this.currentFolder !== null) {
image.drawText(font, 8, GRID_TOP - 2, truncateText(font, this.currentFolder, width - 16), 160);
}
const gridBottom = height - FOOTER_HEIGHT;
const rowH = (gridBottom - GRID_TOP) / VISIBLE_ROWS;
const rowH = (gridBottom - gridTop) / VISIBLE_ROWS;
const colW = width / COLS;
// Scroll to keep the selected row among the fully-visible rows.
this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, this.selectedRow, FULL_ROWS, rows);
const rowY = (row: number) => GRID_TOP + (row - this.scrollRow) * rowH;
const rowY = (row: number) => gridTop + (row - this.scrollRow) * rowH;
// Selection highlight (row band, or a single cell in item mode).
const selY = rowY(this.selectedRow);
@@ -102,14 +173,14 @@ class LauncherGridLayer implements Layer {
drawSelectionHighlight(image, this.selectedCol * colW + 6, selY + 2, colW - 12, rowH - 4, focused, 6);
}
for (let index = 0; index < this.options.apps.length; index++) {
const app = this.options.apps[index]!;
for (let index = 0; index < entries.length; index++) {
const entry = entries[index]!;
const row = Math.floor(index / COLS);
if (row < this.scrollRow) continue;
const blockTop = rowY(row) + Math.max(2, (rowH - ICON_SIZE - font.lineHeight - LABEL_GAP) / 2);
if (blockTop >= gridBottom) break; // fully below the grid
const centerX = (index % COLS) * colW + colW / 2;
const icon = renderIcon(app.icon, ICON_SIZE);
const icon = renderIcon(entry.kind === "app" ? entry.icon : "folder", ICON_SIZE);
if (icon) {
// Clip the icon at the grid bottom so a peeking row shows only its top.
const clipHeight = Math.min(icon.height, Math.floor(gridBottom - blockTop));
@@ -120,21 +191,24 @@ class LauncherGridLayer implements Layer {
}
const labelY = Math.round(blockTop + ICON_SIZE + LABEL_GAP);
if (labelY + font.lineHeight <= gridBottom) {
const label = truncateText(font, app.label, colW - 8);
const label = truncateText(font, entry.label, colW - 8);
image.drawText(font, Math.round(centerX - font.measureText(label) / 2), labelY, label, 210);
}
}
const selectedEntry = entries[this.selectedRow * COLS + this.selectedCol];
const pickVerb = selectedEntry?.kind === "folder" ? "open" : "launch";
const hint =
this.mode === "row"
? `${GESTURE_SCROLL} row ${GESTURE_CLICK} pick ${GESTURE_DOUBLE_CLICK} back`
: `${GESTURE_SCROLL} app ${GESTURE_CLICK} launch ${GESTURE_DOUBLE_CLICK} row`;
: `${GESTURE_SCROLL} item ${GESTURE_CLICK} ${pickVerb} ${GESTURE_DOUBLE_CLICK} row`;
image.drawText(font, 8, height - 14, hint, 110);
return image;
}
async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> {
const rows = this.rowCount();
const entries = this.entries();
const rows = this.rowCount(entries.length);
switch (event.type) {
case "scroll-up":
case "scroll-down": {
@@ -142,25 +216,41 @@ class LauncherGridLayer implements Layer {
if (this.mode === "row") {
this.selectedRow = clamp(this.selectedRow + delta, 0, rows - 1);
} else {
this.selectedCol = clamp(this.selectedCol + delta, 0, Math.max(0, this.itemsInRow(this.selectedRow) - 1));
this.selectedCol = clamp(
this.selectedCol + delta,
0,
Math.max(0, this.itemsInRow(entries.length, this.selectedRow) - 1),
);
}
return;
}
case "click": {
if (this.mode === "row") {
this.mode = "item";
// Default to the middle column (clamped to the row's app count).
this.selectedCol = Math.min(Math.floor(COLS / 2), this.itemsInRow(this.selectedRow) - 1);
// Default to the middle column (clamped to the row's item count).
this.selectedCol = Math.min(
Math.floor(COLS / 2),
this.itemsInRow(entries.length, this.selectedRow) - 1,
);
} else {
const index = this.selectedRow * COLS + this.selectedCol;
const app = this.options.apps[index];
if (app) await this.options.launchApp(app.appId);
const entry = entries[this.selectedRow * COLS + this.selectedCol];
if (!entry) return;
if (entry.kind === "folder") {
this.currentFolder = entry.name;
this.mode = "row";
this.selectedRow = 0;
this.scrollRow = 0;
} else {
await this.options.launchApp(entry.appId);
}
}
return;
}
case "double-click":
if (this.mode === "item") {
this.mode = "row";
} else if (this.currentFolder !== null) {
this.exitFolder();
} else {
shell.yieldFocusToSidebar();
}
@@ -177,12 +267,7 @@ class LauncherGridLayer implements Layer {
* new window.
*/
export function createLauncherWindow(options: LauncherOptions): ShellWindow {
const sortedOptions: LauncherOptions = {
...options,
apps: [...options.apps].sort((a, b) => a.label.localeCompare(b.label)),
};
return createInProcessWindow({
const created = createInProcessWindow({
appId: "launcher",
windowId: LAUNCHER_WINDOW_ID,
title: "Apps",
@@ -192,8 +277,21 @@ export function createLauncherWindow(options: LauncherOptions): ShellWindow {
actions: options.actions,
// Not wrapped in YieldAtRootLayer: the grid handles double-click itself to
// back out of item selection before yielding to the sidebar.
baseLayer: new LauncherGridLayer(sortedOptions),
baseLayer: new LauncherGridLayer(options),
submitFrame: options.submitFrame,
setSurfaceVisible: options.setSurfaceVisible,
}).window;
});
// The assistant's folder tools change the grouping from outside the window;
// the settings broadcast is the change signal, and the fingerprint check
// keeps every unrelated setting change from repainting the launcher. The
// launcher is pinned for the app's lifetime, so the subscription never needs
// tearing down.
let lastFolderState = getFolderStateFingerprint();
onAnySettingChanged(() => {
const state = getFolderStateFingerprint();
if (state === lastFolderState) return;
lastFolderState = state;
created.requestRender();
});
return created.window;
}
+103
View File
@@ -0,0 +1,103 @@
/**
* Launcher folder state: which apps are grouped into which named folder.
* Stored as one JSON string (appId -> folder name) in the settings store, so
* it persists and its changes broadcast to every isolate. An unset value means
* the default grouping; any edit persists the whole map, so clearing out the
* defaults sticks. Folders exist only while at least one app is assigned to
* them — there is no separate create/delete step.
*/
import { getStringSetting, setStringSetting } from "../../native/settings-store";
const STORAGE_KEY = "launcher.folders";
/** The out-of-the-box grouping, applied only while the setting is unset. */
const DEFAULT_ASSIGNMENTS: Record<string, string> = {
blocks: "Games",
minesweeper: "Games",
};
export const FOLDER_NAME_MAX_LENGTH = 24;
/** appId -> folder name. Malformed stored JSON reads as "no folders". */
export function getFolderAssignments(): Record<string, string> {
const raw = getStringSetting(STORAGE_KEY, "");
if (!raw) return { ...DEFAULT_ASSIGNMENTS };
try {
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
const assignments: Record<string, string> = {};
for (const appId of Object.keys(parsed)) {
const folder = parsed[appId];
if (typeof folder === "string" && folder.trim()) {
assignments[appId] = folder.trim();
}
}
return assignments;
} catch {
return {};
}
}
/** folder name -> appIds (assignment order), folder names sorted. */
export function getFolders(): Map<string, string[]> {
const assignments = getFolderAssignments();
const unsorted = new Map<string, string[]>();
for (const appId of Object.keys(assignments)) {
const folder = assignments[appId]!;
const members = unsorted.get(folder);
if (members) {
members.push(appId);
} else {
unsorted.set(folder, [appId]);
}
}
const folders = new Map<string, string[]>();
for (const name of Array.from(unsorted.keys()).sort((a, b) => a.localeCompare(b))) {
folders.set(name, unsorted.get(name)!);
}
return folders;
}
/** Assign an app to a folder, or (with null) return it to the top level. */
export function setAppFolder(appId: string, folder: string | null): void {
const assignments = getFolderAssignments();
if (folder) {
assignments[appId] = folder;
} else {
delete assignments[appId];
}
setStringSetting(STORAGE_KEY, JSON.stringify(assignments));
}
/** Move every app out of a folder. Returns how many apps were moved. */
export function disbandFolder(folder: string): number {
const assignments = getFolderAssignments();
let moved = 0;
for (const appId of Object.keys(assignments)) {
if (assignments[appId] === folder) {
delete assignments[appId];
moved++;
}
}
if (moved > 0) {
setStringSetting(STORAGE_KEY, JSON.stringify(assignments));
}
return moved;
}
/**
* Match an existing folder name case-insensitively (so "games" reuses
* "Games" instead of creating a near-duplicate), else the trimmed input.
*/
export function resolveFolderName(input: string): string {
const trimmed = input.trim();
for (const name of getFolders().keys()) {
if (name.toLowerCase() === trimmed.toLowerCase()) return name;
}
return trimmed;
}
/** Raw stored value, for cheap change detection by the launcher window. */
export function getFolderStateFingerprint(): string {
return getStringSetting(STORAGE_KEY, "");
}
+32 -5
View File
@@ -171,6 +171,8 @@ class ShellAlertLayer implements Layer {
class Shell {
private windows: ShellWindow[] = [];
private selectedIndex = 0;
/** Window ids in most-recently-visible-first order; closing the visible window returns to the next entry. */
private mruWindowIds: string[] = [];
private focus: FocusKind = "sidebar";
private screenOn = true;
private lastInputAtMs = Date.now();
@@ -229,21 +231,42 @@ class Shell {
const existing = this.windows.findIndex((w) => w.windowId === window.windowId);
if (existing >= 0) {
this.windows[existing] = window;
if (existing === this.selectedIndex) this.noteWindowVisible(window.windowId);
} else {
this.windows.push(window);
if (this.windows.length - 1 === this.selectedIndex) this.noteWindowVisible(window.windowId);
}
}
/** Move a window to the front of the most-recently-visible order. */
private noteWindowVisible(windowId: string): void {
this.mruWindowIds = this.mruWindowIds.filter((id) => id !== windowId);
this.mruWindowIds.unshift(windowId);
}
/** Index of the most recently visible window still in the registry, or -1. */
private mostRecentWindowIndex(): number {
for (const id of this.mruWindowIds) {
const index = this.windows.findIndex((w) => w.windowId === id);
if (index >= 0) return index;
}
return -1;
}
removeWindow(windowId: string): void {
const index = this.windows.findIndex((w) => w.windowId === windowId);
if (index < 0) return;
const wasSelected = index === this.selectedIndex;
this.windows.splice(index, 1);
this.attention.delete(windowId);
if (this.selectedIndex > index) {
this.mruWindowIds = this.mruWindowIds.filter((id) => id !== windowId);
if (wasSelected) {
// Return to the most recently visible remaining window.
const mruIndex = this.mostRecentWindowIndex();
this.selectedIndex =
mruIndex >= 0 ? mruIndex : Math.min(index, Math.max(0, this.windows.length - 1));
} else if (this.selectedIndex > index) {
this.selectedIndex--;
} else if (this.selectedIndex >= this.windows.length) {
this.selectedIndex = Math.max(0, this.windows.length - 1);
}
if (this.focus === "window" && (wasSelected || !this.windows.length)) {
this.focus = "sidebar";
@@ -251,8 +274,11 @@ class Shell {
if (wasSelected) {
// Hand the foreground to whatever is now selected.
const next = this.windows[this.selectedIndex];
next?.setForeground?.(true);
next?.requestRender();
if (next) {
this.noteWindowVisible(next.windowId);
next.setForeground?.(true);
next.requestRender();
}
}
this.config.requestShellRender();
}
@@ -579,6 +605,7 @@ class Shell {
const previous = this.windows[this.selectedIndex];
this.selectedIndex = index;
const next = this.windows[index];
if (next) this.noteWindowVisible(next.windowId);
previous?.setForeground?.(false);
next?.setForeground?.(true);
next?.requestRender();
+5 -1
View File
@@ -35,6 +35,7 @@ export type WorkerAppReply =
title: string;
iconLetter: string;
icon?: IconName;
iconGlyph?: string;
focus?: boolean;
}
| { type: "set-title"; windowId: string; title: string }
@@ -86,6 +87,8 @@ export type WorkerWindowSpec = {
iconLetter: string;
/** Lucide icon name for the sidebar indicator; falls back to iconLetter. */
icon?: IconName;
/** Per-window character variant of `icon` (e.g. ">3" terminal icons). */
iconGlyph?: string;
/** Foreground and focus the window once its surface exists. */
focus?: boolean;
};
@@ -152,6 +155,7 @@ export class WorkerAppHost {
title: message.title,
iconLetter: message.iconLetter,
icon: message.icon,
iconGlyph: message.iconGlyph,
focus: message.focus,
});
break;
@@ -242,7 +246,7 @@ export class WorkerAppHost {
this.post({ type: "close-window", windowId: spec.windowId });
this.options.removeSurface(surfaceId);
},
drawIcon: windowIcon(spec.icon, spec.iconLetter),
drawIcon: windowIcon(spec.icon, spec.iconLetter, spec.iconGlyph),
handleInput: (event, frameId) => {
this.post({
type: "input",