import { findPalette } from "./palettes.ts"; import type { Palette } from "./palettes.ts"; export interface SkinHost { getThemeName(): string | undefined; getEditorFactory(): Factory | undefined; setEditorFactory(factory: Factory | undefined): void; requestRender(): void; warn(message: string): void; } export interface TerminalControl { activate(palette: Palette): Promise; restore(): void; dispose(): void; } export interface ControllerOptions { palettes: readonly Palette[]; host: SkinHost; terminal: TerminalControl; factory: Factory; schedule?: (callback: () => void) => void; } /** Host-independent state machine; all UI mutations happen outside rendering. */ export class SkinController { private options: ControllerOptions; private schedule: (callback: () => void) => void; private enabled = true; private disposed = false; private queued = false; private retryRequested = false; private activePalette: Palette | undefined; private ownsEditor = false; private previousFactory: Factory | undefined; private interrupted = false; private warnedEditor = false; private warnedTerminal = false; constructor(options: ControllerOptions) { this.options = options; this.schedule = options.schedule ?? queueMicrotask; } getPalette(): Palette | undefined { if (this.disposed || !this.enabled) return undefined; return findPalette(this.options.palettes, this.options.host.getThemeName()); } observe(): void { if (this.disposed || this.queued) return; this.queued = true; this.schedule(() => { this.queued = false; if (!this.disposed) this.reconcile(); }); } enable(): void { if (this.disposed) return; this.enabled = true; this.interrupted = false; this.retryRequested = true; this.observe(); } disable(): void { if (this.disposed) return; this.enabled = false; this.activePalette = undefined; this.retryRequested = false; // Command callbacks are outside rendering: cancel capture immediately, before // an already-queued OSC reply can apply colors after the user chose off. this.options.terminal.restore(); this.releaseEditor(); this.options.host.requestRender(); this.observe(); } private reconcile(): void { const { host, terminal, factory } = this.options; const palette = this.getPalette(); const changed = palette?.themeName !== this.activePalette?.themeName; const hadPalette = this.activePalette !== undefined; this.activePalette = palette; const retry = this.retryRequested; this.retryRequested = false; if (!palette) { if (hadPalette) terminal.restore(); this.releaseEditor(); this.interrupted = false; if (changed) host.requestRender(); return; } let installed = false; const currentFactory = host.getEditorFactory(); if (this.ownsEditor && currentFactory !== factory) { // Another extension took over; never re-acquire or restore over its editor. this.ownsEditor = false; this.previousFactory = undefined; this.interrupted = true; this.warnEditor("Another extension replaced the editor. Keeping its editor; theme and terminal colors remain active."); } if (!this.ownsEditor && !this.interrupted) { if (currentFactory !== undefined && currentFactory !== factory) { this.interrupted = true; this.warnEditor("A custom editor is already active. Keeping it; theme and terminal colors still apply. Disable the other editor and use /theme-trio on to retry input styling."); } else { this.previousFactory = currentFactory; try { host.setEditorFactory(factory); this.ownsEditor = true; installed = true; } catch { // Pi records the factory before invoking it. Recover a partial install // only if no other extension has replaced that factory in the meantime. try { if (host.getEditorFactory() === factory) host.setEditorFactory(this.previousFactory); } catch { this.warnEditor("Could not restore the input after an editor error. Use /reload; theme and terminal colors remain available."); } this.previousFactory = undefined; this.interrupted = true; this.warnEditor("Could not install the input skin. Theme and terminal colors remain available."); } } } if (changed || retry) { void terminal.activate(palette).catch(() => { if (!this.disposed && !this.warnedTerminal) { this.warnedTerminal = true; host.warn("Terminal color synchronization failed. Input and theme styling remain available."); } }); } if (changed || installed) host.requestRender(); } private releaseEditor(): void { if (!this.ownsEditor) return; const { host, factory } = this.options; const previous = this.previousFactory; this.ownsEditor = false; this.previousFactory = undefined; if (host.getEditorFactory() === factory) host.setEditorFactory(previous); } private warnEditor(message: string): void { if (this.warnedEditor || this.disposed) return; this.warnedEditor = true; this.options.host.warn(message); } dispose(): void { if (this.disposed) return; this.disposed = true; this.activePalette = undefined; try { this.options.terminal.dispose(); } finally { this.releaseEditor(); } } } export interface ThemeCommandHost { mode: string; getThemeName(): string | undefined; select(title: string, items: string[]): Promise; setTheme(name: string): { success: boolean; error?: string }; notify(message: string, level: "info" | "warning" | "error"): void; } export interface SkinCommands { enable(): void; disable(): void } export const COMMAND_USAGE = "Usage: /theme-trio [frappe | dracula | one-monokai | on | off]"; /** Commands are also pure-host adapters, so tests do not import Pi's runtime. */ export async function handleThemeCommand( args: string, palettes: readonly Palette[], controller: SkinCommands, host: ThemeCommandHost, ): Promise { if (host.mode !== "tui") { host.notify("/theme-trio is available in Pi's interactive terminal UI only.", "warning"); return; } const argument = args.trim().toLowerCase(); if (argument === "off") { controller.disable(); host.notify("Input skin and terminal color sync disabled for this session; the Pi palette is unchanged.", "info"); return; } if (argument === "on" && findPalette(palettes, host.getThemeName())) { controller.enable(); return; } let palette: Palette | undefined; if (argument === "" || argument === "on") { const currentName = host.getThemeName(); const items = palettes.map((item) => `${item.label}${item.themeName === currentName ? " (current)" : ""}`); const selection = await host.select("Pi theme trio", items); if (selection === undefined) return; palette = palettes[items.indexOf(selection)]; } else { palette = findPalette(palettes, argument); } if (!palette) { host.notify(COMMAND_USAGE, "warning"); return; } const result = host.setTheme(palette.themeName); if (!result.success) { host.notify(result.error || `Could not select ${palette.label}`, "error"); return; } controller.enable(); }