Make Terminal a native feature
- Move the Terminal plugin into src/lib/features/terminal/ on the host Svelte runtime, with xterm 6.0.0 and addon-fit 0.11.0. - Buttons, shortcuts, Help rows, and the close guard follow the Terminal switch. The first use loads the module. - Add Settings → Terminal and the terminal settings section. The first start copies the old runestone.terminal key. - The 16 ANSI colors come from the --rs-ansi-* tokens. - Off asks first when a shell runs in any window (pty_running). - Rust: no pty-data or pty-exit events, an owner check for write, resize, and close, output joined up to 64 KiB or 8 ms, and the sessions of a reloaded page close. - Remove api.pty, the terminal contribution, TerminalSlot, and the plugin loader of the smoke harness. - Check only the tested switches in the Background smoke test. - Update the tests, the menu inventory, the docs, and UI-058.
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
<script lang="ts">
|
||||
// The place of the terminal panel in the workbench and in the terminal window. It is in the main bundle.
|
||||
// The first mount loads the Terminal feature (xterm included). An unmount closes the sessions of this panel.
|
||||
import { onMount } from "svelte";
|
||||
import { t } from "$lib/i18n";
|
||||
import { terminalInstance, type TerminalAction, type TerminalMount, type TerminalProps } from "./terminalHost";
|
||||
let props: TerminalProps = $props();
|
||||
let container: HTMLDivElement;
|
||||
let mounted = $state.raw<TerminalMount>();
|
||||
let loading = $state(true);
|
||||
let error = $state("");
|
||||
let ready: Promise<TerminalMount | undefined> = Promise.resolve(undefined);
|
||||
onMount(() => {
|
||||
let disposed = false;
|
||||
ready = terminalInstance().then(instance => {
|
||||
if (disposed) return undefined;
|
||||
mounted = instance.mountDock(container, { ...props });
|
||||
return mounted;
|
||||
}).catch(reason => { if (!disposed) error = String(reason); return undefined; }).finally(() => { loading = false; });
|
||||
return () => {
|
||||
disposed = true;
|
||||
const current = mounted;
|
||||
mounted = undefined;
|
||||
void current?.dispose().catch(reason => console.error("The terminal panel did not close cleanly.", reason));
|
||||
};
|
||||
});
|
||||
$effect(() => { mounted?.update({ ...props }); });
|
||||
/** Run a terminal action. It waits for the first load. */
|
||||
export async function command(action: Exclude<TerminalAction, "toggle">) { await (await ready)?.command(action); }
|
||||
</script>
|
||||
{#if error}<p class="error" role="alert">{$t("The terminal could not start: {error}", { error })}</p>{/if}
|
||||
{#if loading}<p class="loading">{$t("Loading the terminal…")}</p>{/if}
|
||||
<div class="terminal-host" bind:this={container}></div>
|
||||
<style>
|
||||
.terminal-host { display: flex; flex-direction: column; flex: 1; height: 100%; min-height: 0; min-width: 0; }
|
||||
.error, .loading { margin: 0; padding: 7px 12px; font-size: 12px; }
|
||||
.error { color: var(--rs-error); }
|
||||
.loading { color: var(--rs-text-dim); }
|
||||
</style>
|
||||
@@ -0,0 +1,113 @@
|
||||
<!--
|
||||
Settings → Terminal. It is in the main bundle and loads no feature code, so it does not load xterm.
|
||||
It shows only while Terminal is on. Each change saves at once to the `terminal` section, and open terminals take it.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { onDestroy, onMount } from "svelte";
|
||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import { t, tr } from "$lib/i18n";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import { showActionMenu } from "$lib/ui/managedActionMenu";
|
||||
import { FONT_SIZE, SCROLLBACK, onTerminalChange, readTerminal, writeTerminal, type TerminalSettings } from "./terminalSettings";
|
||||
|
||||
type Profile = { id: string; title: string; kind: string };
|
||||
const initial = readTerminal();
|
||||
let settings = $state<TerminalSettings>(initial);
|
||||
let fontSize = $state<number | undefined>(initial.fontSize);
|
||||
let scrollback = $state<number | undefined>(initial.scrollback);
|
||||
let profiles = $state<Profile[]>([]);
|
||||
let profileNote = $state("");
|
||||
let message = $state("");
|
||||
let error = $state("");
|
||||
let closeMenu = () => {};
|
||||
/** The shells that a new terminal can use. The Node.js debug terminal is not a default. */
|
||||
const shells = $derived(profiles.filter(profile => profile.kind !== "node"));
|
||||
const current = $derived(shells.find(profile => profile.id === settings.defaultProfile) ?? shells[0]);
|
||||
|
||||
function read() {
|
||||
settings = readTerminal();
|
||||
fontSize = settings.fontSize;
|
||||
scrollback = settings.scrollback;
|
||||
}
|
||||
function save(next: TerminalSettings) {
|
||||
error = "";
|
||||
settings = next;
|
||||
writeTerminal(next).then(() => { message = tr("Changes saved."); })
|
||||
.catch(() => { error = tr("Could not save these settings. Your previous settings still apply. Try again."); message = ""; });
|
||||
}
|
||||
function changeNumber(value: number | undefined, range: { min: number; max: number }, key: "fontSize" | "scrollback") {
|
||||
if (typeof value !== "number" || !Number.isInteger(value) || value < range.min || value > range.max) {
|
||||
error = tr("Choose a whole number from {min} to {max}.", { min: range.min.toLocaleString(), max: range.max.toLocaleString() });
|
||||
message = "";
|
||||
return;
|
||||
}
|
||||
save({ ...settings, [key]: value });
|
||||
}
|
||||
function profileMenu(event: MouseEvent) {
|
||||
closeMenu();
|
||||
const anchor = event.currentTarget as HTMLButtonElement;
|
||||
const bounds = anchor.getBoundingClientRect();
|
||||
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: tr("Default terminal profile"), parent: anchor.closest("dialog") ?? undefined,
|
||||
items: shells.map(profile => ({ label: profile.title, icon: "code", radio: true, checked: current?.id === profile.id,
|
||||
run: () => save({ ...settings, defaultProfile: profile.id }) })) }).close;
|
||||
}
|
||||
onMount(() => {
|
||||
const stop = onTerminalChange(read);
|
||||
if (!isTauri()) profileNote = tr("The desktop app lists the installed shells.");
|
||||
else invoke<Profile[]>("pty_profiles").then(found => {
|
||||
profiles = found;
|
||||
if (!found.some(profile => profile.kind !== "node")) profileNote = tr("RuneStone found no supported shells on PATH.");
|
||||
}).catch(reason => { profileNote = tr("RuneStone could not list the shells: {error}", { error: String(reason) }); });
|
||||
return stop;
|
||||
});
|
||||
onDestroy(() => closeMenu());
|
||||
</script>
|
||||
|
||||
<div class="terminal-settings">
|
||||
<h2>{$t("Terminal")}</h2>
|
||||
<p class="intro">{$t("Font, scrollback, and cursor apply to open terminals. The default profile applies to new terminals.")}</p>
|
||||
<div class="card">
|
||||
<div class="setting-row">
|
||||
<div><span class="name" id="terminal-profile-label">{$t("Default profile")}</span><p id="terminal-profile-description">{profileNote || $t("The shell of a new terminal.")}</p></div>
|
||||
<button class="picker" type="button" aria-label={$t("Default profile")} aria-describedby="terminal-profile-description" aria-haspopup="menu" disabled={!shells.length} onclick={profileMenu}>
|
||||
{current?.title ?? $t("No shell")}<Icon icon="chevron-down" />
|
||||
</button>
|
||||
</div>
|
||||
<div class="setting-row">
|
||||
<div><label for="terminal-font-size">{$t("Font size")}</label><p id="terminal-font-description">{$t("From {min} to {max} pixels.", { min: FONT_SIZE.min, max: FONT_SIZE.max })}</p></div>
|
||||
<input id="terminal-font-size" type="number" min={FONT_SIZE.min} max={FONT_SIZE.max} step="1" required aria-describedby="terminal-font-description" bind:value={fontSize} onchange={() => changeNumber(fontSize, FONT_SIZE, "fontSize")} />
|
||||
</div>
|
||||
<div class="setting-row">
|
||||
<div><label for="terminal-scrollback">{$t("Scrollback lines")}</label><p id="terminal-scrollback-description">{$t("The lines that a terminal keeps above the screen, from {min} to {max}.", { min: SCROLLBACK.min.toLocaleString(), max: SCROLLBACK.max.toLocaleString() })}</p></div>
|
||||
<input id="terminal-scrollback" type="number" min={SCROLLBACK.min} max={SCROLLBACK.max} step="100" required aria-describedby="terminal-scrollback-description" bind:value={scrollback} onchange={() => changeNumber(scrollback, SCROLLBACK, "scrollback")} />
|
||||
</div>
|
||||
<div class="setting-row">
|
||||
<div><label for="terminal-cursor-blink">{$t("Blink cursor")}</label><p id="terminal-blink-description">{$t("The cursor blinks in the focused terminal.")}</p></div>
|
||||
<input id="terminal-cursor-blink" class="rs-switch" type="checkbox" role="switch" aria-describedby="terminal-blink-description" checked={settings.cursorBlink} onchange={event => save({ ...settings, cursorBlink: event.currentTarget.checked })} />
|
||||
</div>
|
||||
</div>
|
||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||
<p class="saved" role="status">{message}</p>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.terminal-settings { min-width: 0; }
|
||||
h2 { margin: 0; font-size: var(--rs-settings-heading-size); font-weight: 600; color: var(--rs-text-strong); }
|
||||
p { margin: 0; color: var(--rs-text-dim); line-height: 1.45; overflow-wrap: anywhere; }
|
||||
.intro { margin: 6px 0 var(--rs-settings-section-gap); }
|
||||
.card { padding: 0 12px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||
.setting-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px 16px; padding: var(--rs-settings-row-padding) 0; }
|
||||
.setting-row > div:first-child { flex: 1 1 200px; min-width: 0; }
|
||||
.setting-row + .setting-row { border-top: 1px solid var(--rs-border); }
|
||||
.setting-row label, .name { font-weight: 500; color: var(--rs-text); }
|
||||
.setting-row p { margin-top: 3px; font-size: var(--rs-settings-description-size); }
|
||||
input[type=number], .picker { min-height: var(--rs-settings-control-height); box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||
input[type=number] { width: 96px; }
|
||||
.picker { display: inline-flex; align-items: center; justify-content: space-between; gap: var(--rs-settings-gap); max-width: 100%; min-width: 160px; text-align: left; cursor: pointer; }
|
||||
.picker:not(:disabled):hover { background: var(--rs-bg-active); }
|
||||
.picker:disabled { color: var(--rs-text-dim); cursor: default; }
|
||||
.picker :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
|
||||
:is(.picker, input):focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||
.saved { font-size: 12px; color: var(--rs-ok); min-height: 20px; margin-top: 10px; }
|
||||
.error { color: var(--rs-error); margin-top: 10px; }
|
||||
</style>
|
||||
@@ -4,7 +4,7 @@
|
||||
import { message, tr } from "../i18n/index.ts";
|
||||
import type { PluginCommand, PluginView } from "../plugins/sdk.ts";
|
||||
|
||||
export type FeatureId = "git" | "background";
|
||||
export type FeatureId = "git" | "background" | "terminal";
|
||||
|
||||
/** A view of a feature. The workbench shows it as a tab or in the side pane, as it shows a plugin view. */
|
||||
export interface FeatureViewInfo {
|
||||
@@ -69,6 +69,16 @@ export const FEATURES: readonly FeatureEntry[] = [
|
||||
{ id: "pause", title: () => tr("Pause background"), icon: "pause" },
|
||||
],
|
||||
},
|
||||
{
|
||||
// Terminal replaces the Terminal plugin. Its panel is not a view: the workbench and the terminal window show it
|
||||
// (`src/lib/features/TerminalHost.svelte`), and the first use loads the module. Its settings are in Settings → Terminal.
|
||||
id: "terminal", owner: "runestone.terminal", name: message("Terminal"),
|
||||
description: message("Run shells, tasks, and the active file in a panel below the editor or in a separate window."),
|
||||
keywords: "terminal shell console powershell bash cmd command prompt task run pty xterm",
|
||||
defaultOn: true, followsPackage: true,
|
||||
views: [],
|
||||
commands: [],
|
||||
},
|
||||
];
|
||||
|
||||
export function featureEntry(id: FeatureId): FeatureEntry {
|
||||
|
||||
@@ -7,6 +7,7 @@ import type { FeatureModule } from "./types.ts";
|
||||
const imports: Record<FeatureId, () => Promise<FeatureModule>> = {
|
||||
git: () => import("./git/index.ts"),
|
||||
background: () => import("./background/index.ts"),
|
||||
terminal: () => import("./terminal/index.ts"),
|
||||
};
|
||||
|
||||
const modules = new Map<FeatureId, Promise<FeatureModule>>();
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
// The first start of a version with a new native feature. The switch takes the state of the old plugin package,
|
||||
// or the default of the feature when the feature does not follow its package (`followsPackage`).
|
||||
// `features_legacy` in `src-tauri/src/features.rs` reads the old package state and its kept settings. It changes nothing.
|
||||
// The first start also makes the `background` section from the old Background Slideshow settings (`backgroundSettings.ts`).
|
||||
// The first start also makes the `background` section from the old Background Slideshow settings (`backgroundSettings.ts`),
|
||||
// and the `terminal` section from the localStorage key of the Terminal plugin (`terminalSettings.ts`).
|
||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import { readSection, writeSection } from "../settings/store.ts";
|
||||
import { readAppearance } from "../theme/appearance.ts";
|
||||
import { FEATURES, featureEntry, type FeatureEntry, type FeatureId } from "./catalog.ts";
|
||||
import { storedSwitches } from "./state.ts";
|
||||
import { hasImage, migrateBackground, writeBackground, type BackgroundMigrationHost } from "./backgroundSettings.ts";
|
||||
import { LEGACY_TERMINAL_KEY, migrateTerminal, writeTerminal, type TerminalMigrationHost } from "./terminalSettings.ts";
|
||||
|
||||
/** What the host reports about one old plugin package. */
|
||||
export interface LegacyPlugin {
|
||||
@@ -42,11 +44,21 @@ const desktopBackground: BackgroundMigrationHost = {
|
||||
write: writeBackground,
|
||||
};
|
||||
|
||||
const desktopTerminal: TerminalMigrationHost = {
|
||||
missing: () => readSection("terminal") === undefined,
|
||||
legacy: () => localStorage.getItem(LEGACY_TERMINAL_KEY),
|
||||
write: writeTerminal,
|
||||
};
|
||||
|
||||
/**
|
||||
* Give each feature without a stored switch the state of its old package, and make a missing `background` section.
|
||||
* Give each feature without a stored switch the state of its old package, and make a missing `background` or `terminal` section.
|
||||
* It runs before the first render. When the host cannot report the packages, nothing is written, so the next start tries again.
|
||||
* The `terminal` section needs no package report, so it migrates also then.
|
||||
*/
|
||||
export async function migrateFeatures(host: MigrationHost = desktopHost, background: BackgroundMigrationHost = desktopBackground): Promise<FeatureId[]> {
|
||||
export async function migrateFeatures(host: MigrationHost = desktopHost, background: BackgroundMigrationHost = desktopBackground,
|
||||
terminal: TerminalMigrationHost = desktopTerminal): Promise<FeatureId[]> {
|
||||
try { await migrateTerminal(terminal); }
|
||||
catch (reason) { console.error("RuneStone could not copy the old terminal settings.", reason); }
|
||||
const current = host.read();
|
||||
const stored = storedSwitches(current);
|
||||
const missing = FEATURES.filter(entry => stored[entry.id] === undefined);
|
||||
|
||||
@@ -68,6 +68,9 @@ export class FeatureSession {
|
||||
/** Load the module and start the instance now, without a view. Later calls use the same instance. */
|
||||
async start(): Promise<void> { await this.running(); }
|
||||
|
||||
/** The instance of this window, for a feature with a surface that is not a view, such as the terminal panel. */
|
||||
loadInstance(): Promise<FeatureInstance> { return this.running(); }
|
||||
|
||||
/** True after the instance started. */
|
||||
get started(): boolean { return this.instance !== undefined; }
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<script lang="ts">
|
||||
// Keeps the panel props as state, so `update` from the host reaches the panel.
|
||||
import { untrack } from "svelte";
|
||||
import type { TerminalAction, TerminalProps } from "../terminalHost";
|
||||
import type { TerminalSessions } from "./sessions";
|
||||
import TerminalDock from "./TerminalDock.svelte";
|
||||
let { initial, sessions }: { initial: TerminalProps; sessions: TerminalSessions } = $props();
|
||||
let dockProps = $state<TerminalProps>(untrack(() => initial));
|
||||
let dock: TerminalDock;
|
||||
export function update(value: TerminalProps) { dockProps = value; }
|
||||
export async function command(action: Exclude<TerminalAction, "toggle">) { await dock.command(action); }
|
||||
</script>
|
||||
<TerminalDock bind:this={dock} {...dockProps} {sessions} />
|
||||
@@ -0,0 +1,290 @@
|
||||
<script lang="ts">
|
||||
// The terminal panel: a ribbon, the panes of the active group side by side, and a session rail when more than one session runs.
|
||||
// A split adds a pane to the group of the active session. Close ends all sessions of the panel, and the next show starts a new one.
|
||||
import { onMount, tick, untrack } from "svelte";
|
||||
import { t, tr } from "$lib/i18n";
|
||||
import IconButton from "$lib/ui/IconButton.svelte";
|
||||
import { showActionMenu, type MenuHandle } from "$lib/ui/managedActionMenu";
|
||||
import type { ActionMenuItem } from "$lib/ui/actionMenu";
|
||||
import { keys } from "$lib/ui/shortcuts";
|
||||
import { workspaceRead } from "$lib/workspace/api";
|
||||
import { TERMINAL_KEYS, type TerminalAction } from "../terminalKeys";
|
||||
import { onTerminalChange, readTerminal, writeTerminal, type TerminalSettings } from "../terminalSettings";
|
||||
import type { TerminalProps } from "../terminalHost";
|
||||
import { directoryCommand, fileCommand, parseTasks, pickProfile, remember, type ShellProfile, type TerminalControl } from "./model";
|
||||
import type { TerminalSessions } from "./sessions";
|
||||
import TerminalPicker from "./TerminalPicker.svelte";
|
||||
import TerminalPane, { type PaneState } from "./TerminalPane.svelte";
|
||||
|
||||
type Session = { id: string; group: string; title: string; state: PaneState; profile: ShellProfile; directory: string; weight: number; command?: string };
|
||||
type Picker = { title: string; items: { label: string; detail?: string; value: string }[]; onPick: (value: string) => void; empty?: string };
|
||||
let { cwd, visible, maximized = false, standalone = false, onClose, onMaximize = () => {}, activeFile = false, onRunFile, getSelection = () => "", onConfigureTasks, onOpenSettings, sessions: shells }:
|
||||
TerminalProps & { sessions: TerminalSessions } = $props();
|
||||
let sessions = $state<Session[]>([]);
|
||||
let profiles = $state<ShellProfile[]>([]);
|
||||
let settings = $state<TerminalSettings>(readTerminal());
|
||||
let activeId = $state("");
|
||||
let loading = $state(true);
|
||||
let error = $state("");
|
||||
let railWidth = $state(205);
|
||||
let picker = $state<Picker | null>(null);
|
||||
let closing = $state(false);
|
||||
let restartOnShow = false;
|
||||
let recentCommands = $state<string[]>([]);
|
||||
let recentDirectories = $state<string[]>([]);
|
||||
let menu: MenuHandle | undefined;
|
||||
let menuAnchor: HTMLElement | undefined;
|
||||
let profileAnchor: HTMLDivElement;
|
||||
let moreAnchor: HTMLDivElement;
|
||||
let panes: HTMLDivElement;
|
||||
let sequence = 0;
|
||||
let stopResize: (() => void) | undefined;
|
||||
let ready: Promise<void> = Promise.resolve();
|
||||
const controls = new Map<string, TerminalControl>();
|
||||
const active = $derived(sessions.find(session => session.id === activeId));
|
||||
const group = $derived(sessions.filter(session => session.group === active?.group));
|
||||
const totalWeight = $derived(group.reduce((sum, session) => sum + session.weight, 0));
|
||||
|
||||
function report(reason: unknown) { error = String(reason); }
|
||||
function stateLabel(state: PaneState) {
|
||||
if (state.kind === "exited") return state.code === null ? $t("Exited") : $t("Exited ({code})", { code: state.code });
|
||||
if (state.kind === "starting") return $t("Starting");
|
||||
return state.kind === "running" ? $t("Running") : $t("Failed");
|
||||
}
|
||||
function defaultProfile() { return pickProfile(profiles, settings.defaultProfile); }
|
||||
export function addSession(profile = defaultProfile(), split = false, command?: string, title?: string) {
|
||||
if (!profile || closing) return;
|
||||
const id = crypto.randomUUID();
|
||||
const next: Session = { id, group: split && active ? active.group : id, title: title || `${profile.title} ${++sequence}`, state: { kind: "starting" }, profile,
|
||||
directory: split && active ? active.directory : cwd, weight: 1, command };
|
||||
if (split) for (const member of group) member.weight = 1;
|
||||
sessions = [...sessions, next]; activeId = id;
|
||||
recentDirectories = remember(recentDirectories, next.directory);
|
||||
}
|
||||
function killSession(id: string) {
|
||||
const previous = sessions.findIndex(session => session.id === id);
|
||||
const sibling = sessions.find(session => session.group === sessions[previous]?.group && session.id !== id);
|
||||
sessions = sessions.filter(session => session.id !== id);
|
||||
if (activeId === id) activeId = sibling?.id || sessions[Math.max(0, previous - 1)]?.id || "";
|
||||
void tick().then(() => controls.get(activeId)?.focus());
|
||||
}
|
||||
async function closeDock() {
|
||||
if (closing) return;
|
||||
closing = true;
|
||||
closeMenu(); picker = null;
|
||||
try {
|
||||
await ready;
|
||||
// Mount the pending panes before their sessions close.
|
||||
await tick();
|
||||
const results = await Promise.allSettled(sessions.map(session => shells.close(session.id)));
|
||||
const failures = results.filter(result => result.status === "rejected");
|
||||
if (failures.length) throw new Error(failures.map(result => String(result.reason)).join("\n"));
|
||||
sessions = []; activeId = "";
|
||||
restartOnShow = true;
|
||||
onClose();
|
||||
} catch (reason) { report(reason); }
|
||||
finally { closing = false; }
|
||||
}
|
||||
function select(id: string) { activeId = id; }
|
||||
function closeMenu() { menu?.close(); menu = undefined; }
|
||||
function showMenu(anchor: HTMLElement, items: ActionMenuItem[], name: string) {
|
||||
const same = menu?.open && menuAnchor === anchor;
|
||||
closeMenu(); if (same) return;
|
||||
menuAnchor = anchor;
|
||||
const bounds = anchor.getBoundingClientRect();
|
||||
menu = showActionMenu({ x: bounds.right - 430, y: bounds.bottom + 4, items, label: name }, shells.signal);
|
||||
}
|
||||
function profileMenu() {
|
||||
showMenu(profileAnchor, [
|
||||
{ label: tr("New terminal"), icon: "plus", shortcut: keys(TERMINAL_KEYS.new), run: () => addSession() },
|
||||
{ label: tr("New terminal window"), icon: "external", shortcut: keys(TERMINAL_KEYS.window), run: () => void shells.openWindow().catch(report) },
|
||||
{ label: tr("Split terminal"), icon: "column", shortcut: keys(TERMINAL_KEYS.split), disabled: !active, run: () => addSession(active?.profile, true) },
|
||||
{ separator: true },
|
||||
...profiles.map(profile => ({ label: profile.title, icon: "code" as const, title: profile.kind === "node" ? tr("A Node.js REPL with a local inspector. Attach an external debugger to it.") : undefined, run: () => addSession(profile) })),
|
||||
{ label: tr("Split terminal with profile"), icon: "column", disabled: !active, children: profiles.map(profile => ({ label: profile.title, icon: "code", run: () => addSession(profile, true) })) },
|
||||
{ separator: true },
|
||||
{ label: tr("Terminal settings"), icon: "settings", disabled: !onOpenSettings, run: () => onOpenSettings?.() },
|
||||
{ label: tr("Select the default profile"), icon: "select", run: () => picker = { title: tr("Select the default terminal profile"), items: profiles.filter(profile => profile.kind !== "node").map(profile => ({ label: profile.title, value: profile.id, detail: profile.id === defaultProfile()?.id ? tr("Default") : undefined })), onPick: value => persist({ ...settings, defaultProfile: value }) } },
|
||||
{ separator: true },
|
||||
{ label: tr("Run a task…"), icon: "task", run: () => void runTask() },
|
||||
{ label: tr("Configure tasks…"), icon: "code", disabled: !onConfigureTasks, run: () => void onConfigureTasks?.().catch(report) },
|
||||
], tr("Terminal profiles"));
|
||||
}
|
||||
function persist(next: TerminalSettings) {
|
||||
settings = { ...next };
|
||||
void writeTerminal(next).catch(report);
|
||||
}
|
||||
async function runFile() {
|
||||
const target = active;
|
||||
if (!target || !onRunFile) return;
|
||||
try { const path = await onRunFile(); if (path) controls.get(target.id)?.send(fileCommand(path, target.profile.kind)); } catch (reason) { report(reason); }
|
||||
}
|
||||
function runSelection() {
|
||||
const text = getSelection();
|
||||
if (!text) { error = tr("Select text in the editor first."); return; }
|
||||
controls.get(activeId)?.send(text);
|
||||
}
|
||||
function historyPicker(kind: "commands" | "directories") {
|
||||
const target = active;
|
||||
if (!target) return;
|
||||
picker = { title: kind === "commands" ? tr("Run a recent command") : tr("Go to a recent folder"),
|
||||
items: (kind === "commands" ? recentCommands : recentDirectories).map(value => ({ label: value, value })),
|
||||
empty: kind === "commands" ? tr("No commands yet. Shell commands show after the next prompt.") : tr("No folders yet."),
|
||||
onPick: value => { try { controls.get(target.id)?.send(kind === "commands" ? value : directoryCommand(value, target.profile.kind)); } catch (reason) { report(reason); } } };
|
||||
}
|
||||
async function runTask() {
|
||||
try {
|
||||
const tasks = parseTasks(await workspaceRead(".runestone/tasks.json"));
|
||||
picker = { title: tr("Run a task"), items: tasks.map((task, index) => ({ label: task.label, detail: task.command, value: String(index) })), empty: tr("No tasks yet. Choose Configure tasks… to add one."), onPick: index => {
|
||||
const task = tasks[Number(index)];
|
||||
const profile = task.profile ? profiles.find(profile => profile.id === task.profile) : defaultProfile();
|
||||
if (!profile) { error = tr("The profile of this task is not installed: {profile}", { profile: task.profile ?? "" }); return; }
|
||||
addSession(profile, false, task.command, task.label);
|
||||
} };
|
||||
} catch (reason) { error = tr("RuneStone cannot read .runestone/tasks.json. Use Configure tasks… to make or change it. {error}", { error: String(reason) }); }
|
||||
}
|
||||
function moreMenu() {
|
||||
showMenu(moreAnchor, [
|
||||
{ label: tr("Scroll to the previous command"), icon: "up", shortcut: keys(TERMINAL_KEYS.previous), disabled: !active, run: () => controls.get(activeId)?.scrollCommand(-1) },
|
||||
{ label: tr("Scroll to the next command"), icon: "down", shortcut: keys(TERMINAL_KEYS.next), disabled: !active, run: () => controls.get(activeId)?.scrollCommand(1) },
|
||||
{ label: tr("Clear the terminal"), icon: "clear", disabled: !active, run: () => controls.get(activeId)?.clear() },
|
||||
{ label: tr("Run the active file"), icon: "code", disabled: !active || !activeFile, run: () => void runFile() },
|
||||
{ label: tr("Run selected text"), icon: "select", disabled: !active || !activeFile, run: runSelection },
|
||||
{ label: tr("Start dictation"), icon: "comment", disabled: !active, title: tr("Start Windows voice typing in the focused terminal"), run: () => { controls.get(activeId)?.focus(); void shells.dictation().catch(report); } },
|
||||
{ separator: true },
|
||||
{ label: tr("Go to a recent folder…"), icon: "external", shortcut: keys(TERMINAL_KEYS.directories), disabled: !active, run: () => historyPicker("directories") },
|
||||
{ label: tr("Run a recent command…"), icon: "task", shortcut: keys(TERMINAL_KEYS.commands), disabled: !active, run: () => historyPicker("commands") },
|
||||
], tr("Terminal actions"));
|
||||
}
|
||||
export async function command(action: Exclude<TerminalAction, "toggle">) {
|
||||
await ready;
|
||||
if (action === "new") addSession();
|
||||
else if (action === "split") addSession(active?.profile || defaultProfile(), !!active);
|
||||
else if (action === "window") void shells.openWindow().catch(report);
|
||||
else if (action === "previous" || action === "next") controls.get(activeId)?.scrollCommand(action === "previous" ? -1 : 1);
|
||||
else historyPicker(action);
|
||||
}
|
||||
function beginResize(event: PointerEvent, update: (x: number) => void) {
|
||||
if (event.button !== 0) return;
|
||||
event.preventDefault(); stopResize?.();
|
||||
const move = (event: PointerEvent) => update(event.clientX);
|
||||
stopResize = () => { window.removeEventListener("pointermove", move); window.removeEventListener("pointerup", stop); window.removeEventListener("pointercancel", stop); stopResize = undefined; };
|
||||
const stop = () => stopResize?.();
|
||||
window.addEventListener("pointermove", move); window.addEventListener("pointerup", stop); window.addEventListener("pointercancel", stop);
|
||||
}
|
||||
function resizeRail(event: PointerEvent) { const x = event.clientX, width = railWidth; beginResize(event, next => railWidth = Math.min(340, Math.max(140, width + x - next))); }
|
||||
function resizeSplit(event: PointerEvent, session: Session) {
|
||||
const index = group.indexOf(session), previous = group[index - 1];
|
||||
if (!previous) return;
|
||||
const x = event.clientX, before = previous.weight, after = session.weight, width = panes.clientWidth, total = totalWeight;
|
||||
beginResize(event, next => { const change = (next - x) / width * total; previous.weight = Math.min(before + after - .15, Math.max(.15, before + change)); session.weight = before + after - previous.weight; });
|
||||
}
|
||||
function paneLeft(session: Session) { return group.slice(0, group.indexOf(session)).reduce((sum, item) => sum + item.weight, 0) / totalWeight * 100; }
|
||||
onMount(() => {
|
||||
let disposed = false;
|
||||
ready = shells.profiles().then(found => {
|
||||
if (disposed) return;
|
||||
profiles = found;
|
||||
if (profiles.length) addSession(); else error = tr("RuneStone found no supported shells on PATH.");
|
||||
}).catch(report).finally(() => loading = false);
|
||||
// Settings → Terminal and other windows change the settings. Open sessions take the new font, scrollback, and cursor.
|
||||
const stopSettings = onTerminalChange(() => { settings = readTerminal(); });
|
||||
return () => { disposed = true; stopSettings(); closeMenu(); stopResize?.(); };
|
||||
});
|
||||
$effect(() => { if (!visible) { closeMenu(); picker = null; } });
|
||||
$effect(() => {
|
||||
if (visible) untrack(() => {
|
||||
if (restartOnShow) { restartOnShow = false; addSession(); }
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="dock" style:--rail="{railWidth}px">
|
||||
<header class="ribbon">
|
||||
<span class="label" title={cwd}>{$t("Terminal")}</span><span class="directory" title={active?.directory || cwd}>{active?.directory || cwd}</span>
|
||||
<div class="actions">
|
||||
{#if sessions.length === 1 && active}<span class="single-session" title={`${active.title} · ${stateLabel(active.state)}`}>{active.profile.title}</span>{/if}
|
||||
<IconButton icon="plus" label={$t("New terminal")} disabled={loading || !profiles.length} onclick={() => addSession()} />
|
||||
<div bind:this={profileAnchor}><IconButton icon="chevron-down" label={$t("Terminal profiles and tasks")} disabled={loading} onclick={profileMenu} /></div>
|
||||
<IconButton icon="split" label={$t("Split terminal ({shortcut})", { shortcut: keys(TERMINAL_KEYS.split) })} disabled={!active} onclick={() => addSession(active?.profile, true)} />
|
||||
<div bind:this={moreAnchor}><IconButton icon="more" label={$t("More terminal actions")} onclick={moreMenu} /></div>
|
||||
<IconButton icon="trash" label={$t("Kill terminal")} disabled={!active} onclick={() => killSession(activeId)} />
|
||||
{#if !standalone}<IconButton icon={maximized ? "restore" : "maximize"} label={maximized ? $t("Restore panel") : $t("Maximize panel")} onclick={onMaximize} />{/if}
|
||||
<IconButton icon="close" label={standalone ? $t("Close terminal window") : $t("Close terminal (end all sessions)")} disabled={closing} onclick={() => void closeDock()} />
|
||||
</div>
|
||||
</header>
|
||||
{#if error}<div class="error" role="alert"><span>{error}</span><IconButton icon="close" label={$t("Dismiss the terminal error")} onclick={() => error = ""} /></div>{/if}
|
||||
<div class="body">
|
||||
<div class="panes" bind:this={panes}>
|
||||
{#each sessions as session (session.id)}
|
||||
<div class="pane" class:shown={session.group === active?.group} class:focused={session.id === activeId}
|
||||
style:left="{session.group === active?.group ? paneLeft(session) : 0}%" style:width="{session.group === active?.group ? session.weight / totalWeight * 100 : 100}%">
|
||||
{#if group.length > 1 && session.group === active?.group}<div class="pane-label">{session.title}</div>{/if}
|
||||
<TerminalPane id={session.id} {cwd} directory={session.directory} profile={session.profile} {settings} sessions={shells}
|
||||
active={visible && session.group === active?.group} focused={session.id === activeId} onFocus={() => activeId = session.id}
|
||||
onState={state => { session.state = state; if (state.kind === "running" && session.command) { controls.get(session.id)?.send(session.command); session.command = undefined; } }}
|
||||
onControl={control => { if (control) controls.set(session.id, control); else controls.delete(session.id); }}
|
||||
onCommand={command => recentCommands = remember(recentCommands, command)}
|
||||
onDirectory={directory => { session.directory = directory; recentDirectories = remember(recentDirectories, directory); }} />
|
||||
{#if session.group === active?.group && group.indexOf(session) > 0}
|
||||
<div class="split-gutter" role="separator" aria-label={$t("Resize split terminals")} aria-orientation="vertical" onpointerdown={event => resizeSplit(event, session)}></div>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
{#if !sessions.length}<div class="empty"><p>{loading ? $t("Finding the installed shells…") : $t("No terminal sessions.")}</p><button disabled={loading || !profiles.length} onclick={() => addSession()}>{$t("Start a terminal")}</button></div>{/if}
|
||||
</div>
|
||||
{#if sessions.length > 1}
|
||||
<div class="gutter" role="separator" aria-orientation="vertical" aria-label={$t("Resize terminal list")} onpointerdown={resizeRail}></div>
|
||||
<nav class="rail" aria-label={$t("Terminal list")}>
|
||||
{#each sessions as session (session.id)}
|
||||
<div class="item" data-session={session.id} class:active={session.id === activeId} class:grouped={sessions.filter(item => item.group === session.group).length > 1}>
|
||||
<button class="pick" aria-pressed={session.id === activeId} title={`${session.title} · ${stateLabel(session.state)} · ${session.directory}`} onclick={() => select(session.id)}
|
||||
onkeydown={event => {
|
||||
if (event.key === "Delete") { event.preventDefault(); killSession(session.id); }
|
||||
if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); const next = sessions[(sessions.indexOf(session) + (event.key === "ArrowDown" ? 1 : sessions.length - 1)) % sessions.length]; activeId = next.id; (event.currentTarget.closest("nav")?.querySelector(`[data-session="${next.id}"] .pick`) as HTMLButtonElement)?.focus(); }
|
||||
}}><span class="shell-icon" aria-hidden="true">›_</span><span class="session-name">{session.title}<small>{stateLabel(session.state)}</small></span></button>
|
||||
<div class="row-actions">
|
||||
<IconButton icon="split" label={$t("Split {title}", { title: session.title })} onclick={() => { activeId = session.id; addSession(session.profile, true); }} />
|
||||
<IconButton icon="trash" label={$t("Kill {title} ({shortcut})", { title: session.title, shortcut: keys("Delete") })} onclick={() => killSession(session.id)} />
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</nav>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{#if picker}<TerminalPicker {...picker} onClose={() => picker = null} />{/if}
|
||||
<style>
|
||||
.dock { display: flex; flex-direction: column; height: 100%; min-height: 0; container-type: inline-size; }
|
||||
.ribbon { display: flex; flex-wrap: wrap; align-items: center; gap: 0 10px; flex: 0 0 auto; min-height: var(--rs-titlebar-height, 36px); padding: 0 8px; background: var(--rs-image-sidebar-bg, color-mix(in srgb, var(--rs-bg-elevated) 82%, transparent)); }
|
||||
.label { font-size: 13px; color: var(--rs-text-strong); }
|
||||
.directory { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--rs-text-dim); font-size: 12px; }
|
||||
.actions, .row-actions { display: flex; align-items: center; flex-shrink: 0; }
|
||||
.actions { flex-wrap: wrap; max-width: 100%; }
|
||||
.single-session { max-width: 130px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; color: var(--rs-text-dim); margin-right: 6px; }
|
||||
.body { display: flex; flex: 1; min-height: 0; }
|
||||
.panes { flex: 1; position: relative; min-width: 0; min-height: 0; }
|
||||
.pane { display: flex; flex-direction: column; position: absolute; top: 0; bottom: 0; visibility: hidden; min-width: 0; overflow: hidden; }
|
||||
.pane.shown { visibility: visible; }
|
||||
.pane :global(.term) { flex: 1; min-height: 0; height: auto; }
|
||||
.pane-label { flex: 0 0 23px; padding: 3px 10px; font-size: 11px; color: var(--rs-text-dim); border-top: 1px solid transparent; background: var(--rs-image-editor-bg, color-mix(in srgb, var(--rs-bg) 90%, transparent)); }
|
||||
.focused .pane-label { color: var(--rs-text-strong); border-top-color: var(--rs-accent); }
|
||||
.split-gutter { position: absolute; top: 0; bottom: 0; left: 0; width: 4px; cursor: col-resize; background: var(--rs-border); }
|
||||
.gutter { flex: 0 0 4px; cursor: col-resize; }
|
||||
.gutter:hover, .split-gutter:hover { background: var(--rs-accent); }
|
||||
.rail { flex: 0 0 var(--rail); width: var(--rail); overflow: auto; padding: 4px; border-left: 1px solid var(--rs-border); background: var(--rs-image-sidebar-bg, color-mix(in srgb, var(--rs-bg-elevated) 82%, transparent)); }
|
||||
.item { display: flex; align-items: center; min-width: 0; border-left: 2px solid transparent; border-radius: var(--rs-control-radius); }
|
||||
.item.grouped { border-left-color: var(--rs-border); }
|
||||
.item.active { background: var(--rs-image-control-hover-bg, color-mix(in srgb, var(--rs-bg-active) 92%, transparent)); border-left-color: var(--rs-accent); }
|
||||
.pick { display: flex; align-items: center; gap: 7px; flex: 1; min-width: 0; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); text-align: left; padding: 5px; }
|
||||
.shell-icon { color: var(--rs-text-dim); }
|
||||
.session-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
small { display: block; font-size: 10px; color: var(--rs-text-dim); }
|
||||
.row-actions { visibility: hidden; }
|
||||
.item:hover .row-actions, .item:focus-within .row-actions, .item.active .row-actions { visibility: visible; }
|
||||
.error { padding: 3px 4px 3px 12px; display: flex; align-items: center; gap: 8px; color: var(--rs-error); font-size: 12px; border-bottom: 1px solid var(--rs-border); }
|
||||
.error span { flex: 1; }
|
||||
.empty button { background: var(--rs-bg-active); color: var(--rs-text); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); padding: 4px 8px; }
|
||||
.empty { height: 100%; padding: 20px; color: var(--rs-text-dim); background: var(--rs-image-editor-bg, color-mix(in srgb, var(--rs-bg) 90%, transparent)); }
|
||||
@container (max-width: 700px) { .rail { flex-basis: 150px; width: 150px; } .row-actions { display: none; } .directory, .single-session { display: none; } .label { flex: 1; } }
|
||||
</style>
|
||||
@@ -0,0 +1,259 @@
|
||||
<script lang="ts" module>
|
||||
/** The state of one shell. `code` is the exit code, when the shell gave one. */
|
||||
export type PaneState = { kind: "starting" | "running" | "failed" } | { kind: "exited"; code: number | null };
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
// One xterm and its shell. Input before the shell starts waits in a buffer, xterm's answers to start-up queries included.
|
||||
// OSC 133 marks the prompts for command scrolling. OSC 633 reports the folder and the last command (src-tauri/src/pty.rs).
|
||||
import { FitAddon } from "@xterm/addon-fit";
|
||||
import { Terminal, type IMarker } from "@xterm/xterm";
|
||||
import { onMount } from "svelte";
|
||||
import { tr } from "$lib/i18n";
|
||||
import { terminalShortcut } from "../terminalKeys";
|
||||
import type { TerminalSettings } from "../terminalSettings";
|
||||
import { terminalTypography } from "./typography";
|
||||
import { terminalTheme, watchTerminalAppearance } from "./theme";
|
||||
import type { ShellProfile, TerminalControl } from "./model";
|
||||
import type { TerminalSessions } from "./sessions";
|
||||
|
||||
type Props = {
|
||||
id: string;
|
||||
cwd: string;
|
||||
active: boolean;
|
||||
focused: boolean;
|
||||
profile: ShellProfile;
|
||||
directory: string;
|
||||
settings: TerminalSettings;
|
||||
sessions: TerminalSessions;
|
||||
onFocus: () => void;
|
||||
onControl: (control: TerminalControl | null) => void;
|
||||
onCommand: (command: string) => void;
|
||||
onDirectory: (directory: string) => void;
|
||||
onState: (state: PaneState) => void;
|
||||
};
|
||||
|
||||
let { id, cwd, active, focused, profile, directory, settings, sessions, onFocus, onControl, onCommand, onDirectory, onState }: Props = $props();
|
||||
let host: HTMLDivElement | undefined = $state();
|
||||
let focusTerminal: (() => void) | undefined = $state();
|
||||
let instance = $state.raw<Terminal>();
|
||||
let resizeTerminal: (() => void) | undefined;
|
||||
|
||||
$effect(() => { if (active && focused && !document.activeElement?.closest(".rail")) focusTerminal?.(); });
|
||||
$effect(() => {
|
||||
if (instance) {
|
||||
instance.options.fontSize = settings.fontSize;
|
||||
instance.options.scrollback = settings.scrollback;
|
||||
instance.options.cursorBlink = settings.cursorBlink;
|
||||
requestAnimationFrame(() => resizeTerminal?.());
|
||||
}
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
if (!host) return;
|
||||
const theme = terminalTheme(host);
|
||||
host.style.setProperty("--rs-terminal-selection", theme.selectionBackground!);
|
||||
const term = new Terminal({
|
||||
scrollback: settings.scrollback,
|
||||
...terminalTypography(host),
|
||||
fontSize: settings.fontSize,
|
||||
cursorBlink: settings.cursorBlink,
|
||||
allowProposedApi: true,
|
||||
allowTransparency: true,
|
||||
theme,
|
||||
});
|
||||
const fit = new FitAddon();
|
||||
term.loadAddon(fit);
|
||||
term.open(host);
|
||||
instance = term;
|
||||
let disposed = false;
|
||||
let opened = false;
|
||||
let exited = false;
|
||||
const pendingInput: string[] = [];
|
||||
let writes = Promise.resolve();
|
||||
const fail = (reason: unknown) => {
|
||||
if (!disposed) term.writeln(`\r\n${String(reason)}`);
|
||||
};
|
||||
let selectionRevision = 0;
|
||||
const selection = term.onSelectionChange(() => { selectionRevision++; });
|
||||
const copySelection = (clearAfterCopy = false) => {
|
||||
const text = term.getSelection();
|
||||
if (!text) return;
|
||||
const revision = selectionRevision;
|
||||
void navigator.clipboard.writeText(text).then(() => {
|
||||
if (clearAfterCopy && !disposed && selectionRevision === revision) term.clearSelection();
|
||||
}).catch(fail);
|
||||
};
|
||||
const copyOnRightClick = (event: MouseEvent) => {
|
||||
if (!term.hasSelection()) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
copySelection(true);
|
||||
};
|
||||
// Copy the selected text before xterm prepares its own context menu.
|
||||
host.addEventListener("contextmenu", copyOnRightClick, true);
|
||||
term.attachCustomKeyEventHandler(event => {
|
||||
const copy = (event.ctrlKey || event.metaKey) && !event.altKey && event.key.toLowerCase() === "c";
|
||||
if (copy && (term.hasSelection() || event.shiftKey)) {
|
||||
if (event.type === "keydown") {
|
||||
event.preventDefault();
|
||||
copySelection();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return !terminalShortcut(event);
|
||||
});
|
||||
const resize = () => {
|
||||
if (disposed || !host?.clientWidth || !host?.clientHeight) return;
|
||||
fit.fit();
|
||||
if (opened && !exited) void sessions.resize(id, term.cols, term.rows).catch(fail);
|
||||
};
|
||||
const stopAppearance = watchTerminalAppearance(host, () => {
|
||||
if (disposed || !host) return;
|
||||
const theme = terminalTheme(host);
|
||||
if (host.style.getPropertyValue("--rs-terminal-selection") !== theme.selectionBackground) {
|
||||
host.style.setProperty("--rs-terminal-selection", theme.selectionBackground!);
|
||||
}
|
||||
term.options.theme = theme;
|
||||
Object.assign(term.options, terminalTypography(host));
|
||||
resize();
|
||||
});
|
||||
resizeTerminal = resize;
|
||||
focusTerminal = () => { resize(); term.focus(); };
|
||||
const send = (data: string) => {
|
||||
if (exited || disposed) return;
|
||||
if (!opened) { pendingInput.push(data); return; }
|
||||
writes = writes.then(() => sessions.write(id, data)).catch(fail);
|
||||
};
|
||||
const onData = term.onData(send);
|
||||
let markers: IMarker[] = [];
|
||||
let prompt: { marker: IMarker; column: number } | undefined;
|
||||
const promptParser = term.parser.registerOscHandler(133, data => {
|
||||
if (data === "A") {
|
||||
const marker = term.registerMarker(0);
|
||||
if (marker) markers = [...markers.filter(item => !item.isDisposed), marker].slice(-1000);
|
||||
}
|
||||
if (data === "B") {
|
||||
prompt?.marker.dispose();
|
||||
const marker = term.registerMarker(0);
|
||||
prompt = marker ? { marker, column: term.buffer.active.cursorX } : undefined;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
const integration = term.parser.registerOscHandler(633, data => {
|
||||
const separator = data.indexOf(";");
|
||||
const type = data.slice(0, separator), value = data.slice(separator + 1);
|
||||
try {
|
||||
if (type === "Cwd") onDirectory(value);
|
||||
if (type === "RSCwd" || type === "RSCommand") {
|
||||
const decoded = new TextDecoder().decode(Uint8Array.from(atob(value), char => char.charCodeAt(0)));
|
||||
if (type === "RSCwd") onDirectory(decoded); else onCommand(decoded);
|
||||
}
|
||||
} catch { /* Ignore shell integration output that is not valid. */ }
|
||||
return true;
|
||||
});
|
||||
// Command Prompt has no history hook, so the pane reads the command line from the screen at Enter.
|
||||
const keys = term.onKey(({ domEvent }) => {
|
||||
if (profile.kind !== "cmd" || domEvent.key !== "Enter" || !prompt || prompt.marker.isDisposed) return;
|
||||
const buffer = term.buffer.active;
|
||||
let command = "";
|
||||
for (let line = prompt.marker.line; line <= buffer.baseY + buffer.cursorY; line++) {
|
||||
command += buffer.getLine(line)?.translateToString(true, line === prompt.marker.line ? prompt.column : 0) || "";
|
||||
}
|
||||
if (command.trim()) onCommand(command);
|
||||
prompt.marker.dispose(); prompt = undefined;
|
||||
});
|
||||
onControl({
|
||||
focus: () => { resize(); term.focus(); },
|
||||
clear: () => { markers.forEach(marker => marker.dispose()); markers = []; term.clear(); term.focus(); },
|
||||
scrollCommand: direction => {
|
||||
const lines = markers.filter(marker => !marker.isDisposed).map(marker => marker.line);
|
||||
const current = term.buffer.active.viewportY;
|
||||
const target = direction < 0 ? lines.reverse().find(line => line < current) : lines.find(line => line > current);
|
||||
if (target !== undefined) term.scrollToLine(target); else if (direction > 0) term.scrollToBottom();
|
||||
},
|
||||
send: (text, execute = true) => {
|
||||
if (exited) return;
|
||||
term.paste(text.replace(/\r?\n/g, "\r"));
|
||||
if (execute) send("\r");
|
||||
term.focus();
|
||||
},
|
||||
});
|
||||
const start = async () => {
|
||||
try {
|
||||
resize();
|
||||
// The host sends output from the start, because shells and agents can print at once.
|
||||
await sessions.open(id, {
|
||||
cwd, cols: term.cols, rows: term.rows, profile: profile.id, directory,
|
||||
onData: data => { if (!disposed) term.write(data); },
|
||||
onExit: code => {
|
||||
if (disposed) return;
|
||||
exited = true;
|
||||
onState({ kind: "exited", code });
|
||||
term.writeln(`\r\n[${code === null ? tr("Process exited") : tr("Process exited with code {code}", { code })}]`);
|
||||
},
|
||||
});
|
||||
opened = true;
|
||||
if (disposed) { await sessions.close(id); return; }
|
||||
for (const data of pendingInput.splice(0)) {
|
||||
writes = writes.then(() => sessions.write(id, data)).catch(fail);
|
||||
}
|
||||
if (!exited) onState({ kind: "running" });
|
||||
resize();
|
||||
if (active && focused) term.focus();
|
||||
} catch (reason) {
|
||||
fail(reason);
|
||||
if (!disposed) onState({ kind: "failed" });
|
||||
}
|
||||
};
|
||||
void start();
|
||||
const observer = new ResizeObserver(resize);
|
||||
observer.observe(host);
|
||||
return () => {
|
||||
disposed = true;
|
||||
focusTerminal = undefined;
|
||||
instance = undefined;
|
||||
resizeTerminal = undefined;
|
||||
onControl(null);
|
||||
observer.disconnect();
|
||||
stopAppearance();
|
||||
onData.dispose();
|
||||
selection.dispose();
|
||||
host?.removeEventListener("contextmenu", copyOnRightClick, true);
|
||||
promptParser.dispose(); integration.dispose(); keys.dispose();
|
||||
void sessions.close(id).catch(() => {});
|
||||
term.dispose();
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="term" data-cwd={directory} bind:this={host} onfocusin={onFocus}></div>
|
||||
|
||||
<style>
|
||||
.term {
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
padding: 4px;
|
||||
background: var(--rs-image-editor-bg, color-mix(in srgb, var(--rs-bg) 90%, transparent));
|
||||
}
|
||||
|
||||
.term :global(.xterm),
|
||||
.term :global(.xterm-viewport) {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.term :global(.xterm-viewport) {
|
||||
/* Whole terminal rows can leave a gap above the bottom edge. */
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
/* The DOM renderer blends the selection on its transparent black base first. */
|
||||
.term :global(.xterm .xterm-selection div) {
|
||||
background-color: var(--rs-terminal-selection) !important;
|
||||
}
|
||||
|
||||
/* xterm marks selected glyphs as top decorations with opaque fills. */
|
||||
.term :global(.xterm-rows .xterm-decoration-top) {
|
||||
background-color: transparent !important;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,46 @@
|
||||
<script lang="ts">
|
||||
// A filter list for tasks, recent commands, recent folders, and profiles. It uses the shared picker rows of menu.css.
|
||||
import { onMount, tick } from "svelte";
|
||||
import { t } from "$lib/i18n";
|
||||
import IconButton from "$lib/ui/IconButton.svelte";
|
||||
import { keys } from "$lib/ui/shortcuts";
|
||||
let { title, items, onPick, onClose, empty }: {
|
||||
title: string; items: { label: string; detail?: string; value: string }[];
|
||||
onPick: (value: string) => void; onClose: () => void; empty?: string;
|
||||
} = $props();
|
||||
let query = $state("");
|
||||
let selected = $state(0);
|
||||
let dialog: HTMLDialogElement;
|
||||
let input: HTMLInputElement;
|
||||
const listId = $props.id();
|
||||
const matches = $derived(items.filter(item => `${item.label} ${item.detail || ""}`.toLowerCase().includes(query.toLowerCase())));
|
||||
async function pick(value?: string) { if (value !== undefined) { const choose = onPick; onClose(); await tick(); choose(value); } }
|
||||
onMount(() => { dialog.showModal(); input.focus(); });
|
||||
</script>
|
||||
<dialog class="rs-picker" bind:this={dialog} oncancel={onClose} aria-label={title}>
|
||||
<header>{title}<IconButton icon="close" label={$t("Close the list")} onclick={onClose} /></header>
|
||||
<input bind:this={input} bind:value={query} role="combobox" aria-expanded="true" aria-controls={listId} aria-activedescendant={matches[selected] ? `${listId}-${selected}` : undefined} aria-autocomplete="list" aria-label={title} placeholder={$t("Type to filter…")} oninput={() => selected = 0} onkeydown={event => {
|
||||
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
||||
event.preventDefault(); selected = Math.max(0, Math.min(matches.length - 1, selected + (event.key === "ArrowDown" ? 1 : -1)));
|
||||
dialog.querySelector(`[data-index="${selected}"]`)?.scrollIntoView({ block: "nearest" });
|
||||
}
|
||||
if (event.key === "Enter") { event.preventDefault(); void pick(matches[selected]?.value); }
|
||||
}} />
|
||||
<div class="results" id={listId} role="listbox" aria-label={$t("{title}: choices", { title })}>
|
||||
{#each matches as item, index}
|
||||
<button class="rs-picker-row" id={`${listId}-${index}`} role="option" aria-selected={index === selected} data-index={index} onclick={() => void pick(item.value)}><span class="entry-label">{item.label}{#if item.detail}<small class="rs-picker-hint">{item.detail}</small>{/if}</span></button>
|
||||
{/each}
|
||||
{#if !matches.length}<p>{query ? $t("No entries match the filter.") : empty ?? $t("No entries yet.")}</p>{/if}
|
||||
</div>
|
||||
<footer>{$t("{up} {down} select · {enter} choose · {escape} close", { up: "↑", down: "↓", enter: keys("Enter"), escape: keys("Escape") })}</footer>
|
||||
</dialog>
|
||||
<style>
|
||||
dialog { margin-top: 12vh; width: min(640px, 85vw); }
|
||||
dialog::backdrop { background: var(--rs-scrim); }
|
||||
header { display: flex; align-items: center; justify-content: space-between; padding: 8px 16px; }
|
||||
input { width: 100%; box-sizing: border-box; padding: var(--rs-menu-row-padding); min-height: var(--rs-menu-row-height); background: var(--rs-bg); color: var(--rs-text-strong); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||
.results { max-height: 50vh; overflow: auto; }
|
||||
.entry-label { min-width: 0; overflow-wrap: anywhere; white-space: pre-wrap; }
|
||||
footer, p { color: var(--rs-text-dim); }
|
||||
footer { padding: var(--rs-menu-row-padding); border-top: 1px solid var(--rs-border); font-size: var(--rs-settings-description-size); }
|
||||
</style>
|
||||
@@ -0,0 +1,36 @@
|
||||
// The Terminal feature. `loader.ts` imports this module at the first use of a terminal panel:
|
||||
// the Terminal button, a terminal shortcut, or a terminal window. Settings → Terminal does not load it.
|
||||
// It starts shells through the `pty_*` commands of src-tauri/src/pty.rs (`transport.ts`).
|
||||
import { flushSync, mount, unmount } from "svelte";
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import type { TerminalInstance, TerminalMount } from "../terminalHost.ts";
|
||||
import type { FeatureContext } from "../types.ts";
|
||||
import { TerminalSessions } from "./sessions.ts";
|
||||
import { desktopTransport } from "./transport.ts";
|
||||
import TerminalBridge from "./TerminalBridge.svelte";
|
||||
// The xterm styles load with the feature chunk.
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
|
||||
export function start(_context: FeatureContext): TerminalInstance {
|
||||
const sessions = new TerminalSessions(desktopTransport);
|
||||
const docks = new Set<() => Promise<void>>();
|
||||
return {
|
||||
mount() { throw new Error(tr("This view is unavailable.")); },
|
||||
mountDock(element, props): TerminalMount {
|
||||
if (sessions.stopped) throw new Error(tr("This feature is off."));
|
||||
const instance = mount(TerminalBridge, { target: element, props: { initial: props, sessions } });
|
||||
flushSync();
|
||||
let stopping: Promise<void> | undefined;
|
||||
const dispose = () => stopping ??= unmount(instance).then(() => { docks.delete(dispose); });
|
||||
docks.add(dispose);
|
||||
return { update: value => instance.update(value), command: action => instance.command(action), dispose };
|
||||
},
|
||||
/** Remove the panels, then stop the shells that are left. Panels close their own sessions when they unmount. */
|
||||
async dispose() {
|
||||
const results = await Promise.allSettled([...docks].map(dispose => dispose()));
|
||||
await sessions.closeAll();
|
||||
const errors = results.filter(result => result.status === "rejected");
|
||||
if (errors.length) throw new Error(errors.map(result => String(result.reason)).join("\n"));
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// Shell commands, tasks, and history of the terminal panel. Plain functions, so the unit tests run them without a DOM.
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
|
||||
export type ShellKind = "powershell" | "bash" | "cmd" | "node";
|
||||
/** A shell that `pty_profiles` found (src-tauri/src/pty.rs). */
|
||||
export type ShellProfile = { id: string; title: string; kind: ShellKind };
|
||||
/** The controls of one terminal pane for the panel. */
|
||||
export type TerminalControl = { focus(): void; clear(): void; scrollCommand(direction: -1 | 1): void; send(text: string, execute?: boolean): void };
|
||||
/** One task of `.runestone/tasks.json`. */
|
||||
export type TerminalTask = { label: string; command: string; profile?: string };
|
||||
|
||||
/** The profile of a new terminal: the default profile when it exists, then the first shell that is not Node.js. */
|
||||
export function pickProfile(profiles: readonly ShellProfile[], preferred: string): ShellProfile | undefined {
|
||||
return profiles.find(profile => profile.id === preferred) || profiles.find(profile => profile.kind !== "node") || profiles[0];
|
||||
}
|
||||
|
||||
/** Quote a path for a shell, so that the shell does not expand it. */
|
||||
export function quoteShell(value: string, kind: ShellKind): string {
|
||||
if (/[\r\n\0]/.test(value)) throw new Error(tr("A path cannot contain line breaks or null characters."));
|
||||
if (kind === "cmd") {
|
||||
// Command Prompt expands % and ! also between quotes. Refuse the path instead of running another path.
|
||||
if (/["%!]/.test(value)) throw new Error(tr("Use PowerShell for a path with quotes, % or !."));
|
||||
return `"${value}"`;
|
||||
}
|
||||
if (kind === "bash") return `'${value.replaceAll("'", "'\\''")}'`;
|
||||
return `'${value.replaceAll("'", "''")}'`;
|
||||
}
|
||||
|
||||
/** The command that goes to a folder in a shell. */
|
||||
export function directoryCommand(path: string, kind: ShellKind): string {
|
||||
if (kind === "node") return `process.chdir(${JSON.stringify(path)})`;
|
||||
const normalized = kind === "bash" ? path.replaceAll("\\", "/") : path;
|
||||
return `${kind === "powershell" ? "Set-Location -LiteralPath" : kind === "cmd" ? "cd /d" : "cd --"} ${quoteShell(normalized, kind)}`;
|
||||
}
|
||||
|
||||
/** The command that runs a file in a shell. The file extension selects the program. */
|
||||
export function fileCommand(path: string, kind: ShellKind): string {
|
||||
if (kind === "node") throw new Error(tr("Select a shell terminal to run files. The debug terminal is a Node.js REPL."));
|
||||
const ext = path.split(".").pop()?.toLowerCase();
|
||||
const quoted = quoteShell(kind === "bash" ? path.replaceAll("\\", "/") : path, kind);
|
||||
const runner = ext === "py" ? "python" : ["js", "mjs", "cjs"].includes(ext || "") ? "node"
|
||||
: ext === "ps1" ? "powershell -NoLogo -File" : ext === "sh" ? "bash" : ext === "rb" ? "ruby"
|
||||
: ext === "bat" || ext === "cmd" ? "cmd /c" : ext === "exe" ? "" : null;
|
||||
if (runner === null) throw new Error(tr("RuneStone cannot run this file type. Use Run selected text, or add a task."));
|
||||
return `${runner || (kind === "powershell" ? "&" : "")}${runner || kind === "powershell" ? " " : ""}${quoted}`;
|
||||
}
|
||||
|
||||
/** The tasks of `.runestone/tasks.json`. Each task must be valid before the panel offers one. */
|
||||
export function parseTasks(text: string): TerminalTask[] {
|
||||
const value = JSON.parse(text);
|
||||
if (!Array.isArray(value?.tasks)) throw new Error(tr("The tasks file needs a \"tasks\" array."));
|
||||
return value.tasks.map((task: unknown) => {
|
||||
if (!task || typeof task !== "object" || !("label" in task) || typeof task.label !== "string" || !task.label.trim()
|
||||
|| !("command" in task) || typeof task.command !== "string" || !task.command.trim()
|
||||
|| ("profile" in task && typeof task.profile !== "string")) throw new Error(tr("Each task needs a label, a command, and an optional profile ID."));
|
||||
return task as TerminalTask;
|
||||
});
|
||||
}
|
||||
|
||||
/** Put a value first in a history list without duplicates. The list keeps 100 values. */
|
||||
export function remember(items: string[], value: string): string[] {
|
||||
return value.trim() ? [value, ...items.filter(item => item !== value)].slice(0, 100) : items;
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
// The shell sessions of one Terminal instance. The panes call this layer, and this layer calls the host (`transport.ts`).
|
||||
// A close waits for the start of its shell, so a close cannot leave a late shell running.
|
||||
// `closeAll` runs when Terminal goes off or the window closes the feature.
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import type { ShellProfile } from "./model.ts";
|
||||
|
||||
/** What a pane asks for when it starts a shell. `id` is the pane ID. The host uses it as the session ID. */
|
||||
export interface PtyRequest { id: string; cwd: string; cols: number; rows: number; profile?: string; directory?: string }
|
||||
|
||||
/** The host commands of the terminal (`pty_*` in src-tauri/src/pty.rs). Tests give a fake transport. */
|
||||
export interface PtyTransport {
|
||||
/** Start a shell. `onData` gets the raw output bytes and `onExit` the exit code, from the start on. */
|
||||
open(request: PtyRequest, onData: (data: Uint8Array) => void, onExit: (code: number | null) => void): Promise<void>;
|
||||
write(id: string, data: string): Promise<void>;
|
||||
resize(id: string, cols: number, rows: number): Promise<void>;
|
||||
close(id: string): Promise<void>;
|
||||
profiles(): Promise<ShellProfile[]>;
|
||||
openWindow(): Promise<void>;
|
||||
dictation(): Promise<void>;
|
||||
}
|
||||
|
||||
export interface OpenOptions extends Omit<PtyRequest, "id"> {
|
||||
/** Raw output. A UTF-8 character can be split between two calls. */
|
||||
onData(data: Uint8Array): void;
|
||||
onExit?(code: number | null): void;
|
||||
}
|
||||
|
||||
export class TerminalSessions {
|
||||
private readonly transport: PtyTransport;
|
||||
private readonly controller = new AbortController();
|
||||
/** The sessions whose shell started and did not exit. */
|
||||
private readonly live = new Set<string>();
|
||||
private readonly opening = new Map<string, Promise<void>>();
|
||||
private readonly closing = new Map<string, Promise<void>>();
|
||||
/** Pane IDs that closed. A closed ID cannot start again. */
|
||||
private readonly closed = new Set<string>();
|
||||
|
||||
constructor(transport: PtyTransport) { this.transport = transport; }
|
||||
|
||||
/** Aborts when the instance stops. Menus of the panel close then. */
|
||||
get signal(): AbortSignal { return this.controller.signal; }
|
||||
get stopped(): boolean { return this.controller.signal.aborted; }
|
||||
|
||||
private check() { if (this.stopped) throw new Error(tr("This feature is off.")); }
|
||||
|
||||
/** Start a shell for pane `id`. */
|
||||
open(id: string, options: OpenOptions): Promise<void> {
|
||||
try {
|
||||
this.check();
|
||||
if (this.closed.has(id)) throw new Error(tr("This terminal is closed."));
|
||||
if (this.live.has(id) || this.opening.has(id)) throw new Error(tr("This terminal is already running."));
|
||||
} catch (reason) { return Promise.reject(reason); }
|
||||
let exited = false;
|
||||
const active = () => !this.closed.has(id) && !this.stopped;
|
||||
const { onData, onExit, ...request } = options;
|
||||
const pending = Promise.resolve().then(() => this.transport.open({ id, ...request },
|
||||
data => { if (active()) onData(data); },
|
||||
code => {
|
||||
if (exited) return;
|
||||
exited = true;
|
||||
this.live.delete(id);
|
||||
if (active()) onExit?.(code);
|
||||
})).then(() => { if (!exited) this.live.add(id); });
|
||||
this.opening.set(id, pending);
|
||||
void pending.finally(() => this.opening.delete(id)).catch(() => {});
|
||||
return pending;
|
||||
}
|
||||
|
||||
private session(id: string) {
|
||||
this.check();
|
||||
if (!this.live.has(id)) throw new Error(tr("This terminal is not running."));
|
||||
}
|
||||
|
||||
async write(id: string, data: string): Promise<void> { this.session(id); await this.transport.write(id, data); }
|
||||
async resize(id: string, cols: number, rows: number): Promise<void> { this.session(id); await this.transport.resize(id, cols, rows); }
|
||||
|
||||
/** Stop the shell of pane `id`. Later calls return the same promise until the close ends. */
|
||||
close(id: string): Promise<void> {
|
||||
this.closed.add(id);
|
||||
const pending = this.closing.get(id);
|
||||
if (pending) return pending;
|
||||
if (!this.live.has(id) && !this.opening.has(id)) return Promise.resolve();
|
||||
const close = Promise.resolve(this.opening.get(id)).catch(() => {})
|
||||
.then(() => this.live.has(id) ? this.transport.close(id) : undefined)
|
||||
.then(() => { this.live.delete(id); })
|
||||
.finally(() => this.closing.delete(id));
|
||||
this.closing.set(id, close);
|
||||
return close;
|
||||
}
|
||||
|
||||
profiles(): Promise<ShellProfile[]> {
|
||||
try { this.check(); } catch (reason) { return Promise.reject(reason); }
|
||||
return this.transport.profiles();
|
||||
}
|
||||
openWindow(): Promise<void> {
|
||||
try { this.check(); } catch (reason) { return Promise.reject(reason); }
|
||||
return this.transport.openWindow();
|
||||
}
|
||||
dictation(): Promise<void> {
|
||||
try { this.check(); } catch (reason) { return Promise.reject(reason); }
|
||||
return this.transport.dictation();
|
||||
}
|
||||
|
||||
/** Stop all sessions. Starts that are in progress finish first, then close. Later opens fail. */
|
||||
async closeAll(): Promise<void> {
|
||||
this.controller.abort();
|
||||
await Promise.allSettled([...this.opening.values()]);
|
||||
const results = await Promise.allSettled([...this.live, ...this.closing.keys()].map(id => this.close(id)));
|
||||
const errors = results.filter(result => result.status === "rejected");
|
||||
if (errors.length) throw new Error(errors.map(result => String(result.reason)).join("\n"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// The terminal colors come from the theme tokens. The 16 ANSI colors use the `--rs-ansi-*` tokens of
|
||||
// src/lib/theme/roles.ts, so the theme editor and custom themes change them. xterm needs hex colors.
|
||||
import type { ITheme } from "@xterm/xterm";
|
||||
import { ANSI_COLORS } from "../../theme/roles.ts";
|
||||
|
||||
/** The highest alpha of the selection, so the selected text stays readable on every background. */
|
||||
export const SELECTION_ALPHA = Math.floor(255 * 0.65);
|
||||
|
||||
type Key = Exclude<keyof ITheme, "extendedAnsi" | "background">;
|
||||
const capitalize = (name: string) => name[0].toUpperCase() + name.slice(1);
|
||||
|
||||
/** The token of each xterm color, and the highest alpha of the color when it has one. */
|
||||
export const TERMINAL_TOKENS: readonly { key: Key; token: string; maxAlpha?: number }[] = [
|
||||
{ key: "foreground", token: "var(--rs-text)" },
|
||||
{ key: "cursor", token: "var(--rs-accent)" },
|
||||
{ key: "cursorAccent", token: "var(--rs-bg)" },
|
||||
{ key: "selectionBackground", token: "var(--rs-selection)", maxAlpha: SELECTION_ALPHA },
|
||||
{ key: "selectionForeground", token: "var(--rs-selection-text, var(--rs-text))" },
|
||||
...ANSI_COLORS.map(color => ({ key: color as Key, token: `var(--rs-ansi-${color})` })),
|
||||
...ANSI_COLORS.map(color => ({ key: `bright${capitalize(color)}` as Key, token: `var(--rs-ansi-bright-${color})` })),
|
||||
];
|
||||
|
||||
/** The xterm theme. `resolve` turns a CSS color into a hex color, with the alpha capped at `maxAlpha`. The background is transparent. */
|
||||
export function terminalColors(resolve: (css: string, maxAlpha: number) => string): ITheme {
|
||||
const theme: ITheme = { background: "#00000000" };
|
||||
for (const { key, token, maxAlpha = 255 } of TERMINAL_TOKENS) theme[key] = resolve(token, maxAlpha);
|
||||
return theme;
|
||||
}
|
||||
|
||||
/** The xterm theme for the tokens that apply to `element`. */
|
||||
export function terminalTheme(element: HTMLElement): ITheme {
|
||||
const probe = document.createElement("span");
|
||||
probe.style.display = "none";
|
||||
element.append(probe);
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = canvas.height = 1;
|
||||
const context = canvas.getContext("2d", { willReadFrequently: true })!;
|
||||
try {
|
||||
return terminalColors((value, maxAlpha) => {
|
||||
probe.style.color = value;
|
||||
context.clearRect(0, 0, 1, 1);
|
||||
const resolved = getComputedStyle(probe).color;
|
||||
context.fillStyle = resolved;
|
||||
context.fillRect(0, 0, 1, 1);
|
||||
const alpha = context.getImageData(0, 0, 1, 1).data[3];
|
||||
if (maxAlpha < 255) {
|
||||
// Paint the color opaque, so premultiplied alpha does not change the hue.
|
||||
context.fillStyle = `rgb(from ${resolved} r g b / 1)`;
|
||||
context.fillRect(0, 0, 1, 1);
|
||||
}
|
||||
const channels = [...context.getImageData(0, 0, 1, 1).data];
|
||||
channels[3] = Math.min(alpha, maxAlpha);
|
||||
return "#" + channels.map(byte => byte.toString(16).padStart(2, "0")).join("");
|
||||
});
|
||||
} finally {
|
||||
probe.remove();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `update` in the next frame after a theme change: the `runestone-theme-changed` event of `applyAppearance`,
|
||||
* or a change of a class, style, or theme attribute of `element` or its parents. Returns the function that stops it.
|
||||
*/
|
||||
export function watchTerminalAppearance(element: HTMLElement, update: () => void): () => void {
|
||||
let frame = 0;
|
||||
const queue = () => {
|
||||
cancelAnimationFrame(frame);
|
||||
frame = requestAnimationFrame(update);
|
||||
};
|
||||
const observer = new MutationObserver(queue);
|
||||
for (let node: HTMLElement | null = element; node; node = node.parentElement) {
|
||||
observer.observe(node, { attributes: true, attributeFilter: ["class", "style", "data-theme", "data-palette"] });
|
||||
}
|
||||
observer.observe(document.head, { childList: true, subtree: true, characterData: true });
|
||||
window.addEventListener("runestone-theme-changed", queue);
|
||||
return () => { observer.disconnect(); window.removeEventListener("runestone-theme-changed", queue); cancelAnimationFrame(frame); };
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// The desktop side of the terminal: the `pty_*` commands of src-tauri/src/pty.rs.
|
||||
// Each shell sends its output over a channel to this webview only. Output arrives as raw bytes (an ArrayBuffer),
|
||||
// and the exit as `{ exit: code }`. The host checks that each session belongs to the calling window.
|
||||
import { Channel, invoke } from "@tauri-apps/api/core";
|
||||
import type { ShellProfile } from "./model.ts";
|
||||
import type { PtyTransport } from "./sessions.ts";
|
||||
|
||||
/**
|
||||
* The ID of this page load. At the first start in a new page, the host closes the sessions that an earlier page
|
||||
* of the same window left, for example before a reload. Every panel of this page uses the same ID.
|
||||
*/
|
||||
const page = crypto.randomUUID();
|
||||
|
||||
export const desktopTransport: PtyTransport = {
|
||||
open: (request, onData, onExit) => {
|
||||
const channel = new Channel<ArrayBuffer | { exit: number | null }>(message => {
|
||||
if (message instanceof ArrayBuffer) onData(new Uint8Array(message));
|
||||
else if (message && typeof message === "object" && "exit" in message) onExit(message.exit);
|
||||
});
|
||||
return invoke<void>("pty_open", { ...request, page, channel });
|
||||
},
|
||||
write: (id, data) => invoke<void>("pty_write", { id, data }),
|
||||
resize: (id, cols, rows) => invoke<void>("pty_resize", { id, cols, rows }),
|
||||
close: id => invoke<void>("pty_close", { id }),
|
||||
profiles: () => invoke<ShellProfile[]>("pty_profiles"),
|
||||
openWindow: () => invoke<void>("pty_new_window", { id: crypto.randomUUID() }),
|
||||
dictation: () => invoke<void>("pty_dictation"),
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { ITerminalOptions } from "@xterm/xterm";
|
||||
|
||||
/** The code font of the theme, so the terminal and the code editor use the same font and weight. */
|
||||
export function terminalTypography(element: HTMLElement): Pick<ITerminalOptions, "fontFamily" | "fontWeight" | "fontWeightBold"> {
|
||||
const style = getComputedStyle(element);
|
||||
const weight = Number(style.getPropertyValue("--rs-code-font-weight").trim() || 300);
|
||||
return {
|
||||
fontFamily: style.getPropertyValue("--rs-font-mono").trim() || '"Cascadia Mono", "Cascadia Code", "JetBrains Mono", "Fira Code", Consolas, ui-monospace, monospace',
|
||||
fontWeight: (Number.isFinite(weight) && weight >= 100 && weight <= 900 ? weight : 300) as ITerminalOptions["fontWeight"],
|
||||
fontWeightBold: 600,
|
||||
};
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
// The xterm style sheet. Vite bundles it with the feature chunk. The unit test type check has no Vite types, so it needs this declaration.
|
||||
declare module "@xterm/xterm/css/xterm.css";
|
||||
@@ -0,0 +1,48 @@
|
||||
// The contract between the hosts of the terminal panel (the workbench and the terminal window) and the Terminal feature.
|
||||
// This file is in the main bundle. It loads no feature code: `terminalInstance` loads the module at first use.
|
||||
import { featureInstance } from "../plugins/external.ts";
|
||||
import type { TerminalAction } from "./terminalKeys.ts";
|
||||
import type { FeatureInstance } from "./types.ts";
|
||||
|
||||
export type { TerminalAction } from "./terminalKeys.ts";
|
||||
|
||||
/** What the host gives to the terminal panel. */
|
||||
export interface TerminalProps {
|
||||
/** The workspace folder. A new terminal starts there. */
|
||||
cwd: string;
|
||||
visible: boolean;
|
||||
maximized?: boolean;
|
||||
/** True in a terminal window, which has no maximize control. */
|
||||
standalone?: boolean;
|
||||
/** The panel closed all its sessions. */
|
||||
onClose: () => void;
|
||||
onMaximize?: () => void;
|
||||
/** True when the active tab is a text file that Run active file can run. */
|
||||
activeFile?: boolean;
|
||||
/** Save the active file and return its absolute path, or null. */
|
||||
onRunFile?: () => Promise<string | null>;
|
||||
/** The selected text of the editor. */
|
||||
getSelection?: () => string;
|
||||
/** Open `.runestone/tasks.json`, and make it first when it does not exist. */
|
||||
onConfigureTasks?: () => Promise<void>;
|
||||
/** Open Settings, where Settings → Terminal is. */
|
||||
onOpenSettings?: () => void;
|
||||
}
|
||||
|
||||
/** One terminal panel in a host element. */
|
||||
export interface TerminalMount {
|
||||
update(props: TerminalProps): void;
|
||||
command(action: Exclude<TerminalAction, "toggle">): Promise<void>;
|
||||
/** Close the sessions of the panel and remove it. */
|
||||
dispose(): Promise<void>;
|
||||
}
|
||||
|
||||
/** The instance of the Terminal feature in one window. */
|
||||
export interface TerminalInstance extends FeatureInstance {
|
||||
mountDock(element: HTMLElement, props: TerminalProps): TerminalMount;
|
||||
}
|
||||
|
||||
/** Load the Terminal feature if necessary and return its instance in this window. Fails while Terminal is off. */
|
||||
export async function terminalInstance(): Promise<TerminalInstance> {
|
||||
return await featureInstance("terminal") as TerminalInstance;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// The shortcuts of the Terminal feature. This file is in the main bundle, because the workbench routes the keys
|
||||
// and Help lists them while the feature code is not loaded yet.
|
||||
import { message } from "../i18n/index.ts";
|
||||
|
||||
/** The actions of a terminal shortcut. "toggle" shows or hides the terminal panel. */
|
||||
export type TerminalAction = "toggle" | "new" | "window" | "split" | "previous" | "next" | "commands" | "directories";
|
||||
export type TerminalKeyEvent = Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "code" | "key">;
|
||||
|
||||
/** The terminal action of a key event, or null. Backquote and Digit5 match the physical key on each keyboard layout. */
|
||||
export function terminalShortcut(event: TerminalKeyEvent): TerminalAction | null {
|
||||
if (!event.ctrlKey && !event.metaKey) return null;
|
||||
if (event.code === "Backquote" || event.key === "`") return event.shiftKey ? event.altKey ? "window" : "new" : "toggle";
|
||||
if (event.shiftKey && event.code === "Digit5" && !event.altKey) return "split";
|
||||
if (!event.shiftKey && !event.altKey && event.key.toLowerCase() === "j") return "toggle";
|
||||
if (!event.shiftKey && !event.altKey && event.key === "ArrowUp") return "previous";
|
||||
if (!event.shiftKey && !event.altKey && event.key === "ArrowDown") return "next";
|
||||
if (!event.shiftKey && event.altKey && event.key.toLowerCase() === "r") return "commands";
|
||||
if (!event.shiftKey && !event.altKey && event.key.toLowerCase() === "g") return "directories";
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The written combination of each action, for menus and Help. `keys()` in `src/lib/ui/shortcuts.ts` gives the label. */
|
||||
export const TERMINAL_KEYS = {
|
||||
toggle: "Mod+J",
|
||||
new: "Mod+Shift+`",
|
||||
window: "Mod+Shift+Alt+`",
|
||||
split: "Mod+Shift+5",
|
||||
previous: "Mod+ArrowUp",
|
||||
next: "Mod+ArrowDown",
|
||||
commands: "Mod+Alt+R",
|
||||
directories: "Mod+G",
|
||||
} as const satisfies Record<TerminalAction, string>;
|
||||
|
||||
/** The Terminal rows of Help. They show only while Terminal is on. */
|
||||
export const TERMINAL_SHORTCUTS: readonly { label: string; keys: string }[] = [
|
||||
{ label: message("Show or hide the terminal"), keys: TERMINAL_KEYS.toggle },
|
||||
{ label: message("New terminal"), keys: TERMINAL_KEYS.new },
|
||||
{ label: message("New terminal window"), keys: TERMINAL_KEYS.window },
|
||||
{ label: message("Split terminal"), keys: TERMINAL_KEYS.split },
|
||||
{ label: message("Scroll to the previous command"), keys: TERMINAL_KEYS.previous },
|
||||
{ label: message("Scroll to the next command"), keys: TERMINAL_KEYS.next },
|
||||
{ label: message("Run a recent command"), keys: TERMINAL_KEYS.commands },
|
||||
{ label: message("Go to a recent folder"), keys: TERMINAL_KEYS.directories },
|
||||
{ label: message("Copy the selected output"), keys: "Mod+Shift+C" },
|
||||
];
|
||||
@@ -0,0 +1,76 @@
|
||||
// The settings of the Terminal feature: the `terminal` section of the settings file.
|
||||
// This file is in the main bundle, because Settings → Terminal and the first-start migration need it without xterm.
|
||||
import { onSettingsChange, readSection, writeSection } from "../settings/store.ts";
|
||||
|
||||
export interface TerminalSettings {
|
||||
/** The profile of a new terminal. An empty value or an unknown profile selects the first shell that is not Node.js. */
|
||||
defaultProfile: string;
|
||||
/** From 9 to 28 pixels. */
|
||||
fontSize: number;
|
||||
/** From 100 to 100,000 lines. */
|
||||
scrollback: number;
|
||||
cursorBlink: boolean;
|
||||
}
|
||||
|
||||
export const DEFAULT_TERMINAL: Readonly<TerminalSettings> = Object.freeze({ defaultProfile: "", fontSize: 13, scrollback: 10000, cursorBlink: true });
|
||||
export const FONT_SIZE = { min: 9, max: 28 } as const;
|
||||
export const SCROLLBACK = { min: 100, max: 100000 } as const;
|
||||
/** The localStorage key of the Terminal plugin. The first start copies it into the `terminal` section and keeps it. */
|
||||
export const LEGACY_TERMINAL_KEY = "runestone.terminal";
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
}
|
||||
|
||||
const limit = (value: unknown, range: { min: number; max: number }, fallback: number) =>
|
||||
typeof value === "number" && Number.isFinite(value) ? Math.min(range.max, Math.max(range.min, Math.round(value))) : fallback;
|
||||
|
||||
/** Valid settings from any value. Invalid fields take the defaults. */
|
||||
export function normalizeTerminal(value: unknown): TerminalSettings {
|
||||
const raw = record(value);
|
||||
return {
|
||||
defaultProfile: typeof raw.defaultProfile === "string" ? raw.defaultProfile : DEFAULT_TERMINAL.defaultProfile,
|
||||
fontSize: limit(raw.fontSize, FONT_SIZE, DEFAULT_TERMINAL.fontSize),
|
||||
scrollback: limit(raw.scrollback, SCROLLBACK, DEFAULT_TERMINAL.scrollback),
|
||||
cursorBlink: typeof raw.cursorBlink === "boolean" ? raw.cursorBlink : DEFAULT_TERMINAL.cursorBlink,
|
||||
};
|
||||
}
|
||||
|
||||
export function readTerminal(): TerminalSettings {
|
||||
return normalizeTerminal(readSection("terminal"));
|
||||
}
|
||||
|
||||
/** Save the settings. Keys of a newer version stay. */
|
||||
export function writeTerminal(next: TerminalSettings): Promise<void> {
|
||||
return writeSection("terminal", { ...record(readSection("terminal")), ...normalizeTerminal(next) });
|
||||
}
|
||||
|
||||
/** Run `listener` after each change of the terminal settings in any window. Returns the function that stops it. */
|
||||
export function onTerminalChange(listener: () => void): () => void {
|
||||
return onSettingsChange("terminal", listener);
|
||||
}
|
||||
|
||||
/** The host side of the first-start migration of the `terminal` section. */
|
||||
export interface TerminalMigrationHost {
|
||||
/** True when the settings file has no `terminal` section. */
|
||||
missing(): boolean;
|
||||
/** The value of the old localStorage key, or null. */
|
||||
legacy(): string | null;
|
||||
write(value: TerminalSettings): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make the `terminal` section from the localStorage key of the Terminal plugin. The old key stays, so an older version keeps it.
|
||||
* Without an old key, nothing is written and the defaults apply. Returns the written settings, or null.
|
||||
*/
|
||||
export async function migrateTerminal(host: TerminalMigrationHost): Promise<TerminalSettings | null> {
|
||||
if (!host.missing()) return null;
|
||||
let raw: string | null;
|
||||
try { raw = host.legacy(); } catch { return null; }
|
||||
if (raw === null) return null;
|
||||
let parsed: unknown;
|
||||
try { parsed = JSON.parse(raw); } catch { parsed = null; }
|
||||
const value = normalizeTerminal(parsed);
|
||||
await host.write(value);
|
||||
return value;
|
||||
}
|
||||
Reference in New Issue
Block a user