import type { Palette } from "./palettes.ts"; export interface RgbColor { r: number; g: number; b: number } export interface TerminalColors { foreground?: RgbColor; background?: RgbColor } export interface TerminalAdapter { queryTerminalColors(options: { timeoutMs: number }): Promise; write(data: string): void; } function isRgb(value: unknown): value is RgbColor { if (!value || typeof value !== "object") return false; const rgb = value as RgbColor; return [rgb.r, rgb.g, rgb.b].every((channel) => Number.isInteger(channel) && channel >= 0 && channel <= 255); } export function oscColor(target: 10 | 11, color: string | RgbColor): string { let rgb: RgbColor; if (typeof color === "string") { if (!/^#[\da-f]{6}$/i.test(color)) throw new Error("Expected a six-digit RGB color"); rgb = { r: Number.parseInt(color.slice(1, 3), 16), g: Number.parseInt(color.slice(3, 5), 16), b: Number.parseInt(color.slice(5, 7), 16) }; } else { if (!isRgb(color)) throw new Error("Invalid terminal RGB color"); rgb = color; } const value = [rgb.r, rgb.g, rgb.b].map((channel) => channel.toString(16).padStart(2, "0")).join("/"); return `\x1b]${target};rgb:${value}\x1b\\`; } /** Owns temporary OSC 10/11 colors, never terminal profile or ANSI palette settings. */ export class TerminalColorManager { private adapter: TerminalAdapter; private warn: (message: string) => void; private original: { foreground: RgbColor; background: RgbColor } | undefined; private desired: Palette | undefined; private pending: { epoch: number; task: Promise } | undefined; private epoch = 0; private applied = false; private appliedKey: string | undefined; private warned = false; private disposed = false; constructor(adapter: TerminalAdapter, warn: (message: string) => void) { this.adapter = adapter; this.warn = warn; } activate(palette: Palette): Promise { if (this.disposed) return Promise.resolve(false); this.desired = palette; if (this.original) return Promise.resolve(this.applyLatest()); if (this.pending?.epoch === this.epoch) return this.pending.task; const pending = { epoch: this.epoch, task: Promise.resolve(false) }; this.pending = pending; pending.task = this.captureOriginal(pending.epoch).finally(() => { if (this.pending === pending) this.pending = undefined; }); return pending.task; } private async captureOriginal(epoch: number): Promise { try { const colors = await this.adapter.queryTerminalColors({ timeoutMs: 250 }); // A newer palette in the same ownership epoch is fine; off/shutdown is not. if (this.disposed || epoch !== this.epoch || !this.desired) return false; if (!isRgb(colors.foreground) || !isRgb(colors.background)) { this.warnOnce("Terminal colors were not reported in time. Keeping the terminal unchanged; theme and input styling still work. Use /theme-trio on to retry."); return false; } this.original = { foreground: { ...colors.foreground }, background: { ...colors.background } }; return this.applyLatest(); } catch { if (!this.disposed && epoch === this.epoch && this.desired) { this.warnOnce("Could not query terminal colors. Keeping the terminal unchanged; theme and input styling still work. Use /theme-trio on to retry."); } return false; } } private applyLatest(): boolean { if (!this.original || !this.desired || this.disposed) return false; const palette = this.desired; const key = `${palette.terminalFg}/${palette.terminalBg}`; if (this.appliedKey === key) return true; try { // Mark ownership before writing so even a failed/partial write can be restored. this.applied = true; this.adapter.write(oscColor(10, palette.terminalFg) + oscColor(11, palette.terminalBg)); this.appliedKey = key; return true; } catch { this.warnOnce("Could not apply terminal colors. Attempting to restore the captured colors; theme and input styling remain available."); this.restore(); return false; } } restore(): void { ++this.epoch; this.desired = undefined; this.pending = undefined; const original = this.original; const applied = this.applied; this.original = undefined; this.applied = false; this.appliedKey = undefined; if (original && applied) { try { this.adapter.write(oscColor(10, original.foreground) + oscColor(11, original.background)); } catch { this.warnOnce("Could not restore terminal colors. Close this terminal tab or reset its color scheme if necessary."); } } } dispose(): void { if (this.disposed) return; this.restore(); this.disposed = true; } private warnOnce(message: string): void { if (this.warned || this.disposed) return; this.warned = true; this.warn(message); } }