diff --git a/CLAUDE.md b/CLAUDE.md index 7067bde..df3a048 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -169,6 +169,16 @@ README doesn't: conventions, environment and pitfalls. header, adds drag and drop, live reload on `folder-changed` (keeps tab, sheet and selection) and `index.html#folder=[&project=…][&commit=]`. +- Integrated terminal (`src/desktop/terminal.js` panel + `vt.js` DOM-free + emulator, `src-tauri/src/terminal.rs`): header button `#term-toggle` + (added by `initHeader`, so on all three pages) or Ctrl+`. The user's + `$SHELL` on a pty (posix_openpt via `libc`, no pty crate; Unix only, the + commands refuse on Windows), started in the page's `folder=`/`local=` or + home, with the AppImage env removed (`outside_appimage`). `term_open/write/ + resize/attach/close`, output as `term-data` {id, data, end}; Rust keeps a + 256 KB backlog so the next page reattaches (sessionStorage `kivi.terminal`). + Hide keeps the shell; × ends it. Ctrl+C copies when text is selected, + Ctrl+V / Ctrl+Shift+V paste (bracketed when asked). - Folder chooser (`pickFolder`, tauri.js → `pick_folder` in `src-tauri/src/picker.rs`): on Linux GTK's `FileChooserNative` with `GTK_USE_PORTAL=1` (set at start-up, removed for children by diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index dc0b58b..b930b1f 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2023,6 +2023,7 @@ version = "0.1.0" dependencies = [ "git2", "gtk", + "libc", "notify", "notify-debouncer-mini", "reqwest 0.12.28", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 25f04d9..803a516 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -29,6 +29,10 @@ git2 = { version = "0.20", default-features = false, features = ["vendored-libgi notify = "6" notify-debouncer-mini = "0.4" +# The integrated terminal's pseudo-terminal (terminal.rs). Already in the tree through Tauri. +[target.'cfg(unix)'.dependencies] +libc = "0.2" + # The folder chooser through the desktop portal (picker.rs). The same GTK as Tauri's. [target.'cfg(target_os = "linux")'.dependencies] gtk = "0.18" diff --git a/src-tauri/src/kicad.rs b/src-tauri/src/kicad.rs index f9ca725..63a81db 100644 --- a/src-tauri/src/kicad.rs +++ b/src-tauri/src/kicad.rs @@ -183,7 +183,8 @@ pub fn kicad_open(program: String, project: String) -> Result<(), String> { /// The AppImage's launcher points GTK, GIO and XDG_DATA_DIRS into the image /// (`$APPDIR/usr/…`). KiCad must start with the system's own, so those entries /// are dropped from what the child inherits (and KiVi's own GTK_USE_PORTAL, picker.rs). -fn outside_appimage(cmd: &mut Command) { +/// Also used for the terminal's shell (terminal.rs). +pub(crate) fn outside_appimage(cmd: &mut Command) { crate::picker::clean_child_env(cmd); let Some(appdir) = std::env::var("APPDIR").ok().filter(|d| !d.is_empty()) else { return }; for (k, v) in appimage_env_fixes(&appdir, std::env::vars()) { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 6123a67..1535182 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -6,6 +6,7 @@ mod git; mod git_http; mod kicad; mod picker; +mod terminal; use std::path::{Path, PathBuf}; use std::sync::Mutex; @@ -263,8 +264,14 @@ pub fn run() { .plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_opener::init()) .manage(Workspace::default()) + .manage(terminal::imp::Terminals::default()) .invoke_handler(tauri::generate_handler![ picker::pick_folder, + terminal::imp::term_open, + terminal::imp::term_write, + terminal::imp::term_resize, + terminal::imp::term_attach, + terminal::imp::term_close, open_folder, list_folder, read_file, diff --git a/src-tauri/src/picker.rs b/src-tauri/src/picker.rs index 3f72734..cf4abfd 100644 --- a/src-tauri/src/picker.rs +++ b/src-tauri/src/picker.rs @@ -18,7 +18,7 @@ pub fn use_portal() { } } -/// Undo `use_portal` for a program KiVi starts (KiCad). +/// Undo `use_portal` for a program KiVi starts (KiCad, the terminal's shell). pub fn clean_child_env(cmd: &mut std::process::Command) { if std::env::var_os("KIVI_SET_GTK_USE_PORTAL").is_some() { cmd.env_remove("GTK_USE_PORTAL").env_remove("KIVI_SET_GTK_USE_PORTAL"); diff --git a/src-tauri/src/terminal.rs b/src-tauri/src/terminal.rs new file mode 100644 index 0000000..8128396 --- /dev/null +++ b/src-tauri/src/terminal.rs @@ -0,0 +1,349 @@ +//! The integrated terminal: the user's shell on a pseudo-terminal, shown by +//! src/desktop/terminal.js. Output goes to the page as `term-data` events +//! ({id, data, end}); the last part is also kept here (`backlog`), so a page +//! opened later (the viewer, the diff, the home page) reattaches to the same +//! shell with its recent output. Unix only (posix_openpt through libc, no +//! extra crate); on Windows the commands refuse. + +use serde::Serialize; + +#[derive(Serialize, Clone)] +pub struct TermData { + id: u32, + data: String, + /// Bytes of output so far, this chunk included (to drop what a reattach already got). + end: u64, +} + +#[derive(Serialize)] +pub struct Backlog { + data: String, + end: u64, +} + +#[cfg(unix)] +pub mod imp { + use super::{Backlog, TermData}; + use std::collections::HashMap; + use std::fs::File; + use std::io::{self, Read, Write}; + use std::os::unix::io::FromRawFd; + use std::os::unix::process::CommandExt; + use std::process::{Child, Command, Stdio}; + use std::sync::{Arc, Mutex}; + + use tauri::{AppHandle, Emitter, Manager, State}; + + /// Output kept for reattaching, in bytes. + const BACKLOG: usize = 256 * 1024; + + struct Output { + backlog: String, + end: u64, + } + + struct Session { + master: File, + pid: i32, + out: Arc>, + } + + #[derive(Default)] + pub struct Terminals { + next: Mutex, + sessions: Mutex>, + } + + fn last_err(what: &str) -> String { + format!("{what}: {}", io::Error::last_os_error()) + } + + fn set_size(fd: i32, cols: u16, rows: u16) { + let ws = libc::winsize { ws_row: rows.max(1), ws_col: cols.max(1), ws_xpixel: 0, ws_ypixel: 0 }; + unsafe { libc::ioctl(fd, libc::TIOCSWINSZ, &ws as *const libc::winsize) }; + } + + /// A new pseudo-terminal: (master, slave), both close-on-exec. + fn open_pty(cols: u16, rows: u16) -> Result<(File, File), String> { + static PTSNAME: Mutex<()> = Mutex::new(()); // ptsname uses a static buffer + unsafe { + let m = libc::posix_openpt(libc::O_RDWR | libc::O_NOCTTY); + if m < 0 { + return Err(last_err("posix_openpt")); + } + let master = File::from_raw_fd(m); + libc::fcntl(m, libc::F_SETFD, libc::FD_CLOEXEC); + if libc::grantpt(m) != 0 || libc::unlockpt(m) != 0 { + return Err(last_err("grantpt")); + } + let s = { + let _guard = PTSNAME.lock().unwrap(); + let name = libc::ptsname(m); + if name.is_null() { + return Err(last_err("ptsname")); + } + libc::open(name, libc::O_RDWR | libc::O_NOCTTY | libc::O_CLOEXEC) + }; + if s < 0 { + return Err(last_err("open pty")); + } + set_size(m, cols, rows); + Ok((master, File::from_raw_fd(s))) + } + } + + /// Text from the front of `buf`, leaving an incomplete UTF-8 sequence at its end for the next read. + fn take_text(buf: &mut Vec) -> String { + let end = match std::str::from_utf8(buf) { + Err(e) if e.error_len().is_none() => e.valid_up_to(), + _ => buf.len(), + }; + let rest = buf.split_off(end); + let text = String::from_utf8_lossy(buf).into_owned(); + *buf = rest; + text + } + + fn user_shell() -> String { + std::env::var("SHELL").ok().filter(|s| !s.is_empty()).unwrap_or_else(|| "/bin/sh".into()) + } + + fn spawn_shell(shell: &str, cwd: &str, slave: File) -> Result { + let mut cmd = Command::new(shell); + let dir = std::path::Path::new(cwd); + if dir.is_dir() { + cmd.current_dir(dir); + } else if let Some(home) = std::env::var_os("HOME") { + cmd.current_dir(home); + } + crate::kicad::outside_appimage(&mut cmd); + cmd.env("TERM", "xterm-256color").env("COLORTERM", "truecolor").env("TERM_PROGRAM", "KiVi"); + let out = slave.try_clone().map_err(|e| e.to_string())?; + let err = slave.try_clone().map_err(|e| e.to_string())?; + cmd.stdin(Stdio::from(slave)).stdout(Stdio::from(out)).stderr(Stdio::from(err)); + // Its own session, with the pty as controlling terminal, so Ctrl+C and job control work. + unsafe { + cmd.pre_exec(|| { + // Ignored signals are inherited, and a shell can't un-ignore them: if KiVi was + // started with SIGHUP ignored (nohup, some launchers), closing the terminal + // would never end the shell. Give it the defaults a terminal would. + for sig in [libc::SIGHUP, libc::SIGINT, libc::SIGQUIT, libc::SIGTERM, libc::SIGTSTP, libc::SIGTTIN, libc::SIGTTOU, libc::SIGCHLD, libc::SIGPIPE] { + libc::signal(sig, libc::SIG_DFL); + } + if libc::setsid() < 0 { + return Err(io::Error::last_os_error()); + } + if libc::ioctl(0, libc::TIOCSCTTY as _, 0) < 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) + }); + } + cmd.spawn().map_err(|e| format!("Couldn't start {shell}: {e}")) + // `cmd` (and with it our copies of the slave) is dropped here, so the + // master reads EIO once the shell and its children are gone. + } + + /// Start the user's shell in `cwd` (the home folder if it isn't a folder); returns its id. + #[tauri::command] + pub fn term_open(cwd: Option, cols: u16, rows: u16, app: AppHandle, terms: State) -> Result { + let (master, slave) = open_pty(cols, rows)?; + let mut child = spawn_shell(&user_shell(), cwd.as_deref().unwrap_or(""), slave)?; + let pid = child.id() as i32; + let id = { + let mut next = terms.next.lock().unwrap(); + *next += 1; + *next + }; + let out = Arc::new(Mutex::new(Output { backlog: String::new(), end: 0 })); + let mut reader = master.try_clone().map_err(|e| e.to_string())?; + terms.sessions.lock().unwrap().insert(id, Session { master, pid, out: out.clone() }); + + let exit_app = app.clone(); + std::thread::spawn(move || { + let mut buf = [0u8; 16 * 1024]; + let mut pending = Vec::new(); + loop { + match reader.read(&mut buf) { + Ok(0) => break, + Ok(n) => { + pending.extend_from_slice(&buf[..n]); + let data = take_text(&mut pending); + if data.is_empty() { + continue; + } + // Under the lock, so a reattach sees either all of a chunk or none of it. + let mut o = out.lock().unwrap(); + o.end += data.len() as u64; + o.backlog.push_str(&data); + if o.backlog.len() > BACKLOG { + let mut cut = o.backlog.len() - BACKLOG; + while !o.backlog.is_char_boundary(cut) { + cut += 1; + } + o.backlog.drain(..cut); + } + let _ = app.emit("term-data", TermData { id, data, end: o.end }); + } + Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, + Err(_) => break, // EIO: nothing has the pty open any more + } + } + }); + // The shell's exit ends the terminal, even when something it started + // (an agent, a background job) still holds the pty open, so the read + // above would never see EIO. + std::thread::spawn(move || { + let _ = child.wait(); + std::thread::sleep(std::time::Duration::from_millis(150)); // let its last output through + exit_app.state::().sessions.lock().unwrap().remove(&id); + let _ = exit_app.emit("term-exit", id); + }); + Ok(id) + } + + /// Keyboard input (and pastes) for the shell. + #[tauri::command] + pub fn term_write(id: u32, data: String, terms: State) -> Result<(), String> { + let mut sessions = terms.sessions.lock().unwrap(); + let s = sessions.get_mut(&id).ok_or("the terminal has closed")?; + s.master.write_all(data.as_bytes()).map_err(|e| e.to_string()) + } + + /// The panel's new size in character cells. + #[tauri::command] + pub fn term_resize(id: u32, cols: u16, rows: u16, terms: State) -> Result<(), String> { + use std::os::unix::io::AsRawFd; + let sessions = terms.sessions.lock().unwrap(); + let s = sessions.get(&id).ok_or("the terminal has closed")?; + set_size(s.master.as_raw_fd(), cols, rows); + Ok(()) + } + + /// The recent output of a running terminal (a page reattaching), or None if it has exited. + #[tauri::command] + pub fn term_attach(id: u32, terms: State) -> Option { + let sessions = terms.sessions.lock().unwrap(); + let o = sessions.get(&id)?.out.lock().unwrap(); + Some(Backlog { data: o.backlog.clone(), end: o.end }) + } + + /// Close a terminal: hang up its shell (and what runs in its session). + #[tauri::command] + pub fn term_close(id: u32, terms: State) { + if let Some(s) = terms.sessions.lock().unwrap().remove(&id) { + end_session(s.pid); + // Dropping the master hangs up the pty for everything else in the session. + } + } + + /// Hang up the shell's process group, and kill it if it's still there 2 s later + /// (a shell busy with a command can outlive the hang-up). + fn end_session(pid: i32) { + unsafe { libc::kill(-pid, libc::SIGHUP) }; + std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_secs(2)); + unsafe { libc::kill(-pid, libc::SIGKILL) }; // ESRCH when already gone + }); + } + + #[cfg(test)] + mod tests { + use super::{end_session, open_pty, set_size, spawn_shell, take_text}; + use std::io::{Read, Write}; + use std::os::unix::io::AsRawFd; + + #[test] + fn shell_runs_on_the_pty_with_its_size_and_folder() { + let dir = std::env::temp_dir(); + let (mut master, slave) = open_pty(100, 30).unwrap(); + let mut child = spawn_shell("/bin/sh", &dir.to_string_lossy(), slave).unwrap(); + set_size(master.as_raw_fd(), 120, 40); // what the panel does on resize + master.write_all(b"stty size; pwd; tty; echo DONE-$((40+2))\n").unwrap(); + // Read on a thread until the marker shows, with a time limit instead of waiting for EOF. + let mut reader = master.try_clone().unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let mut buf = [0u8; 4096]; + while let Ok(n) = reader.read(&mut buf) { + if n == 0 || tx.send(buf[..n].to_vec()).is_err() { + break; + } + } + }); + let mut out = Vec::new(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while !String::from_utf8_lossy(&out).contains("DONE-42") { + let left = deadline.saturating_duration_since(std::time::Instant::now()); + match rx.recv_timeout(left) { + Ok(chunk) => out.extend(chunk), + Err(_) => break, + } + } + // End it as term_close does (hang-up, then a kill after 2 s); never wait unbounded. + end_session(child.id() as i32); + let gone = std::time::Instant::now() + std::time::Duration::from_secs(5); + let ended = loop { + if child.try_wait().unwrap().is_some() { + break true; + } + if std::time::Instant::now() > gone { + break false; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + }; + let text = String::from_utf8_lossy(&out); + assert!(ended, "the shell outlived term_close:\n{text}"); + assert!(text.contains("DONE-42"), "{text}"); + assert!(text.contains("40 120"), "{text}"); + assert!(text.contains(&*std::fs::canonicalize(&dir).unwrap().to_string_lossy()), "{text}"); + assert!(text.contains("/dev/pts/"), "{text}"); + } + + #[test] + fn split_utf8_waits_for_the_rest() { + let mut buf = "aé".as_bytes().to_vec(); + buf.pop(); // half of "é" + assert_eq!(take_text(&mut buf), "a"); + assert_eq!(buf.len(), 1); + buf.push(0xA9); + assert_eq!(take_text(&mut buf), "é"); + assert!(buf.is_empty()); + } + } +} + +#[cfg(not(unix))] +pub mod imp { + use super::Backlog; + + const NO: &str = "The terminal isn't available on this system yet"; + + #[derive(Default)] + pub struct Terminals; + + #[tauri::command] + pub fn term_open(cwd: Option, cols: u16, rows: u16) -> Result { + let _ = (cwd, cols, rows); + Err(NO.into()) + } + #[tauri::command] + pub fn term_write(id: u32, data: String) -> Result<(), String> { + let _ = (id, data); + Err(NO.into()) + } + #[tauri::command] + pub fn term_resize(id: u32, cols: u16, rows: u16) -> Result<(), String> { + let _ = (id, cols, rows); + Err(NO.into()) + } + #[tauri::command] + pub fn term_attach(id: u32) -> Option { + let _ = id; + None + } + #[tauri::command] + pub fn term_close(id: u32) { + let _ = id; + } +} diff --git a/src/desktop/account.js b/src/desktop/account.js index 11513a7..dd5ea69 100644 --- a/src/desktop/account.js +++ b/src/desktop/account.js @@ -17,6 +17,7 @@ import { parseModelSource } from "../sources.js"; import { forge } from "../forge/index.js"; import { ICONS } from "./icons.js"; import { appInstallUrl, chooseForge, inspectKicad, pickFolder, signInTo, signOut as signOutOf } from "./tauri.js"; +import { initTerminal } from "./terminal.js"; // Where KiCad usually is, as the path box's example and the folder picker's start. const KICAD_HINT = /Windows/.test(navigator.userAgent) @@ -93,6 +94,17 @@ export function initHeader({ homeLinks = true, onAccountChange = () => location. el.className = "account"; actions.appendChild(el); } + // The integrated terminal (terminal.js): its button sits left of the account menu. + const term = document.createElement("button"); + term.type = "button"; + term.id = "term-toggle"; + term.className = "btn icon"; + term.title = "Terminal (Ctrl+`)"; + term.setAttribute("aria-label", "Terminal"); + term.setAttribute("aria-pressed", "false"); + term.innerHTML = ICONS.terminal; + el.parentNode.insertBefore(term, el); + initTerminal(term); const dlg = document.createElement("dialog"); dlg.id = "settings"; diff --git a/src/desktop/desktop.css b/src/desktop/desktop.css index ff81dff..6b08ed2 100644 --- a/src/desktop/desktop.css +++ b/src/desktop/desktop.css @@ -134,3 +134,21 @@ .fab { width: 52px; height: 52px; border-radius: 50%; display: grid; place-items: center; background: var(--accent); color: var(--accent-ink); border: 0; cursor: pointer; box-shadow: 0 6px 18px rgb(0 0 0 / 0.45); } .fab:hover { filter: brightness(1.08); } .project-grid { padding-bottom: 72px; } /* the last row stays clear of "+" */ +.add-menu { bottom: calc(28px + var(--term-h, 0px)); } /* above the terminal when it's open */ + +/* Integrated terminal (terminal.js): the last child of the page's flex column. */ +.term-panel { --term-bg: #0b0d10; --term-fg: var(--text); flex: none; position: relative; display: flex; flex-direction: column; background: var(--term-bg); border-top: 1px solid var(--border); min-height: 120px; } +.term-grip { position: absolute; left: 0; right: 0; top: -4px; height: 8px; cursor: ns-resize; z-index: 2; } +.term-head { display: flex; align-items: center; gap: 10px; padding: 4px 8px 4px 12px; background: var(--surface); border-bottom: 1px solid var(--border-soft); font-size: 12px; } +.term-name { font-weight: 600; } +.term-cwd { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; } +.term-tools { margin-left: auto; display: flex; gap: 4px; } +.term-tools .btn.icon { width: 26px; } +.term-view { position: relative; flex: 1; min-height: 0; display: flex; } +.term-scroll { flex: 1; overflow-y: auto; overflow-x: hidden; padding: 4px 8px; color: var(--term-fg); font: 13px/17px var(--mono); cursor: text; user-select: text; } +.term-row { height: 17px; white-space: pre; overflow: hidden; } +.term-wide { display: inline-block; width: calc(2 * var(--cw, 8px)); } +.term-cursor { background: var(--accent); color: var(--term-bg) !important; } +.term-view:not(:focus-within) .term-cursor { background: transparent; color: inherit !important; outline: 1px solid var(--accent); outline-offset: -1px; } +.term-input { position: absolute; left: 0; bottom: 0; width: 1px; height: 1px; opacity: 0; border: 0; padding: 0; resize: none; overflow: hidden; pointer-events: none; } +.term-probe { position: absolute; visibility: hidden; font: 13px/17px var(--mono); white-space: pre; } diff --git a/src/desktop/icons.js b/src/desktop/icons.js index 9b0a066..67e96f1 100644 --- a/src/desktop/icons.js +++ b/src/desktop/icons.js @@ -26,5 +26,6 @@ export const ICONS = { signIn: stroke(``), signOut: stroke(``), folder: stroke(``), + terminal: stroke(``), chevron: stroke(``), }; diff --git a/src/desktop/terminal.js b/src/desktop/terminal.js new file mode 100644 index 0000000..d6f9e69 --- /dev/null +++ b/src/desktop/terminal.js @@ -0,0 +1,457 @@ +// The integrated terminal: a panel at the bottom of every desktop page, opened +// with the header's terminal button or Ctrl+` (as in VS Code and JetBrains IDEs). +// It runs the user's shell (terminal.rs) in the open project's folder, or the +// home folder on the home page. Hiding the panel keeps the shell running, and +// so does moving between pages: the next page reattaches to it and replays its +// recent output. The × button ends the shell; so does `exit`. +// +// vt.js turns the output into character cells; this file draws them as one +//
per row (so the text can be selected and copied normally), with the +// lines scrolled off the top kept above as scrollback. + +import { toast } from "../app/ui.js"; +import { invoke, listen } from "./tauri.js"; +import { DEF, Screen } from "./vt.js"; + +const STATE_KEY = "kivi.terminal"; // {id, open, height}, per window (sessionStorage) +const SCROLLBACK = 5000; // lines +const ROW_PX = 17; + +// The 16 ANSI colours, tuned to the app's dark theme. +const PALETTE = [ + "#20242a", "#f07178", "#a6d189", "#f0c674", "#81a2be", "#c397d8", "#7fd3df", "#c5c8c6", + "#5c6370", "#ff8b8b", "#c3e88d", "#ffd580", "#9cc4ff", "#e0b0ff", "#a6f0fb", "#ffffff", +]; + +function colour(c) { + if (c == null) return null; + if (typeof c === "string") return c; + if (c < 16) return PALETTE[c]; + if (c < 232) { + const i = c - 16; + const l = [0, 95, 135, 175, 215, 255]; + return `rgb(${l[Math.floor(i / 36)]},${l[Math.floor(i / 6) % 6]},${l[i % 6]})`; + } + const g = 8 + 10 * (c - 232); + return `rgb(${g},${g},${g})`; +} + +const styles = new WeakMap(); +function styleOf(a) { + if (a === DEF) return ""; + if (!styles.has(a)) { + let fg = a.fg; + if (a.bold && typeof fg === "number" && fg < 8) fg += 8; // bold shows as bright, as most terminals do + let f = colour(fg); + let b = colour(a.bg); + if (a.inverse) [f, b] = [b ?? "var(--term-bg)", f ?? "var(--term-fg)"]; + const css = [ + f && `color:${f}`, + b && `background:${b}`, + a.bold && "font-weight:600", + a.italic && "font-style:italic", + a.underline && "text-decoration:underline", + a.dim && "opacity:.6", + ].filter(Boolean); + styles.set(a, css.length ? ` style="${css.join(";")}"` : ""); + } + return styles.get(a); +} + +const esc = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]); + +/** One row as HTML; `cursor` is the cursor's column on this row, or -1. */ +function rowHtml(line, cursor) { + // Trailing blanks are left out, so copied text has no trailing spaces. + let last = line.length - 1; + while (last >= 0 && line[last].ch === " " && line[last].a.bg == null && !line[last].a.inverse) last--; + last = Math.max(last, cursor); + let html = ""; + let run = ""; + let attr = null; + const flush = () => { + if (run) html += attr === DEF ? esc(run) : `${esc(run)}`; + run = ""; + }; + for (let x = 0; x <= last; x++) { + const c = line[x]; + if (c.ch === "") continue; // right half of a wide character + const wide = line[x + 1]?.ch === ""; + if (x === cursor || wide) { + flush(); + const cls = [x === cursor && "term-cursor", wide && "term-wide"].filter(Boolean).join(" "); + html += `${esc(c.ch)}`; + attr = null; + continue; + } + if (c.a !== attr) { + flush(); + attr = c.a; + } + run += c.ch; + } + flush(); + return html; +} + +/** Bytes for a key press, or null to let the hidden input take it (text, pastes). */ +function keyBytes(e, appCursor) { + const mod = 1 + (e.shiftKey ? 1 : 0) + (e.altKey ? 2 : 0) + (e.ctrlKey ? 4 : 0); + const csi = (code, tilde) => (tilde ? `\x1b[${code}${mod > 1 ? `;${mod}` : ""}~` : mod > 1 ? `\x1b[1;${mod}${code}` : appCursor ? `\x1bO${code}` : `\x1b[${code}`); + switch (e.key) { + case "Enter": + return e.altKey ? "\x1b\r" : "\r"; + case "Backspace": + return e.ctrlKey ? "\x08" : e.altKey ? "\x1b\x7f" : "\x7f"; + case "Tab": + return e.shiftKey ? "\x1b[Z" : "\t"; + case "Escape": + return "\x1b"; + case "ArrowUp": + return csi("A"); + case "ArrowDown": + return csi("B"); + case "ArrowRight": + return csi("C"); + case "ArrowLeft": + return csi("D"); + case "Home": + return csi("H"); + case "End": + return csi("F"); + case "Insert": + return csi(2, true); + case "Delete": + return csi(3, true); + case "PageUp": + return csi(5, true); + case "PageDown": + return csi(6, true); + } + const fkey = /^F(\d{1,2})$/.exec(e.key); + if (fkey) { + const n = Number(fkey[1]); + if (n <= 4) return mod > 1 ? `\x1b[1;${mod}${"PQRS"[n - 1]}` : `\x1bO${"PQRS"[n - 1]}`; + const code = { 5: 15, 6: 17, 7: 18, 8: 19, 9: 20, 10: 21, 11: 23, 12: 24 }[n]; + return code ? csi(code, true) : null; + } + if (e.ctrlKey && !e.altKey && !e.metaKey) { + // Ctrl+letter by the key's position too, so it works with any keyboard layout. + const k = e.key.length === 1 && /[a-z]/i.test(e.key) ? e.key.toLowerCase() : /^Key([A-Z])$/.exec(e.code)?.[1].toLowerCase(); + if (k) return String.fromCharCode(k.charCodeAt(0) - 96); + const special = { " ": "\x00", "@": "\x00", "2": "\x00", "[": "\x1b", "\\": "\x1c", "]": "\x1d", "^": "\x1e", "6": "\x1e", "_": "\x1f", "-": "\x1f", "/": "\x1f", "?": "\x7f" }[e.key]; + return special ?? null; + } + if (e.altKey && !e.ctrlKey && !e.metaKey && e.key.length === 1) return `\x1b${e.key}`; + return null; +} + +function loadState() { + try { + return JSON.parse(sessionStorage.getItem(STATE_KEY)) ?? {}; + } catch { + return {}; + } +} + +class TerminalPanel { + constructor(button) { + this.button = button; + this.state = loadState(); + this.id = null; // the running shell + this.queue = null; // output that arrived before the shell's id or backlog did + this.end = 0; // bytes of output drawn so far + this.raf = 0; + this.lastCursor = -1; + this.muted = false; // replaying a backlog: don't answer old queries + + const panel = document.createElement("section"); + panel.id = "term-panel"; + panel.className = "term-panel"; + panel.hidden = true; + panel.setAttribute("aria-label", "Terminal"); + panel.innerHTML = ` +
+
+ Terminal + + + + + +
+
+
+ + +
`; + document.body.appendChild(panel); + this.panel = panel; + this.view = panel.querySelector(".term-view"); + this.scroll = panel.querySelector(".term-scroll"); + this.back = panel.querySelector(".term-back"); + this.screenEl = panel.querySelector(".term-screen"); + this.input = panel.querySelector(".term-input"); + this.screen = new Screen(80, 24, (answer) => !this.muted && this.send(answer)); + panel.style.height = `${this.state.height ?? 280}px`; + + panel.querySelector('[data-term="hide"]').addEventListener("click", () => this.hide()); + panel.querySelector('[data-term="kill"]').addEventListener("click", () => this.kill()); + this.wireInput(); + this.wireGrip(panel.querySelector(".term-grip")); + new ResizeObserver(() => !panel.hidden && this.fit()).observe(this.view); + + listen("term-data", (e) => this.onData(e.payload)); + listen("term-exit", (e) => e.payload === this.id && this.onExit()); + + if (this.state.id) this.attach(this.state.id).then(() => this.state.open && this.show()); + else if (this.state.open) this.show(); + } + + save() { + try { + sessionStorage.setItem(STATE_KEY, JSON.stringify(this.state)); + } catch { + /* storage unavailable: the next page starts without the terminal */ + } + } + + /** The folder the page shows: the viewer's or the diff's local folder, else none (home). */ + cwd() { + const h = new URLSearchParams(location.hash.slice(1)); + return h.get("folder") ?? h.get("local") ?? null; + } + + toggle() { + if (this.panel.hidden) this.show(); + else this.hide(); + } + + /** Let fixed elements (the home page's "+") sit above the panel. */ + syncHeight() { + document.body.style.setProperty("--term-h", this.panel.hidden ? "0px" : `${this.panel.offsetHeight}px`); + } + + async show() { + this.panel.hidden = false; + this.syncHeight(); + this.button.setAttribute("aria-pressed", "true"); + this.state.open = true; + this.save(); + this.fit(); + this.input.focus({ preventScroll: true }); + if (!this.id) await this.start(); + } + + hide() { + this.panel.hidden = true; + this.syncHeight(); + this.button.setAttribute("aria-pressed", "false"); + this.state.open = false; + this.save(); + this.input.blur(); + } + + async start() { + const cwd = this.cwd(); + this.screen.reset(); + this.back.textContent = ""; + this.end = 0; + this.queue = []; + try { + const { cols, rows } = this.screen; + this.id = await invoke("term_open", { cwd, cols, rows }); + } catch (e) { + this.queue = null; + toast(`Couldn't start a terminal: ${e.message ?? e}`, true); + this.hide(); + return; + } + this.panel.querySelector(".term-cwd").textContent = this.state.cwd = cwd ?? "~"; + this.state.id = this.id; + this.save(); + const early = this.queue; + this.queue = null; + for (const p of early) this.onData(p); + } + + /** Reconnect to the shell an earlier page started. */ + async attach(id) { + this.queue = []; + const backlog = await invoke("term_attach", { id }).catch(() => null); + const early = this.queue; + this.queue = null; + if (!backlog) { + this.state.id = null; + this.save(); + return; + } + this.id = id; + this.panel.querySelector(".term-cwd").textContent = this.state.cwd ?? ""; + this.muted = true; + this.screen.write(backlog.data); + this.muted = false; + this.end = backlog.end; + for (const p of early) if (p.id === id && p.end > this.end) this.onData(p); + this.draw(); + } + + onData(p) { + if (this.queue) return void this.queue.push(p); + if (p.id !== this.id || p.end <= this.end) return; + this.end = p.end; + this.screen.write(p.data); + if (!this.raf) this.raf = requestAnimationFrame(() => this.draw()); + } + + onExit() { + this.id = null; + this.state.id = null; + this.save(); + this.hide(); + } + + kill() { + if (this.id) invoke("term_close", { id: this.id }).catch(() => {}); + this.onExit(); + } + + send(data) { + if (this.id) invoke("term_write", { id: this.id, data }).catch((e) => toast(`Terminal: ${e.message ?? e}`, true)); + } + + /** Size the screen to the panel, in character cells. */ + fit() { + const probe = this.panel.querySelector(".term-probe"); + const cw = probe.getBoundingClientRect().width / 20 || 8; + this.view.style.setProperty("--cw", `${cw}px`); + const cols = Math.max(20, Math.floor((this.scroll.clientWidth - 16) / cw)); + const rows = Math.max(4, Math.floor((this.scroll.clientHeight - 8) / ROW_PX)); + if (cols === this.screen.cols && rows === this.screen.rows && this.screenEl.childElementCount === rows) return; + this.screen.resize(cols, rows); + if (this.id) invoke("term_resize", { id: this.id, cols, rows }).catch(() => {}); + this.draw(); + } + + draw() { + this.raf = 0; + const s = this.screen; + const atBottom = this.scroll.scrollTop + this.scroll.clientHeight >= this.scroll.scrollHeight - ROW_PX; + if (s.clearBack) { + this.back.textContent = ""; + s.clearBack = false; + } + if (s.out.length) { + const frag = document.createDocumentFragment(); + for (const line of s.out) { + const d = document.createElement("div"); + d.className = "term-row"; + d.innerHTML = rowHtml(line, -1); + frag.appendChild(d); + } + s.out.length = 0; + this.back.appendChild(frag); + for (let extra = this.back.childElementCount - SCROLLBACK; extra > 0; extra--) this.back.firstElementChild.remove(); + } + while (this.screenEl.childElementCount < s.rows) { + const d = document.createElement("div"); + d.className = "term-row"; + this.screenEl.appendChild(d); + } + while (this.screenEl.childElementCount > s.rows) this.screenEl.lastElementChild.remove(); + const cursor = s.cursorVisible ? s.y : -1; + s.dirty.add(this.lastCursor); + s.dirty.add(cursor); + this.lastCursor = cursor; + for (const r of s.dirty) if (r >= 0 && r < s.rows) this.screenEl.children[r].innerHTML = rowHtml(s.lines[r], r === cursor ? s.x : -1); + s.dirty.clear(); + if (atBottom) this.scroll.scrollTop = this.scroll.scrollHeight; + } + + wireInput() { + const input = this.input; + const selected = () => { + const sel = getSelection(); + return sel && !sel.isCollapsed && this.view.contains(sel.anchorNode) ? sel.toString() : ""; + }; + const copy = (text) => navigator.clipboard?.writeText(text).catch(() => document.execCommand("copy")); + input.addEventListener("keydown", (e) => { + e.stopPropagation(); // the page's own shortcuts (M, Escape, …) stay out of the way + if (e.isComposing) return; + const k = e.key.toLowerCase(); + // Ctrl+Shift+C copies; Ctrl+C copies when text is selected, else interrupts. + if (e.ctrlKey && k === "c" && (e.shiftKey || selected())) { + e.preventDefault(); + copy(selected()); + getSelection().removeAllRanges(); + return; + } + if (e.ctrlKey && k === "v") return; // the browser pastes into the input: see "paste" + if (e.shiftKey && (e.key === "PageUp" || e.key === "PageDown")) { + e.preventDefault(); + this.scroll.scrollBy(0, (e.key === "PageUp" ? -1 : 1) * (this.scroll.clientHeight - ROW_PX)); + return; + } + const bytes = keyBytes(e, this.screen.appCursor); + if (bytes == null) return; // typed text arrives through "input" + e.preventDefault(); + this.scroll.scrollTop = this.scroll.scrollHeight; + this.send(bytes); + }); + // Typed text, dead keys and input methods: whatever the input received. + const take = () => { + if (input.value) this.send(input.value); + input.value = ""; + }; + input.addEventListener("input", (e) => !e.isComposing && take()); + input.addEventListener("compositionend", take); + input.addEventListener("paste", (e) => { + e.preventDefault(); + const text = e.clipboardData.getData("text/plain").replace(/\r?\n/g, "\r"); + if (text) this.send(this.screen.bracketed ? `\x1b[200~${text}\x1b[201~` : text); + }); + // Clicking the terminal types into it, unless the click made a selection to copy. + this.view.addEventListener("mouseup", () => !selected() && input.focus({ preventScroll: true })); + } + + wireGrip(grip) { + grip.addEventListener("pointerdown", (e) => { + e.preventDefault(); + grip.setPointerCapture(e.pointerId); + const startY = e.clientY; + const startH = this.panel.getBoundingClientRect().height; + const move = (ev) => { + const h = Math.max(120, Math.min(innerHeight - 160, startH + startY - ev.clientY)); + this.panel.style.height = `${h}px`; + this.syncHeight(); + }; + const up = () => { + grip.removeEventListener("pointermove", move); + this.state.height = Math.round(this.panel.getBoundingClientRect().height); + this.save(); + }; + grip.addEventListener("pointermove", move); + grip.addEventListener("pointerup", up, { once: true }); + }); + } +} + +/** + * Add the terminal panel to the page, toggled by `button` and Ctrl+`. + * @param {HTMLButtonElement} button the header's terminal button + */ +export function initTerminal(button) { + const panel = new TerminalPanel(button); + button.addEventListener("click", () => panel.toggle()); + window.addEventListener( + "keydown", + (e) => { + if (e.ctrlKey && !e.altKey && !e.metaKey && e.code === "Backquote") { + e.preventDefault(); + e.stopPropagation(); + panel.toggle(); + } + }, + true, + ); +} diff --git a/src/desktop/vt.js b/src/desktop/vt.js new file mode 100644 index 0000000..372c708 --- /dev/null +++ b/src/desktop/vt.js @@ -0,0 +1,516 @@ +// A small terminal emulator: turns a shell's output (text plus xterm escape +// sequences) into a grid of character cells for terminal.js to draw. It covers +// what shells, prompts, git, less, top and editors use: cursor movement, +// erasing, scroll regions, insert/delete, 16/256/true colour, the alternate +// screen, bracketed paste and the cursor-position report. No DOM, so it can run +// headless. Lines scrolled off the top of the main screen are collected in `out` +// for the scrollback. + +/** The default look of a cell. Attributes are frozen objects shared by cells. */ +export const DEF = Object.freeze({ fg: null, bg: null, bold: false, dim: false, italic: false, underline: false, inverse: false }); + +/** Columns a character takes: 0 (combining), 1, or 2 (East Asian wide, emoji). */ +export function charWidth(c) { + if ((c >= 0x300 && c <= 0x36f) || c === 0x200d || (c >= 0xfe00 && c <= 0xfe0f) || (c >= 0x20d0 && c <= 0x20ff)) return 0; + if ( + (c >= 0x1100 && c <= 0x115f) || (c >= 0x2e80 && c <= 0xa4cf) || (c >= 0xac00 && c <= 0xd7a3) || + (c >= 0xf900 && c <= 0xfaff) || (c >= 0xfe30 && c <= 0xfe4f) || (c >= 0xff00 && c <= 0xff60) || + (c >= 0xffe0 && c <= 0xffe6) || (c >= 0x1f300 && c <= 0x1f64f) || (c >= 0x1f900 && c <= 0x1f9ff) || + (c >= 0x20000 && c <= 0x3fffd) + ) + return 2; + return 1; +} + +export class Screen { + /** + * @param {number} cols + * @param {number} rows + * @param {(answer: string) => void} reply answers to the shell's queries (cursor position, device attributes) + */ + constructor(cols, rows, reply = () => {}) { + this.cols = cols; + this.rows = rows; + this.reply = reply; + this.out = []; // lines scrolled into the scrollback since the last draw + this.dirty = new Set(); // screen rows to redraw + this.reset(); + } + + reset() { + this.attr = DEF; + this.eraseCache = new Map(); + this.main = this.blankLines(this.rows); + this.alt = null; + this.lines = this.main; + this.x = 0; + this.y = 0; + this.top = 0; + this.bottom = this.rows - 1; + this.wrapPending = false; // the cursor is past the last column; the next character wraps + this.saved = null; + this.appCursor = false; + this.cursorVisible = true; + this.bracketed = false; + this.autowrap = true; + this.state = "ground"; + this.buf = ""; + this.clearBack = true; // the scrollback is wiped too (also by CSI 3 J) + this.markAll(); + } + + markAll() { + for (let r = 0; r < this.rows; r++) this.dirty.add(r); + } + + /** Erased cells keep the current background colour, as xterm's do. */ + eraseAttr() { + const bg = this.attr.bg; + if (bg == null) return DEF; + if (!this.eraseCache.has(bg)) this.eraseCache.set(bg, Object.freeze({ ...DEF, bg })); + return this.eraseCache.get(bg); + } + + blankLine(n = this.cols) { + const a = this.eraseAttr(); + return Array.from({ length: n }, () => ({ ch: " ", a })); + } + + blankLines(n) { + return Array.from({ length: n }, () => this.blankLine()); + } + + /** Feed output from the shell. */ + write(text) { + for (const ch of text) { + const c = ch.codePointAt(0); + switch (this.state) { + case "ground": + this.ground(ch, c); + break; + case "esc": + this.esc(ch); + break; + case "csi": + if (c >= 0x40 && c <= 0x7e) { + this.state = "ground"; + this.csi(ch, this.buf); + } else if (c === 0x1b) this.state = "esc"; + else if (c < 0x20) this.ground(ch, c); // control characters still work inside a sequence + else this.buf += ch; + break; + case "osc": // OSC, DCS and the like: skipped up to BEL or ESC \ + if (c === 7) this.state = "ground"; + else if (c === 0x1b) this.state = "oscEsc"; + break; + case "oscEsc": + this.state = "ground"; + if (ch !== "\\") this.esc(ch); + break; + case "charset": // ESC ( B and friends: only one character set here + this.state = "ground"; + break; + } + } + } + + ground(ch, c) { + if (c >= 0x20 && c !== 0x7f) return this.print(ch, c); + switch (c) { + case 0x1b: + this.state = "esc"; + break; + case 13: + this.x = 0; + this.wrapPending = false; + break; + case 10: + case 11: + case 12: + this.lineFeed(); + break; + case 8: + if (this.x > 0) this.x--; + this.wrapPending = false; + break; + case 9: + this.x = Math.min(this.cols - 1, (Math.floor(this.x / 8) + 1) * 8); + break; + } + } + + print(ch, c) { + const w = charWidth(c); + if (w === 0) { + // A combining mark joins the character before it. + const px = this.wrapPending ? this.x : this.x - 1; + if (px >= 0) { + const cell = this.lines[this.y][px]; + this.lines[this.y][px] = { ch: cell.ch + ch, a: cell.a }; + this.dirty.add(this.y); + } + return; + } + if (this.wrapPending && this.autowrap) { + this.x = 0; + this.lineFeed(); + } + this.wrapPending = false; + if (w === 2 && this.x === this.cols - 1 && this.autowrap) { + this.lines[this.y][this.x] = { ch: " ", a: this.attr }; + this.dirty.add(this.y); + this.x = 0; + this.lineFeed(); + } + const line = this.lines[this.y]; + line[this.x] = { ch, a: this.attr }; + if (w === 2 && this.x + 1 < this.cols) line[this.x + 1] = { ch: "", a: this.attr }; // the wide character's right half + this.dirty.add(this.y); + this.x += w; + if (this.x >= this.cols) { + this.x = this.cols - 1; + this.wrapPending = true; + } + } + + lineFeed() { + if (this.y === this.bottom) this.scrollUp(1, this.top, this.bottom, true); + else if (this.y < this.rows - 1) this.y++; + } + + /** Move rows top..bottom up by n; with `toBack`, what leaves the top of the main screen goes to the scrollback. */ + scrollUp(n, top = this.top, bottom = this.bottom, toBack = false) { + n = Math.min(n, bottom - top + 1); + for (let i = 0; i < n; i++) { + const [gone] = this.lines.splice(top, 1); + this.lines.splice(bottom, 0, this.blankLine()); + if (toBack && top === 0 && this.lines === this.main) this.out.push(gone); + } + for (let r = top; r <= bottom; r++) this.dirty.add(r); + } + + scrollDown(n, top = this.top, bottom = this.bottom) { + n = Math.min(n, bottom - top + 1); + for (let i = 0; i < n; i++) { + this.lines.splice(bottom, 1); + this.lines.splice(top, 0, this.blankLine()); + } + for (let r = top; r <= bottom; r++) this.dirty.add(r); + } + + esc(ch) { + this.state = "ground"; + switch (ch) { + case "[": + this.state = "csi"; + this.buf = ""; + break; + case "]": + case "P": + case "_": + case "^": + this.state = "osc"; + break; + case "(": + case ")": + case "*": + case "+": + this.state = "charset"; + break; + case "7": + this.saveCursor(); + break; + case "8": + this.restoreCursor(); + break; + case "D": + this.lineFeed(); + break; + case "E": + this.x = 0; + this.lineFeed(); + break; + case "M": + if (this.y === this.top) this.scrollDown(1); + else if (this.y > 0) this.y--; + break; + case "c": + this.reset(); + break; + } + } + + saveCursor() { + this.saved = { x: this.x, y: this.y, attr: this.attr }; + } + + restoreCursor() { + if (!this.saved) return; + this.x = Math.min(this.saved.x, this.cols - 1); + this.y = Math.min(this.saved.y, this.rows - 1); + this.attr = this.saved.attr; + this.wrapPending = false; + } + + csi(final, buf) { + let prefix = ""; + if (/^[?>=<]/.test(buf)) { + prefix = buf[0]; + buf = buf.slice(1); + } + if (/[\x20-\x2f]/.test(buf)) return; // with intermediates (cursor shape, …): not drawn here + const ps = buf.split(/[;:]/).map((n) => parseInt(n, 10) || 0); + const p = (i, d = 1) => ps[i] || d; + const clampX = (v) => Math.max(0, Math.min(this.cols - 1, v)); + const clampY = (v) => Math.max(0, Math.min(this.rows - 1, v)); + if (prefix && !"hlcJKm".includes(final)) return; + if (prefix === ">" || prefix === "=") { + if (final === "c" && prefix === ">") this.reply("\x1b[>0;276;0c"); + return; // modifyOtherKeys (CSI > … m) and the like + } + const line = this.lines[this.y]; + if ("ABCDEFGHadef`".includes(final)) this.wrapPending = false; + switch (final) { + case "A": + this.y = clampY(this.y - p(0)); + break; + case "B": + case "e": + this.y = clampY(this.y + p(0)); + break; + case "C": + case "a": + this.x = clampX(this.x + p(0)); + break; + case "D": + this.x = clampX(this.x - p(0)); + break; + case "E": + this.x = 0; + this.y = clampY(this.y + p(0)); + break; + case "F": + this.x = 0; + this.y = clampY(this.y - p(0)); + break; + case "G": + case "`": + this.x = clampX(p(0) - 1); + break; + case "d": + this.y = clampY(p(0) - 1); + break; + case "H": + case "f": + this.y = clampY(p(0) - 1); + this.x = clampX(p(1) - 1); + break; + case "J": + this.eraseDisplay(ps[0]); + break; + case "K": + this.eraseLine(ps[0]); + break; + case "@": { + const n = Math.min(p(0), this.cols - this.x); + line.splice(this.x, 0, ...this.blankLine(n)); + line.length = this.cols; + this.dirty.add(this.y); + break; + } + case "P": { + const n = Math.min(p(0), this.cols - this.x); + line.splice(this.x, n); + line.push(...this.blankLine(n)); + this.dirty.add(this.y); + break; + } + case "X": { + const a = this.eraseAttr(); + for (let i = this.x; i < Math.min(this.cols, this.x + p(0)); i++) line[i] = { ch: " ", a }; + this.dirty.add(this.y); + break; + } + case "L": + if (this.y >= this.top && this.y <= this.bottom) this.scrollDown(p(0), this.y, this.bottom); + this.x = 0; + break; + case "M": + if (this.y >= this.top && this.y <= this.bottom) this.scrollUp(p(0), this.y, this.bottom); + this.x = 0; + break; + case "S": + this.scrollUp(p(0)); + break; + case "T": + if (ps.length <= 1) this.scrollDown(p(0)); + break; + case "m": + if (!prefix) this.sgr(ps); + break; + case "r": { + const top = p(0) - 1; + const bottom = Math.min(this.rows, p(1, this.rows)) - 1; + [this.top, this.bottom] = top < bottom ? [top, bottom] : [0, this.rows - 1]; + this.x = 0; + this.y = 0; + this.wrapPending = false; + break; + } + case "h": + case "l": + if (prefix === "?") for (const n of ps) this.mode(n, final === "h"); + break; + case "s": + this.saveCursor(); + break; + case "u": + this.restoreCursor(); + break; + case "n": + if (ps[0] === 6) this.reply(`\x1b[${this.y + 1};${this.x + 1}R`); + else if (ps[0] === 5) this.reply("\x1b[0n"); + break; + case "c": + if (!prefix) this.reply("\x1b[?1;2c"); + break; + } + } + + eraseDisplay(n) { + const blankFrom = (from) => { + for (let r = from; r < this.rows; r++) { + this.lines[r] = this.blankLine(); + this.dirty.add(r); + } + }; + if (n === 0) { + this.eraseLine(0); + blankFrom(this.y + 1); + } else if (n === 1) { + for (let r = 0; r < this.y; r++) { + this.lines[r] = this.blankLine(); + this.dirty.add(r); + } + this.eraseLine(1); + } else { + blankFrom(0); + if (n === 3) this.clearBack = true; + } + } + + eraseLine(n) { + const line = this.lines[this.y]; + const a = this.eraseAttr(); + const [from, to] = n === 0 ? [this.x, this.cols] : n === 1 ? [0, this.x + 1] : [0, this.cols]; + for (let i = from; i < to; i++) line[i] = { ch: " ", a }; + this.dirty.add(this.y); + } + + mode(n, on) { + switch (n) { + case 1: + this.appCursor = on; + break; + case 7: + this.autowrap = on; + break; + case 25: + this.cursorVisible = on; + this.dirty.add(this.y); + break; + case 47: + case 1047: + case 1049: + if (on && !this.alt) { + if (n === 1049) this.saveCursor(); + this.alt = this.blankLines(this.rows); + this.lines = this.alt; + this.markAll(); + } else if (!on && this.alt) { + this.alt = null; + this.lines = this.main; + if (n === 1049) this.restoreCursor(); + this.markAll(); + } + break; + case 2004: + this.bracketed = on; + break; + } + } + + sgr(ps) { + const a = { ...this.attr }; + for (let i = 0; i < ps.length; i++) { + const n = ps[i]; + if (n === 0) Object.assign(a, DEF); + else if (n === 1) a.bold = true; + else if (n === 2) a.dim = true; + else if (n === 3) a.italic = true; + else if (n === 4) a.underline = true; + else if (n === 7) a.inverse = true; + else if (n === 22) a.bold = a.dim = false; + else if (n === 23) a.italic = false; + else if (n === 24) a.underline = false; + else if (n === 27) a.inverse = false; + else if (n >= 30 && n <= 37) a.fg = n - 30; + else if (n >= 90 && n <= 97) a.fg = n - 82; + else if (n === 39) a.fg = null; + else if (n >= 40 && n <= 47) a.bg = n - 40; + else if (n >= 100 && n <= 107) a.bg = n - 92; + else if (n === 49) a.bg = null; + else if (n === 38 || n === 48) { + let c = null; + if (ps[i + 1] === 5) { + c = ps[i + 2] ?? 0; + i += 2; + } else if (ps[i + 1] === 2) { + const [r, g, b] = [ps[i + 2] ?? 0, ps[i + 3] ?? 0, ps[i + 4] ?? 0]; + c = `rgb(${r},${g},${b})`; + i += 4; + } + if (n === 38) a.fg = c; + else a.bg = c; + } + } + this.attr = Object.freeze(a); + } + + /** New size in cells. Lines that no longer fit above the cursor go to the scrollback. */ + resize(cols, rows) { + if (cols === this.cols && rows === this.rows) return; + this.cols = cols; + const fit = (lines) => { + for (const l of lines) { + if (l.length > cols) l.length = cols; + while (l.length < cols) l.push({ ch: " ", a: DEF }); + } + }; + const height = (lines, active) => { + const excess = lines.length - rows; + if (excess > 0) { + const fromTop = active ? Math.max(0, Math.min(excess, this.y - rows + 1)) : 0; + const gone = lines.splice(0, fromTop); + if (lines === this.main) this.out.push(...gone); + lines.length = rows; + if (active) this.y -= fromTop; + } + while (lines.length < rows) lines.push(this.blankLine()); + }; + fit(this.main); + height(this.main, this.lines === this.main); + if (this.alt) { + fit(this.alt); + height(this.alt, true); + } + this.rows = rows; + this.top = 0; + this.bottom = rows - 1; + this.x = Math.min(this.x, cols - 1); + this.y = Math.max(0, Math.min(this.y, rows - 1)); + this.wrapPending = false; + this.dirty.clear(); + this.markAll(); + } +}