diff --git a/app/assistant/window-tools.ts b/app/assistant/window-tools.ts new file mode 100644 index 00000000..3b206394 --- /dev/null +++ b/app/assistant/window-tools.ts @@ -0,0 +1,282 @@ +/** + * Always-available window-management assistant tools: launch launcher apps, + * list / focus / close shell windows, and manage the launcher's folder + * grouping. Registered from the dashboard controller (which owns launchApp); + * mirrors what the user can do from the launcher grid and the sidebar. + */ +import { shell, type ShellWindow } from "../ui/shell/shell"; +import type { LauncherAppEntry } from "../ui/shell/launcher-app"; +import { + disbandFolder, + FOLDER_NAME_MAX_LENGTH, + getFolderAssignments, + getFolders, + resolveFolderName, + setAppFolder, +} from "../ui/shell/launcher-folders"; +import { toolRegistry, type ToolRegistry, type ToolResult } from "./tool-registry"; + +export type WindowToolsOptions = { + /** The launcher's app list; fixes the ids apps.launch accepts. */ + apps: LauncherAppEntry[]; + /** Launch (or focus) an app exactly as the launcher grid would. */ + launchApp: (appId: string) => Promise | void; + /** Repaint the shell surface so the sidebar reflects a focus change. */ + requestShellRender: () => void; +}; + +let registered = false; + +export function registerWindowTools( + options: WindowToolsOptions, + registry: ToolRegistry = toolRegistry, +): void { + if (registered) return; + registered = true; + + const appIds = options.apps.map((app) => app.appId).sort(); + + registry.registerSystemTool( + { + name: "apps.launch", + description: + "Open an app on the glasses and bring it to the foreground. If the app already has a window open, this focuses it instead. Wakes the display if it is off.", + inputSchema: { + type: "object", + properties: { + app_id: { type: "string", enum: appIds, description: "The app to open." }, + }, + required: ["app_id"], + additionalProperties: false, + }, + }, + async (args) => { + const appId = String(args?.app_id ?? "").trim(); + if (appIds.indexOf(appId) < 0) { + return err(`Unknown app: ${appId}. Available apps: ${appIds.join(", ")}`); + } + shell.wake("window"); + await options.launchApp(appId); + return ok(`Opened ${appId}.`); + }, + ); + + registry.registerSystemTool( + { + name: "apps.list_windows", + description: + "List the open windows in the glasses sidebar: window id, title, owning app, and which one is foreground. Pinned windows (the launcher) cannot be closed.", + inputSchema: { type: "object", properties: {}, additionalProperties: false }, + proactive: true, + }, + () => { + const foregroundId = shell.foregroundWindow()?.windowId ?? null; + const lines = shell.getWindows().map((window) => { + const marks = [ + window.windowId === foregroundId ? "foreground" : null, + window.closeable ? null : "pinned", + ] + .filter(Boolean) + .join(", "); + return `- ${window.windowId} — "${window.title}" (app: ${window.appId})${marks ? ` [${marks}]` : ""}`; + }); + return ok(lines.join("\n")); + }, + ); + + registry.registerSystemTool( + { + name: "apps.focus_window", + description: + "Bring an already-open window to the foreground and give it input focus. Wakes the display if it is off. To open an app that has no window yet, use apps.launch instead.", + inputSchema: { + type: "object", + properties: { + window_id: { + type: "string", + description: + "A window id from apps.list_windows, or an app id when that app has exactly one window open.", + }, + }, + required: ["window_id"], + additionalProperties: false, + }, + }, + (args) => { + const window = resolveWindow(String(args?.window_id ?? "").trim()); + if (typeof window === "string") return err(window); + shell.wake("window"); + shell.focusWindow(window.windowId); + options.requestShellRender(); + return ok(`Focused ${window.windowId} ("${window.title}").`); + }, + ); + + registry.registerSystemTool( + { + name: "apps.close_window", + description: "Close an open window. Pinned windows (the launcher) cannot be closed.", + inputSchema: { + type: "object", + properties: { + window_id: { + type: "string", + description: + "A window id from apps.list_windows, or an app id when that app has exactly one window open.", + }, + }, + required: ["window_id"], + additionalProperties: false, + }, + }, + (args) => { + const window = resolveWindow(String(args?.window_id ?? "").trim()); + if (typeof window === "string") return err(window); + if (!window.closeable) { + return err(`Window ${window.windowId} is pinned and can't be closed.`); + } + shell.closeWindow(window.windowId); + return ok(`Closed ${window.windowId} ("${window.title}").`); + }, + ); + + registry.registerSystemTool( + { + name: "apps.list_folders", + description: + "List the app launcher's folders and the apps inside each, plus the ungrouped top-level apps.", + inputSchema: { type: "object", properties: {}, additionalProperties: false }, + proactive: true, + }, + () => { + const lines: string[] = []; + for (const [name, members] of getFolders()) { + const known = members.filter((appId) => appIds.indexOf(appId) >= 0).sort(); + if (known.length) lines.push(`${name}: ${known.join(", ")}`); + } + const assignments = getFolderAssignments(); + const ungrouped = appIds.filter((appId) => !assignments[appId]); + lines.push(`Ungrouped: ${ungrouped.length ? ungrouped.join(", ") : "(none)"}`); + return ok(lines.join("\n")); + }, + ); + + registry.registerSystemTool( + { + name: "apps.move_to_folder", + description: + "Group an app into a named launcher folder, creating the folder if it doesn't exist yet. The app appears inside the folder in the launcher grid instead of at the top level.", + inputSchema: { + type: "object", + properties: { + app_id: { type: "string", enum: appIds, description: "The app to move." }, + folder: { + type: "string", + description: "The folder name. An existing folder's name matches case-insensitively.", + }, + }, + required: ["app_id", "folder"], + additionalProperties: false, + }, + }, + (args) => { + const appId = String(args?.app_id ?? "").trim(); + if (appIds.indexOf(appId) < 0) { + return err(`Unknown app: ${appId}. Available apps: ${appIds.join(", ")}`); + } + const folder = resolveFolderName(String(args?.folder ?? "")); + if (!folder) return err("folder must be a non-empty name"); + if (folder.length > FOLDER_NAME_MAX_LENGTH) { + return err(`Folder names are limited to ${FOLDER_NAME_MAX_LENGTH} characters.`); + } + setAppFolder(appId, folder); + return ok(`Moved ${appId} into "${folder}".`); + }, + ); + + registry.registerSystemTool( + { + name: "apps.remove_from_folder", + description: + "Move an app out of its launcher folder back to the top-level grid. A folder disappears when its last app is removed.", + inputSchema: { + type: "object", + properties: { + app_id: { type: "string", enum: appIds, description: "The app to ungroup." }, + }, + required: ["app_id"], + additionalProperties: false, + }, + }, + (args) => { + const appId = String(args?.app_id ?? "").trim(); + if (appIds.indexOf(appId) < 0) { + return err(`Unknown app: ${appId}. Available apps: ${appIds.join(", ")}`); + } + const folder = getFolderAssignments()[appId]; + if (!folder) return ok(`${appId} isn't in a folder.`); + setAppFolder(appId, null); + return ok(`Removed ${appId} from "${folder}".`); + }, + ); + + registry.registerSystemTool( + { + name: "apps.disband_folder", + description: + "Delete a launcher folder by moving all of its apps back to the top-level grid.", + inputSchema: { + type: "object", + properties: { + folder: { type: "string", description: "The folder to disband (case-insensitive)." }, + }, + required: ["folder"], + additionalProperties: false, + }, + }, + (args) => { + const folder = resolveFolderName(String(args?.folder ?? "")); + if (!folder) return err("folder must be a non-empty name"); + const moved = disbandFolder(folder); + if (moved === 0) { + const names = Array.from(getFolders().keys()); + return err( + names.length + ? `No folder named "${folder}". Folders: ${names.join(", ")}` + : `No folder named "${folder}". There are no folders.`, + ); + } + return ok(`Disbanded "${folder}"; ${moved} app${moved === 1 ? "" : "s"} moved to the top level.`); + }, + ); +} + +/** + * Find an open window by exact window id, falling back to an app id that has + * exactly one window. Returns an error message string when nothing (or more + * than one thing) matches. + */ +function resolveWindow(id: string): ShellWindow | string { + if (!id) return "window_id is required"; + const windows = shell.getWindows(); + const exact = windows.find((window) => window.windowId === id); + if (exact) return exact; + const byApp = windows.filter((window) => window.appId === id); + if (byApp.length === 1) return byApp[0]!; + if (byApp.length > 1) { + return `App ${id} has ${byApp.length} windows open: ${byApp + .map((window) => window.windowId) + .join(", ")}. Pass one of those window ids.`; + } + return `No open window matches "${id}". Open windows: ${windows + .map((window) => window.windowId) + .join(", ")}`; +} + +function ok(content: string): ToolResult { + return { ok: true, content }; +} + +function err(error: string): ToolResult { + return { ok: false, error }; +} diff --git a/app/g2/dashboard-controller.ts b/app/g2/dashboard-controller.ts index b7bb3bdf..096e4033 100644 --- a/app/g2/dashboard-controller.ts +++ b/app/g2/dashboard-controller.ts @@ -27,8 +27,13 @@ import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage } from "../graphics/image"; import { rawInputEventToInputEvent, shell, type ShellInputOutcome } from "../ui/shell/shell"; import { registerSystemTools } from "../assistant/system-tools"; import { registerNavigateTools } from "../assistant/navigate-tools"; +import { registerWindowTools } from "../assistant/window-tools"; import { WorkerAppHost } from "../ui/shell/worker-window"; -import { createLauncherWindow, LAUNCHER_SURFACE_ID } from "../ui/shell/launcher-app"; +import { + createLauncherWindow, + LAUNCHER_SURFACE_ID, + type LauncherAppEntry, +} from "../ui/shell/launcher-app"; import { createSettingsAppWindow, SETTINGS_SURFACE_ID, @@ -141,6 +146,25 @@ const LOW_BATTERY_PERCENT = 5; const EVEN_APP_DETECTED_MESSAGE = "The Even Realities app appears to be running. If Faceclaw has trouble connecting, open its app settings and force stop it."; +// The launcher grid's app list; also fixes the app ids apps.launch accepts. +const LAUNCHER_APPS: LauncherAppEntry[] = [ + { appId: "timer", label: "Timer", icon: "timer" }, + { appId: "terminal", label: "Terminal", icon: "terminal" }, + { appId: "files", label: "Files", icon: "folder" }, + { appId: "music", label: "Music", icon: "music" }, + { appId: "nightscout", label: "Nightscout", icon: "nightscout" }, + { appId: "transcribe", label: "Transcribe", icon: "mic" }, + { appId: "notifications", label: "Notifications", icon: "bell" }, + { appId: "calendar", label: "Calendar", icon: "calendar" }, + { appId: "weather", label: "Weather", icon: "cloud-sun" }, + { appId: "navigate", label: "Navigate", icon: "map" }, + { appId: "blocks", label: "Blocks", icon: "l-piece" }, + { appId: "minesweeper", label: "Minesweeper", icon: "bomb" }, + { appId: "freecell", label: "Freecell", icon: "spade" }, + { appId: "debug-tests", label: "Debug tests", icon: "flask-conical" }, + { appId: "settings", label: "Settings", icon: "settings" }, +]; + function createInitialDisplayPreview(): ImageSource | null { return grayImageToPreviewSource(new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0)); } @@ -244,6 +268,12 @@ class DashboardController { registerSystemTools(); // nav.* tools launch the Navigate app on demand, so they need launchApp. registerNavigateTools((appId) => this.launchApp(appId)); + // apps.* tools mirror the launcher grid and sidebar (launch, focus, close). + registerWindowTools({ + apps: LAUNCHER_APPS, + launchApp: (appId) => this.launchApp(appId), + requestShellRender: () => this.requestShellRender(), + }); shell.configure({ actions: { ...sharedActions, @@ -265,21 +295,7 @@ class DashboardController { ...sharedActions, requestRender: () => shell.foregroundWindow()?.requestRender(), }, - apps: [ - { appId: "timer", label: "Timer", icon: "timer" }, - { appId: "terminal", label: "Terminal", icon: "terminal" }, - { appId: "files", label: "Files", icon: "folder" }, - { appId: "music", label: "Music", icon: "music" }, - { appId: "nightscout", label: "Nightscout", icon: "nightscout" }, - { appId: "transcribe", label: "Transcribe", icon: "mic" }, - { appId: "notifications", label: "Notifications", icon: "bell" }, - { appId: "calendar", label: "Calendar", icon: "calendar" }, - { appId: "weather", label: "Weather", icon: "cloud-sun" }, - { appId: "navigate", label: "Navigate", icon: "map" }, - { appId: "blocks", label: "Blocks", icon: "l-piece" }, - { appId: "debug-tests", label: "Debug tests", icon: "flask-conical" }, - { appId: "settings", label: "Settings", icon: "settings" }, - ], + apps: LAUNCHER_APPS, launchApp: (appId) => this.launchApp(appId), submitFrame: (image, paintMs, frameId) => this.submitWindowFrame(LAUNCHER_SURFACE_ID, image, paintMs, frameId), @@ -1210,6 +1226,10 @@ class DashboardController { worker = new Worker("../workers/navigate-app.worker"); } else if (appId === "blocks") { worker = new Worker("../workers/blocks-app.worker"); + } else if (appId === "minesweeper") { + worker = new Worker("../workers/minesweeper-app.worker"); + } else if (appId === "freecell") { + worker = new Worker("../workers/freecell-app.worker"); } else { return null; } @@ -1329,6 +1349,40 @@ class DashboardController { this.appendLog("launched blocks:main"); return; } + if (appId === "minesweeper") { + const existing = shell.getWindows().find((window) => window.appId === "minesweeper"); + if (existing) { + shell.focusWindow(existing.windowId); + this.requestShellRender(); + return; + } + host.openWindow({ + windowId: "minesweeper:main", + title: "Minesweeper", + iconLetter: "M", + icon: "bomb", + focus: true, + }); + this.appendLog("launched minesweeper:main"); + return; + } + if (appId === "freecell") { + const existing = shell.getWindows().find((window) => window.appId === "freecell"); + if (existing) { + shell.focusWindow(existing.windowId); + this.requestShellRender(); + return; + } + host.openWindow({ + windowId: "freecell:main", + title: "Freecell", + iconLetter: "F", + icon: "spade", + focus: true, + }); + this.appendLog("launched freecell:main"); + return; + } if (appId === "navigate") { // Navigation needs precise location; prompt on the phone while the // window opens (the worker can't show permission dialogs). diff --git a/app/graphics/icons.ts b/app/graphics/icons.ts index bb19b67b..389780e1 100644 --- a/app/graphics/icons.ts +++ b/app/graphics/icons.ts @@ -25,6 +25,10 @@ export const ICON_SVGS = { // Not a Lucide icon: an L-tetromino built from four squares, for Blocks. "l-piece": '', + bomb: + '', + spade: + '', terminal: '', "file-text": @@ -63,18 +67,85 @@ export const ICON_SVGS = { export type IconName = keyof typeof ICON_SVGS; +// The "_" element of the terminal icon, swapped out for a session glyph in +// renderIconWithGlyph. +const TERMINAL_UNDERSCORE = ''; + +/** + * Session-marker glyphs for per-terminal window icons: the terminal icon's + * "_" replaced by a character, drawn in the same stroked style. Hand-fitted + * to the box x 11.5–16.5, y 8–16 beside the ">" chevron. The zero is slashed + * to keep it distinct from the letter O. + */ +const TERMINAL_GLYPH_SHAPES: Record = { + "0": '', + "1": '', + "2": '', + "3": '', + "4": '', + "5": '', + "6": '', + "7": '', + "8": '', + "9": '', + A: '', + B: '', + C: '', + D: '', + E: '', + F: '', + G: '', + H: '', + I: '', + J: '', + K: '', + L: '', + M: '', + N: '', + O: '', + P: '', + Q: '', + R: '', + S: '', + T: '', + U: '', + V: '', + W: '', + X: '', + Y: '', + Z: '', +}; + +/** Characters usable as terminal-icon glyphs, in allocation order (1-9 first, 0 as the tenth). */ +export const TERMINAL_ICON_GLYPHS = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + const cache = new Map(); /** Render an icon SVG to a size×size grayscale bitmap, rendered once and cached. */ export function renderIcon(name: IconName, size: number): GrayImage | null { - const key = `${name}:${size}`; + return renderSvgCached(name, ICON_SVGS[name], size); +} + +/** + * Render an icon with a glyph character substituted in — currently only the + * terminal icon, whose "_" becomes the glyph (">3" instead of ">_"). Falls + * back to the plain icon for other names or unsupported characters. + */ +export function renderIconWithGlyph(name: IconName, glyph: string, size: number): GrayImage | null { + const shape = name === "terminal" ? TERMINAL_GLYPH_SHAPES[glyph] : undefined; + if (!shape) return renderIcon(name, size); + return renderSvgCached(`${name}[${glyph}]`, ICON_SVGS.terminal.replace(TERMINAL_UNDERSCORE, shape), size); +} + +function renderSvgCached(cacheName: string, svg: string, size: number): GrayImage | null { + const key = `${cacheName}:${size}`; const cached = cache.get(key); if (cached !== undefined) return cached; let icon: GrayImage | null = null; if (global.isAndroid) { try { - const bytes = com.faceclaw.app.IconRenderer.renderSvgGray(ICON_SVGS[name], Math.round(size), ICON_STROKE_WIDTH); + const bytes = com.faceclaw.app.IconRenderer.renderSvgGray(svg, Math.round(size), ICON_STROKE_WIDTH); if (bytes && bytes.length >= size * size) { icon = new GrayImage(size, size, 0); for (let i = 0; i < size * size; i++) { @@ -82,7 +153,7 @@ export function renderIcon(name: IconName, size: number): GrayImage | null { } } } catch (error) { - console.warn(`renderIcon(${name}) failed: ${error}`); + console.warn(`renderIcon(${cacheName}) failed: ${error}`); } } cache.set(key, icon); diff --git a/app/ui/shell/chrome-layer.ts b/app/ui/shell/chrome-layer.ts index fc313388..24178685 100644 --- a/app/ui/shell/chrome-layer.ts +++ b/app/ui/shell/chrome-layer.ts @@ -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); } /** diff --git a/app/ui/shell/launcher-app.ts b/app/ui/shell/launcher-app.ts index a75a3e8a..239b3298 100644 --- a/app/ui/shell/launcher-app.ts +++ b/app/ui/shell/launcher-app.ts @@ -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 { - 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; } diff --git a/app/ui/shell/launcher-folders.ts b/app/ui/shell/launcher-folders.ts new file mode 100644 index 00000000..61a296eb --- /dev/null +++ b/app/ui/shell/launcher-folders.ts @@ -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 = { + 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 { + 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 = {}; + 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 { + const assignments = getFolderAssignments(); + const unsorted = new Map(); + 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(); + 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, ""); +} diff --git a/app/ui/shell/shell.ts b/app/ui/shell/shell.ts index 4ac79696..aa79a892 100644 --- a/app/ui/shell/shell.ts +++ b/app/ui/shell/shell.ts @@ -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(); diff --git a/app/ui/shell/worker-window.ts b/app/ui/shell/worker-window.ts index d7fd26a2..0d2a1c28 100644 --- a/app/ui/shell/worker-window.ts +++ b/app/ui/shell/worker-window.ts @@ -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", diff --git a/app/workers/freecell-app.worker.ts b/app/workers/freecell-app.worker.ts new file mode 100644 index 00000000..73f50a53 --- /dev/null +++ b/app/workers/freecell-app.worker.ts @@ -0,0 +1,760 @@ +/** + * Freecell solitaire app worker. One singleton window holds a standard + * 52-card Freecell game: 8 cascades, 4 free cells, 4 foundations. Red suits + * render dim and black suits bright, since the display has no color. + * + * Controls: scroll moves a cursor through the 16 locations (free cells, + * foundations, then cascades, wrapping). Click selects a source, then click + * on a destination moves there; cascade-to-cascade moves take the longest + * legal run that fits (supermoves via empty cells/columns). Double-click + * sends the card at the cursor to its foundation, or cancels a pending + * selection. Long-press opens the window menu (undo, new game, restart). + * Safe cards auto-play to the foundations after every move. + */ +import "@nativescript/core/globals"; +import { GrayImage } from "../graphics/image"; +import { getDefaultSmallFont, getFont } from "../graphics/bdffont"; +import * as frameTimings from "../native/frame-timings"; +import type { DashboardInputEvent } from "../ui/layers"; +import { buildSoundSequencePayload, type Step } from "../ui/apps/sound-effects"; +import { defaultWindowMenuItems, WindowMenu } from "../ui/window-menu"; +import type { MenuItem } from "../ui/menu"; +import type { WorkerAppMessage, WorkerAppReply } from "../ui/shell/worker-window"; +import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_LONG_PRESS } from "../ui/gestures"; + +declare const global: any; +declare const com: any; + +const largeFont = getFont("terminus32"); +const mediumFont = getFont("terminus24"); +const labelFont = getFont("terminus16"); +const smallFont = getDefaultSmallFont(); + +/** Cards are 0..51: suit = card % 4 (♠♥♣♦, alternating colors), rank 1..13. */ +const SUIT_CHARS = ["♠", "♥", "♣", "♦"] as const; +const RANK_CHARS = ["", "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"] as const; + +function suitOf(card: number): number { + return card % 4; +} +function rankOf(card: number): number { + return Math.floor(card / 4) + 1; +} +function isRed(card: number): boolean { + return (card & 1) === 1; +} +function cardLabel(card: number): string { + return RANK_CHARS[rankOf(card)]! + SUIT_CHARS[suitOf(card)]!; +} + +/** Red suits render dimmer than black so card color survives grayscale. */ +const BLACK_SHADE = 255; +const RED_SHADE = 150; + +const CARD_W = 60; +const CARD_H = 36; +const TOP_Y = 4; +const CASCADE_Y = 48; + +/** + * Cursor locations, in scroll order: free cells 0-3, foundations 0-3 (the + * top row left to right), then cascades 0-7. + */ +const LOC_CELL0 = 0; +const LOC_FOUNDATION0 = 4; +const LOC_CASCADE0 = 8; +const LOC_COUNT = 16; + +/** Buzzer effects, tuned soft like the other games' (shared piezo). */ +const SFX_SELECT: Step[] = [{ freq: 880, duty: 40, ms: 20 }]; +const SFX_MOVE: Step[] = [{ freq: 660, duty: 40, ms: 15 }]; +const SFX_FOUNDATION: Step[] = [{ freq: 1047, duty: 40, ms: 25 }]; +const SFX_ERROR: Step[] = [{ freq: 220, duty: 45, ms: 60 }]; +const SFX_UNDO: Step[] = [{ freq: 550, duty: 40, ms: 30 }]; +/** Also the new-game and sound-toggled-on confirmation. */ +const SFX_NEW_GAME: Step[] = [ + { freq: 880, duty: 40, ms: 60 }, + { freq: 1319, duty: 40, ms: 110 }, +]; +const SFX_WIN: Step[] = [ + { freq: 1047, ms: 55 }, + { freq: 1319, ms: 55 }, + { freq: 1568, ms: 55 }, + { freq: 2093, ms: 70 }, + { freq: 1, duty: 0, ms: 30 }, + { freq: 2093, ms: 160 }, +]; + +type Snapshot = { + cascades: number[][]; + cells: Array; + foundations: Array; + moves: number; +}; + +type FreecellWindow = { + windowId: string; + surfaceId: string; + viewportWidth: number; + viewportHeight: number; + foreground: boolean; + /** Whether this window is the shell's input target (pushed with each message). */ + focused: boolean; + /** Long-press window menu; created on first open. */ + menu: WindowMenu | null; + phase: "playing" | "won"; + cascades: number[][]; + cells: Array; + /** Top card of each foundation pile, or null while empty. */ + foundations: Array; + /** The shuffle behind the current game, kept so a deal can be restarted. */ + dealOrder: number[]; + undoStack: Snapshot[]; + moves: number; + cursor: number; + /** Location of the pending source selection, if any. */ + selected: number | null; + soundOn: boolean; + lastSubmittedFingerprint: string; +}; + +const windows = new Map(); + +function post(message: WorkerAppReply): void { + global.postMessage(message); +} + +global.onmessage = (event: { data: WorkerAppMessage }) => { + const message = event.data; + switch (message.type) { + case "open-window": { + const window: FreecellWindow = { + windowId: message.windowId, + surfaceId: message.surfaceId, + viewportWidth: message.viewport.width, + viewportHeight: message.viewport.height, + foreground: false, + focused: false, + menu: null, + phase: "playing", + cascades: [], + cells: [null, null, null, null], + foundations: [null, null, null, null], + dealOrder: [], + undoStack: [], + moves: 0, + cursor: LOC_CASCADE0, + selected: null, + soundOn: true, + lastSubmittedFingerprint: "", + }; + newGame(window, false); + windows.set(message.windowId, window); + break; + } + case "close-window": + windows.delete(message.windowId); + break; + case "input": { + const window = windows.get(message.windowId); + if (!window) { + frameTimings.finishFrame(message.frameId, "discarded: unknown freecell window"); + break; + } + window.focused = message.focused; + handleInput(window, message.event as DashboardInputEvent, message.frameId); + break; + } + case "render": { + const window = windows.get(message.windowId); + if (!window) break; + window.focused = message.focused; + renderAndSubmit(window, 0); + break; + } + case "foreground": { + const window = windows.get(message.windowId); + if (!window) break; + window.foreground = message.foreground; + window.focused = message.focused; + if (window.foreground) renderAndSubmit(window, 0); + break; + } + } +}; + +/** + * Fire a buzzer effect. Non-blocking: the firmware's sequencer plays the + * steps on its own timer, and the Java call is safe from the worker thread. + */ +function playSfx(window: FreecellWindow, steps: Step[]): void { + if (!window.soundOn || steps.length === 0) return; + try { + const communicator = com.faceclaw.app.FaceclawBleCommunicator.getActive(); + if (!communicator) return; + communicator.playBuzzerSequence(buildSoundSequencePayload(steps).buffer); + } catch (error) { + console.warn(`freecell sfx failed: ${error}`); + } +} + +/** The window's long-press menu (game actions + default entries). */ +function openWindowMenu(window: FreecellWindow): void { + const items: MenuItem[] = []; + if (window.undoStack.length > 0 && window.phase === "playing") { + items.push({ + label: `Undo (${window.undoStack.length})`, + onSelect: (ctx) => { + ctx.stack.pop(); + undoMove(window); + }, + }); + } + items.push( + { + label: "New game", + onSelect: (ctx) => { + ctx.stack.pop(); + newGame(window, false); + playSfx(window, SFX_NEW_GAME); + }, + }, + { + label: "Restart this deal", + onSelect: (ctx) => { + ctx.stack.pop(); + newGame(window, true); + playSfx(window, SFX_NEW_GAME); + }, + }, + { + label: window.soundOn ? "Sound: on" : "Sound: off", + onSelect: (ctx) => { + ctx.stack.pop(); + window.soundOn = !window.soundOn; + if (window.soundOn) playSfx(window, SFX_NEW_GAME); + }, + }, + ); + windowMenu(window).open([...items, ...defaultWindowMenuItems(window.windowId, post)]); +} + +function windowMenu(window: FreecellWindow): WindowMenu { + if (!window.menu) { + window.menu = new WindowMenu({ + size: { width: window.viewportWidth, height: window.viewportHeight }, + paintBase: () => paintContent(window), + isFocused: () => window.focused, + }); + } + return window.menu; +} + +function handleInput(window: FreecellWindow, event: DashboardInputEvent, frameId: number): void { + // An open window menu owns all input (it closes itself via pop). + if (window.menu?.isOpen()) { + window.menu + .handleInput(event) + .catch((error) => console.error(`freecell menu input failed: ${error}`)) + .then(() => renderAndSubmit(window, frameId)); + return; + } + + if (window.phase === "playing") { + handlePlayingInput(window, event, frameId); + } else { + handleWonInput(window, event, frameId); + } +} + +function handlePlayingInput(window: FreecellWindow, event: DashboardInputEvent, frameId: number): void { + switch (event.type) { + case "scroll-up": + window.cursor = (window.cursor + LOC_COUNT - 1) % LOC_COUNT; + break; + case "scroll-down": + window.cursor = (window.cursor + 1) % LOC_COUNT; + break; + case "click": + if (window.selected === null) { + if (locationHasCard(window, window.cursor)) { + window.selected = window.cursor; + playSfx(window, SFX_SELECT); + } else { + playSfx(window, SFX_ERROR); + } + } else if (window.selected === window.cursor) { + window.selected = null; + } else { + performMove(window, window.selected, window.cursor); + } + break; + case "double-click": + if (window.selected !== null) { + window.selected = null; + } else { + sendToFoundation(window, window.cursor); + } + break; + case "long-press": + openWindowMenu(window); + break; + default: + frameTimings.finishFrame(frameId, "discarded: freecell ignored input"); + return; + } + renderAndSubmit(window, frameId); +} + +function handleWonInput(window: FreecellWindow, event: DashboardInputEvent, frameId: number): void { + switch (event.type) { + case "click": + newGame(window, false); + playSfx(window, SFX_NEW_GAME); + break; + case "double-click": + frameTimings.finishFrame(frameId, "discarded: freecell yielded focus"); + post({ type: "yield-focus", windowId: window.windowId }); + return; + case "long-press": + openWindowMenu(window); + break; + default: + frameTimings.finishFrame(frameId, "discarded: freecell ignored input"); + return; + } + renderAndSubmit(window, frameId); +} + +function newGame(window: FreecellWindow, keepDeal: boolean): void { + if (!keepDeal || window.dealOrder.length !== 52) { + const order = Array.from({ length: 52 }, (_, i) => i); + for (let i = order.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [order[i], order[j]] = [order[j]!, order[i]!]; + } + window.dealOrder = order; + } + window.cascades = Array.from({ length: 8 }, () => []); + for (let i = 0; i < 52; i++) { + window.cascades[i % 8]!.push(window.dealOrder[i]!); + } + window.cells = [null, null, null, null]; + window.foundations = [null, null, null, null]; + window.undoStack = []; + window.moves = 0; + window.cursor = LOC_CASCADE0; + window.selected = null; + window.phase = "playing"; +} + +function snapshot(window: FreecellWindow): Snapshot { + return { + cascades: window.cascades.map((cascade) => [...cascade]), + cells: [...window.cells], + foundations: [...window.foundations], + moves: window.moves, + }; +} + +function undoMove(window: FreecellWindow): void { + const previous = window.undoStack.pop(); + if (!previous) return; + window.cascades = previous.cascades; + window.cells = previous.cells; + window.foundations = previous.foundations; + window.moves = previous.moves; + window.selected = null; + playSfx(window, SFX_UNDO); +} + +function locationHasCard(window: FreecellWindow, location: number): boolean { + if (location < LOC_FOUNDATION0) return window.cells[location] !== null; + if (location < LOC_CASCADE0) return window.foundations[location - LOC_FOUNDATION0] !== null; + return window.cascades[location - LOC_CASCADE0]!.length > 0; +} + +/** True if `card` can go on `onto` in a cascade (descending, alternating color). */ +function canStack(card: number, onto: number): boolean { + return rankOf(onto) === rankOf(card) + 1 && isRed(onto) !== isRed(card); +} + +function foundationCanAccept(pileTop: number | null, card: number): boolean { + if (pileTop === null) return rankOf(card) === 1; + return suitOf(pileTop) === suitOf(card) && rankOf(card) === rankOf(pileTop) + 1; +} + +/** The foundation pile this card can legally go to right now, or -1. */ +function foundationIndexFor(window: FreecellWindow, card: number): number { + for (let i = 0; i < 4; i++) { + const top = window.foundations[i]!; + if (top !== null && suitOf(top) === suitOf(card)) { + return rankOf(card) === rankOf(top) + 1 ? i : -1; + } + } + if (rankOf(card) === 1) { + return window.foundations.indexOf(null); + } + return -1; +} + +/** Length of the movable tail run (descending, alternating colors). */ +function tailRunLength(cascade: number[]): number { + let length = Math.min(1, cascade.length); + while (length < cascade.length && canStack(cascade[cascade.length - length]!, cascade[cascade.length - length - 1]!)) { + length++; + } + return length; +} + +/** + * Supermove capacity: (empty free cells + 1) doubled per empty cascade. A + * move into an empty cascade can't count that cascade as a waypoint. + */ +function moveCapacity(window: FreecellWindow, excludeCascade: number): number { + const freeCells = window.cells.filter((cell) => cell === null).length; + let capacity = freeCells + 1; + for (let i = 0; i < 8; i++) { + if (i !== excludeCascade && window.cascades[i]!.length === 0) capacity *= 2; + } + return capacity; +} + +/** The card a location would give up right now (cascade top), or null. */ +function topCardAt(window: FreecellWindow, location: number): number | null { + if (location < LOC_FOUNDATION0) return window.cells[location]!; + if (location < LOC_CASCADE0) return window.foundations[location - LOC_FOUNDATION0]!; + const cascade = window.cascades[location - LOC_CASCADE0]!; + return cascade.length > 0 ? cascade[cascade.length - 1]! : null; +} + +/** Remove the card `topCardAt` reported (single-card sources only). */ +function takeCardFrom(window: FreecellWindow, location: number): void { + if (location < LOC_FOUNDATION0) { + window.cells[location] = null; + } else if (location < LOC_CASCADE0) { + const pile = location - LOC_FOUNDATION0; + const top = window.foundations[pile]!; + window.foundations[pile] = rankOf(top!) > 1 ? top! - 4 : null; + } else { + window.cascades[location - LOC_CASCADE0]!.pop(); + } +} + +/** + * Attempt a user move between two locations; on success commit it as one + * undoable step (including any safe auto-plays it unlocks). + */ +function performMove(window: FreecellWindow, src: number, dst: number): void { + const before = snapshot(window); + const result = attemptMove(window, src, dst); + if (!result.moved) { + playSfx(window, SFX_ERROR); + return; + } + window.undoStack.push(before); + if (window.undoStack.length > 200) window.undoStack.shift(); + window.moves++; + window.selected = null; + playSfx(window, result.toFoundation ? SFX_FOUNDATION : SFX_MOVE); + autoSafeMoves(window); + checkWin(window); +} + +function attemptMove(window: FreecellWindow, src: number, dst: number): { moved: boolean; toFoundation: boolean } { + const failed = { moved: false, toFoundation: false }; + const srcIsCascade = src >= LOC_CASCADE0; + const dstIsCell = dst < LOC_FOUNDATION0; + const dstIsFoundation = !dstIsCell && dst < LOC_CASCADE0; + + if (dstIsFoundation) { + if (src >= LOC_FOUNDATION0 && src < LOC_CASCADE0) return failed; + const card = topCardAt(window, src); + const pile = dst - LOC_FOUNDATION0; + if (card === null || !foundationCanAccept(window.foundations[pile]!, card)) return failed; + takeCardFrom(window, src); + window.foundations[pile] = card; + return { moved: true, toFoundation: true }; + } + + if (dstIsCell) { + if (window.cells[dst] !== null) return failed; + const card = topCardAt(window, src); + if (card === null) return failed; + takeCardFrom(window, src); + window.cells[dst] = card; + return { moved: true, toFoundation: false }; + } + + // Destination is a cascade. + const dstCascade = window.cascades[dst - LOC_CASCADE0]!; + const dstTop = dstCascade.length > 0 ? dstCascade[dstCascade.length - 1]! : null; + + if (!srcIsCascade) { + const card = topCardAt(window, src); + if (card === null) return failed; + if (dstTop !== null && !canStack(card, dstTop)) return failed; + takeCardFrom(window, src); + dstCascade.push(card); + return { moved: true, toFoundation: false }; + } + + const srcCascade = window.cascades[src - LOC_CASCADE0]!; + if (srcCascade.length === 0) return failed; + const capacity = moveCapacity(window, dstTop === null ? dst - LOC_CASCADE0 : -1); + const maxRun = Math.min(tailRunLength(srcCascade), capacity); + // Take the longest legal run; onto an empty cascade any run length works. + for (let n = maxRun; n >= 1; n--) { + const bottom = srcCascade[srcCascade.length - n]!; + if (dstTop === null || canStack(bottom, dstTop)) { + dstCascade.push(...srcCascade.splice(srcCascade.length - n, n)); + return { moved: true, toFoundation: false }; + } + } + return failed; +} + +/** Double-click convenience: the card at `location` goes to its foundation. */ +function sendToFoundation(window: FreecellWindow, location: number): void { + if (location >= LOC_FOUNDATION0 && location < LOC_CASCADE0) { + playSfx(window, SFX_ERROR); + return; + } + const card = topCardAt(window, location); + const pile = card === null ? -1 : foundationIndexFor(window, card); + if (pile < 0) { + playSfx(window, SFX_ERROR); + return; + } + performMove(window, location, LOC_FOUNDATION0 + pile); +} + +/** Foundation rank per suit (0 while that suit has no pile). */ +function foundationRankBySuit(window: FreecellWindow): number[] { + const ranks = [0, 0, 0, 0]; + for (const top of window.foundations) { + if (top !== null) ranks[suitOf(top)] = rankOf(top); + } + return ranks; +} + +/** + * A card is safe to auto-play when no cascade card could still need it: + * rank 2 or less, or both opposite-color foundations at rank-1 or higher. + */ +function isSafeAutoPlay(window: FreecellWindow, card: number): boolean { + const rank = rankOf(card); + if (rank <= 2) return true; + const ranks = foundationRankBySuit(window); + const oppositeMin = isRed(card) ? Math.min(ranks[0]!, ranks[2]!) : Math.min(ranks[1]!, ranks[3]!); + return oppositeMin >= rank - 1; +} + +/** Repeatedly move safe cards (cell or cascade top) to the foundations. */ +function autoSafeMoves(window: FreecellWindow): void { + let moved = true; + while (moved) { + moved = false; + for (let location = 0; location < LOC_COUNT; location++) { + if (location >= LOC_FOUNDATION0 && location < LOC_CASCADE0) continue; + const card = topCardAt(window, location); + if (card === null || !isSafeAutoPlay(window, card)) continue; + const pile = foundationIndexFor(window, card); + if (pile < 0) continue; + takeCardFrom(window, location); + window.foundations[pile] = card; + moved = true; + } + } +} + +function checkWin(window: FreecellWindow): void { + const done = window.foundations.every((top) => top !== null && rankOf(top) === 13); + if (!done) return; + window.phase = "won"; + window.selected = null; + playSfx(window, SFX_WIN); +} + +// --------------------------------------------------------------------------- +// Painting + +type Layout = { + pitch: number; + marginX: number; + /** Vertical pixels per buried cascade card (its visible label strip). */ + strip: (cascadeLength: number) => number; +}; + +function layoutFor(window: FreecellWindow): Layout { + const pitch = Math.floor((window.viewportWidth - 12) / 8); + const marginX = Math.floor((window.viewportWidth - (pitch * 8 - (pitch - CARD_W))) / 2); + const available = window.viewportHeight - CASCADE_Y - 2; + return { + pitch, + marginX, + strip: (cascadeLength: number) => + cascadeLength <= 1 ? 0 : Math.min(16, Math.floor((available - CARD_H) / (cascadeLength - 1))), + }; +} + +function paint(window: FreecellWindow): GrayImage { + if (window.menu?.isOpen()) { + return window.menu.paint(); + } + return paintContent(window); +} + +function paintContent(window: FreecellWindow): GrayImage { + const image = new GrayImage(window.viewportWidth, window.viewportHeight, 0); + const layout = layoutFor(window); + const colX = (i: number) => layout.marginX + i * layout.pitch; + + // Top row: free cells then foundations, with a divider between the groups. + for (let i = 0; i < 4; i++) { + const card = window.cells[i]!; + if (card === null) { + image.drawRoundedRect(colX(i), TOP_Y, CARD_W, CARD_H, 70, 4); + } else { + paintCard(image, colX(i), TOP_Y, card, window.selected === LOC_CELL0 + i, true); + } + } + image.drawLine(colX(4) - 4, TOP_Y + 4, colX(4) - 4, TOP_Y + CARD_H - 4, 70); + for (let i = 0; i < 4; i++) { + const x = colX(4 + i); + const card = window.foundations[i]!; + if (card === null) { + image.drawRoundedRect(x, TOP_Y, CARD_W, CARD_H, 70, 4); + image.drawText(labelFont, x + Math.round((CARD_W - labelFont.measureText("A")) / 2), TOP_Y + 10, "A", 70); + } else { + paintCard(image, x, TOP_Y, card, window.selected === LOC_FOUNDATION0 + i, true); + } + } + + for (let i = 0; i < 8; i++) { + paintCascade(image, window, layout, i); + } + paintCursor(image, window, layout); + if (window.phase === "won") paintWinOverlay(image, window); + return image; +} + +function paintCascade(image: GrayImage, window: FreecellWindow, layout: Layout, index: number): void { + const x = layout.marginX + index * layout.pitch; + const cascade = window.cascades[index]!; + if (cascade.length === 0) { + image.drawRoundedRect(x, CASCADE_Y, CARD_W, CARD_H, 45, 4); + return; + } + const strip = layout.strip(cascade.length); + // How many tail cards the pending selection would move (highlighted). + let highlightFrom = cascade.length; + if (window.selected === LOC_CASCADE0 + index) { + const run = Math.min(tailRunLength(cascade), moveCapacity(window, -1)); + highlightFrom = cascade.length - run; + } + for (let i = 0; i < cascade.length; i++) { + paintCard(image, x, CASCADE_Y + i * strip, cascade[i]!, i >= highlightFrom, i === cascade.length - 1); + } +} + +function paintCard( + image: GrayImage, + x: number, + y: number, + card: number, + selected: boolean, + fullyVisible: boolean, +): void { + const shade = isRed(card) ? RED_SHADE : BLACK_SHADE; + image.fillRoundedRect(x, y, CARD_W, CARD_H, selected ? 60 : 25, 4); + image.drawRoundedRect(x, y, CARD_W, CARD_H, selected ? 255 : 160, 4); + if (selected) image.drawRoundedRect(x + 1, y + 1, CARD_W - 2, CARD_H - 2, 255, 3); + image.drawText(labelFont, x + 5, y + 2, cardLabel(card), shade); + if (fullyVisible) { + image.drawText(mediumFont, x + CARD_W - 18, y + CARD_H - 29, SUIT_CHARS[suitOf(card)]!, shade); + } +} + +/** Bright double outline around the cursor's location, minesweeper-style. */ +function paintCursor(image: GrayImage, window: FreecellWindow, layout: Layout): void { + if (window.phase !== "playing") return; + let x: number; + let y: number; + let height: number; + if (window.cursor < LOC_CASCADE0) { + x = layout.marginX + (window.cursor % 8) * layout.pitch; + y = TOP_Y; + height = CARD_H; + } else { + const index = window.cursor - LOC_CASCADE0; + const cascade = window.cascades[index]!; + x = layout.marginX + index * layout.pitch; + y = CASCADE_Y; + height = cascade.length === 0 ? CARD_H : (cascade.length - 1) * layout.strip(cascade.length) + CARD_H; + } + image.drawRect(x - 3, y - 3, CARD_W + 6, height + 6, 255); + image.drawRect(x - 2, y - 2, CARD_W + 4, height + 4, 255); +} + +function paintWinOverlay(image: GrayImage, window: FreecellWindow): void { + const width = 320; + const height = 120; + const x = Math.round((window.viewportWidth - width) / 2); + const y = Math.round((window.viewportHeight - height) / 2); + image.fillRoundedRect(x, y, width, height, 0, 8); + image.drawRoundedRect(x, y, width, height, 200, 8); + drawCenteredIn(image, largeFont, x, width, y + 14, "You win!", 255); + drawCenteredIn(image, smallFont, x, width, y + 56, `${window.moves} moves`, 170); + drawCenteredIn(image, smallFont, x, width, y + 80, `${GESTURE_CLICK} new game ${GESTURE_DOUBLE_CLICK} leave`, 150); + drawCenteredIn(image, smallFont, x, width, y + 98, `${GESTURE_LONG_PRESS} menu`, 150); +} + +function drawCenteredIn( + image: GrayImage, + font: typeof smallFont, + x: number, + width: number, + y: number, + text: string, + value: number, +): void { + image.drawText(font, Math.round(x + (width - font.measureText(text)) / 2), y, text, value); +} + +function renderAndSubmit(window: FreecellWindow, inputFrameId: number): void { + const frameId = inputFrameId > 0 ? inputFrameId : frameTimings.startFrame(`render:${window.windowId}`); + try { + const paintStartedAtMs = Date.now(); + const image = frameTimings.span(frameId, "paint", () => + frameTimings.runWithFrame(frameId, () => paint(window)), + ); + const paintMs = Date.now() - paintStartedAtMs; + const fingerprint = image.fingerprint(); + if (fingerprint === window.lastSubmittedFingerprint) { + frameTimings.finishFrame(frameId, "discarded: freecell content unchanged"); + return; + } + const communicator = com.faceclaw.app.FaceclawBleCommunicator.getActive(); + if (!communicator) { + frameTimings.finishFrame(frameId, "discarded: no active communicator"); + return; + } + const buffer = image.to8bppBuffer(); + communicator.submitSurfaceFrame( + buffer.buffer, + window.surfaceId, + 0, + 0, + image.width, + image.height, + fingerprint, + paintMs, + frameId, + ); + window.lastSubmittedFingerprint = fingerprint; + } catch (error) { + frameTimings.finishFrame(frameId, "discarded: freecell render failed"); + console.error(`freecell worker render failed: ${error}`); + } +} diff --git a/app/workers/minesweeper-app.worker.ts b/app/workers/minesweeper-app.worker.ts new file mode 100644 index 00000000..1b6a6ecb --- /dev/null +++ b/app/workers/minesweeper-app.worker.ts @@ -0,0 +1,730 @@ +/** + * Minesweeper app worker. One singleton window holds the whole game: a fixed + * 12×9 board with a difficulty setting that varies the mine count. Mines are + * placed on the first reveal (never under or adjacent to it), and the clock + * runs only while the game is live, foreground, and the screen is on. + * + * Controls (in play) are a two-layer selection. Row-select: scroll picks a + * row, click switches to column-select, double-click pauses. Column-select: + * scroll moves along the row, click reveals (or chords a satisfied number), + * long-press toggles a flag, double-click returns to row-select. + * Paused/won/lost: click resumes or starts a new game, double-click yields + * focus, long-press opens the window menu. + */ +import "@nativescript/core/globals"; +import { GrayImage } from "../graphics/image"; +import { getDefaultSmallFont, getFont } from "../graphics/bdffont"; +import * as frameTimings from "../native/frame-timings"; +import type { DashboardInputEvent } from "../ui/layers"; +import { buildSoundSequencePayload, type Step } from "../ui/apps/sound-effects"; +import { defaultWindowMenuItems, WindowMenu } from "../ui/window-menu"; +import type { WorkerAppMessage, WorkerAppReply } from "../ui/shell/worker-window"; +import { + GESTURE_CLICK, + GESTURE_DOUBLE_CLICK, + GESTURE_LONG_PRESS, + GESTURE_SCROLL, +} from "../ui/gestures"; +import { clamp } from "../util/numeric-util"; + +declare const global: any; +declare const com: any; + +const largeFont = getFont("terminus32"); +const mediumFont = getFont("terminus24"); +const smallFont = getDefaultSmallFont(); + +const COLS = 12; +const ROWS = 9; +const CELL = 26; +const BOARD_X = 14; +const BOARD_Y = 14; +const PANEL_X = BOARD_X + COLS * CELL + 28; + +const DIFFICULTIES = [ + { name: "Easy", mines: 14 }, + { name: "Medium", mines: 20 }, + { name: "Hard", mines: 26 }, +] as const; + +/** Number glyph shades by adjacent-mine count; higher counts read brighter. */ +const COUNT_SHADES = [0, 140, 170, 200, 220, 235, 245, 250, 250]; + +const CELL_HIDDEN = 0; +const CELL_REVEALED = 1; +const CELL_FLAGGED = 2; + +/** Buzzer effects, tuned soft like the Blocks ones (shared piezo). */ +const SFX_REVEAL: Step[] = [{ freq: 660, duty: 40, ms: 15 }]; +const SFX_FLAG: Step[] = [{ freq: 880, duty: 40, ms: 30 }]; +const SFX_UNFLAG: Step[] = [{ freq: 550, duty: 40, ms: 30 }]; +const SFX_BOOM: Step[] = [ + { freq: 220, duty: 55, ms: 80 }, + { freq: 140, duty: 55, ms: 120 }, + { freq: 90, duty: 60, ms: 320 }, +]; +const SFX_WIN: Step[] = [ + { freq: 1047, ms: 55 }, + { freq: 1319, ms: 55 }, + { freq: 1568, ms: 55 }, + { freq: 2093, ms: 70 }, + { freq: 1, duty: 0, ms: 30 }, + { freq: 2093, ms: 160 }, +]; +const SFX_PAUSE: Step[] = [ + { freq: 1319, duty: 40, ms: 60 }, + { freq: 880, duty: 40, ms: 110 }, +]; +/** Also the new-game and sound-toggled-on confirmation. */ +const SFX_RESUME: Step[] = [ + { freq: 880, duty: 40, ms: 60 }, + { freq: 1319, duty: 40, ms: 110 }, +]; + +type GamePhase = "playing" | "paused" | "won" | "lost"; + +type MinesweeperWindow = { + windowId: string; + surfaceId: string; + viewportWidth: number; + viewportHeight: number; + foreground: boolean; + /** Whether this window is the shell's input target (pushed with each message). */ + focused: boolean; + /** Long-press window menu; created on first open. */ + menu: WindowMenu | null; + phase: GamePhase; + difficultyIndex: number; + /** 1 = mine at this cell; empty until the first reveal places the mines. */ + mines: Uint8Array; + /** Adjacent-mine counts, precomputed at placement. */ + counts: Uint8Array; + /** Per-cell CELL_HIDDEN / CELL_REVEALED / CELL_FLAGGED. */ + cellState: Uint8Array; + minesPlaced: boolean; + cursorX: number; + cursorY: number; + /** Two-layer selection: pick a row first, then a cell along it. */ + selectMode: "row" | "column"; + flagCount: number; + revealedCount: number; + /** The mine that ended the game, painted highlighted; -1 otherwise. */ + explodedIndex: number; + /** Clock: accumulated play time plus the live segment since runningSinceMs. */ + elapsedMs: number; + runningSinceMs: number | null; + tickTimer: ReturnType | null; + soundOn: boolean; + lastSubmittedFingerprint: string; +}; + +const windows = new Map(); +let screenOn = true; + +function post(message: WorkerAppReply): void { + global.postMessage(message); +} + +global.onmessage = (event: { data: WorkerAppMessage }) => { + const message = event.data; + switch (message.type) { + case "open-window": { + const window: MinesweeperWindow = { + windowId: message.windowId, + surfaceId: message.surfaceId, + viewportWidth: message.viewport.width, + viewportHeight: message.viewport.height, + foreground: false, + focused: false, + menu: null, + phase: "playing", + difficultyIndex: 0, + mines: new Uint8Array(COLS * ROWS), + counts: new Uint8Array(COLS * ROWS), + cellState: new Uint8Array(COLS * ROWS), + minesPlaced: false, + cursorX: Math.floor(COLS / 2), + cursorY: Math.floor(ROWS / 2), + selectMode: "row", + flagCount: 0, + revealedCount: 0, + explodedIndex: -1, + elapsedMs: 0, + runningSinceMs: null, + tickTimer: null, + soundOn: true, + lastSubmittedFingerprint: "", + }; + windows.set(message.windowId, window); + break; + } + case "close-window": { + const window = windows.get(message.windowId); + if (window?.tickTimer) clearInterval(window.tickTimer); + windows.delete(message.windowId); + break; + } + case "input": { + const window = windows.get(message.windowId); + if (!window) { + frameTimings.finishFrame(message.frameId, "discarded: unknown minesweeper window"); + break; + } + window.focused = message.focused; + inferForeground(window, message.focused); + handleInput(window, message.event as DashboardInputEvent, message.frameId); + break; + } + case "render": { + const window = windows.get(message.windowId); + if (!window) break; + window.focused = message.focused; + inferForeground(window, message.focused); + renderAndSubmit(window, 0); + break; + } + case "foreground": { + const window = windows.get(message.windowId); + if (!window) break; + window.foreground = message.foreground; + window.focused = message.focused; + // The player can't see the board while backgrounded, so don't let the + // clock keep running. + if (!window.foreground && window.phase === "playing") window.phase = "paused"; + syncClock(window); + if (window.foreground) renderAndSubmit(window, 0); + break; + } + case "screen": + screenOn = message.on; + for (const window of windows.values()) { + if (!screenOn && window.phase === "playing") window.phase = "paused"; + syncClock(window); + } + break; + } +}; + +/** + * Input and render messages only ever target the shell's foreground window, + * so a focused message proves this window is foreground. This backstops the + * "foreground" message itself, which can be lost while a freshly spawned + * worker is still evaluating its bundle (see the Blocks worker). + */ +function inferForeground(window: MinesweeperWindow, focused: boolean): void { + if (!focused || window.foreground) return; + window.foreground = true; + syncClock(window); +} + +/** + * Fire a buzzer effect. Non-blocking: the firmware's sequencer plays the + * steps on its own timer, and the Java call is safe from the worker thread. + */ +function playSfx(window: MinesweeperWindow, steps: Step[]): void { + if (!window.soundOn || steps.length === 0) return; + try { + const communicator = com.faceclaw.app.FaceclawBleCommunicator.getActive(); + if (!communicator) return; + communicator.playBuzzerSequence(buildSoundSequencePayload(steps).buffer); + } catch (error) { + console.warn(`minesweeper sfx failed: ${error}`); + } +} + +/** The window's long-press menu (game actions + default entries). */ +function openWindowMenu(window: MinesweeperWindow): void { + const nextDifficulty = DIFFICULTIES[(window.difficultyIndex + 1) % DIFFICULTIES.length]!; + windowMenu(window).open([ + { + label: "New game", + onSelect: (ctx) => { + ctx.stack.pop(); + resetGame(window); + playSfx(window, SFX_RESUME); + }, + }, + { + label: `Difficulty: ${DIFFICULTIES[window.difficultyIndex]!.name} → ${nextDifficulty.name}`, + onSelect: (ctx) => { + ctx.stack.pop(); + window.difficultyIndex = (window.difficultyIndex + 1) % DIFFICULTIES.length; + resetGame(window); + playSfx(window, SFX_RESUME); + }, + }, + { + label: window.soundOn ? "Sound: on" : "Sound: off", + onSelect: (ctx) => { + ctx.stack.pop(); + window.soundOn = !window.soundOn; + if (window.soundOn) playSfx(window, SFX_RESUME); + }, + }, + ...defaultWindowMenuItems(window.windowId, post), + ]); +} + +function windowMenu(window: MinesweeperWindow): WindowMenu { + if (!window.menu) { + window.menu = new WindowMenu({ + size: { width: window.viewportWidth, height: window.viewportHeight }, + paintBase: () => paintContent(window), + isFocused: () => window.focused, + }); + } + return window.menu; +} + +function handleInput(window: MinesweeperWindow, event: DashboardInputEvent, frameId: number): void { + // An open window menu owns all input (it closes itself via pop). + if (window.menu?.isOpen()) { + window.menu + .handleInput(event) + .catch((error) => console.error(`minesweeper menu input failed: ${error}`)) + .then(() => renderAndSubmit(window, frameId)); + return; + } + + if (window.phase === "playing") { + handlePlayingInput(window, event, frameId); + } else { + handleIdleInput(window, event, frameId); + } +} + +function handlePlayingInput(window: MinesweeperWindow, event: DashboardInputEvent, frameId: number): void { + const rowMode = window.selectMode === "row"; + switch (event.type) { + case "scroll-up": + if (rowMode) { + window.cursorY = clamp(window.cursorY - 1, 0, ROWS - 1); + } else { + window.cursorX = clamp(window.cursorX - 1, 0, COLS - 1); + } + break; + case "scroll-down": + if (rowMode) { + window.cursorY = clamp(window.cursorY + 1, 0, ROWS - 1); + } else { + window.cursorX = clamp(window.cursorX + 1, 0, COLS - 1); + } + break; + case "click": + if (rowMode) { + window.selectMode = "column"; + } else { + revealAtCursor(window); + } + break; + case "long-press": + if (rowMode) { + frameTimings.finishFrame(frameId, "discarded: minesweeper ignored input"); + return; + } + toggleFlag(window); + break; + case "double-click": + if (rowMode) { + window.phase = "paused"; + syncClock(window); + playSfx(window, SFX_PAUSE); + } else { + window.selectMode = "row"; + } + break; + default: + frameTimings.finishFrame(frameId, "discarded: minesweeper ignored input"); + return; + } + renderAndSubmit(window, frameId); +} + +/** Input while paused, won, or lost. */ +function handleIdleInput(window: MinesweeperWindow, event: DashboardInputEvent, frameId: number): void { + switch (event.type) { + case "click": + if (window.phase === "paused") { + window.phase = "playing"; + } else { + resetGame(window); + } + syncClock(window); + playSfx(window, SFX_RESUME); + break; + case "double-click": + frameTimings.finishFrame(frameId, "discarded: minesweeper yielded focus"); + post({ type: "yield-focus", windowId: window.windowId }); + return; + case "long-press": + openWindowMenu(window); + break; + default: + frameTimings.finishFrame(frameId, "discarded: minesweeper ignored input"); + return; + } + renderAndSubmit(window, frameId); +} + +function resetGame(window: MinesweeperWindow): void { + window.mines.fill(0); + window.counts.fill(0); + window.cellState.fill(CELL_HIDDEN); + window.minesPlaced = false; + window.flagCount = 0; + window.revealedCount = 0; + window.explodedIndex = -1; + window.elapsedMs = 0; + window.runningSinceMs = null; + window.phase = "playing"; + window.selectMode = "row"; + syncClock(window); +} + +function mineCount(window: MinesweeperWindow): number { + return DIFFICULTIES[window.difficultyIndex]!.mines; +} + +function forEachNeighbor(x: number, y: number, callback: (nx: number, ny: number) => void): void { + for (let ny = Math.max(0, y - 1); ny <= Math.min(ROWS - 1, y + 1); ny++) { + for (let nx = Math.max(0, x - 1); nx <= Math.min(COLS - 1, x + 1); nx++) { + if (nx !== x || ny !== y) callback(nx, ny); + } + } +} + +/** Place mines everywhere except the 3×3 around the first reveal, then count. */ +function placeMines(window: MinesweeperWindow, safeX: number, safeY: number): void { + const candidates: number[] = []; + for (let y = 0; y < ROWS; y++) { + for (let x = 0; x < COLS; x++) { + if (Math.abs(x - safeX) <= 1 && Math.abs(y - safeY) <= 1) continue; + candidates.push(y * COLS + x); + } + } + for (let i = candidates.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [candidates[i], candidates[j]] = [candidates[j]!, candidates[i]!]; + } + for (const index of candidates.slice(0, mineCount(window))) { + window.mines[index] = 1; + } + for (let y = 0; y < ROWS; y++) { + for (let x = 0; x < COLS; x++) { + let count = 0; + forEachNeighbor(x, y, (nx, ny) => { + if (window.mines[ny * COLS + nx]) count++; + }); + window.counts[y * COLS + x] = count; + } + } + window.minesPlaced = true; + syncClock(window); +} + +/** Reveal a cell, flood-filling zero-count regions. Returns true on a mine. */ +function revealCell(window: MinesweeperWindow, x: number, y: number): boolean { + const index = y * COLS + x; + if (window.cellState[index] !== CELL_HIDDEN) return false; + if (window.mines[index]) { + window.explodedIndex = index; + loseGame(window); + return true; + } + const stack = [index]; + window.cellState[index] = CELL_REVEALED; + window.revealedCount++; + while (stack.length > 0) { + const current = stack.pop()!; + if (window.counts[current] !== 0) continue; + forEachNeighbor(current % COLS, Math.floor(current / COLS), (nx, ny) => { + const neighbor = ny * COLS + nx; + if (window.cellState[neighbor] !== CELL_HIDDEN) return; + window.cellState[neighbor] = CELL_REVEALED; + window.revealedCount++; + stack.push(neighbor); + }); + } + return false; +} + +function revealAtCursor(window: MinesweeperWindow): void { + const { cursorX, cursorY } = window; + const index = cursorY * COLS + cursorX; + if (window.cellState[index] === CELL_FLAGGED) return; + + if (window.cellState[index] === CELL_REVEALED) { + chordAtCursor(window); + return; + } + if (!window.minesPlaced) placeMines(window, cursorX, cursorY); + if (!revealCell(window, cursorX, cursorY)) { + playSfx(window, SFX_REVEAL); + checkWin(window); + } +} + +/** + * Chord: clicking a revealed number whose flag count is satisfied reveals its + * remaining hidden neighbors (classic both-buttons shortcut). Wrong flags + * still explode. + */ +function chordAtCursor(window: MinesweeperWindow): void { + const { cursorX, cursorY } = window; + const count = window.counts[cursorY * COLS + cursorX]!; + if (count === 0) return; + let flags = 0; + forEachNeighbor(cursorX, cursorY, (nx, ny) => { + if (window.cellState[ny * COLS + nx] === CELL_FLAGGED) flags++; + }); + if (flags !== count) return; + let exploded = false; + let revealedAny = false; + forEachNeighbor(cursorX, cursorY, (nx, ny) => { + if (exploded || window.cellState[ny * COLS + nx] !== CELL_HIDDEN) return; + revealedAny = true; + if (revealCell(window, nx, ny)) exploded = true; + }); + if (!exploded && revealedAny) { + playSfx(window, SFX_REVEAL); + checkWin(window); + } +} + +function toggleFlag(window: MinesweeperWindow): void { + const index = window.cursorY * COLS + window.cursorX; + if (window.cellState[index] === CELL_REVEALED) return; + if (window.cellState[index] === CELL_FLAGGED) { + window.cellState[index] = CELL_HIDDEN; + window.flagCount--; + playSfx(window, SFX_UNFLAG); + } else { + window.cellState[index] = CELL_FLAGGED; + window.flagCount++; + playSfx(window, SFX_FLAG); + } +} + +function checkWin(window: MinesweeperWindow): void { + if (window.revealedCount !== COLS * ROWS - mineCount(window)) return; + window.phase = "won"; + // Flag the remaining mines for the player; the counter drops to zero. + for (let index = 0; index < window.mines.length; index++) { + if (window.mines[index] && window.cellState[index] === CELL_HIDDEN) { + window.cellState[index] = CELL_FLAGGED; + } + } + window.flagCount = mineCount(window); + syncClock(window); + playSfx(window, SFX_WIN); +} + +function loseGame(window: MinesweeperWindow): void { + window.phase = "lost"; + syncClock(window); + playSfx(window, SFX_BOOM); +} + +/** + * Keep the clock and the once-a-second repaint interval running exactly when + * play time is accruing: game live (mines placed), foreground, screen on. + */ +function syncClock(window: MinesweeperWindow): void { + const shouldRun = + window.phase === "playing" && window.minesPlaced && window.foreground && screenOn; + const now = Date.now(); + if (shouldRun && window.runningSinceMs === null) { + window.runningSinceMs = now; + } else if (!shouldRun && window.runningSinceMs !== null) { + window.elapsedMs += now - window.runningSinceMs; + window.runningSinceMs = null; + } + if (shouldRun && window.tickTimer === null) { + window.tickTimer = setInterval(() => renderAndSubmit(window, 0), 1000); + } else if (!shouldRun && window.tickTimer !== null) { + clearInterval(window.tickTimer); + window.tickTimer = null; + } +} + +function elapsedMs(window: MinesweeperWindow): number { + const runningMs = window.runningSinceMs === null ? 0 : Date.now() - window.runningSinceMs; + return window.elapsedMs + runningMs; +} + +function paint(window: MinesweeperWindow): GrayImage { + if (window.menu?.isOpen()) { + return window.menu.paint(); + } + return paintContent(window); +} + +function paintContent(window: MinesweeperWindow): GrayImage { + const image = new GrayImage(window.viewportWidth, window.viewportHeight, 0); + image.drawRect(BOARD_X - 2, BOARD_Y - 2, COLS * CELL + 4, ROWS * CELL + 4, 120); + if (window.phase === "paused") { + // Hide the board so pausing can't be used to study it off the clock. + drawCenteredIn(image, mediumFont, BOARD_X, COLS * CELL, BOARD_Y + 80, "PAUSED", 230); + drawCenteredIn(image, smallFont, BOARD_X, COLS * CELL, BOARD_Y + 120, `${GESTURE_CLICK} resume`, 150); + drawCenteredIn(image, smallFont, BOARD_X, COLS * CELL, BOARD_Y + 140, `${GESTURE_DOUBLE_CLICK} leave`, 150); + } else { + paintBoard(image, window); + } + paintPanel(image, window); + return image; +} + +function paintBoard(image: GrayImage, window: MinesweeperWindow): void { + for (let y = 0; y < ROWS; y++) { + for (let x = 0; x < COLS; x++) { + paintCell(image, window, x, y); + } + } + // Cursor: a double bright outline so it stays visible over any cell. In + // row-select it spans the whole selected row; in column-select it marks the + // cell (games over show neither). + if (window.phase !== "playing") return; + const cx = BOARD_X + window.cursorX * CELL; + const cy = BOARD_Y + window.cursorY * CELL; + if (window.selectMode === "row") { + image.drawRect(BOARD_X - 1, cy - 1, COLS * CELL + 1, CELL + 1, 255); + image.drawRect(BOARD_X, cy, COLS * CELL - 1, CELL - 1, 255); + } else { + image.drawRect(cx - 1, cy - 1, CELL + 1, CELL + 1, 255); + image.drawRect(cx, cy, CELL - 1, CELL - 1, 255); + } +} + +function paintCell(image: GrayImage, window: MinesweeperWindow, x: number, y: number): void { + const index = y * COLS + x; + const cx = BOARD_X + x * CELL; + const cy = BOARD_Y + y * CELL; + const state = window.cellState[index]!; + const isMine = window.mines[index] === 1; + const gameOver = window.phase === "lost"; + + if (state === CELL_REVEALED || (gameOver && isMine)) { + if (isMine) { + // The fatal mine gets an inverted cell so it stands out. + if (index === window.explodedIndex) image.fillRect(cx, cy, CELL - 1, CELL - 1, 200); + drawMine(image, cx, cy, index === window.explodedIndex ? 1 : 220); + return; + } + image.drawRect(cx, cy, CELL - 1, CELL - 1, 22); + const count = window.counts[index]!; + if (count > 0) { + const digit = String(count); + const dx = cx + Math.round((CELL - 1 - mediumFont.measureText(digit)) / 2); + image.drawText(mediumFont, dx, cy + 1, digit, COUNT_SHADES[count]!); + } + return; + } + + // Hidden (or flagged) cell face. + image.fillRect(cx, cy, CELL - 1, CELL - 1, 55); + if (state === CELL_FLAGGED) { + drawFlag(image, cx, cy, 245); + // A flag that turned out wrong gets crossed out at game over. + if (gameOver && !isMine) { + image.drawLine(cx + 3, cy + 3, cx + CELL - 5, cy + CELL - 5, 255); + image.drawLine(cx + CELL - 5, cy + 3, cx + 3, cy + CELL - 5, 255); + } + } +} + +function drawFlag(image: GrayImage, cx: number, cy: number, shade: number): void { + image.drawLine(cx + 10, cy + 5, cx + 10, cy + 20, shade); + image.fillRect(cx + 11, cy + 5, 7, 4, shade); + image.fillRect(cx + 11, cy + 9, 4, 3, shade); + image.drawLine(cx + 7, cy + 20, cx + 13, cy + 20, shade); +} + +function drawMine(image: GrayImage, cx: number, cy: number, shade: number): void { + const centerX = cx + Math.floor((CELL - 1) / 2); + const centerY = cy + Math.floor((CELL - 1) / 2); + // A rounded blob plus four spikes reads as a mine at this size. + image.fillRoundedRect(centerX - 6, centerY - 6, 13, 13, shade, 6); + image.drawLine(centerX - 9, centerY, centerX + 9, centerY, shade); + image.drawLine(centerX, centerY - 9, centerX, centerY + 9, shade); + image.drawLine(centerX - 7, centerY - 7, centerX + 7, centerY + 7, shade); + image.drawLine(centerX - 7, centerY + 7, centerX + 7, centerY - 7, shade); +} + +function paintPanel(image: GrayImage, window: MinesweeperWindow): void { + drawStat(image, PANEL_X, BOARD_Y, "Mines", String(mineCount(window) - window.flagCount)); + drawStat(image, PANEL_X, BOARD_Y + 62, "Time", formatElapsed(elapsedMs(window))); + image.drawText(smallFont, PANEL_X, BOARD_Y + 126, DIFFICULTIES[window.difficultyIndex]!.name, 140); + + if (window.phase === "won" || window.phase === "lost") { + image.drawText(mediumFont, PANEL_X, BOARD_Y + 152, window.phase === "won" ? "CLEARED!" : "BOOM!", 250); + image.drawText(smallFont, PANEL_X, BOARD_Y + 178, `${GESTURE_CLICK} new game`, 150); + image.drawText(smallFont, PANEL_X, BOARD_Y + 198, `${GESTURE_LONG_PRESS} menu`, 150); + } else if (window.selectMode === "row") { + image.drawText(smallFont, PANEL_X, 200, `${GESTURE_SCROLL} row ${GESTURE_CLICK} pick`, 115); + image.drawText(smallFont, PANEL_X, 222, `${GESTURE_DOUBLE_CLICK} pause`, 115); + } else { + image.drawText(smallFont, PANEL_X, 200, `${GESTURE_SCROLL} cell ${GESTURE_CLICK} dig`, 115); + image.drawText(smallFont, PANEL_X, 222, `${GESTURE_LONG_PRESS} flag ${GESTURE_DOUBLE_CLICK} rows`, 115); + } +} + +function drawStat(image: GrayImage, x: number, y: number, label: string, value: string): void { + image.drawText(smallFont, x, y, label, 140); + image.drawText(largeFont, x, y + 18, value, 235); +} + +function formatElapsed(totalMs: number): string { + const totalSeconds = Math.floor(totalMs / 1000); + const minutes = Math.floor(totalSeconds / 60); + const seconds = totalSeconds % 60; + return `${minutes}:${String(seconds).padStart(2, "0")}`; +} + +function drawCenteredIn( + image: GrayImage, + font: typeof smallFont, + x: number, + width: number, + y: number, + text: string, + value: number, +): void { + image.drawText(font, Math.round(x + (width - font.measureText(text)) / 2), y, text, value); +} + +function renderAndSubmit(window: MinesweeperWindow, inputFrameId: number): void { + const frameId = inputFrameId > 0 ? inputFrameId : frameTimings.startFrame(`render:${window.windowId}`); + try { + const paintStartedAtMs = Date.now(); + const image = frameTimings.span(frameId, "paint", () => + frameTimings.runWithFrame(frameId, () => paint(window)), + ); + const paintMs = Date.now() - paintStartedAtMs; + const fingerprint = image.fingerprint(); + if (fingerprint === window.lastSubmittedFingerprint) { + frameTimings.finishFrame(frameId, "discarded: minesweeper content unchanged"); + return; + } + const communicator = com.faceclaw.app.FaceclawBleCommunicator.getActive(); + if (!communicator) { + frameTimings.finishFrame(frameId, "discarded: no active communicator"); + return; + } + const buffer = image.to8bppBuffer(); + communicator.submitSurfaceFrame( + buffer.buffer, + window.surfaceId, + 0, + 0, + image.width, + image.height, + fingerprint, + paintMs, + frameId, + ); + window.lastSubmittedFingerprint = fingerprint; + } catch (error) { + frameTimings.finishFrame(frameId, "discarded: minesweeper render failed"); + console.error(`minesweeper worker render failed: ${error}`); + } +} diff --git a/app/workers/terminal-app.worker.ts b/app/workers/terminal-app.worker.ts index 9d828ddc..e462e6fe 100644 --- a/app/workers/terminal-app.worker.ts +++ b/app/workers/terminal-app.worker.ts @@ -15,6 +15,7 @@ import "@nativescript/core/globals"; import { GrayImage } from "../graphics/image"; import { getFont } from "../graphics/bdffont"; +import { TERMINAL_ICON_GLYPHS } from "../graphics/icons"; import * as frameTimings from "../native/frame-timings"; import { GESTURE_DOUBLE_CLICK } from "../ui/gestures"; import { @@ -81,6 +82,8 @@ type ViewWindow = BaseWindow & { kind: "view"; socket: string; label: string; + /** Sidebar-icon character (">3"); "" if every glyph was taken at open time. */ + glyph: string; client: G2MirrorClient; emulator: TerminalEmulator; receivedData: boolean; @@ -103,7 +106,7 @@ type ViewWindow = BaseWindow & { type TerminalWindow = HubWindow | ViewWindow; const windows = new Map(); -const pendingViews = new Map(); +const pendingViews = new Map(); // The view an assistant tool acts on when the terminal isn't foregrounded: // the last view to be foregrounded or receive input. let activeViewId: string | null = null; @@ -269,7 +272,7 @@ function openWindow(windowId: string, surfaceId: string, viewport: { width: numb const pendingView = pendingViews.get(windowId); if (pendingView) { pendingViews.delete(windowId); - windows.set(windowId, createViewWindow(windowId, surfaceId, pendingView.socket, pendingView.label)); + windows.set(windowId, createViewWindow(windowId, surfaceId, pendingView)); renderHubWindows(); return; } @@ -365,7 +368,12 @@ function renderHubWindows(): void { } } -function createViewWindow(windowId: string, surfaceId: string, socket: string, label: string): ViewWindow { +function createViewWindow( + windowId: string, + surfaceId: string, + view: { socket: string; label: string; glyph: string }, +): ViewWindow { + const { socket, label, glyph } = view; const client = new G2MirrorClient(clientOptions()); const window: ViewWindow = { kind: "view", @@ -378,6 +386,7 @@ function createViewWindow(windowId: string, surfaceId: string, socket: string, l menu: null, socket, label, + glyph, client, emulator: new TerminalEmulator(gridCols, gridRows), receivedData: false, @@ -663,10 +672,36 @@ function openViewWindowFor(session: G2MirrorSession): void { openViewWindow(session.socket, sessionLabel(session)); } +/** + * Lowest unused sidebar-icon character for a new view window (its terminal + * icon shows ">N"). Glyphs free up when their window closes, since usage is + * recomputed from the live windows; "" (plain ">_" icon) if all are taken. + */ +function allocateViewGlyph(): string { + const used = new Set(); + for (const window of windows.values()) { + if (window.kind === "view") used.add(window.glyph); + } + for (const pending of pendingViews.values()) used.add(pending.glyph); + for (const glyph of TERMINAL_ICON_GLYPHS) { + if (!used.has(glyph)) return glyph; + } + return ""; +} + function openViewWindow(socket: string, label: string): void { const windowId = `terminal:view:${nextViewSerial++}`; - pendingViews.set(windowId, { socket, label }); - post({ type: "open-window-request", windowId, title: label, iconLetter: "T", icon: "terminal", focus: true }); + const glyph = allocateViewGlyph(); + pendingViews.set(windowId, { socket, label, glyph }); + post({ + type: "open-window-request", + windowId, + title: label, + iconLetter: "T", + icon: "terminal", + iconGlyph: glyph || undefined, + focus: true, + }); } /** Preset names the user listed in Settings > Terminal (the wire protocol has no way to enumerate the server's). */