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;
|
||||
}
|
||||
@@ -3563,6 +3563,103 @@ export const messageRows: [string, string, string, string][] = [
|
||||
["{count} images.", "{count} images.", "{count} 枚の画像。", "{count} 张图像。"],
|
||||
["{count} matches. Type more of the name to see other images.", "{count} résultats. Saisissez une plus grande partie du nom pour voir d’autres images.", "{count} 件一致しました。ほかの画像を表示するには、名前をさらに入力してください。", "{count} 个匹配项。请输入更多名称以查看其他图像。"],
|
||||
["{name}: skipped {count} unreadable images.", "{name} : {count} images illisibles ignorées.", "{name}: 読み込めない {count} 枚の画像をスキップしました。", "{name}:已跳过 {count} 张无法读取的图像。"],
|
||||
// The Terminal feature (src/lib/features/terminal/, Settings → Terminal).
|
||||
["A Node.js REPL with a local inspector. Attach an external debugger to it.", "Un REPL Node.js avec un inspecteur local. Attachez-y un débogueur externe.", "ローカルインスペクター付きの Node.js REPL です。外部デバッガーを接続してください。", "带本地检查器的 Node.js REPL。请将外部调试器附加到它。"],
|
||||
["A path cannot contain line breaks or null characters.", "Un chemin ne peut pas contenir de sauts de ligne ni de caractères nuls.", "パスに改行文字やヌル文字を含めることはできません。", "路径不能包含换行符或空字符。"],
|
||||
["Blink cursor", "Curseur clignotant", "カーソルを点滅", "光标闪烁"],
|
||||
["Choose a whole number from {min} to {max}.", "Choisissez un nombre entier de {min} à {max}.", "{min} から {max} までの整数を選択してください。", "请选择 {min} 到 {max} 之间的整数。"],
|
||||
["Clear the terminal", "Effacer le terminal", "ターミナルをクリア", "清除终端"],
|
||||
["Close terminal (end all sessions)", "Fermer le terminal (terminer toutes les sessions)", "ターミナルを閉じる(すべてのセッションを終了)", "关闭终端(结束所有会话)"],
|
||||
["Close terminal window", "Fermer la fenêtre du terminal", "ターミナルウィンドウを閉じる", "关闭终端窗口"],
|
||||
["Close the list", "Fermer la liste", "リストを閉じる", "关闭列表"],
|
||||
["Configure tasks…", "Configurer les tâches…", "タスクを構成…", "配置任务…"],
|
||||
["Copy the selected output", "Copier la sortie sélectionnée", "選択した出力をコピー", "复制所选输出"],
|
||||
["Default", "Par défaut", "既定", "默认"],
|
||||
["Default profile", "Profil par défaut", "既定のプロファイル", "默认配置文件"],
|
||||
["Default terminal profile", "Profil de terminal par défaut", "既定のターミナルプロファイル", "默认终端配置文件"],
|
||||
["Dismiss the terminal error", "Ignorer l’erreur du terminal", "ターミナルのエラーを閉じる", "关闭终端错误"],
|
||||
["Each task needs a label, a command, and an optional profile ID.", "Chaque tâche nécessite un libellé, une commande et un ID de profil facultatif.", "各タスクにはラベル、コマンド、および任意のプロファイル ID が必要です。", "每个任务都需要标签、命令以及可选的配置文件 ID。"],
|
||||
["Exited", "Terminé", "終了", "已退出"],
|
||||
["Exited ({code})", "Terminé ({code})", "終了 ({code})", "已退出({code})"],
|
||||
["Failed", "Échec", "失敗", "失败"],
|
||||
["Finding the installed shells…", "Recherche des shells installés…", "インストール済みのシェルを検索中…", "正在查找已安装的 shell…"],
|
||||
["Font size", "Taille de police", "フォントサイズ", "字体大小"],
|
||||
["Font, scrollback, and cursor apply to open terminals. The default profile applies to new terminals.", "La police, l’historique de défilement et le curseur s’appliquent aux terminaux ouverts. Le profil par défaut s’applique aux nouveaux terminaux.", "フォント、スクロールバック、カーソルは開いているターミナルに適用されます。既定のプロファイルは新しいターミナルに適用されます。", "字体、回滚和光标应用于已打开的终端。默认配置文件应用于新终端。"],
|
||||
["From {min} to {max} pixels.", "De {min} à {max} pixels.", "{min} から {max} ピクセルまで。", "{min} 到 {max} 像素。"],
|
||||
["Go to a recent folder", "Aller à un dossier récent", "最近のフォルダーに移動", "转到最近的文件夹"],
|
||||
["Go to a recent folder…", "Aller à un dossier récent…", "最近のフォルダーに移動…", "转到最近的文件夹…"],
|
||||
["Kill terminal", "Arrêter le terminal", "ターミナルを強制終了", "终止终端"],
|
||||
["Kill {title} ({shortcut})", "Arrêter {title} ({shortcut})", "{title} を強制終了 ({shortcut})", "终止 {title}({shortcut})"],
|
||||
["Loading the terminal…", "Chargement du terminal…", "ターミナルを読み込み中…", "正在加载终端…"],
|
||||
["Maximize panel", "Agrandir le panneau", "パネルを最大化", "最大化面板"],
|
||||
["More terminal actions", "Autres actions du terminal", "その他のターミナル操作", "更多终端操作"],
|
||||
["New terminal", "Nouveau terminal", "新しいターミナル", "新建终端"],
|
||||
["New terminal window", "Nouvelle fenêtre de terminal", "新しいターミナルウィンドウ", "新建终端窗口"],
|
||||
["No commands yet. Shell commands show after the next prompt.", "Aucune commande pour l’instant. Les commandes du shell apparaissent après la prochaine invite.", "コマンドはまだありません。シェルのコマンドは次のプロンプトの後に表示されます。", "还没有命令。shell 命令会在下一个提示符之后显示。"],
|
||||
["No entries match the filter.", "Aucune entrée ne correspond au filtre.", "フィルターに一致する項目はありません。", "没有与筛选条件匹配的条目。"],
|
||||
["No entries yet.", "Aucune entrée pour l’instant.", "項目はまだありません。", "还没有条目。"],
|
||||
["No folders yet.", "Aucun dossier pour l’instant.", "フォルダーはまだありません。", "还没有文件夹。"],
|
||||
["No shell", "Aucun shell", "シェルなし", "无 shell"],
|
||||
["No tasks yet. Choose Configure tasks… to add one.", "Aucune tâche pour l’instant. Choisissez Configurer les tâches… pour en ajouter une.", "タスクはまだありません。[タスクを構成…]を選んで追加してください。", "还没有任务。请选择“配置任务…”来添加任务。"],
|
||||
["No terminal sessions.", "Aucune session de terminal.", "ターミナルセッションはありません。", "没有终端会话。"],
|
||||
["Process exited", "Processus terminé", "プロセスが終了しました", "进程已退出"],
|
||||
["Process exited with code {code}", "Processus terminé avec le code {code}", "プロセスがコード {code} で終了しました", "进程已退出,代码为 {code}"],
|
||||
["Resize split terminals", "Redimensionner les terminaux divisés", "分割したターミナルのサイズを変更", "调整拆分终端的大小"],
|
||||
["Resize terminal list", "Redimensionner la liste des terminaux", "ターミナル一覧のサイズを変更", "调整终端列表的大小"],
|
||||
["Restore panel", "Restaurer le panneau", "パネルを元に戻す", "还原面板"],
|
||||
["Run a recent command", "Exécuter une commande récente", "最近のコマンドを実行", "运行最近的命令"],
|
||||
["Run a recent command…", "Exécuter une commande récente…", "最近のコマンドを実行…", "运行最近的命令…"],
|
||||
["Run a task", "Exécuter une tâche", "タスクを実行", "运行任务"],
|
||||
["Run a task…", "Exécuter une tâche…", "タスクを実行…", "运行任务…"],
|
||||
["Run selected text", "Exécuter le texte sélectionné", "選択したテキストを実行", "运行所选文本"],
|
||||
["Run shells, tasks, and the active file in a panel below the editor or in a separate window.", "Exécutez des shells, des tâches et le fichier actif dans un panneau sous l’éditeur ou dans une fenêtre séparée.", "エディターの下のパネルまたは別のウィンドウで、シェル、タスク、アクティブなファイルを実行します。", "在编辑器下方的面板或单独的窗口中运行 shell、任务和当前文件。"],
|
||||
["Run the active file", "Exécuter le fichier actif", "アクティブなファイルを実行", "运行当前文件"],
|
||||
["RuneStone cannot read .runestone/tasks.json. Use Configure tasks… to make or change it. {error}", "RuneStone ne peut pas lire .runestone/tasks.json. Utilisez Configurer les tâches… pour le créer ou le modifier. {error}", "RuneStone は .runestone/tasks.json を読み込めません。[タスクを構成…]で作成または変更してください。{error}", "RuneStone 无法读取 .runestone/tasks.json。请使用“配置任务…”来创建或更改它。{error}"],
|
||||
["RuneStone cannot run this file type. Use Run selected text, or add a task.", "RuneStone ne peut pas exécuter ce type de fichier. Utilisez Exécuter le texte sélectionné, ou ajoutez une tâche.", "RuneStone はこの種類のファイルを実行できません。[選択したテキストを実行]を使うか、タスクを追加してください。", "RuneStone 无法运行此类文件。请使用“运行所选文本”,或添加任务。"],
|
||||
["RuneStone could not list the shells: {error}", "RuneStone n’a pas pu lister les shells : {error}", "RuneStone はシェルを一覧表示できませんでした: {error}", "RuneStone 无法列出 shell:{error}"],
|
||||
["RuneStone found no supported shells on PATH.", "RuneStone n’a trouvé aucun shell pris en charge dans PATH.", "RuneStone は PATH 上にサポートされているシェルを見つけられませんでした。", "RuneStone 在 PATH 中未找到受支持的 shell。"],
|
||||
["Running", "En cours", "実行中", "正在运行"],
|
||||
["Scroll to the next command", "Défiler jusqu’à la commande suivante", "次のコマンドまでスクロール", "滚动到下一个命令"],
|
||||
["Scroll to the previous command", "Défiler jusqu’à la commande précédente", "前のコマンドまでスクロール", "滚动到上一个命令"],
|
||||
["Scrollback lines", "Lignes d’historique de défilement", "スクロールバックの行数", "回滚行数"],
|
||||
["Select a shell terminal to run files. The debug terminal is a Node.js REPL.", "Sélectionnez un terminal shell pour exécuter des fichiers. Le terminal de débogage est un REPL Node.js.", "ファイルを実行するにはシェルのターミナルを選択してください。デバッグターミナルは Node.js REPL です。", "请选择 shell 终端来运行文件。调试终端是 Node.js REPL。"],
|
||||
["Select text in the editor first.", "Sélectionnez d’abord du texte dans l’éditeur.", "先にエディターでテキストを選択してください。", "请先在编辑器中选择文本。"],
|
||||
["Select the default profile", "Sélectionner le profil par défaut", "既定のプロファイルを選択", "选择默认配置文件"],
|
||||
["Select the default terminal profile", "Sélectionner le profil de terminal par défaut", "既定のターミナルプロファイルを選択", "选择默认终端配置文件"],
|
||||
["Split terminal", "Diviser le terminal", "ターミナルを分割", "拆分终端"],
|
||||
["Split terminal ({shortcut})", "Diviser le terminal ({shortcut})", "ターミナルを分割 ({shortcut})", "拆分终端({shortcut})"],
|
||||
["Split terminal with profile", "Diviser le terminal avec un profil", "プロファイルを指定してターミナルを分割", "使用配置文件拆分终端"],
|
||||
["Split {title}", "Diviser {title}", "{title} を分割", "拆分 {title}"],
|
||||
["Start Windows voice typing in the focused terminal", "Démarrer la saisie vocale Windows dans le terminal actif", "フォーカスのあるターミナルで Windows の音声入力を開始", "在聚焦的终端中启动 Windows 语音输入"],
|
||||
["Start a terminal", "Démarrer un terminal", "ターミナルを開始", "启动终端"],
|
||||
["Start dictation", "Démarrer la dictée", "音声入力を開始", "开始听写"],
|
||||
["Starting", "Démarrage", "開始中", "正在启动"],
|
||||
["Terminal actions", "Actions du terminal", "ターミナルの操作", "终端操作"],
|
||||
["Terminal is off. Turn it on in Settings → Features.", "Le terminal est désactivé. Activez-le dans Paramètres → Fonctionnalités.", "ターミナルはオフです。[設定]→[機能]でオンにしてください。", "终端已关闭。请在“设置”→“功能”中将其打开。"],
|
||||
["Terminal list", "Liste des terminaux", "ターミナル一覧", "终端列表"],
|
||||
["Terminal profiles", "Profils du terminal", "ターミナルプロファイル", "终端配置文件"],
|
||||
["Terminal profiles and tasks", "Profils et tâches du terminal", "ターミナルのプロファイルとタスク", "终端配置文件和任务"],
|
||||
["Terminal sessions will end.", "Les sessions du terminal vont se terminer.", "ターミナルセッションは終了します。", "终端会话将结束。"],
|
||||
["Terminal settings", "Paramètres du terminal", "ターミナルの設定", "终端设置"],
|
||||
["The cursor blinks in the focused terminal.", "Le curseur clignote dans le terminal actif.", "フォーカスのあるターミナルでカーソルが点滅します。", "光标在聚焦的终端中闪烁。"],
|
||||
["The desktop app lists the installed shells.", "L’application de bureau liste les shells installés.", "デスクトップアプリはインストール済みのシェルを一覧表示します。", "桌面应用会列出已安装的 shell。"],
|
||||
["The lines that a terminal keeps above the screen, from {min} to {max}.", "Les lignes qu’un terminal conserve au-dessus de l’écran, de {min} à {max}.", "ターミナルが画面の上に保持する行数({min} から {max} まで)。", "终端在屏幕上方保留的行数,从 {min} 到 {max}。"],
|
||||
["The profile of this task is not installed: {profile}", "Le profil de cette tâche n’est pas installé : {profile}", "このタスクのプロファイルはインストールされていません: {profile}", "此任务的配置文件未安装:{profile}"],
|
||||
["The shell of a new terminal.", "Le shell d’un nouveau terminal.", "新しいターミナルのシェル。", "新终端的 shell。"],
|
||||
["The tasks file needs a \"tasks\" array.", "Le fichier des tâches nécessite un tableau « tasks ».", "タスクファイルには \"tasks\" 配列が必要です。", "任务文件需要一个 \"tasks\" 数组。"],
|
||||
["The terminal could not start: {error}", "Le terminal n’a pas pu démarrer : {error}", "ターミナルを開始できませんでした: {error}", "终端无法启动:{error}"],
|
||||
["This terminal is already running.", "Ce terminal est déjà en cours d’exécution.", "このターミナルはすでに実行中です。", "此终端已在运行。"],
|
||||
["This terminal is closed.", "Ce terminal est fermé.", "このターミナルは閉じられています。", "此终端已关闭。"],
|
||||
["This terminal is not running.", "Ce terminal n’est pas en cours d’exécution.", "このターミナルは実行されていません。", "此终端未在运行。"],
|
||||
["Turn off Terminal", "Désactiver le terminal", "ターミナルをオフにする", "关闭终端"],
|
||||
["Turn off Terminal?", "Désactiver le terminal ?", "ターミナルをオフにしますか?", "要关闭终端吗?"],
|
||||
["Type to filter…", "Tapez pour filtrer…", "入力して絞り込み…", "输入以筛选…"],
|
||||
["Unsaved edits will be discarded.", "Les modifications non enregistrées seront perdues.", "保存されていない編集内容は破棄されます。", "未保存的编辑将被丢弃。"],
|
||||
["Use PowerShell for a path with quotes, % or !.", "Utilisez PowerShell pour un chemin contenant des guillemets, % ou !.", "引用符、%、! を含むパスには PowerShell を使用してください。", "对于包含引号、% 或 ! 的路径,请使用 PowerShell。"],
|
||||
["{title}: choices", "{title} : choix", "{title}: 選択肢", "{title}:选项"],
|
||||
["{up} {down} select · {enter} choose · {escape} close", "{up} {down} sélectionner · {enter} choisir · {escape} fermer", "{up} {down} 選択 · {enter} 決定 · {escape} 閉じる", "{up} {down} 选择 · {enter} 确定 · {escape} 关闭"],
|
||||
// The native features without the desktop host.
|
||||
["This feature needs the desktop app.", "Cette fonctionnalité nécessite l’application de bureau.", "この機能にはデスクトップアプリが必要です。", "此功能需要桌面应用。"],
|
||||
];
|
||||
export const catalogs: Record<Exclude<Locale, 'en'>, Record<string, string>> = {
|
||||
fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])),
|
||||
|
||||
@@ -11,6 +11,10 @@
|
||||
import { FEATURES, type FeatureId } from "$lib/features/catalog";
|
||||
import { featureSwitches, setFeature } from "$lib/features/state";
|
||||
import { featureErrors } from "$lib/features/loader";
|
||||
import { TERMINAL_SHORTCUTS } from "$lib/features/terminalKeys";
|
||||
import TerminalSettings from "$lib/features/TerminalSettings.svelte";
|
||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import { confirm } from "@tauri-apps/plugin-dialog";
|
||||
import { onMount, untrack, type Snippet } from "svelte";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import IconButton, { type IconName } from "$lib/ui/IconButton.svelte";
|
||||
@@ -19,13 +23,16 @@
|
||||
import { appVersion as version } from "../appVersion";
|
||||
import { COMMAND_LABELS, OTHER_SHORTCUTS, commandShortcut, shortcutKeys, type WorkbenchCommand } from "./workbenchKeys";
|
||||
import { isMac } from "$lib/ui/shortcuts";
|
||||
// Help lists every shortcut: the workbench commands, then the editor and file tree shortcuts.
|
||||
const shortcutSections = (() => {
|
||||
const general = (Object.keys(COMMAND_LABELS) as WorkbenchCommand[]).map(command => ({ label: COMMAND_LABELS[command], keys: commandShortcut(command) })).filter(item => item.keys);
|
||||
// Help lists every shortcut: the workbench commands, then the editor and file tree shortcuts, then Terminal while it is on.
|
||||
const shortcutSections = $derived.by(() => {
|
||||
const terminal = $featureSwitches.terminal;
|
||||
const general = (Object.keys(COMMAND_LABELS) as WorkbenchCommand[]).filter(command => terminal || command !== "toggle-terminal")
|
||||
.map(command => ({ label: COMMAND_LABELS[command], keys: commandShortcut(command) })).filter(item => item.keys);
|
||||
const others = new Map<string, { label: string; keys: string }[]>();
|
||||
for (const item of OTHER_SHORTCUTS) others.set(item.section, [...(others.get(item.section) ?? []), { label: item.label, keys: shortcutKeys(isMac() && item.macKeys ? item.macKeys : item.keys) }]);
|
||||
if (terminal) others.set("Terminal", TERMINAL_SHORTCUTS.map(item => ({ label: item.label, keys: shortcutKeys(item.keys) })));
|
||||
return [{ name: "General", items: general }, ...[...others].map(([name, items]) => ({ name, items }))];
|
||||
})();
|
||||
});
|
||||
|
||||
let { settings, help = false, standalone = false, windowError = "", windowControls, onSave, onClose }: {
|
||||
settings: AppSettings;
|
||||
@@ -69,7 +76,8 @@
|
||||
label: tool.title, icon: "settings" as const,
|
||||
keywords: `${$installedPlugins.plugins.find(row => row.manifest.id === tool.owner)?.manifest.name ?? tool.owner} settings configuration`,
|
||||
})));
|
||||
const matches = $derived([...sections, ...(browserEnabled ? [{ id: "browser" as const, label: $t("Browser"), icon: "globe" as const, keywords: "browser profiles search cookies cache web privacy" }] : []), ...pluginSections].filter(item => `${item.label} ${item.keywords}`.toLowerCase().includes(query.trim().toLowerCase())));
|
||||
const terminalSection = $derived($featureSwitches.terminal ? [{ id: "terminal" as const, label: $t("Terminal"), icon: "terminal" as const, keywords: "terminal shell profile default font size scrollback lines cursor blink powershell bash cmd" }] : []);
|
||||
const matches = $derived([...sections, ...(browserEnabled ? [{ id: "browser" as const, label: $t("Browser"), icon: "globe" as const, keywords: "browser profiles search cookies cache web privacy" }] : []), ...terminalSection, ...pluginSections].filter(item => `${item.label} ${item.keywords}`.toLowerCase().includes(query.trim().toLowerCase())));
|
||||
const selected = $derived(matches.find(item => item.id === section) ?? matches[0]);
|
||||
const selectedPlugin = $derived(pluginSections.find(item => item.id === selected?.id));
|
||||
|
||||
@@ -99,8 +107,22 @@
|
||||
apply({ ...settings, autosaveSeconds: seconds });
|
||||
}
|
||||
|
||||
function changeFeature(id: FeatureId, on: boolean) {
|
||||
/** True when a window runs a shell. The host counts the sessions of all windows. */
|
||||
async function shellsRunning(): Promise<boolean> {
|
||||
if (!isTauri()) return false;
|
||||
try { return await invoke<number>("pty_running") > 0; }
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
async function changeFeature(id: FeatureId, on: boolean, input: HTMLInputElement) {
|
||||
error = "";
|
||||
// Terminal off ends the shells of every window, so ask first, with the words of the close guard of the workbench.
|
||||
if (id === "terminal" && !on && await shellsRunning()) {
|
||||
let accepted = false;
|
||||
try { accepted = await confirm(`${$t("Terminal sessions will end.")}\n${$t("Turn off Terminal?")}`, { title: $t("Turn off Terminal"), kind: "warning" }); }
|
||||
catch (reason) { error = String(reason); }
|
||||
if (!accepted) { input.checked = true; return; }
|
||||
}
|
||||
setFeature(id, on).then(() => { message = $t("Changes saved."); })
|
||||
.catch(() => { error = $t("Could not save these settings. Your previous settings still apply. Try again."); message = ""; });
|
||||
}
|
||||
@@ -201,7 +223,7 @@
|
||||
<p id={`feature-${feature.id}-description`}>{$t(feature.description)}</p>
|
||||
{#if $featureErrors[feature.id]}<p class="error" role="alert">{$t("{name} could not load: {error}", { name: $t(feature.name), error: $featureErrors[feature.id] ?? "" })}</p>{/if}
|
||||
</div>
|
||||
<input id={`feature-${feature.id}`} class="rs-switch" type="checkbox" role="switch" aria-describedby={`feature-${feature.id}-description`} checked={$featureSwitches[feature.id]} onchange={event => changeFeature(feature.id, event.currentTarget.checked)} />
|
||||
<input id={`feature-${feature.id}`} class="rs-switch" type="checkbox" role="switch" aria-describedby={`feature-${feature.id}-description`} checked={$featureSwitches[feature.id]} onchange={event => void changeFeature(feature.id, event.currentTarget.checked, event.currentTarget)} />
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
@@ -211,6 +233,8 @@
|
||||
<PluginManager />
|
||||
{:else if selected.id === "browser"}
|
||||
<BrowserSlot kind="settings" />
|
||||
{:else if selected.id === "terminal"}
|
||||
<TerminalSettings />
|
||||
{:else if selectedPlugin}
|
||||
{#key selectedPlugin.id}<PluginSettings owner={selectedPlugin.owner} id={selectedPlugin.view} />{/key}
|
||||
{:else}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
<script lang="ts">
|
||||
import { t } from "$lib/i18n";
|
||||
import TerminalSlot from "$lib/plugins/TerminalSlot.svelte";
|
||||
import TerminalHost from "$lib/features/TerminalHost.svelte";
|
||||
import { featureSwitches } from "$lib/features/state";
|
||||
import { terminalShortcut, type TerminalAction } from "$lib/features/terminalKeys";
|
||||
import type PluginEditor from "$lib/plugins/PluginEditor.svelte";
|
||||
import { featureOfOwner } from "$lib/features/catalog";
|
||||
import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab, waitForPluginStartup, pluginTools, installedPlugins, runPluginCommand } from "$lib/plugins/external";
|
||||
@@ -14,7 +16,6 @@
|
||||
import type { ViewMode } from "./ViewModes.svelte";
|
||||
import { selectedEditorText } from "$lib/editor/selection";
|
||||
import { pluginHost } from "$lib/plugins/registry";
|
||||
import type { Contributions } from "$lib/plugins/contracts";
|
||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
import { confirm, message as dialogMessage } from "@tauri-apps/plugin-dialog";
|
||||
@@ -173,9 +174,9 @@
|
||||
let templateManager = $state(false);
|
||||
let terminalStarted = $state(false);
|
||||
let terminalMaximized = $state(false);
|
||||
let terminalDock: TerminalSlot | undefined = $state();
|
||||
const terminalContribution = $derived.by(() => { void $pluginHost; return pluginHost.get("terminal"); });
|
||||
const terminalEnabled = $derived(!!terminalContribution);
|
||||
let terminalDock: TerminalHost | undefined = $state();
|
||||
// The Terminal buttons, shortcuts, and command work from the switch alone. The first use loads the feature.
|
||||
const terminalEnabled = $derived($featureSwitches.terminal);
|
||||
const sidebarNavigation = $derived($pluginNavigation.filter(item => item.placement === "sidebar"));
|
||||
const ribbonNavigation = $derived($pluginNavigation.filter(item => item.placement !== "sidebar" && !item.toolbar));
|
||||
const browserContribution = $derived.by(() => { void $pluginHost; return pluginHost.get("browser"); });
|
||||
@@ -429,7 +430,7 @@
|
||||
if (terminalOpen && bottomHeight < 220) bottomHeight = 260;
|
||||
}
|
||||
|
||||
async function terminalAction(action: Exclude<ReturnType<Contributions["terminal"]["shortcut"]>, null | "toggle">) {
|
||||
async function terminalAction(action: Exclude<TerminalAction, "toggle">) {
|
||||
if (!terminalEnabled) return;
|
||||
if (!workspace) { error = $t("Open a workspace to start a terminal."); return; }
|
||||
const started = terminalStarted;
|
||||
@@ -965,7 +966,7 @@
|
||||
void pluginPaneComponents[$pluginView.key]?.openFind();
|
||||
return;
|
||||
}
|
||||
const action = pluginHost.get("terminal")?.shortcut(event);
|
||||
const action = terminalEnabled ? terminalShortcut(event) : null;
|
||||
const terminalTarget = event.target instanceof Element && !!event.target.closest(".dock");
|
||||
if (action && (["toggle", "new", "split", "window"].includes(action) || terminalTarget)) {
|
||||
event.preventDefault();
|
||||
@@ -1248,7 +1249,7 @@
|
||||
if (closing) return;
|
||||
closing = true;
|
||||
try {
|
||||
const message = [hasDirty ? "Unsaved edits will be discarded." : "", terminalStarted ? "Terminal sessions will end." : ""].filter(Boolean).join("\n");
|
||||
const message = [hasDirty ? $t("Unsaved edits will be discarded.") : "", terminalStarted ? $t("Terminal sessions will end.") : ""].filter(Boolean).join("\n");
|
||||
if (await confirm(`${message}\n${$t("Close RuneStone?")}`, { title: $t("Close workspace"), kind: "warning" })) {
|
||||
saveDocumentTabs();
|
||||
await getCurrentWindow().destroy();
|
||||
@@ -1392,7 +1393,7 @@
|
||||
onCursor={(pane, line, column) => { if (pane.id === documentPanes.active) cursor = { line, column }; }}
|
||||
onOpenLink={(pane, kind, target) => void openLink(kind, target, pane.buffer?.relPath ?? "", pane.id)}
|
||||
/>
|
||||
{#if terminalContribution && terminalStarted}
|
||||
{#if terminalEnabled && terminalStarted}
|
||||
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions (A focusable separator is the splitter pattern.) -->
|
||||
<div
|
||||
class="gutter gutter-h" class:terminal-hidden={!terminalOpen}
|
||||
@@ -1408,7 +1409,8 @@
|
||||
<section class="bottom" class:terminal-hidden={!terminalOpen}>
|
||||
{#if workspace}
|
||||
{#key workspace.root}
|
||||
<TerminalSlot contribution={terminalContribution} bind:this={terminalDock} cwd={workspace.root} visible={terminalOpen} onClose={() => { terminalOpen = false; terminalStarted = false; terminalMaximized = false; }}
|
||||
<TerminalHost bind:this={terminalDock} cwd={workspace.root} visible={terminalOpen} onClose={() => { terminalOpen = false; terminalStarted = false; terminalMaximized = false; }}
|
||||
onOpenSettings={() => void openSettings()}
|
||||
maximized={terminalMaximized} onMaximize={() => terminalMaximized = !terminalMaximized}
|
||||
activeFile={buffer?.kind === "text" && !reading} onRunFile={terminalFile}
|
||||
getSelection={() => selectedEditorText(buffer?.id)} onConfigureTasks={configureTasks} />
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from "svelte";
|
||||
import type { Contributions, TerminalProps, TerminalMount, TerminalAction } from "./contracts";
|
||||
let { contribution, ...props }: TerminalProps & { contribution: Contributions["terminal"] } = $props();
|
||||
let container: HTMLDivElement;
|
||||
let mounted = $state.raw<TerminalMount>();
|
||||
let error = $state("");
|
||||
onMount(() => {
|
||||
try { mounted = contribution.mount(container, { ...props }); }
|
||||
catch (reason) { error = String(reason); }
|
||||
return () => { void Promise.resolve(mounted?.dispose()).catch(reason => error = String(reason)); mounted = undefined; };
|
||||
});
|
||||
$effect(() => { mounted?.update({ ...props }); });
|
||||
export async function command(action: Exclude<TerminalAction, "toggle">) { await mounted?.command(action); }
|
||||
</script>
|
||||
{#if error}<p role="alert">{error}</p>{/if}
|
||||
<div class="plugin-terminal" bind:this={container}></div>
|
||||
<style>.plugin-terminal { display: flex; flex-direction: column; flex: 1; height: 100%; min-height: 0; min-width: 0; }</style>
|
||||
@@ -1,2 +1,2 @@
|
||||
// Contribution types are part of the public plugin SDK (packages/plugin-sdk/src/contributions.ts).
|
||||
export type { Contributions, TerminalAction, TerminalMount, TerminalProps } from "./sdk.ts";
|
||||
export type { Contributions } from "./sdk.ts";
|
||||
|
||||
@@ -4,17 +4,17 @@ import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { workspaceList, workspaceRead, workspaceReadBytes, workspaceWrite } from "../workspace/api";
|
||||
import { ExternalSession, deadline } from "./externalSession";
|
||||
import { filesTransport, ptyTransport } from "./nativeServices";
|
||||
import { filesTransport } from "./nativeServices";
|
||||
import { pluginAccess, type PluginTool } from "./access";
|
||||
import { containsPane, splitPane, removePane, type SplitLayout } from "../workspace/splitLayout";
|
||||
import type { PluginViewOpenOptions } from "./sdk";
|
||||
import type { PluginModule, PluginSnapshot, InstalledPlugin, Dispose, PluginView, PluginDocumentContext, PluginDocumentType } from "./sdk";
|
||||
import { locale } from "../i18n";
|
||||
import { FEATURES, type FeatureEntry } from "../features/catalog";
|
||||
import { locale, tr } from "../i18n";
|
||||
import { FEATURES, featureEntry, type FeatureEntry, type FeatureId } from "../features/catalog";
|
||||
import { FeatureSession } from "../features/session";
|
||||
import { featureSwitches, type FeatureSwitches } from "../features/state";
|
||||
import { LAUNCH_RULES, launchWanted, runsInWindow } from "../features/launch";
|
||||
import type { FeatureContext } from "../features/types";
|
||||
import type { FeatureContext, FeatureInstance } from "../features/types";
|
||||
|
||||
export const installedPlugins = writable<PluginSnapshot>({ root: "", plugins: [] });
|
||||
export const externalErrors = writable<Record<string, string>>({});
|
||||
@@ -104,6 +104,9 @@ const restarted = new Set<string>();
|
||||
let queue: Promise<void> = Promise.resolve();
|
||||
export function waitForPluginStartup() { return queue; }
|
||||
let started = false;
|
||||
let markStarted: () => void = () => {};
|
||||
/** Resolves when `startExternalPlugins` subscribes to the feature switches. A child component can mount before that. */
|
||||
const whenStarted = new Promise<void>(resolve => { markStarted = resolve; });
|
||||
let browserWindow = false;
|
||||
let settingsWindow = false;
|
||||
let generation = 0;
|
||||
@@ -272,7 +275,6 @@ async function activate(row: InstalledPlugin, builtin?: PluginModule) {
|
||||
let leased = false;
|
||||
const session = new ExternalSession(id, {
|
||||
completionTransport,
|
||||
pty: ptyTransport,
|
||||
files: filesTransport(id),
|
||||
backgrounds: true,
|
||||
openFile: async path => { if (!openFile) throw new Error("File opening is unavailable."); await openFile(path); },
|
||||
@@ -399,6 +401,19 @@ function syncFeatures(switches: FeatureSwitches) {
|
||||
launchFeatures();
|
||||
}).catch(reason => pluginServiceError.set(String(reason)));
|
||||
}
|
||||
/**
|
||||
* The instance of a feature that is on in this window. The first call loads the feature module.
|
||||
* It waits for the feature switches when the window starts. It fails while the feature is off.
|
||||
*/
|
||||
export async function featureInstance(id: FeatureId): Promise<FeatureInstance> {
|
||||
if (!isTauri()) throw new Error(tr("This feature needs the desktop app."));
|
||||
const owner = featureEntry(id).owner;
|
||||
await whenStarted;
|
||||
if (sessions.get(owner)?.hash !== "feature") await queue;
|
||||
const loaded = sessions.get(owner);
|
||||
if (loaded?.hash !== "feature") throw new Error(tr("This feature is off."));
|
||||
return (loaded.session as FeatureSession).loadInstance();
|
||||
}
|
||||
/** Start the instance of each running feature whose launch rule wants it now. */
|
||||
function launchFeatures() {
|
||||
for (const entry of FEATURES) {
|
||||
@@ -426,6 +441,7 @@ export function startExternalPlugins(options: { browserWindow?: boolean } = {}):
|
||||
}).catch(reason => report(builtIn.id, reason));
|
||||
}
|
||||
const offFeatures = featureSwitches.subscribe(syncFeatures);
|
||||
markStarted();
|
||||
const offLaunch = Object.values(LAUNCH_RULES).map(rule => rule.subscribe(launchFeatures));
|
||||
// Feature titles follow the interface language.
|
||||
const offLocale = locale.subscribe(() => publish());
|
||||
|
||||
@@ -4,14 +4,14 @@ import { registerCompletionInput } from "../completion/input.ts";
|
||||
import { showActionMenu } from "../ui/managedActionMenu.ts";
|
||||
import { backgroundHub } from "./backgrounds.ts";
|
||||
import { serviceHub as defaultServiceHub, type ServiceHub } from "./services.ts";
|
||||
import type { Dispose, FilesApi, FilesTransport, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext, PtyApi, PtyOpenOptions, PtySession, PtyTransport } from "./sdk.ts";
|
||||
import type { Dispose, FilesApi, FilesTransport, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext } from "./sdk.ts";
|
||||
|
||||
/** The host services that a session gives to its plugin. The host binds them to the plugin ID. */
|
||||
export type SessionServices = Pick<PluginApi, "workspace" | "settings" | "assets"> & {
|
||||
/** True gives the plugin `api.backgrounds`: the background frames of each target. */
|
||||
openFile?: PluginApi["openFile"]; backgrounds?: boolean;
|
||||
completionTransport?: NonNullable<PluginApi["completion"]>["transport"];
|
||||
pty?: PtyTransport; files?: FilesTransport; serviceHub?: ServiceHub;
|
||||
files?: FilesTransport; serviceHub?: ServiceHub;
|
||||
};
|
||||
|
||||
export function deadline<T>(work: Promise<T>, milliseconds = 5000): Promise<T> {
|
||||
@@ -37,7 +37,6 @@ export class ExternalSession {
|
||||
private backgroundSubscriptions = new Set<() => void>();
|
||||
private serviceOwner = Symbol('plugin services');
|
||||
private serviceSubscriptions = new Set<() => void>();
|
||||
private ptySessions = new Map<string, () => Promise<void>>();
|
||||
readonly id: string;
|
||||
private services: SessionServices;
|
||||
private changed: () => void;
|
||||
@@ -65,7 +64,6 @@ export class ExternalSession {
|
||||
};
|
||||
const api: PluginApi = {
|
||||
id: this.id, signal: this.controller.signal,
|
||||
...(this.services.pty ? { pty: this.ptyApi(this.services.pty) } : {}),
|
||||
...(this.services.files ? { files: this.filesApi(this.services.files) } : {}),
|
||||
services: this.servicesApi(this.services.serviceHub ?? defaultServiceHub),
|
||||
...(this.services.backgrounds ? { backgrounds: {
|
||||
@@ -175,52 +173,6 @@ export class ExternalSession {
|
||||
this.check();
|
||||
return request().then(value => { this.check(); return value; });
|
||||
}
|
||||
private ptyApi(pty: PtyTransport): PtyApi {
|
||||
const size = (cols: unknown, rows: unknown) => {
|
||||
if (![cols, rows].every(value => Number.isInteger(value) && (value as number) > 0 && (value as number) <= 10_000)) throw new Error("Terminal columns and rows must be positive integers.");
|
||||
};
|
||||
const validate = (options: PtyOpenOptions) => {
|
||||
this.check();
|
||||
if (!options || typeof options.onData !== "function" || (options.onExit !== undefined && typeof options.onExit !== "function")) throw new Error("A terminal session needs an onData function.");
|
||||
if (typeof options.cwd !== "string") throw new Error("Supply the workspace folder as cwd.");
|
||||
size(options.cols, options.rows);
|
||||
};
|
||||
const open = async (options: PtyOpenOptions): Promise<PtySession> => {
|
||||
const id = crypto.randomUUID();
|
||||
let closed = false, exited = false, closing: Promise<void> | undefined;
|
||||
const exit = (code: number | null) => {
|
||||
if (exited) return;
|
||||
exited = true; this.ptySessions.delete(id);
|
||||
if (!closed && !this.stopped) options.onExit?.(code);
|
||||
};
|
||||
const opening = pty.open({ id, cwd: options.cwd, cols: options.cols, rows: options.rows, ...(options.profile === undefined ? {} : { profile: options.profile }), ...(options.directory === undefined ? {} : { directory: options.directory }) },
|
||||
data => { if (!closed && !this.stopped) options.onData(data); }, exit);
|
||||
// Wait for the start, so that a close cannot leave a late shell running.
|
||||
const close = () => closing ??= (async () => {
|
||||
closed = true;
|
||||
try { await opening; } catch { this.ptySessions.delete(id); return; }
|
||||
this.ptySessions.delete(id);
|
||||
await pty.close(id);
|
||||
})();
|
||||
this.ptySessions.set(id, close);
|
||||
try { await opening; } catch (error) { this.ptySessions.delete(id); closed = true; throw error; }
|
||||
if (this.stopped) { await close(); this.check(); }
|
||||
const live = () => { this.check(); if (closed) throw new Error("This terminal is closed."); };
|
||||
return {
|
||||
id,
|
||||
write: data => { live(); if (typeof data !== "string") throw new Error("Terminal input must be text."); return pty.write(id, data); },
|
||||
resize: (cols, rows) => { live(); size(cols, rows); return pty.resize(id, cols, rows); },
|
||||
close,
|
||||
};
|
||||
};
|
||||
return {
|
||||
version: 1,
|
||||
profiles: () => this.backgroundRequest(() => pty.profiles()),
|
||||
open: options => { validate(options); return open(options); },
|
||||
openWindow: () => { this.check(); return pty.openWindow(); },
|
||||
dictation: () => { this.check(); return pty.dictation(); },
|
||||
};
|
||||
}
|
||||
private filesApi(files: FilesTransport): FilesApi {
|
||||
const text = (value: unknown, label: string) => { if (typeof value !== "string" || !value) throw new Error(`Supply the ${label} as text.`); };
|
||||
return {
|
||||
@@ -293,10 +245,6 @@ export class ExternalSession {
|
||||
try { await deadline(Promise.resolve().then(cleanup)); } catch (error) { errors.push(error); }
|
||||
}
|
||||
this.cleanups = [];
|
||||
// Stop the terminal sessions that the plugin cleanup left open.
|
||||
for (const close of [...this.ptySessions.values()]) {
|
||||
try { await deadline(close()); } catch (error) { errors.push(error); }
|
||||
}
|
||||
if (errors.length) throw new Error(errors.map(String).join("\n"));
|
||||
})();
|
||||
return this.stopping;
|
||||
|
||||
@@ -1,26 +1,5 @@
|
||||
import { Channel, invoke } from "@tauri-apps/api/core";
|
||||
import type { FilesTransport, FolderEntry, FolderGrant, PtyProfile, PtyTransport } from "./sdk.ts";
|
||||
|
||||
/**
|
||||
* Terminal sessions over a channel to this webview. The output arrives as raw bytes, and no
|
||||
* `pty-data` or `pty-exit` event goes to other windows. The released Terminal plugin uses the
|
||||
* events instead, and the host keeps them for sessions without a channel.
|
||||
*/
|
||||
export const ptyTransport: 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, 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<PtyProfile[]>("pty_profiles"),
|
||||
openWindow: () => invoke<void>("pty_new_window", { id: crypto.randomUUID() }),
|
||||
dictation: () => invoke<void>("pty_dictation"),
|
||||
};
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import type { FilesTransport, FolderEntry, FolderGrant } from "./sdk.ts";
|
||||
|
||||
/** Folder grants of one plugin. The plugin ID comes from the host, not from the plugin. */
|
||||
export function filesTransport(plugin: string): FilesTransport {
|
||||
|
||||
@@ -9,7 +9,7 @@ export class ContributionRegistry {
|
||||
return this.entries.get(key)?.value as Contributions[K] | undefined;
|
||||
}
|
||||
register<K extends keyof Contributions>(owner: string, key: K, value: Contributions[K]): () => void {
|
||||
if (key !== "terminal" && key !== "browser") throw new Error("Unknown plugin contribution.");
|
||||
if (key !== "browser") throw new Error("Unknown plugin contribution.");
|
||||
if (this.entries.has(key)) throw new Error(`Contribution already registered: ${key}`);
|
||||
const entry = { owner, value };
|
||||
this.entries.set(key, entry); this.emit();
|
||||
|
||||
+1
-11
@@ -1,18 +1,8 @@
|
||||
// The public plugin API comes from the SDK package (packages/plugin-sdk). Change the public types there.
|
||||
// The relative path works in SvelteKit, svelte-check, Vite, and the Node unit tests.
|
||||
import type { FilesApi, PluginManifest, PtyProfile } from "../../../packages/plugin-sdk/src/index.ts";
|
||||
import type { FilesApi, PluginManifest } from "../../../packages/plugin-sdk/src/index.ts";
|
||||
export * from "../../../packages/plugin-sdk/src/index.ts";
|
||||
|
||||
/** The native side of `PtyApi`. `onData` and `onExit` receive the output of this session only. */
|
||||
export interface PtyTransport {
|
||||
open(request: { id: string; cwd: string; cols: number; rows: number; profile?: string; directory?: string }, 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<PtyProfile[]>;
|
||||
openWindow(): Promise<void>;
|
||||
dictation(): Promise<void>;
|
||||
}
|
||||
/** The native side of `FilesApi`, bound to one plugin ID by the host. */
|
||||
export type FilesTransport = Omit<FilesApi, "version">;
|
||||
export type ExternalManifest = PluginManifest;
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
import { invoke, isTauri } from '@tauri-apps/api/core';
|
||||
import { listen } from '@tauri-apps/api/event';
|
||||
|
||||
export const SETTINGS_SECTIONS = ['general', 'appearance', 'customThemes', 'customThemesLegacy', 'language', 'features', 'background'] as const;
|
||||
export const SETTINGS_SECTIONS = ['general', 'appearance', 'customThemes', 'customThemesLegacy', 'language', 'features', 'background', 'terminal'] as const;
|
||||
export type SettingsSection = typeof SETTINGS_SECTIONS[number];
|
||||
export type SettingsSections = Partial<Record<SettingsSection, unknown>>;
|
||||
|
||||
@@ -23,6 +23,7 @@ export const LEGACY_KEYS: Readonly<Record<SettingsSection, string>> = {
|
||||
language: 'runestone.language',
|
||||
features: 'runestone.features',
|
||||
background: 'runestone.background',
|
||||
terminal: 'runestone.terminal',
|
||||
};
|
||||
|
||||
/** Make the first settings file from the old localStorage values. `read` returns the value of a key, or null. */
|
||||
|
||||
+18
-14
@@ -2,36 +2,40 @@
|
||||
import { startExternalPlugins } from "$lib/plugins/external";
|
||||
import { onMount } from "svelte";
|
||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
import { t } from "$lib/i18n";
|
||||
import Workbench from "$lib/layout/Workbench.svelte";
|
||||
import BrowserWindow from "$lib/layout/BrowserWindow.svelte";
|
||||
import SettingsWindow from "$lib/layout/SettingsWindow.svelte";
|
||||
import TerminalSlot from "$lib/plugins/TerminalSlot.svelte";
|
||||
import { pluginHost } from "$lib/plugins/registry";
|
||||
import TerminalHost from "$lib/features/TerminalHost.svelte";
|
||||
import { featureSwitches } from "$lib/features/state";
|
||||
import { terminalShortcut } from "$lib/features/terminalKeys";
|
||||
const terminalRoot = new URLSearchParams(location.search).get("terminalWindow");
|
||||
const browserWindow = new URLSearchParams(location.search).get("browserWindow") === "true";
|
||||
const settingsWindow = new URLSearchParams(location.search).get("settingsWindow") === "true";
|
||||
let dock: TerminalSlot | undefined = $state();
|
||||
let dock: TerminalHost | undefined = $state();
|
||||
let error = $state("");
|
||||
const terminal = $derived.by(() => { void $pluginHost; return pluginHost.get("terminal"); });
|
||||
onMount(() => startExternalPlugins({ browserWindow }));
|
||||
function keydown(event: KeyboardEvent) {
|
||||
if (!terminalRoot || event.target instanceof Element && event.target.closest("dialog, [role=menu]")) return;
|
||||
const action = terminal?.shortcut(event);
|
||||
if (!terminalRoot || !$featureSwitches.terminal || event.target instanceof Element && event.target.closest("dialog, [role=menu]")) return;
|
||||
const action = terminalShortcut(event);
|
||||
if (action && action !== "toggle") { event.preventDefault(); void dock?.command(action).catch(reason => error = String(reason)); }
|
||||
}
|
||||
</script>
|
||||
<svelte:window onkeydown={keydown} />
|
||||
{#if terminalRoot}
|
||||
<div class="terminal-window">
|
||||
{#if error}<p role="alert">{error}</p>{/if}
|
||||
{#if terminal}
|
||||
{#key terminal}
|
||||
<TerminalSlot bind:this={dock} contribution={terminal} cwd={terminalRoot} visible standalone
|
||||
onClose={() => void getCurrentWindow().destroy().catch(reason => error = String(reason))} />
|
||||
{/key}
|
||||
{:else}<p>Install and enable the Terminal plugin in Settings → Plug-ins in the main window.</p>{/if}
|
||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||
{#if $featureSwitches.terminal}
|
||||
<TerminalHost bind:this={dock} cwd={terminalRoot} visible standalone
|
||||
onClose={() => void getCurrentWindow().destroy().catch(reason => error = String(reason))} />
|
||||
{:else}<p class="off">{$t("Terminal is off. Turn it on in Settings → Features.")}</p>{/if}
|
||||
</div>
|
||||
{:else if browserWindow}<BrowserWindow />
|
||||
{:else if settingsWindow}<SettingsWindow />
|
||||
{:else}<Workbench />{/if}
|
||||
<style>.terminal-window { height: 100vh; display: flex; flex-direction: column; }</style>
|
||||
<style>
|
||||
.terminal-window { height: 100vh; display: flex; flex-direction: column; }
|
||||
.error, .off { margin: 0; padding: 12px 16px; }
|
||||
.error { color: var(--rs-error); }
|
||||
.off { color: var(--rs-text-dim); }
|
||||
</style>
|
||||
|
||||
Reference in New Issue
Block a user