- crates/terminal: portable-pty sessions (ConPTY on Windows) with reader, writer and waiter threads, UTF-8 chunking, a 1 MiB output buffer with backpressure, a non-blocking input queue, resize, kill and exit codes; default shell pwsh -> powershell -> cmd on Windows, $SHELL or /bin/sh. - Engine: terminal.create/input/resize/close, terminalOutput (capped per terminal and per pump, round-robin) and terminalExited through the pump; terminals close with the project and on app.quit. - UI: Terminal tab in the bottom panel (tabs next to Find), xterm.js with the fit addon, sub-tabs, copy/paste, a focus rule that leaves plain Ctrl keys to the shell, terminal.open (Mod+Shift+T), --lt-terminal-* ANSI tokens in both themes (text colours AA) and a 4.5:1 minimum contrast. - Tests: real-shell crate tests (UTF-8, backpressure), engine and TCP control tests, Vitest with a mocked xterm; live check on port 7936; docs and parity rows. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
334 lines
11 KiB
TypeScript
334 lines
11 KiB
TypeScript
/**
|
|
* The command store: every command the user can reach, engine and UI, the
|
|
* global keymap built from their default shortcuts, and running commands
|
|
* from the keyboard, the palette and `uiCommand` events.
|
|
*
|
|
* - **List:** `listCommands` from the engine, refreshed when a project opens
|
|
* or closes and whenever the palette opens, plus the UI commands of
|
|
* {@link UI_COMMANDS} (also before the engine lists them).
|
|
* - **Keymap:** one listener on the window in the capture phase, so
|
|
* shortcuts also work while CodeMirror or an input has the focus. A
|
|
* disabled command's shortcut is swallowed and does nothing. While a
|
|
* terminal has the focus, only shortcuts with Mod+Shift or Mod+Alt (any
|
|
* Cmd shortcut on macOS) reach Lutra; the shell gets the others (M3.6,
|
|
* `components/terminal/keys.ts`).
|
|
* - **Handlers:** components supply the behaviour of UI commands and the
|
|
* context of engine commands (the editor runs `file.save` with the active
|
|
* buffer) with {@link useCommandsStore}'s `provide`. Other engine
|
|
* commands run with empty params.
|
|
* - **Errors:** a failed command raises an error toast (M1.12).
|
|
* - **Palette:** running any command but `palette.open` closes the palette
|
|
* first (the modal rule, `modals.ts`); likewise any command but
|
|
* `menu.open` closes the app menu (M3.9).
|
|
*/
|
|
import { defineStore } from "pinia";
|
|
import { computed, ref, shallowReactive } from "vue";
|
|
import { hasMessage, t } from "../i18n";
|
|
import { listCommands, onEngineEvent, run, type CommandInfo, type EngineEventPayload, type JsonValue } from "../ipc";
|
|
import { useNotificationsStore } from "../stores/notifications";
|
|
import { useModalsStore } from "./modals";
|
|
import { shortcutReachesLutra } from "../components/terminal/keys";
|
|
import { buildKeymap, commandFor, formatShortcut, isMac } from "./keymap";
|
|
import { UI_COMMANDS } from "./uiCommands";
|
|
|
|
/** Behaviour a component supplies for a command. */
|
|
export interface CommandHandler {
|
|
/**
|
|
* Runs the command.
|
|
*
|
|
* @param params - the params it was run with (`{}` from the keyboard and
|
|
* the palette, as given in a `uiCommand` event).
|
|
*/
|
|
run: (params: JsonValue) => void | Promise<void>;
|
|
/** Whether it can run now; always when absent. Reactive reads update the palette. */
|
|
enabled?: () => boolean;
|
|
}
|
|
|
|
/** A command as the palette shows it. */
|
|
export interface PaletteEntry {
|
|
/** Command id. */
|
|
id: string;
|
|
/** Label: the catalog text for UI commands, the engine's label otherwise. */
|
|
label: string;
|
|
/** Default shortcut formatted for display, or null. */
|
|
shortcut: string | null;
|
|
/** Whether it can run now. */
|
|
enabled: boolean;
|
|
/** Menu path with `/` separators, or null if the command is in no menu (M3.9). */
|
|
menuPath: string | null;
|
|
/** Whether the frontend runs it (a UI command, label from the catalog). */
|
|
ui: boolean;
|
|
}
|
|
|
|
/** Most recently run commands remembered. */
|
|
export const MAX_RECENT = 20;
|
|
|
|
/** The UI command that opens the app menu, which therefore keeps it open. */
|
|
const MENU_OPEN = "menu.open";
|
|
|
|
/** The UI commands that open the go-to popup, which therefore keep it open. */
|
|
const GOTO_OPEN = new Set(["goto.fileOpen", "goto.classOpen", "goto.symbolOpen"]);
|
|
|
|
/**
|
|
* Reads the command list from the engine, keeping well-formed entries.
|
|
*
|
|
* @param raw - the `listCommands` result.
|
|
*/
|
|
function toCommandInfos(raw: unknown): CommandInfo[] | null {
|
|
if (!Array.isArray(raw)) {
|
|
return null;
|
|
}
|
|
return (raw as unknown[]).filter(
|
|
(c): c is CommandInfo =>
|
|
typeof c === "object" &&
|
|
c !== null &&
|
|
"id" in c &&
|
|
typeof c.id === "string" &&
|
|
"label" in c &&
|
|
typeof c.label === "string",
|
|
);
|
|
}
|
|
|
|
/**
|
|
* The label of a command: the catalog text of its `labelKey` when the
|
|
* catalog has it, else the engine's label.
|
|
*
|
|
* @param info - the command.
|
|
*/
|
|
function labelOf(info: CommandInfo): string {
|
|
return typeof info.labelKey === "string" && hasMessage(info.labelKey) ? t(info.labelKey) : info.label;
|
|
}
|
|
|
|
/** Store of the commands, the keymap and the recently run commands. */
|
|
export const useCommandsStore = defineStore("commands", () => {
|
|
const notifications = useNotificationsStore();
|
|
const modals = useModalsStore();
|
|
/** Commands as the engine lists them; empty until loaded. */
|
|
const infos = ref<CommandInfo[]>([]);
|
|
/** Handlers supplied by components, by command id. */
|
|
const handlers = shallowReactive(new Map<string, CommandHandler>());
|
|
/** Ids of recently run commands, most recent first. */
|
|
const recent = ref<string[]>([]);
|
|
/** Whether `Mod` means Cmd. */
|
|
const mac = isMac();
|
|
/** Ends the engine event subscription; set while started. */
|
|
let unsubscribe: (() => void) | null = null;
|
|
|
|
/** Every command: the engine's list plus UI commands it does not list yet. */
|
|
const all = computed<CommandInfo[]>(() => {
|
|
const listed = new Set(infos.value.map((info) => info.id));
|
|
const local = UI_COMMANDS.filter((spec) => !listed.has(spec.id)).map(
|
|
(spec): CommandInfo => ({
|
|
id: spec.id,
|
|
label: spec.labelKey,
|
|
labelKey: spec.labelKey,
|
|
menuPath: spec.menuPath ?? null,
|
|
defaultShortcut: spec.defaultShortcut ?? null,
|
|
params: "",
|
|
enabled: true,
|
|
ui: true,
|
|
}),
|
|
);
|
|
return [...infos.value, ...local];
|
|
});
|
|
|
|
/** The keymap of every command with a default shortcut. */
|
|
const keymap = computed(() => buildKeymap(all.value, mac));
|
|
|
|
/**
|
|
* Whether a command can run now: its handler decides if it has one; a UI
|
|
* command without a handler cannot run; otherwise the engine's state.
|
|
*
|
|
* @param id - the command id.
|
|
*/
|
|
function isEnabled(id: string): boolean {
|
|
const handler = handlers.get(id);
|
|
if (handler) {
|
|
return handler.enabled?.() ?? true;
|
|
}
|
|
const info = all.value.find((c) => c.id === id);
|
|
return info !== undefined && info.ui !== true && info.enabled;
|
|
}
|
|
|
|
/**
|
|
* The commands the palette offers: UI commands and engine commands that
|
|
* are user actions (they have a menu path or a default shortcut), not
|
|
* the protocol commands clients call with data (`buffer.edit`).
|
|
*/
|
|
const entries = computed<PaletteEntry[]>(() =>
|
|
all.value
|
|
.filter((info) => info.ui === true || info.menuPath !== null || info.defaultShortcut !== null)
|
|
.map((info) => ({
|
|
id: info.id,
|
|
label: labelOf(info),
|
|
shortcut: typeof info.defaultShortcut === "string" ? formatShortcut(info.defaultShortcut, mac) : null,
|
|
enabled: isEnabled(info.id),
|
|
menuPath: typeof info.menuPath === "string" && info.menuPath !== "" ? info.menuPath : null,
|
|
ui: info.ui === true,
|
|
})),
|
|
);
|
|
|
|
/**
|
|
* Supplies the behaviour of a command.
|
|
*
|
|
* @param id - the command id.
|
|
* @param handler - what running it does.
|
|
* @returns a function that withdraws the handler (only if it is still this one).
|
|
*/
|
|
function provide(id: string, handler: CommandHandler): () => void {
|
|
handlers.set(id, handler);
|
|
return () => {
|
|
if (handlers.get(id) === handler) {
|
|
handlers.delete(id);
|
|
}
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Remembers a command as run most recently. Opening the palette itself
|
|
* is not remembered: it would always head the list it opens.
|
|
*
|
|
* @param id - the command id.
|
|
*/
|
|
function remember(id: string): void {
|
|
if (id === "palette.open") {
|
|
return;
|
|
}
|
|
recent.value = [id, ...recent.value.filter((other) => other !== id)].slice(0, MAX_RECENT);
|
|
}
|
|
|
|
/**
|
|
* Runs a command the user chose (keyboard or palette): through its
|
|
* handler if a component supplied one, else through the engine. A
|
|
* disabled command does nothing. A failure raises an error toast. Any
|
|
* command but `palette.open` closes the palette before it runs, any
|
|
* command but the go-to open commands closes the go-to popup, and any
|
|
* command but `menu.open` closes the app menu.
|
|
*
|
|
* @param id - the command id.
|
|
* @param params - the params.
|
|
*/
|
|
async function execute(id: string, params: JsonValue = {}): Promise<void> {
|
|
if (!isEnabled(id)) {
|
|
return;
|
|
}
|
|
remember(id);
|
|
if (id !== "palette.open") {
|
|
modals.dismiss("palette");
|
|
}
|
|
if (!GOTO_OPEN.has(id)) {
|
|
modals.dismiss("goto");
|
|
}
|
|
if (id !== MENU_OPEN) {
|
|
modals.dismiss("menu");
|
|
}
|
|
const handler = handlers.get(id);
|
|
if (handler) {
|
|
try {
|
|
await handler.run(params);
|
|
} catch (reason: unknown) {
|
|
notifications.notifyError(id, {
|
|
code: "internal",
|
|
message: reason instanceof Error ? reason.message : String(reason),
|
|
});
|
|
}
|
|
return;
|
|
}
|
|
const result = await run(id, params);
|
|
if (!result.ok) {
|
|
notifications.notifyError(id, result.error);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Runs a UI command the engine dispatched (`uiCommand`). One without a
|
|
* handler, or disabled now, raises a warning toast instead, so an agent
|
|
* learns that nothing happened.
|
|
*
|
|
* @param id - the command id; unchecked, it comes from the engine.
|
|
* @param params - its params.
|
|
*/
|
|
async function dispatch(id: unknown, params: unknown): Promise<void> {
|
|
const name = typeof id === "string" ? id : String(id);
|
|
const handler = handlers.get(name);
|
|
if (!handler || !(handler.enabled?.() ?? true)) {
|
|
notifications.notify({ level: "warning", message: t("command.unavailable", { command: name }) });
|
|
return;
|
|
}
|
|
await execute(name, (params ?? {}) as JsonValue);
|
|
}
|
|
|
|
/** Loads the command list from the engine; a failure raises an error toast. */
|
|
async function refresh(): Promise<void> {
|
|
const result = await listCommands();
|
|
const list = result.ok ? toCommandInfos(result.value) : null;
|
|
if (list) {
|
|
infos.value = list;
|
|
} else {
|
|
notifications.notifyError(
|
|
"listCommands",
|
|
result.ok
|
|
? { code: "ipc", message: t("common.error.unexpectedResult", { command: "listCommands" }) }
|
|
: result.error,
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Handles an engine event: runs `uiCommand`s and refreshes the enabled
|
|
* states when a project opens or closes.
|
|
*
|
|
* @param event - the engine event.
|
|
*/
|
|
function onEvent(event: EngineEventPayload): void {
|
|
if (event.kind === "uiCommand") {
|
|
void dispatch(event.id, event.params);
|
|
} else if (event.kind === "projectOpened" || event.kind === "projectClosed") {
|
|
void refresh();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Runs the command bound to a key press.
|
|
*
|
|
* @param event - a key press anywhere in the window.
|
|
*/
|
|
function onKeydown(event: KeyboardEvent): void {
|
|
const id = commandFor(keymap.value, event);
|
|
if (id === null || !shortcutReachesLutra(event, isMac())) {
|
|
return;
|
|
}
|
|
event.preventDefault();
|
|
event.stopPropagation();
|
|
void execute(id);
|
|
}
|
|
|
|
/**
|
|
* Starts the keymap and the `uiCommand` subscription, registers the UI
|
|
* commands with the engine and loads the command list. Starting twice is
|
|
* a no-op.
|
|
*/
|
|
async function start(): Promise<void> {
|
|
if (unsubscribe) {
|
|
return;
|
|
}
|
|
unsubscribe = onEngineEvent(onEvent);
|
|
window.addEventListener("keydown", onKeydown, true);
|
|
const registered = await run("ui.registerCommands", {
|
|
commands: UI_COMMANDS.map((spec) => ({ ...spec })),
|
|
});
|
|
if (!registered.ok) {
|
|
notifications.notifyError("ui.registerCommands", registered.error);
|
|
}
|
|
await refresh();
|
|
}
|
|
|
|
/** Stops the keymap and the subscription. */
|
|
function stop(): void {
|
|
window.removeEventListener("keydown", onKeydown, true);
|
|
unsubscribe?.();
|
|
unsubscribe = null;
|
|
}
|
|
|
|
return { infos, recent, keymap, entries, isEnabled, provide, execute, dispatch, refresh, start, stop };
|
|
});
|