M3.6: integrated terminal with PTY sessions and xterm.js sub-tabs
- 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>
This commit is contained in:
parent
5fa7f0c8b3
commit
a8daf269fb
45 changed files with 3935 additions and 49 deletions
|
|
@ -8,7 +8,10 @@
|
|||
* {@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.
|
||||
* 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
|
||||
|
|
@ -24,6 +27,7 @@ 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";
|
||||
|
||||
|
|
@ -291,7 +295,7 @@ export const useCommandsStore = defineStore("commands", () => {
|
|||
*/
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
const id = commandFor(keymap.value, event);
|
||||
if (id === null) {
|
||||
if (id === null || !shortcutReachesLutra(event, isMac())) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [
|
|||
{ id: "menu.open", labelKey: "command.menu.open", defaultShortcut: "Alt+M" },
|
||||
{ id: "palette.open", labelKey: "command.palette.open", menuPath: "View/Command Palette", defaultShortcut: "Mod+Shift+P" },
|
||||
{ id: "settings.open", labelKey: "command.settings.open", menuPath: "View/Settings…", defaultShortcut: "Mod+," },
|
||||
{ id: "terminal.open", labelKey: "command.terminal.open", menuPath: "View/Terminal", defaultShortcut: "Mod+Shift+T" },
|
||||
{ id: "view.toggleProjectTree", labelKey: "command.view.toggleProjectTree", menuPath: "View/Project", defaultShortcut: "Mod+1" },
|
||||
{ id: "view.toggleStructure", labelKey: "command.view.toggleStructure", menuPath: "View/Structure", defaultShortcut: "Mod+2" },
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1,9 +1,14 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* The bottom panel of the main window: a tool window docked under the
|
||||
* editor (Find since M2.4; later Problems, Terminal and others). A header
|
||||
* with the title, a collapse/expand button and a close button, the content
|
||||
* slot, and a splitter on the top edge to resize it.
|
||||
* The bottom panel of the main window: tool windows docked under the
|
||||
* editor (Find since M2.4, Terminal since M3.6; later Problems and others).
|
||||
* A header with the title, a collapse/expand button and a close button, the
|
||||
* content slot, and a splitter on the top edge to resize it.
|
||||
*
|
||||
* Tabs (M3.6): with `tabs`, the header shows one tab per tool window
|
||||
* instead of the title; a click (or Left/Right on a focused tab) emits
|
||||
* `update:active`. The owner shows the active tool window's content in the
|
||||
* slot, and closing hides the active one.
|
||||
*
|
||||
* The splitter is dragged with the pointer or moved with Up/Down (Shift for
|
||||
* larger steps) when focused. Collapsed, only the header shows. Height and
|
||||
|
|
@ -12,9 +17,17 @@
|
|||
* what closing means.
|
||||
*/
|
||||
import { ChevronDown, ChevronUp, X } from "@lucide/vue";
|
||||
import { computed } from "vue";
|
||||
import { computed, nextTick, ref } from "vue";
|
||||
import { t } from "../../i18n";
|
||||
|
||||
/** A tab of the bottom panel. */
|
||||
export interface BottomTab {
|
||||
/** Tool window id. */
|
||||
id: string;
|
||||
/** Its title. */
|
||||
title: string;
|
||||
}
|
||||
|
||||
/** Props of the bottom panel. */
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
|
|
@ -28,8 +41,12 @@ const props = withDefaults(
|
|||
maxHeight?: number;
|
||||
/** Whether the panel is expanded (true) or collapsed to its header. */
|
||||
open?: boolean;
|
||||
/** Tool windows shown as tabs in the header; none shows the title. */
|
||||
tabs?: readonly BottomTab[];
|
||||
/** Id of the active tab. */
|
||||
active?: string;
|
||||
}>(),
|
||||
{ height: 240, minHeight: 80, maxHeight: 900, open: true },
|
||||
{ height: 240, minHeight: 80, maxHeight: 900, open: true, tabs: () => [], active: "" },
|
||||
);
|
||||
|
||||
/** Events of the bottom panel. */
|
||||
|
|
@ -40,8 +57,39 @@ const emit = defineEmits<{
|
|||
"update:open": [open: boolean];
|
||||
/** The close button was pressed. */
|
||||
close: [];
|
||||
/** A tab was chosen. */
|
||||
"update:active": [id: string];
|
||||
}>();
|
||||
|
||||
/** The tab list element, to move the focus between tabs. */
|
||||
const tabList = ref<HTMLElement | null>(null);
|
||||
|
||||
/**
|
||||
* Moves between tabs with Left/Right and activates the new one.
|
||||
*
|
||||
* @param event - the key event on a tab.
|
||||
* @param index - the index of that tab.
|
||||
*/
|
||||
async function onTabKey(event: KeyboardEvent, index: number): Promise<void> {
|
||||
const count = props.tabs.length;
|
||||
let next: number;
|
||||
if (event.key === "ArrowRight") {
|
||||
next = (index + 1) % count;
|
||||
} else if (event.key === "ArrowLeft") {
|
||||
next = (index - 1 + count) % count;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
const tab = props.tabs[next];
|
||||
if (!tab) {
|
||||
return;
|
||||
}
|
||||
emit("update:active", tab.id);
|
||||
await nextTick();
|
||||
tabList.value?.querySelectorAll<HTMLElement>("[role=tab]")[next]?.focus();
|
||||
}
|
||||
|
||||
/** Inline style carrying the current height. */
|
||||
const bodyStyle = computed(() => ({ height: `${String(props.height)}px` }));
|
||||
|
||||
|
|
@ -118,7 +166,31 @@ function onSplitterKey(event: KeyboardEvent): void {
|
|||
@keydown="onSplitterKey"
|
||||
/>
|
||||
<header class="bottom-panel__header">
|
||||
<span class="bottom-panel__title">{{ title }}</span>
|
||||
<span
|
||||
v-if="tabs.length === 0"
|
||||
class="bottom-panel__title"
|
||||
>{{ title }}</span>
|
||||
<span
|
||||
v-else
|
||||
ref="tabList"
|
||||
class="bottom-panel__tabs"
|
||||
role="tablist"
|
||||
:aria-label="t('common.toolWindow.bottomTabs')"
|
||||
>
|
||||
<button
|
||||
v-for="(tab, index) in tabs"
|
||||
:key="tab.id"
|
||||
type="button"
|
||||
role="tab"
|
||||
class="bottom-panel__tab"
|
||||
:class="{ 'bottom-panel__tab--active': tab.id === active }"
|
||||
:aria-selected="tab.id === active"
|
||||
:tabindex="tab.id === active ? 0 : -1"
|
||||
:data-test="`bottom-tab-${tab.id}`"
|
||||
@click="emit('update:active', tab.id)"
|
||||
@keydown="onTabKey($event, index)"
|
||||
>{{ tab.title }}</button>
|
||||
</span>
|
||||
<span class="bottom-panel__actions">
|
||||
<button
|
||||
type="button"
|
||||
|
|
@ -188,6 +260,39 @@ function onSplitterKey(event: KeyboardEvent): void {
|
|||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.bottom-panel__tabs {
|
||||
display: inline-flex;
|
||||
align-self: stretch;
|
||||
gap: var(--lt-space-xs, 2px);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.bottom-panel__tab {
|
||||
padding: 0 var(--lt-space-m, 8px);
|
||||
color: var(--lt-fg-muted);
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
background: transparent;
|
||||
border: none;
|
||||
border-bottom: 2px solid transparent;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.bottom-panel__tab:hover {
|
||||
color: var(--lt-fg);
|
||||
}
|
||||
|
||||
.bottom-panel__tab--active {
|
||||
color: var(--lt-fg);
|
||||
border-bottom-color: var(--lt-accent);
|
||||
}
|
||||
|
||||
.bottom-panel__tab:focus-visible {
|
||||
outline: 2px solid var(--lt-accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.bottom-panel__actions {
|
||||
display: inline-flex;
|
||||
gap: var(--lt-space-xs, 2px);
|
||||
|
|
|
|||
|
|
@ -15,10 +15,14 @@
|
|||
* `view.toggleStructure` (`Mod+2`): each shows its tool window, or hides
|
||||
* the left window when that tool window is already shown.
|
||||
*
|
||||
* The bottom panel ({@link BottomPanel}) holds the Find tool window. It
|
||||
* appears with the UI command `find.open` (`Mod+Alt+F`, supplied here so it
|
||||
* works before the panel exists), collapses to its header and closes from
|
||||
* its header; the Find store keeps the results while it is closed.
|
||||
* The bottom panel ({@link BottomPanel}) holds the Find and Terminal tool
|
||||
* windows, as tabs in its header while both are shown. Find appears with
|
||||
* the UI command `find.open` (`Mod+Alt+F`), Terminal with `terminal.open`
|
||||
* (`Mod+Shift+T`, M3.6); both are supplied here so they work before the
|
||||
* panel exists, and each makes its tool window the active tab. The panel
|
||||
* collapses to its header; closing it hides the active tool window (the
|
||||
* other one, if shown, becomes active). The Find store keeps the results
|
||||
* and the Terminal store the running terminals while they are hidden.
|
||||
*
|
||||
* A slim header bar along the top (M3.9) holds the app menu
|
||||
* ({@link AppMenu}); its `header` slot can replace it.
|
||||
|
|
@ -28,7 +32,9 @@ import { computed, onBeforeUnmount, onMounted, ref } from "vue";
|
|||
import { useCommandsStore } from "../../commands/store";
|
||||
import { t } from "../../i18n";
|
||||
import { useFindStore } from "../../stores/find";
|
||||
import { useTerminalStore } from "../../stores/terminal";
|
||||
import FindToolWindow from "../find/FindToolWindow.vue";
|
||||
import TerminalToolWindow from "../terminal/TerminalToolWindow.vue";
|
||||
import ProjectToolWindow from "../project/ProjectToolWindow.vue";
|
||||
import StatusBar from "../StatusBar.vue";
|
||||
import StructureToolWindow from "../structure/StructureToolWindow.vue";
|
||||
|
|
@ -72,19 +78,81 @@ function toggleLeft(tool: LeftTool): void {
|
|||
|
||||
const commands = useCommandsStore();
|
||||
const find = useFindStore();
|
||||
const terminal = useTerminalStore();
|
||||
|
||||
/** Tool windows of the bottom panel. */
|
||||
type BottomTool = "find" | "terminal";
|
||||
/** The bottom tool window last chosen. */
|
||||
const bottomTool = ref<BottomTool>("find");
|
||||
/** Bottom tool windows that are shown, in tab order. */
|
||||
const bottomTools = computed(() => {
|
||||
const tools: { id: BottomTool; title: string }[] = [];
|
||||
if (find.visible) tools.push({ id: "find", title: t("find.toolWindow.title") });
|
||||
if (terminal.visible) tools.push({ id: "terminal", title: t("terminal.toolWindow.title") });
|
||||
return tools;
|
||||
});
|
||||
/** The active bottom tool window: the chosen one if shown, else the first. */
|
||||
const bottomActive = computed<BottomTool | null>(() => {
|
||||
const tools = bottomTools.value;
|
||||
return tools.some((tool) => tool.id === bottomTool.value) ? bottomTool.value : (tools[0]?.id ?? null);
|
||||
});
|
||||
/** Expansion of the panel, kept per tool window by its store. */
|
||||
const bottomOpen = computed({
|
||||
get: () => (bottomActive.value === "terminal" ? terminal.expanded : find.expanded),
|
||||
set: (open: boolean) => {
|
||||
if (bottomActive.value === "terminal") {
|
||||
terminal.expanded = open;
|
||||
} else {
|
||||
find.expanded = open;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Makes a bottom tool window the active tab.
|
||||
*
|
||||
* @param id - the tool window id from the panel.
|
||||
*/
|
||||
function chooseBottom(id: string): void {
|
||||
if (id === "find" || id === "terminal") {
|
||||
bottomTool.value = id;
|
||||
}
|
||||
}
|
||||
|
||||
/** Hides the active bottom tool window. */
|
||||
function closeBottom(): void {
|
||||
if (bottomActive.value === "terminal") {
|
||||
terminal.hide();
|
||||
} else {
|
||||
find.hide();
|
||||
}
|
||||
}
|
||||
|
||||
/** Withdraws the command handlers; filled while mounted. */
|
||||
let withdraw: (() => void)[] = [];
|
||||
|
||||
onMounted(() => {
|
||||
find.start();
|
||||
terminal.start();
|
||||
withdraw = [
|
||||
commands.provide("view.toggleProjectTree", {
|
||||
run: () => {
|
||||
toggleLeft("project");
|
||||
},
|
||||
}),
|
||||
commands.provide("find.open", { run: (params) => find.open(params) }),
|
||||
commands.provide("find.open", {
|
||||
run: (params) => {
|
||||
bottomTool.value = "find";
|
||||
return find.open(params);
|
||||
},
|
||||
}),
|
||||
commands.provide("terminal.open", {
|
||||
run: (params) => {
|
||||
bottomTool.value = "terminal";
|
||||
return terminal.open(params);
|
||||
},
|
||||
enabled: () => commands.isEnabled("terminal.create"),
|
||||
}),
|
||||
commands.provide("view.toggleStructure", {
|
||||
run: () => {
|
||||
toggleLeft("structure");
|
||||
|
|
@ -99,6 +167,7 @@ onBeforeUnmount(() => {
|
|||
}
|
||||
withdraw = [];
|
||||
find.stop();
|
||||
terminal.stop();
|
||||
});
|
||||
</script>
|
||||
|
||||
|
|
@ -156,13 +225,20 @@ onBeforeUnmount(() => {
|
|||
</main>
|
||||
</div>
|
||||
<BottomPanel
|
||||
v-if="find.visible"
|
||||
v-if="bottomActive !== null"
|
||||
v-model:height="bottomHeight"
|
||||
v-model:open="find.expanded"
|
||||
:title="t('find.toolWindow.title')"
|
||||
@close="find.hide()"
|
||||
v-model:open="bottomOpen"
|
||||
:title="bottomTools.find((tool) => tool.id === bottomActive)?.title ?? ''"
|
||||
:tabs="bottomTools.length > 1 ? bottomTools : []"
|
||||
:active="bottomActive"
|
||||
@update:active="chooseBottom"
|
||||
@close="closeBottom"
|
||||
>
|
||||
<FindToolWindow />
|
||||
<FindToolWindow v-show="bottomActive === 'find'" />
|
||||
<TerminalToolWindow
|
||||
v-if="terminal.visible"
|
||||
v-show="bottomActive === 'terminal'"
|
||||
/>
|
||||
</BottomPanel>
|
||||
<StatusBar />
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -52,7 +52,7 @@ const ITEM_ORDER = [
|
|||
"view.toggleProjectTree",
|
||||
"view.toggleStructure",
|
||||
"find.open",
|
||||
"terminal.toggle",
|
||||
"terminal.open",
|
||||
"settings.open",
|
||||
"goto.fileOpen",
|
||||
"goto.classOpen",
|
||||
|
|
|
|||
221
ui/src/components/terminal/TerminalToolWindow.vue
Normal file
221
ui/src/components/terminal/TerminalToolWindow.vue
Normal file
|
|
@ -0,0 +1,221 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* The Terminal tool window (M3.6) in the bottom panel: a strip of sub-tabs,
|
||||
* one per terminal, with a close button each and a button for a new
|
||||
* terminal, above the shown terminal. Every terminal's view stays mounted
|
||||
* while the window is, so switching sub-tabs keeps xterm's screen and
|
||||
* scrollback; collapsing or hiding the panel unmounts them, and the store's
|
||||
* history restores the output when they mount again.
|
||||
*
|
||||
* Sub-tabs are a tab list: Left/Right move between them, Home/End jump,
|
||||
* Delete closes the focused one. An ended terminal's tab is dimmed.
|
||||
*/
|
||||
import { Plus, X } from "@lucide/vue";
|
||||
import { nextTick, ref } from "vue";
|
||||
import { t } from "../../i18n";
|
||||
import { useTerminalStore } from "../../stores/terminal";
|
||||
import TerminalView from "./TerminalView.vue";
|
||||
|
||||
const store = useTerminalStore();
|
||||
/** The tab list element, to move the focus between tabs. */
|
||||
const strip = ref<HTMLElement | null>(null);
|
||||
|
||||
/**
|
||||
* Moves between sub-tabs with the keyboard.
|
||||
*
|
||||
* @param event - the key event on a tab.
|
||||
* @param id - the terminal of that tab.
|
||||
*/
|
||||
async function onTabKey(event: KeyboardEvent, id: number): Promise<void> {
|
||||
const ids = store.tabs.map((tab) => tab.id);
|
||||
const index = ids.indexOf(id);
|
||||
let next: number | undefined;
|
||||
if (event.key === "ArrowRight") {
|
||||
next = ids[(index + 1) % ids.length];
|
||||
} else if (event.key === "ArrowLeft") {
|
||||
next = ids[(index - 1 + ids.length) % ids.length];
|
||||
} else if (event.key === "Home") {
|
||||
next = ids[0];
|
||||
} else if (event.key === "End") {
|
||||
next = ids[ids.length - 1];
|
||||
} else if (event.key === "Delete") {
|
||||
event.preventDefault();
|
||||
await store.close(id);
|
||||
return;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
if (next === undefined) {
|
||||
return;
|
||||
}
|
||||
store.activeId = next;
|
||||
await nextTick();
|
||||
strip.value?.querySelector<HTMLElement>(`[data-terminal-tab="${String(next)}"]`)?.focus();
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="terminal-window"
|
||||
data-test="terminal-window"
|
||||
>
|
||||
<div class="terminal-window__bar">
|
||||
<div
|
||||
ref="strip"
|
||||
class="terminal-window__tabs"
|
||||
role="tablist"
|
||||
:aria-label="t('terminal.tabs.label')"
|
||||
>
|
||||
<span
|
||||
v-for="tab in store.tabs"
|
||||
:key="tab.id"
|
||||
class="terminal-window__tab"
|
||||
:class="{
|
||||
'terminal-window__tab--active': tab.id === store.activeId,
|
||||
'terminal-window__tab--exited': tab.exited,
|
||||
}"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
class="terminal-window__tab-label"
|
||||
:aria-selected="tab.id === store.activeId"
|
||||
:tabindex="tab.id === store.activeId ? 0 : -1"
|
||||
:data-terminal-tab="tab.id"
|
||||
data-test="terminal-tab"
|
||||
@click="store.activate(tab.id)"
|
||||
@keydown="onTabKey($event, tab.id)"
|
||||
>{{ tab.exited ? t('terminal.tab.exited', { title: tab.title }) : tab.title }}</button>
|
||||
<button
|
||||
type="button"
|
||||
class="terminal-window__icon"
|
||||
:title="t('terminal.tab.close', { title: tab.title })"
|
||||
:aria-label="t('terminal.tab.close', { title: tab.title })"
|
||||
data-test="terminal-tab-close"
|
||||
@click="store.close(tab.id)"
|
||||
>
|
||||
<X :size="12" />
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="terminal-window__icon"
|
||||
:title="t('terminal.new')"
|
||||
:aria-label="t('terminal.new')"
|
||||
data-test="terminal-new"
|
||||
@click="store.open({ new: true })"
|
||||
>
|
||||
<Plus :size="14" />
|
||||
</button>
|
||||
</div>
|
||||
<p
|
||||
v-if="store.error !== null"
|
||||
class="terminal-window__error"
|
||||
role="alert"
|
||||
data-test="terminal-error"
|
||||
>
|
||||
{{ t('terminal.error.create', { message: store.error }) }}
|
||||
</p>
|
||||
<div class="terminal-window__views">
|
||||
<TerminalView
|
||||
v-for="tab in store.tabs"
|
||||
v-show="tab.id === store.activeId"
|
||||
:key="tab.id"
|
||||
:terminal-id="tab.id"
|
||||
:active="tab.id === store.activeId"
|
||||
role="tabpanel"
|
||||
:aria-label="tab.title"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.terminal-window {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.terminal-window__bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--lt-space-xs, 2px);
|
||||
flex: none;
|
||||
padding: var(--lt-space-xs, 2px) var(--lt-space-s, 4px);
|
||||
border-bottom: 1px solid var(--lt-border);
|
||||
}
|
||||
|
||||
.terminal-window__tabs {
|
||||
display: flex;
|
||||
gap: var(--lt-space-xs, 2px);
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.terminal-window__tab {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
flex: none;
|
||||
border-radius: var(--lt-radius, 4px);
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
|
||||
.terminal-window__tab--active {
|
||||
color: var(--lt-fg);
|
||||
background: var(--lt-tab-active-bg);
|
||||
}
|
||||
|
||||
.terminal-window__tab--exited .terminal-window__tab-label {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.terminal-window__tab-label {
|
||||
padding: var(--lt-space-xs, 2px) var(--lt-space-s, 4px) var(--lt-space-xs, 2px) var(--lt-space-m, 8px);
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
background: transparent;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.terminal-window__icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: var(--lt-space-xs, 2px);
|
||||
color: var(--lt-fg-muted);
|
||||
background: transparent;
|
||||
border: none;
|
||||
border-radius: var(--lt-radius, 4px);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.terminal-window__icon:hover,
|
||||
.terminal-window__tab-label:hover {
|
||||
color: var(--lt-fg);
|
||||
}
|
||||
|
||||
.terminal-window__tab-label:focus-visible,
|
||||
.terminal-window__icon:focus-visible {
|
||||
outline: 2px solid var(--lt-accent);
|
||||
}
|
||||
|
||||
.terminal-window__error {
|
||||
margin: 0;
|
||||
padding: var(--lt-space-s, 4px) var(--lt-space-m, 8px);
|
||||
color: var(--lt-error);
|
||||
}
|
||||
|
||||
.terminal-window__views {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
background: var(--lt-terminal-bg);
|
||||
}
|
||||
</style>
|
||||
172
ui/src/components/terminal/TerminalView.vue
Normal file
172
ui/src/components/terminal/TerminalView.vue
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* One terminal (M3.6): an xterm.js instance bound to an engine terminal.
|
||||
*
|
||||
* On mount it replays the output the store kept, then writes new output as
|
||||
* it arrives. Keys and pasted text go to the store (`terminal.input`).
|
||||
* The fit addon sizes the terminal to its element whenever the element
|
||||
* changes size (panel splitter, window), and the store reports the size
|
||||
* with `terminal.resize`. Colours, font and size come from the `--lt-*`
|
||||
* tokens and follow `themeChanged`. Copy, paste and which shortcuts reach
|
||||
* Lutra follow the rules in `keys.ts`.
|
||||
*/
|
||||
import { onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||
import { isMac } from "../../commands/keymap";
|
||||
import { onEngineEvent, type EngineEventPayload } from "../../ipc";
|
||||
import { useTerminalStore } from "../../stores/terminal";
|
||||
import { clipboardAction, TERMINAL_ATTRIBUTE } from "./keys";
|
||||
import { createXterm, terminalTheme, type XtermHandle } from "./xterm";
|
||||
|
||||
/** Props of the view. */
|
||||
const props = defineProps<{
|
||||
/** The engine terminal. */
|
||||
terminalId: number;
|
||||
/** Whether this view is the shown sub-tab. */
|
||||
active: boolean;
|
||||
}>();
|
||||
|
||||
const store = useTerminalStore();
|
||||
/** The element xterm renders into. */
|
||||
const host = ref<HTMLElement | null>(null);
|
||||
/** The terminal; null until mounted. */
|
||||
let xterm: XtermHandle | null = null;
|
||||
/** Cleanups to run on unmount. */
|
||||
const cleanups: (() => void)[] = [];
|
||||
|
||||
/** Fits the terminal to its element and reports the size. */
|
||||
function fit(): void {
|
||||
if (!xterm || !props.active) {
|
||||
return;
|
||||
}
|
||||
const size = xterm.fit();
|
||||
if (size) {
|
||||
void store.resize(props.terminalId, size.cols, size.rows);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the clipboard keys; every other key goes to xterm.
|
||||
*
|
||||
* @param event - the key event xterm received.
|
||||
* @returns false when xterm should not handle the key.
|
||||
*/
|
||||
function onKey(event: KeyboardEvent): boolean {
|
||||
const term = xterm?.term;
|
||||
if (!term) {
|
||||
return true;
|
||||
}
|
||||
const action = clipboardAction(event, term.hasSelection(), isMac());
|
||||
if (action === "copy") {
|
||||
event.preventDefault();
|
||||
const text = term.getSelection();
|
||||
if (text !== "") {
|
||||
navigator.clipboard.writeText(text).catch(() => undefined);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return action !== "paste";
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a new theme's tokens.
|
||||
*
|
||||
* @param event - an engine event.
|
||||
*/
|
||||
function onEvent(event: EngineEventPayload): void {
|
||||
if (event.kind === "themeChanged" && xterm && typeof event.tokens === "object") {
|
||||
const tokens = event.tokens;
|
||||
xterm.term.options.theme = terminalTheme((name) => tokens[name] ?? "");
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
const element = host.value;
|
||||
if (!element) {
|
||||
return;
|
||||
}
|
||||
xterm = createXterm(navigator.userAgent.includes("Windows"));
|
||||
const term = xterm.term;
|
||||
term.open(element);
|
||||
term.attachCustomKeyEventHandler(onKey);
|
||||
const { replay, detach } = store.attach(props.terminalId, (data) => {
|
||||
term.write(data);
|
||||
});
|
||||
if (replay !== "") {
|
||||
term.write(replay);
|
||||
}
|
||||
cleanups.push(detach);
|
||||
const typed = term.onData((data) => {
|
||||
store.input(props.terminalId, data);
|
||||
});
|
||||
cleanups.push(() => {
|
||||
typed.dispose();
|
||||
});
|
||||
cleanups.push(onEngineEvent(onEvent));
|
||||
if (typeof ResizeObserver !== "undefined") {
|
||||
const observer = new ResizeObserver(() => {
|
||||
fit();
|
||||
});
|
||||
observer.observe(element);
|
||||
cleanups.push(() => {
|
||||
observer.disconnect();
|
||||
});
|
||||
}
|
||||
fit();
|
||||
if (props.active) {
|
||||
term.focus();
|
||||
}
|
||||
});
|
||||
|
||||
watch(
|
||||
() => [props.active, store.focusRequest] as const,
|
||||
([active]) => {
|
||||
if (active && xterm) {
|
||||
requestAnimationFrame(() => {
|
||||
fit();
|
||||
xterm?.term.focus();
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
for (const fn of cleanups) {
|
||||
fn();
|
||||
}
|
||||
cleanups.length = 0;
|
||||
xterm?.term.dispose();
|
||||
xterm = null;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
ref="host"
|
||||
class="terminal-view"
|
||||
v-bind="{ [TERMINAL_ATTRIBUTE]: '' }"
|
||||
data-test="terminal-view"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.terminal-view {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
min-width: 0;
|
||||
padding: var(--lt-space-xs, 2px) 0 0 var(--lt-space-s, 4px);
|
||||
background: var(--lt-terminal-bg);
|
||||
}
|
||||
|
||||
.terminal-view :deep(.xterm) {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.terminal-view :deep(.xterm .xterm-viewport) {
|
||||
background-color: var(--lt-terminal-bg);
|
||||
}
|
||||
|
||||
.terminal-view :deep(.xterm .composition-view) {
|
||||
color: var(--lt-fg);
|
||||
background: var(--lt-notice-bg);
|
||||
}
|
||||
</style>
|
||||
79
ui/src/components/terminal/keys.ts
Normal file
79
ui/src/components/terminal/keys.ts
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
/**
|
||||
* Keyboard rules of the integrated terminal (M3.6).
|
||||
*
|
||||
* **Focus and shortcut rule:** while a terminal has the focus, keys belong
|
||||
* to the shell. A Lutra shortcut still reaches Lutra when it uses Mod
|
||||
* together with Shift or Alt (`Mod+Shift+P` palette, `Mod+Alt+F` Find,
|
||||
* `Mod+Shift+T` terminal…), or on macOS any Cmd shortcut, since shells get
|
||||
* no Cmd keys. Plain `Ctrl+<key>` and single keys go to the shell, so
|
||||
* `Ctrl+C`, `Ctrl+W`, `Ctrl+P`, `Ctrl+R`, `Ctrl+1`… keep their shell
|
||||
* meaning.
|
||||
*
|
||||
* **Copy and paste:** `Mod+Shift+C` copies the selection, `Mod+Shift+V`
|
||||
* pastes. On Windows and Linux `Ctrl+C` copies when text is selected (and
|
||||
* otherwise interrupts, as the shell expects) and `Ctrl+V` pastes; on macOS
|
||||
* `Cmd+C` and `Cmd+V` do.
|
||||
*/
|
||||
|
||||
/** Attribute on the element that holds a terminal. */
|
||||
export const TERMINAL_ATTRIBUTE = "data-lt-terminal";
|
||||
|
||||
/**
|
||||
* Whether the focus of a key event is inside a terminal.
|
||||
*
|
||||
* @param event - the key event.
|
||||
* @returns true when its target lies in an element with
|
||||
* {@link TERMINAL_ATTRIBUTE}.
|
||||
*/
|
||||
export function inTerminal(event: KeyboardEvent): boolean {
|
||||
const target = event.target;
|
||||
return target instanceof Element && target.closest(`[${TERMINAL_ATTRIBUTE}]`) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a key event that matches a Lutra shortcut should run it, given
|
||||
* the focus rule above.
|
||||
*
|
||||
* @param event - the key event.
|
||||
* @param mac - whether Lutra runs on macOS.
|
||||
* @returns false when a terminal has the focus and the shell should get
|
||||
* the key.
|
||||
*/
|
||||
export function shortcutReachesLutra(event: KeyboardEvent, mac: boolean): boolean {
|
||||
if (!inTerminal(event)) {
|
||||
return true;
|
||||
}
|
||||
if (mac) {
|
||||
return event.metaKey;
|
||||
}
|
||||
return event.ctrlKey && (event.shiftKey || event.altKey);
|
||||
}
|
||||
|
||||
/** What a key in the terminal does with the clipboard. */
|
||||
export type ClipboardAction = "copy" | "paste" | null;
|
||||
|
||||
/**
|
||||
* The clipboard action of a key event in the terminal.
|
||||
*
|
||||
* @param event - the keydown event.
|
||||
* @param hasSelection - whether the terminal has selected text.
|
||||
* @param mac - whether Lutra runs on macOS.
|
||||
* @returns the action, or null when the key goes to the shell.
|
||||
*/
|
||||
export function clipboardAction(event: KeyboardEvent, hasSelection: boolean, mac: boolean): ClipboardAction {
|
||||
if (event.type !== "keydown" || event.altKey) {
|
||||
return null;
|
||||
}
|
||||
const key = event.code;
|
||||
const mod = mac ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey;
|
||||
if (!mod) {
|
||||
return null;
|
||||
}
|
||||
if (key === "KeyC" && (event.shiftKey || hasSelection || mac)) {
|
||||
return "copy";
|
||||
}
|
||||
if (key === "KeyV") {
|
||||
return "paste";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
110
ui/src/components/terminal/xterm.ts
Normal file
110
ui/src/components/terminal/xterm.ts
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
/**
|
||||
* The xterm.js boundary (M3.6): creates a terminal with the fit addon and
|
||||
* maps Lutra's theme tokens onto xterm's theme. Kept apart so that tests
|
||||
* can replace it (`vi.mock`), since jsdom cannot lay xterm out.
|
||||
*/
|
||||
import { FitAddon } from "@xterm/addon-fit";
|
||||
import { Terminal, type ITheme } from "@xterm/xterm";
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
|
||||
/** The parts of an xterm terminal the view uses. */
|
||||
export interface XtermHandle {
|
||||
/** The terminal. */
|
||||
term: Pick<
|
||||
Terminal,
|
||||
| "open"
|
||||
| "write"
|
||||
| "focus"
|
||||
| "dispose"
|
||||
| "onData"
|
||||
| "hasSelection"
|
||||
| "getSelection"
|
||||
| "attachCustomKeyEventHandler"
|
||||
| "options"
|
||||
| "cols"
|
||||
| "rows"
|
||||
>;
|
||||
/** Fits the terminal into its element; returns the new size. */
|
||||
fit: () => { cols: number; rows: number } | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Contrast xterm enforces for every glyph against its background (WCAG AA
|
||||
* for text). Programs often assume a dark background and print ANSI white,
|
||||
* which the light theme keeps light on purpose; xterm darkens such text
|
||||
* until it reaches this ratio.
|
||||
*/
|
||||
export const MINIMUM_CONTRAST = 4.5;
|
||||
|
||||
/** ANSI colour names in xterm's order, as in `--lt-terminal-ansi-<name>`. */
|
||||
export const ANSI_NAMES = ["black", "red", "green", "yellow", "blue", "magenta", "cyan", "white"] as const;
|
||||
|
||||
/**
|
||||
* xterm's theme from Lutra's tokens.
|
||||
*
|
||||
* @param token - reads a token by its full name (`--lt-terminal-bg`);
|
||||
* returns "" for a missing one, which xterm then replaces by its default.
|
||||
* @returns the theme.
|
||||
*/
|
||||
export function terminalTheme(token: (name: string) => string): ITheme {
|
||||
const read = (name: string): string | undefined => {
|
||||
const value = token(`--lt-terminal-${name}`).trim();
|
||||
return value === "" ? undefined : value;
|
||||
};
|
||||
const theme: Record<string, string | undefined> = {
|
||||
background: read("bg"),
|
||||
foreground: read("fg"),
|
||||
cursor: read("cursor"),
|
||||
cursorAccent: read("bg"),
|
||||
selectionBackground: read("selection-bg"),
|
||||
};
|
||||
for (const name of ANSI_NAMES) {
|
||||
theme[name] = read(`ansi-${name}`);
|
||||
theme[`bright${name.charAt(0).toUpperCase()}${name.slice(1)}`] = read(`ansi-bright-${name}`);
|
||||
}
|
||||
return theme;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a token from the document's computed style.
|
||||
*
|
||||
* @param name - the full custom property name.
|
||||
* @returns its value, or "".
|
||||
*/
|
||||
export function documentToken(name: string): string {
|
||||
return getComputedStyle(document.documentElement).getPropertyValue(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a terminal.
|
||||
*
|
||||
* @param windows - whether the shell runs under ConPTY (Windows), which
|
||||
* xterm handles specially when it reflows lines.
|
||||
* @returns the terminal and its fit function.
|
||||
*/
|
||||
export function createXterm(windows: boolean): XtermHandle {
|
||||
const fontSize = Number.parseFloat(documentToken("--lt-font-size-editor"));
|
||||
const term = new Terminal({
|
||||
allowProposedApi: false,
|
||||
cursorBlink: true,
|
||||
minimumContrastRatio: MINIMUM_CONTRAST,
|
||||
scrollback: 5000,
|
||||
fontFamily: documentToken("--lt-font-mono").trim() || "monospace",
|
||||
fontSize: Number.isFinite(fontSize) ? fontSize : 14,
|
||||
theme: terminalTheme(documentToken),
|
||||
...(windows ? { windowsPty: { backend: "conpty" as const } } : {}),
|
||||
});
|
||||
const fitAddon = new FitAddon();
|
||||
term.loadAddon(fitAddon);
|
||||
return {
|
||||
term,
|
||||
fit: () => {
|
||||
const size = fitAddon.proposeDimensions();
|
||||
if (!size || !Number.isFinite(size.cols) || !Number.isFinite(size.rows) || size.cols < 1 || size.rows < 1) {
|
||||
return null;
|
||||
}
|
||||
fitAddon.fit();
|
||||
return { cols: term.cols, rows: term.rows };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -13,6 +13,7 @@
|
|||
"command.menu.open": "Open Main Menu",
|
||||
"command.palette.open": "Command Palette",
|
||||
"command.settings.open": "Settings…",
|
||||
"command.terminal.open": "Terminal",
|
||||
"command.unavailable": "{command} cannot run right now",
|
||||
"command.view.toggleProjectTree": "Show or Hide Project",
|
||||
"command.view.toggleStructure": "Show or Hide Structure",
|
||||
|
|
@ -22,6 +23,7 @@
|
|||
"common.dontSave": "Don't Save",
|
||||
"common.error.unexpectedResult": "unexpected result of {command}",
|
||||
"common.save": "Save",
|
||||
"common.toolWindow.bottomTabs": "Bottom tool windows",
|
||||
"common.toolWindow.collapse": "Collapse {title}",
|
||||
"common.toolWindow.expand": "Expand {title}",
|
||||
"common.toolWindow.hide": "Hide {title}",
|
||||
|
|
@ -162,6 +164,17 @@
|
|||
"structure.kind.trait": "Trait",
|
||||
"structure.toolWindow.title": "Structure",
|
||||
"structure.tree.label": "Declarations of the file",
|
||||
"terminal.error.badAnswer": "The engine answered without a terminal id",
|
||||
"terminal.error.create": "Cannot start a terminal: {message}",
|
||||
"terminal.exited.closed": "Terminal closed",
|
||||
"terminal.exited.code": "Process exited with code {code}",
|
||||
"terminal.new": "New terminal",
|
||||
"terminal.tab.close": "Close {title}",
|
||||
"terminal.tab.exited": "{title} (ended)",
|
||||
"terminal.tab.first": "Local",
|
||||
"terminal.tab.numbered": "Local ({n})",
|
||||
"terminal.tabs.label": "Terminals",
|
||||
"terminal.toolWindow.title": "Terminal",
|
||||
"theme.lutraDark": "Lutra Dark",
|
||||
"theme.lutraLight": "Lutra Light"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -106,6 +106,20 @@ export type EngineEventPayload =
|
|||
symbols: unknown;
|
||||
/** Build time in milliseconds; unchecked. */
|
||||
elapsedMs: unknown;
|
||||
}
|
||||
| {
|
||||
kind: "terminalOutput";
|
||||
/** Terminal from `terminal.create`; unchecked, it comes from the engine. */
|
||||
terminalId: unknown;
|
||||
/** UTF-8 text with escape sequences; unchecked. */
|
||||
data: unknown;
|
||||
}
|
||||
| {
|
||||
kind: "terminalExited";
|
||||
/** Terminal from `terminal.create`; unchecked. */
|
||||
terminalId: unknown;
|
||||
/** Exit code, null when Lutra closed it; unchecked. */
|
||||
code: unknown;
|
||||
};
|
||||
|
||||
/** Callback receiving engine events. */
|
||||
|
|
|
|||
408
ui/src/stores/terminal.ts
Normal file
408
ui/src/stores/terminal.ts
Normal file
|
|
@ -0,0 +1,408 @@
|
|||
/**
|
||||
* The Terminal tool window's state (M3.6): the open terminals (sub-tabs),
|
||||
* their output and the panel's visibility.
|
||||
*
|
||||
* - **Sessions:** `create` runs `terminal.create` (cwd = project root, the
|
||||
* engine's default shell) and adds a tab. Output arrives as
|
||||
* `terminalOutput` events; `terminalExited` marks the tab as ended and
|
||||
* writes a line saying so. Closing a tab runs `terminal.close` for a
|
||||
* running one. The engine closes every terminal with the project, so
|
||||
* `projectClosed` drops the tabs.
|
||||
* - **Output history:** every terminal's output is kept here, at most
|
||||
* {@link HISTORY_CAP} UTF-16 code units per terminal; older output is
|
||||
* dropped from the front (whole event chunks, so an escape sequence may be
|
||||
* cut). A view that mounts (switching tabs, expanding the panel) replays
|
||||
* it, then receives new output through `attach`. Output that arrives
|
||||
* before `terminal.create` answered is kept by id, since events and
|
||||
* command results travel on different channels.
|
||||
* - **Input:** keys go out in order, one `terminal.input` at a time; keys
|
||||
* typed while one is in flight are sent together afterwards.
|
||||
* - **Opening:** `open` (the UI command `terminal.open`) shows the panel,
|
||||
* creates a terminal if none is running (or always with `{new: true}`)
|
||||
* and asks the active view to take the focus.
|
||||
* - **Untrusted input:** event fields are checked; events of unknown shape
|
||||
* are ignored.
|
||||
*/
|
||||
import { defineStore } from "pinia";
|
||||
import { computed, ref } from "vue";
|
||||
import { t } from "../i18n";
|
||||
import { onEngineEvent, run, type EngineEventPayload } from "../ipc";
|
||||
import { useNotificationsStore } from "./notifications";
|
||||
|
||||
/** Most UTF-16 code units of output kept per terminal for replay. */
|
||||
export const HISTORY_CAP = 512 * 1024;
|
||||
|
||||
/** Size a terminal starts with before its view measured itself. */
|
||||
export const DEFAULT_SIZE = { cols: 80, rows: 24 } as const;
|
||||
|
||||
/** One terminal as the tab strip shows it. */
|
||||
export interface TerminalTab {
|
||||
/** Engine terminal id. */
|
||||
id: number;
|
||||
/** Tab label. */
|
||||
title: string;
|
||||
/** Whether the shell ended. */
|
||||
exited: boolean;
|
||||
}
|
||||
|
||||
/** Receives new output of one terminal. */
|
||||
export type TerminalWriter = (data: string) => void;
|
||||
|
||||
/** Output kept for one terminal. */
|
||||
interface History {
|
||||
/** Chunks, oldest first. */
|
||||
chunks: string[];
|
||||
/** Total length of `chunks`. */
|
||||
length: number;
|
||||
}
|
||||
|
||||
/** Input of one terminal waiting to be sent. */
|
||||
interface Outbox {
|
||||
/** Text not sent yet. */
|
||||
pending: string;
|
||||
/** Whether a `terminal.input` is in flight. */
|
||||
busy: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The text written into a terminal when its shell ended.
|
||||
*
|
||||
* @param code - the exit code, or null when Lutra closed it.
|
||||
* @returns the line, dimmed, on a line of its own.
|
||||
*/
|
||||
export function exitLine(code: number | null): string {
|
||||
const text = code === null ? t("terminal.exited.closed") : t("terminal.exited.code", { code });
|
||||
return `\r\n\x1b[2m${text}\x1b[0m\r\n`;
|
||||
}
|
||||
|
||||
/** The terminal store. */
|
||||
export const useTerminalStore = defineStore("terminal", () => {
|
||||
const notifications = useNotificationsStore();
|
||||
|
||||
/** Whether the Terminal tab is in the bottom panel. */
|
||||
const visible = ref(false);
|
||||
/** Whether the panel is expanded while the Terminal tab is active. */
|
||||
const expanded = ref(true);
|
||||
/** Open terminals in tab order. */
|
||||
const tabs = ref<TerminalTab[]>([]);
|
||||
/** The shown terminal, or null without tabs. */
|
||||
const activeId = ref<number | null>(null);
|
||||
/** Counts up whenever the active view should take the focus. */
|
||||
const focusRequest = ref(0);
|
||||
/** The last failed `terminal.create`, shown in the window. */
|
||||
const error = ref<string | null>(null);
|
||||
/** Number of terminals created, for the tab labels. */
|
||||
let created = 0;
|
||||
|
||||
/** Output per terminal id; not reactive, views read it on mount. */
|
||||
const history = new Map<number, History>();
|
||||
/** Views listening for output, per terminal id. */
|
||||
const writers = new Map<number, Set<TerminalWriter>>();
|
||||
/** Pending input per terminal id. */
|
||||
const outboxes = new Map<number, Outbox>();
|
||||
/** Last size sent per terminal id. */
|
||||
const sizes = new Map<number, string>();
|
||||
/** Terminals that ended before their tab existed, with their exit code. */
|
||||
const early = new Map<number, number | null>();
|
||||
/** Ends the event subscription; null while stopped. */
|
||||
let unsubscribe: (() => void) | null = null;
|
||||
|
||||
/** The active tab, if any. */
|
||||
const active = computed(() => tabs.value.find((tab) => tab.id === activeId.value) ?? null);
|
||||
|
||||
/**
|
||||
* Adds output to a terminal's history and hands it to its views.
|
||||
*
|
||||
* @param id - the terminal.
|
||||
* @param data - the text.
|
||||
*/
|
||||
function append(id: number, data: string): void {
|
||||
let kept = history.get(id);
|
||||
if (!kept) {
|
||||
kept = { chunks: [], length: 0 };
|
||||
history.set(id, kept);
|
||||
}
|
||||
kept.chunks.push(data);
|
||||
kept.length += data.length;
|
||||
while (kept.length > HISTORY_CAP && kept.chunks.length > 1) {
|
||||
kept.length -= kept.chunks.shift()?.length ?? 0;
|
||||
}
|
||||
for (const writer of writers.get(id) ?? []) {
|
||||
writer(data);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks a terminal as ended and writes the exit line.
|
||||
*
|
||||
* @param id - the terminal.
|
||||
* @param code - its exit code, or null.
|
||||
*/
|
||||
function ended(id: number, code: number | null): void {
|
||||
const tab = tabs.value.find((candidate) => candidate.id === id);
|
||||
if (!tab) {
|
||||
early.set(id, code);
|
||||
return;
|
||||
}
|
||||
if (tab.exited) {
|
||||
return;
|
||||
}
|
||||
tab.exited = true;
|
||||
outboxes.delete(id);
|
||||
append(id, exitLine(code));
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles engine events: terminal output and exits, and the project
|
||||
* closing.
|
||||
*
|
||||
* @param event - the event; its fields are untrusted.
|
||||
*/
|
||||
function onEvent(event: EngineEventPayload): void {
|
||||
if (event.kind === "terminalOutput") {
|
||||
if (typeof event.terminalId === "number" && typeof event.data === "string" && event.data !== "") {
|
||||
append(event.terminalId, event.data);
|
||||
}
|
||||
} else if (event.kind === "terminalExited") {
|
||||
if (typeof event.terminalId === "number") {
|
||||
ended(event.terminalId, typeof event.code === "number" ? event.code : null);
|
||||
}
|
||||
} else if (event.kind === "projectClosed") {
|
||||
reset();
|
||||
}
|
||||
}
|
||||
|
||||
/** Drops every tab and its output; the engine closed the terminals. */
|
||||
function reset(): void {
|
||||
tabs.value = [];
|
||||
activeId.value = null;
|
||||
visible.value = false;
|
||||
error.value = null;
|
||||
history.clear();
|
||||
outboxes.clear();
|
||||
sizes.clear();
|
||||
early.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a terminal and shows its tab.
|
||||
*
|
||||
* @param size - the size to start with.
|
||||
* @returns the new terminal's id, or null if the engine refused.
|
||||
*/
|
||||
async function create(size: { cols: number; rows: number } = DEFAULT_SIZE): Promise<number | null> {
|
||||
const result = await run<{ terminalId?: unknown }>("terminal.create", { cols: size.cols, rows: size.rows });
|
||||
if (!result.ok) {
|
||||
error.value = result.error.message;
|
||||
return null;
|
||||
}
|
||||
const id = result.value.terminalId;
|
||||
if (typeof id !== "number") {
|
||||
error.value = t("terminal.error.badAnswer");
|
||||
return null;
|
||||
}
|
||||
error.value = null;
|
||||
created += 1;
|
||||
const title = created === 1 ? t("terminal.tab.first") : t("terminal.tab.numbered", { n: created });
|
||||
tabs.value.push({ id, title, exited: false });
|
||||
activeId.value = id;
|
||||
sizes.set(id, `${String(size.cols)}x${String(size.rows)}`);
|
||||
if (early.has(id)) {
|
||||
const code = early.get(id) ?? null;
|
||||
early.delete(id);
|
||||
ended(id, code);
|
||||
}
|
||||
focusRequest.value += 1;
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the Terminal tab: the UI command `terminal.open`. Creates a
|
||||
* terminal when none is running, or always with `{new: true}`.
|
||||
*
|
||||
* @param params - the command params; untrusted.
|
||||
*/
|
||||
async function open(params: unknown = {}): Promise<void> {
|
||||
const p = typeof params === "object" && params !== null && !Array.isArray(params) ? (params as Record<string, unknown>) : {};
|
||||
visible.value = true;
|
||||
expanded.value = true;
|
||||
focusRequest.value += 1;
|
||||
const running = tabs.value.filter((tab) => !tab.exited);
|
||||
if (p.new === true || running.length === 0) {
|
||||
await create();
|
||||
} else if (active.value?.exited !== false) {
|
||||
activeId.value = running[running.length - 1]?.id ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a terminal's tab.
|
||||
*
|
||||
* @param id - the terminal.
|
||||
*/
|
||||
function activate(id: number): void {
|
||||
if (tabs.value.some((tab) => tab.id === id)) {
|
||||
activeId.value = id;
|
||||
focusRequest.value += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes a tab, killing its shell if it still runs. Closing the last tab
|
||||
* hides the Terminal tab.
|
||||
*
|
||||
* @param id - the terminal.
|
||||
*/
|
||||
async function close(id: number): Promise<void> {
|
||||
const index = tabs.value.findIndex((tab) => tab.id === id);
|
||||
const tab = tabs.value[index];
|
||||
if (!tab) {
|
||||
return;
|
||||
}
|
||||
tabs.value.splice(index, 1);
|
||||
history.delete(id);
|
||||
outboxes.delete(id);
|
||||
sizes.delete(id);
|
||||
if (activeId.value === id) {
|
||||
activeId.value = (tabs.value[index] ?? tabs.value[index - 1])?.id ?? null;
|
||||
}
|
||||
if (tabs.value.length === 0) {
|
||||
visible.value = false;
|
||||
}
|
||||
if (!tab.exited) {
|
||||
const result = await run("terminal.close", { terminalId: id });
|
||||
if (!result.ok) {
|
||||
notifications.notifyError("terminal.close", result.error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends keys or pasted text to a terminal, in order.
|
||||
*
|
||||
* @param id - the terminal.
|
||||
* @param data - the text from xterm.js.
|
||||
*/
|
||||
function input(id: number, data: string): void {
|
||||
const tab = tabs.value.find((candidate) => candidate.id === id);
|
||||
if (!tab || tab.exited || data === "") {
|
||||
return;
|
||||
}
|
||||
let box = outboxes.get(id);
|
||||
if (!box) {
|
||||
box = { pending: "", busy: false };
|
||||
outboxes.set(id, box);
|
||||
}
|
||||
box.pending += data;
|
||||
void flush(id, box);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a terminal's pending input unless a send is in flight, and keeps
|
||||
* sending until nothing is pending. A refused input raises an error toast
|
||||
* unless the terminal ended meanwhile.
|
||||
*
|
||||
* @param id - the terminal.
|
||||
* @param box - its outbox.
|
||||
*/
|
||||
async function flush(id: number, box: Outbox): Promise<void> {
|
||||
if (box.busy) {
|
||||
return;
|
||||
}
|
||||
box.busy = true;
|
||||
while (box.pending !== "" && outboxes.get(id) === box) {
|
||||
const data = box.pending;
|
||||
box.pending = "";
|
||||
const result = await run("terminal.input", { terminalId: id, data });
|
||||
if (!result.ok && outboxes.get(id) === box) {
|
||||
notifications.notifyError("terminal.input", result.error);
|
||||
}
|
||||
}
|
||||
box.busy = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells the engine a terminal's new size; repeated sizes are skipped.
|
||||
*
|
||||
* @param id - the terminal.
|
||||
* @param cols - columns, at least 1.
|
||||
* @param rows - rows, at least 1.
|
||||
*/
|
||||
async function resize(id: number, cols: number, rows: number): Promise<void> {
|
||||
const tab = tabs.value.find((candidate) => candidate.id === id);
|
||||
const c = Math.max(1, Math.min(1000, Math.floor(cols)));
|
||||
const r = Math.max(1, Math.min(1000, Math.floor(rows)));
|
||||
const key = `${String(c)}x${String(r)}`;
|
||||
if (!tab || tab.exited || sizes.get(id) === key || !Number.isFinite(cols) || !Number.isFinite(rows)) {
|
||||
return;
|
||||
}
|
||||
sizes.set(id, key);
|
||||
const result = await run("terminal.resize", { terminalId: id, cols: c, rows: r });
|
||||
if (!result.ok) {
|
||||
sizes.delete(id);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects a view to a terminal's output.
|
||||
*
|
||||
* @param id - the terminal.
|
||||
* @param writer - receives new output.
|
||||
* @returns the output so far, for the view to replay, and a function
|
||||
* that disconnects the view.
|
||||
*/
|
||||
function attach(id: number, writer: TerminalWriter): { replay: string; detach: () => void } {
|
||||
let set = writers.get(id);
|
||||
if (!set) {
|
||||
set = new Set();
|
||||
writers.set(id, set);
|
||||
}
|
||||
set.add(writer);
|
||||
const replay = (history.get(id)?.chunks ?? []).join("");
|
||||
return {
|
||||
replay,
|
||||
detach: () => {
|
||||
set.delete(writer);
|
||||
if (set.size === 0) {
|
||||
writers.delete(id);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Hides the Terminal tab; terminals keep running. */
|
||||
function hide(): void {
|
||||
visible.value = false;
|
||||
}
|
||||
|
||||
/** Starts listening to terminal events. Starting twice is a no-op. */
|
||||
function start(): void {
|
||||
unsubscribe ??= onEngineEvent(onEvent);
|
||||
}
|
||||
|
||||
/** Stops listening. */
|
||||
function stop(): void {
|
||||
unsubscribe?.();
|
||||
unsubscribe = null;
|
||||
}
|
||||
|
||||
return {
|
||||
visible,
|
||||
expanded,
|
||||
tabs,
|
||||
activeId,
|
||||
active,
|
||||
focusRequest,
|
||||
error,
|
||||
create,
|
||||
open,
|
||||
activate,
|
||||
close,
|
||||
input,
|
||||
resize,
|
||||
attach,
|
||||
hide,
|
||||
start,
|
||||
stop,
|
||||
};
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue