|
|
|
@@ -1,24 +1,54 @@
|
|
|
|
|
use std::collections::HashMap;
|
|
|
|
|
//! Shell sessions for the native Terminal feature of RuneStone (`src/lib/features/terminal/`).
|
|
|
|
|
|
|
|
|
|
use std::collections::{HashMap, VecDeque};
|
|
|
|
|
use std::io::{Read, Write};
|
|
|
|
|
use std::sync::atomic::{AtomicU64, Ordering};
|
|
|
|
|
use std::sync::mpsc::{Receiver, RecvTimeoutError};
|
|
|
|
|
use std::sync::Mutex;
|
|
|
|
|
use std::thread;
|
|
|
|
|
use std::path::{Path, PathBuf};
|
|
|
|
|
use std::time::{Duration, Instant};
|
|
|
|
|
|
|
|
|
|
use portable_pty::{native_pty_system, CommandBuilder, MasterPty, PtySize};
|
|
|
|
|
use serde::Serialize;
|
|
|
|
|
use tauri::ipc::{Channel, InvokeResponseBody, JavaScriptChannelId};
|
|
|
|
|
use tauri::{AppHandle, Emitter, Manager, State};
|
|
|
|
|
use tauri::{AppHandle, Manager, State};
|
|
|
|
|
|
|
|
|
|
use crate::error::{Error, Result};
|
|
|
|
|
use crate::workspace::{current_root, WorkspaceState};
|
|
|
|
|
use crate::terminal_platform::find_executable;
|
|
|
|
|
|
|
|
|
|
/// The largest output message in bytes.
|
|
|
|
|
const BATCH_BYTES: usize = 64 * 1024;
|
|
|
|
|
/// The longest time that output waits for more output before it goes to the webview.
|
|
|
|
|
const BATCH_WAIT: Duration = Duration::from_millis(8);
|
|
|
|
|
/// The number of retired page IDs that each window keeps.
|
|
|
|
|
const RETIRED_PAGES: usize = 16;
|
|
|
|
|
const NOT_OPEN: &str = "terminal is not open";
|
|
|
|
|
const RETIRED_PAGE: &str = "terminal page is no longer active";
|
|
|
|
|
|
|
|
|
|
pub struct PtyState {
|
|
|
|
|
inner: Mutex<HashMap<String, OpenPty>>,
|
|
|
|
|
inner: Mutex<Sessions>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Default)]
|
|
|
|
|
struct Sessions {
|
|
|
|
|
open: HashMap<String, OpenPty>,
|
|
|
|
|
/// The page IDs of each window, by window label.
|
|
|
|
|
pages: HashMap<String, Pages>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// The page loads of one window. Each page load of the frontend makes a new page ID.
|
|
|
|
|
#[derive(Default)]
|
|
|
|
|
struct Pages {
|
|
|
|
|
current: String,
|
|
|
|
|
retired: VecDeque<String>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
struct OpenPty {
|
|
|
|
|
owner: String,
|
|
|
|
|
/// A unique number for this session. A session ID can come back after a reload.
|
|
|
|
|
serial: u64,
|
|
|
|
|
integration_file: Option<PathBuf>,
|
|
|
|
|
master: Box<dyn MasterPty + Send>,
|
|
|
|
|
writer: std::sync::Arc<Mutex<Box<dyn Write + Send>>>,
|
|
|
|
@@ -33,12 +63,13 @@ impl Drop for OpenPty {
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl PtyState {
|
|
|
|
|
/// Close the window's terminals. Remove them under the lock, then stop the shells outside it.
|
|
|
|
|
/// Close the window's terminals and forget its pages. Remove the terminals under the lock,
|
|
|
|
|
/// then stop the shells outside it.
|
|
|
|
|
pub fn close_window(&self, label: &str) {
|
|
|
|
|
let closed: Vec<OpenPty> = match self.inner.lock() {
|
|
|
|
|
Ok(mut sessions) => {
|
|
|
|
|
let ids: Vec<String> = sessions.iter().filter(|(_, session)| session.owner == label).map(|(id, _)| id.clone()).collect();
|
|
|
|
|
ids.iter().filter_map(|id| sessions.remove(id)).collect()
|
|
|
|
|
sessions.pages.remove(label);
|
|
|
|
|
take_window(&mut sessions.open, label)
|
|
|
|
|
}
|
|
|
|
|
Err(_) => return,
|
|
|
|
|
};
|
|
|
|
@@ -55,22 +86,51 @@ impl PtyState {
|
|
|
|
|
|
|
|
|
|
pub fn new() -> Self {
|
|
|
|
|
Self {
|
|
|
|
|
inner: Mutex::new(HashMap::new()),
|
|
|
|
|
inner: Mutex::new(Sessions::default()),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Clone, Serialize)]
|
|
|
|
|
pub struct PtyData {
|
|
|
|
|
pub id: String,
|
|
|
|
|
// xterm owns UTF-8 decoding so multibyte characters split across reads survive.
|
|
|
|
|
pub data: Vec<u8>,
|
|
|
|
|
/// Remove the sessions of one window from the map. The caller stops them outside the lock.
|
|
|
|
|
fn take_window(open: &mut HashMap<String, OpenPty>, owner: &str) -> Vec<OpenPty> {
|
|
|
|
|
let ids: Vec<String> = open.iter().filter(|(_, session)| session.owner == owner).map(|(id, _)| id.clone()).collect();
|
|
|
|
|
ids.iter().filter_map(|id| open.remove(id)).collect()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Clone, Serialize)]
|
|
|
|
|
pub struct PtyExit {
|
|
|
|
|
pub id: String,
|
|
|
|
|
pub code: Option<u32>,
|
|
|
|
|
/// The number of open sessions of all windows.
|
|
|
|
|
fn running(pty: &PtyState) -> Result<usize> {
|
|
|
|
|
Ok(pty.inner.lock().map_err(|_| Error::new("pty lock"))?.open.len())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// A page ID has 1 to 64 ASCII letters, digits, and hyphens.
|
|
|
|
|
fn check_page(page: &str) -> Result<()> {
|
|
|
|
|
if page.is_empty() || page.len() > 64 || !page.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
|
|
|
|
|
return Err(Error::new("Invalid terminal page ID"));
|
|
|
|
|
}
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Apply the page rule to an open request of the window `owner`. A new page is a reload of
|
|
|
|
|
/// the window. It retires the current page and returns the sessions of the earlier page.
|
|
|
|
|
/// The caller stops them outside the lock. A retired page gets an error, so a late request
|
|
|
|
|
/// of an old page cannot close the sessions of the new page.
|
|
|
|
|
fn enter_page(sessions: &mut Sessions, owner: &str, page: &str) -> Result<Vec<OpenPty>> {
|
|
|
|
|
let Some(pages) = sessions.pages.get_mut(owner) else {
|
|
|
|
|
sessions.pages.insert(owner.to_owned(), Pages { current: page.to_owned(), retired: VecDeque::new() });
|
|
|
|
|
return Ok(Vec::new());
|
|
|
|
|
};
|
|
|
|
|
if pages.current == page {
|
|
|
|
|
return Ok(Vec::new());
|
|
|
|
|
}
|
|
|
|
|
if pages.retired.iter().any(|retired| retired == page) {
|
|
|
|
|
return Err(Error::new(RETIRED_PAGE));
|
|
|
|
|
}
|
|
|
|
|
let earlier = std::mem::replace(&mut pages.current, page.to_owned());
|
|
|
|
|
pages.retired.push_back(earlier);
|
|
|
|
|
while pages.retired.len() > RETIRED_PAGES {
|
|
|
|
|
pages.retired.pop_front();
|
|
|
|
|
}
|
|
|
|
|
Ok(take_window(&mut sessions.open, owner))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// The destination of the output and the exit status of one terminal session.
|
|
|
|
@@ -79,24 +139,6 @@ trait PtyOutput: Send {
|
|
|
|
|
fn exit(&self, code: Option<u32>);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Window events for the released Terminal plugin, which listens for `pty-data` and `pty-exit`.
|
|
|
|
|
/// The events go to the window that opened the session. A global `listen` in that window
|
|
|
|
|
/// receives them. Tauri 2 also delivers an addressed event to a global `listen` in other windows.
|
|
|
|
|
struct EventOutput {
|
|
|
|
|
app: AppHandle,
|
|
|
|
|
owner: String,
|
|
|
|
|
id: String,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl PtyOutput for EventOutput {
|
|
|
|
|
fn data(&self, bytes: &[u8]) {
|
|
|
|
|
let _ = self.app.emit_to(self.owner.as_str(), "pty-data", PtyData { id: self.id.clone(), data: bytes.to_vec() });
|
|
|
|
|
}
|
|
|
|
|
fn exit(&self, code: Option<u32>) {
|
|
|
|
|
let _ = self.app.emit_to(self.owner.as_str(), "pty-exit", PtyExit { id: self.id.clone(), code });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// A channel to the webview that opened the session. Output goes as raw bytes (an
|
|
|
|
|
/// `ArrayBuffer` in JavaScript). The exit status goes as `{ "exit": code }`.
|
|
|
|
|
struct ChannelOutput(Channel<InvokeResponseBody>);
|
|
|
|
@@ -110,23 +152,58 @@ impl PtyOutput for ChannelOutput {
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Use the channel when the caller supplies one. Without a channel, use window events.
|
|
|
|
|
fn output(channel: Option<Channel<InvokeResponseBody>>, events: impl FnOnce() -> Box<dyn PtyOutput>) -> Box<dyn PtyOutput> {
|
|
|
|
|
match channel {
|
|
|
|
|
Some(channel) => Box::new(ChannelOutput(channel)),
|
|
|
|
|
None => events(),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Send the output until the reader reaches EOF. Then send the exit status.
|
|
|
|
|
fn pump(mut reader: impl Read, exit: std::sync::mpsc::Receiver<Option<u32>>, output: &dyn PtyOutput) {
|
|
|
|
|
let mut buf = [0u8; 4096];
|
|
|
|
|
/// Read the PTY until EOF and send each read to `chunks`.
|
|
|
|
|
fn read_chunks(mut reader: impl Read, chunks: std::sync::mpsc::Sender<Vec<u8>>) {
|
|
|
|
|
let mut buf = vec![0u8; 16 * 1024];
|
|
|
|
|
loop {
|
|
|
|
|
match reader.read(&mut buf) {
|
|
|
|
|
Ok(0) | Err(_) => break,
|
|
|
|
|
Ok(n) => output.data(&buf[..n]),
|
|
|
|
|
Ok(n) => {
|
|
|
|
|
if chunks.send(buf[..n].to_vec()).is_err() { break; }
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Join the output chunks into messages, then send the exit status. A message starts with
|
|
|
|
|
/// the first chunk that arrives. It collects more chunks until `wait` after that chunk or
|
|
|
|
|
/// until `max_bytes`. A chunk that does not fit starts the next message. A chunk larger than
|
|
|
|
|
/// `max_bytes` goes in parts. When the reader stops, the loop sends the rest of the output
|
|
|
|
|
/// and then the exit status.
|
|
|
|
|
fn pump(chunks: Receiver<Vec<u8>>, exit: Receiver<Option<u32>>, output: &dyn PtyOutput, max_bytes: usize, wait: Duration) {
|
|
|
|
|
let max_bytes = max_bytes.max(1);
|
|
|
|
|
let mut next: Option<Vec<u8>> = None;
|
|
|
|
|
loop {
|
|
|
|
|
let mut message = match next.take() {
|
|
|
|
|
Some(chunk) => chunk,
|
|
|
|
|
None => match chunks.recv() {
|
|
|
|
|
Ok(chunk) => chunk,
|
|
|
|
|
Err(_) => break,
|
|
|
|
|
},
|
|
|
|
|
};
|
|
|
|
|
let deadline = Instant::now() + wait;
|
|
|
|
|
let mut ended = false;
|
|
|
|
|
while message.len() < max_bytes {
|
|
|
|
|
let now = Instant::now();
|
|
|
|
|
if now >= deadline { break; }
|
|
|
|
|
match chunks.recv_timeout(deadline - now) {
|
|
|
|
|
Ok(chunk) if message.len() + chunk.len() > max_bytes => {
|
|
|
|
|
next = Some(chunk);
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
Ok(chunk) => message.extend(chunk),
|
|
|
|
|
Err(RecvTimeoutError::Timeout) => break,
|
|
|
|
|
Err(RecvTimeoutError::Disconnected) => {
|
|
|
|
|
ended = true;
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
for part in message.chunks(max_bytes) {
|
|
|
|
|
output.data(part);
|
|
|
|
|
}
|
|
|
|
|
if ended { break; }
|
|
|
|
|
}
|
|
|
|
|
output.exit(exit.recv().ok().flatten());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
@@ -246,7 +323,7 @@ fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner:
|
|
|
|
|
integration_file = Some(rc);
|
|
|
|
|
}
|
|
|
|
|
// The cmd prompt cannot encode base64, so it reports the folder as plain text with `Cwd`.
|
|
|
|
|
// The Terminal plugin reads both `Cwd` (plain) and `RSCwd` (base64). A Windows path
|
|
|
|
|
// The Terminal feature reads both `Cwd` (plain) and `RSCwd` (base64). A Windows path
|
|
|
|
|
// cannot contain the escape or bell characters that end the sequence.
|
|
|
|
|
"cmd" => { cmd.args(["/D", "/K", "prompt $E]633;Cwd;$P$E\\$E]133;A$E\\$P$G$E]133;B$E\\"]); }
|
|
|
|
|
"node" => { cmd.args(["--inspect=127.0.0.1:0", "-i"]); }
|
|
|
|
@@ -265,8 +342,10 @@ fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner:
|
|
|
|
|
.spawn_command(cmd)
|
|
|
|
|
.map_err(Error::from_display)?;
|
|
|
|
|
drop(pair.slave);
|
|
|
|
|
static NEXT_SERIAL: AtomicU64 = AtomicU64::new(0);
|
|
|
|
|
let session = OpenPty {
|
|
|
|
|
owner: owner.into(),
|
|
|
|
|
serial: NEXT_SERIAL.fetch_add(1, Ordering::Relaxed),
|
|
|
|
|
integration_file,
|
|
|
|
|
master: pair.master,
|
|
|
|
|
writer: std::sync::Arc::new(Mutex::new(writer)),
|
|
|
|
@@ -284,77 +363,103 @@ pub async fn pty_open(
|
|
|
|
|
webview: tauri::Webview,
|
|
|
|
|
workspace: State<'_, WorkspaceState>,
|
|
|
|
|
id: String,
|
|
|
|
|
page: String,
|
|
|
|
|
cols: u16,
|
|
|
|
|
rows: u16,
|
|
|
|
|
cwd: String,
|
|
|
|
|
profile: Option<String>,
|
|
|
|
|
directory: Option<String>,
|
|
|
|
|
channel: Option<JavaScriptChannelId>,
|
|
|
|
|
channel: JavaScriptChannelId,
|
|
|
|
|
) -> Result<()> {
|
|
|
|
|
check_page(&page)?;
|
|
|
|
|
let root = current_root(&workspace, window.label())?;
|
|
|
|
|
if root.to_string_lossy() != cwd {
|
|
|
|
|
return Err(Error::new("workspace changed before the terminal started"));
|
|
|
|
|
}
|
|
|
|
|
let owner = window.label().to_owned();
|
|
|
|
|
// A session with a channel sends no `pty-data` or `pty-exit` events.
|
|
|
|
|
let channel = channel.map(|channel| channel.channel_on(webview));
|
|
|
|
|
tauri::async_runtime::spawn_blocking(move || open(app, owner, root, id, cols, rows, profile, directory, channel)).await?
|
|
|
|
|
let output = ChannelOutput(channel.channel_on(webview));
|
|
|
|
|
let request = OpenRequest { owner, page, id, cols, rows, profile, directory: directory.map(PathBuf::from).unwrap_or(root) };
|
|
|
|
|
tauri::async_runtime::spawn_blocking(move || open(app, request, output)).await?
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[allow(clippy::too_many_arguments)]
|
|
|
|
|
fn open(
|
|
|
|
|
app: AppHandle,
|
|
|
|
|
struct OpenRequest {
|
|
|
|
|
owner: String,
|
|
|
|
|
root: PathBuf,
|
|
|
|
|
page: String,
|
|
|
|
|
id: String,
|
|
|
|
|
cols: u16,
|
|
|
|
|
rows: u16,
|
|
|
|
|
profile: Option<String>,
|
|
|
|
|
directory: Option<String>,
|
|
|
|
|
channel: Option<Channel<InvokeResponseBody>>,
|
|
|
|
|
) -> Result<()> {
|
|
|
|
|
directory: PathBuf,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Apply the page rule and start the shell under one lock, so two opens cannot race.
|
|
|
|
|
fn open(app: AppHandle, request: OpenRequest, output: impl PtyOutput + 'static) -> Result<()> {
|
|
|
|
|
let pty = app.state::<PtyState>();
|
|
|
|
|
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
|
|
|
|
if guard.contains_key(&id) {
|
|
|
|
|
return Err(Error::new("terminal already exists"));
|
|
|
|
|
}
|
|
|
|
|
let directory = directory.map(PathBuf::from).unwrap_or(root);
|
|
|
|
|
if !directory.is_dir() { return Err(Error::new("Terminal working directory does not exist")); }
|
|
|
|
|
let (session, reader, mut child) = spawn_shell(&directory, cols, rows, profile.as_deref(), &owner)?;
|
|
|
|
|
guard.insert(id.clone(), session);
|
|
|
|
|
drop(guard);
|
|
|
|
|
let (left, started) = {
|
|
|
|
|
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
|
|
|
|
let left = enter_page(&mut guard, &request.owner, &request.page)?;
|
|
|
|
|
(left, start(&mut guard, &request))
|
|
|
|
|
};
|
|
|
|
|
// A reload left these sessions. Stop their shells outside the lock.
|
|
|
|
|
drop(left);
|
|
|
|
|
let (serial, reader, mut child) = started?;
|
|
|
|
|
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
|
|
|
|
|
let wait_app = app.clone();
|
|
|
|
|
let wait_id = id.clone();
|
|
|
|
|
let wait_id = request.id;
|
|
|
|
|
thread::spawn(move || {
|
|
|
|
|
let code = child.wait().ok().map(|status| status.exit_code());
|
|
|
|
|
// Close ConPTY after the shell exits so the output reader reaches EOF.
|
|
|
|
|
// A later session can use the same ID, so remove only this session.
|
|
|
|
|
let session = wait_app
|
|
|
|
|
.state::<PtyState>()
|
|
|
|
|
.inner
|
|
|
|
|
.lock()
|
|
|
|
|
.ok()
|
|
|
|
|
.and_then(|mut sessions| sessions.remove(&wait_id));
|
|
|
|
|
.and_then(|mut sessions| match sessions.open.get(&wait_id) {
|
|
|
|
|
Some(session) if session.serial == serial => sessions.open.remove(&wait_id),
|
|
|
|
|
_ => None,
|
|
|
|
|
});
|
|
|
|
|
drop(session);
|
|
|
|
|
let _ = exit_tx.send(code);
|
|
|
|
|
});
|
|
|
|
|
let output = output(channel, || Box::new(EventOutput { app: app.clone(), owner, id }));
|
|
|
|
|
thread::spawn(move || pump(reader, exit_rx, output.as_ref()));
|
|
|
|
|
let (chunk_tx, chunk_rx) = std::sync::mpsc::channel();
|
|
|
|
|
thread::spawn(move || read_chunks(reader, chunk_tx));
|
|
|
|
|
thread::spawn(move || pump(chunk_rx, exit_rx, &output, BATCH_BYTES, BATCH_WAIT));
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Write input on a blocking worker. A shell that does not read its input can fill the pipe,
|
|
|
|
|
/// and the write then waits. The Terminal plugin waits for each write before the next one.
|
|
|
|
|
#[tauri::command]
|
|
|
|
|
pub async fn pty_write(app: AppHandle, id: String, data: String) -> Result<()> {
|
|
|
|
|
tauri::async_runtime::spawn_blocking(move || write(&app.state::<PtyState>(), &id, &data)).await?
|
|
|
|
|
type StartedShell = (u64, Box<dyn Read + Send>, Box<dyn portable_pty::Child + Send + Sync>);
|
|
|
|
|
|
|
|
|
|
/// Start the shell and insert its session. The caller holds the lock.
|
|
|
|
|
fn start(sessions: &mut Sessions, request: &OpenRequest) -> Result<StartedShell> {
|
|
|
|
|
if sessions.open.contains_key(&request.id) {
|
|
|
|
|
return Err(Error::new("terminal already exists"));
|
|
|
|
|
}
|
|
|
|
|
if !request.directory.is_dir() { return Err(Error::new("Terminal working directory does not exist")); }
|
|
|
|
|
let (session, reader, child) = spawn_shell(&request.directory, request.cols, request.rows, request.profile.as_deref(), &request.owner)?;
|
|
|
|
|
let serial = session.serial;
|
|
|
|
|
sessions.open.insert(request.id.clone(), session);
|
|
|
|
|
Ok((serial, reader, child))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn write(pty: &PtyState, id: &str, data: &str) -> Result<()> {
|
|
|
|
|
/// Find a session of the window `owner`. A session of another window gives the same error
|
|
|
|
|
/// as a missing session.
|
|
|
|
|
fn owned<'a>(sessions: &'a Sessions, owner: &str, id: &str) -> Result<&'a OpenPty> {
|
|
|
|
|
sessions.open.get(id).filter(|session| session.owner == owner).ok_or_else(|| Error::new(NOT_OPEN))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Write input on a blocking worker. A shell that does not read its input can fill the pipe,
|
|
|
|
|
/// and the write then waits. The Terminal feature waits for each write before the next one.
|
|
|
|
|
#[tauri::command]
|
|
|
|
|
pub async fn pty_write(app: AppHandle, window: tauri::Window, id: String, data: String) -> Result<()> {
|
|
|
|
|
let owner = window.label().to_owned();
|
|
|
|
|
tauri::async_runtime::spawn_blocking(move || write(&app.state::<PtyState>(), &owner, &id, &data)).await?
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn write(pty: &PtyState, owner: &str, id: &str, data: &str) -> Result<()> {
|
|
|
|
|
let writer = {
|
|
|
|
|
let guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
|
|
|
|
let session = guard.get(id).ok_or_else(|| Error::new("terminal is not open"))?;
|
|
|
|
|
session.writer.clone()
|
|
|
|
|
owned(&guard, owner, id)?.writer.clone()
|
|
|
|
|
};
|
|
|
|
|
// Other terminals stay usable while this write waits.
|
|
|
|
|
let mut writer = writer.lock().map_err(|_| Error::new("pty writer lock"))?;
|
|
|
|
@@ -366,10 +471,13 @@ fn write(pty: &PtyState, id: &str, data: &str) -> Result<()> {
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[tauri::command]
|
|
|
|
|
pub fn pty_resize(pty: State<PtyState>, id: String, cols: u16, rows: u16) -> Result<()> {
|
|
|
|
|
pub fn pty_resize(pty: State<PtyState>, window: tauri::Window, id: String, cols: u16, rows: u16) -> Result<()> {
|
|
|
|
|
resize(&pty, window.label(), &id, cols, rows)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn resize(pty: &PtyState, owner: &str, id: &str, cols: u16, rows: u16) -> Result<()> {
|
|
|
|
|
let guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
|
|
|
|
let session = guard.get(&id).ok_or_else(|| Error::new("terminal is not open"))?;
|
|
|
|
|
session
|
|
|
|
|
owned(&guard, owner, id)?
|
|
|
|
|
.master
|
|
|
|
|
.resize(PtySize {
|
|
|
|
|
rows: rows.max(2),
|
|
|
|
@@ -382,19 +490,34 @@ pub fn pty_resize(pty: State<PtyState>, id: String, cols: u16, rows: u16) -> Res
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Stop a shell on a blocking worker. Closing a pseudo console can wait for its output.
|
|
|
|
|
/// A missing session and a session of another window are not an error. Neither one closes.
|
|
|
|
|
#[tauri::command]
|
|
|
|
|
pub async fn pty_close(app: AppHandle, id: String) -> Result<()> {
|
|
|
|
|
pub async fn pty_close(app: AppHandle, window: tauri::Window, id: String) -> Result<()> {
|
|
|
|
|
let owner = window.label().to_owned();
|
|
|
|
|
tauri::async_runtime::spawn_blocking(move || {
|
|
|
|
|
let pty = app.state::<PtyState>();
|
|
|
|
|
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
|
|
|
|
let session = guard.remove(&id);
|
|
|
|
|
drop(guard);
|
|
|
|
|
let session = close(&app.state::<PtyState>(), &owner, &id)?;
|
|
|
|
|
drop(session);
|
|
|
|
|
Ok(())
|
|
|
|
|
})
|
|
|
|
|
.await?
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Remove a session of the window `owner` under the lock. The caller stops it outside the lock.
|
|
|
|
|
fn close(pty: &PtyState, owner: &str, id: &str) -> Result<Option<OpenPty>> {
|
|
|
|
|
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
|
|
|
|
if owned(&guard, owner, id).is_err() {
|
|
|
|
|
return Ok(None);
|
|
|
|
|
}
|
|
|
|
|
Ok(guard.open.remove(id))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// The number of open terminals of all windows. The Settings window asks before Terminal
|
|
|
|
|
/// goes off when shells run.
|
|
|
|
|
#[tauri::command]
|
|
|
|
|
pub fn pty_running(pty: State<PtyState>) -> Result<usize> {
|
|
|
|
|
running(&pty)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[tauri::command]
|
|
|
|
|
pub async fn pty_new_window(app: AppHandle, window: tauri::Window, workspace: State<'_, WorkspaceState>, id: String) -> Result<()> {
|
|
|
|
|
let root = current_root(&workspace, window.label())?;
|
|
|
|
@@ -436,28 +559,111 @@ mod tests {
|
|
|
|
|
use std::sync::Arc;
|
|
|
|
|
use std::time::{Duration, Instant};
|
|
|
|
|
|
|
|
|
|
/// Records the window events that a session would send.
|
|
|
|
|
struct FakeEvents(Arc<Mutex<Vec<String>>>);
|
|
|
|
|
impl PtyOutput for FakeEvents {
|
|
|
|
|
fn data(&self, bytes: &[u8]) { self.0.lock().unwrap().push(format!("pty-data {}", String::from_utf8_lossy(bytes))); }
|
|
|
|
|
fn exit(&self, code: Option<u32>) { self.0.lock().unwrap().push(format!("pty-exit {code:?}")); }
|
|
|
|
|
#[derive(Debug, PartialEq)]
|
|
|
|
|
enum Sent {
|
|
|
|
|
Data(Vec<u8>),
|
|
|
|
|
Exit(Option<u32>),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn run_pump(channel: Option<Channel<InvokeResponseBody>>, events: Arc<Mutex<Vec<String>>>) {
|
|
|
|
|
/// Records the messages that a session sends.
|
|
|
|
|
#[derive(Clone, Default)]
|
|
|
|
|
struct Recorder(Arc<Mutex<Vec<Sent>>>);
|
|
|
|
|
impl PtyOutput for Recorder {
|
|
|
|
|
fn data(&self, bytes: &[u8]) { self.0.lock().unwrap().push(Sent::Data(bytes.to_vec())); }
|
|
|
|
|
fn exit(&self, code: Option<u32>) { self.0.lock().unwrap().push(Sent::Exit(code)); }
|
|
|
|
|
}
|
|
|
|
|
impl Recorder {
|
|
|
|
|
fn take(&self) -> Vec<Sent> { std::mem::take(&mut *self.0.lock().unwrap()) }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type Pump = (std::sync::mpsc::Sender<Vec<u8>>, std::sync::mpsc::Sender<Option<u32>>, Recorder, thread::JoinHandle<()>);
|
|
|
|
|
|
|
|
|
|
/// Run the batch loop on its own thread. The test sends the chunks and the exit status.
|
|
|
|
|
fn start_pump(max_bytes: usize, wait: Duration) -> Pump {
|
|
|
|
|
let (chunk_tx, chunk_rx) = std::sync::mpsc::channel();
|
|
|
|
|
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
|
|
|
|
|
exit_tx.send(Some(3)).unwrap();
|
|
|
|
|
let output = output(channel, move || Box::new(FakeEvents(events)));
|
|
|
|
|
pump(std::io::Cursor::new(b"hello \xce\xbb".to_vec()), exit_rx, output.as_ref());
|
|
|
|
|
let recorder = Recorder::default();
|
|
|
|
|
let output = recorder.clone();
|
|
|
|
|
let handle = thread::spawn(move || pump(chunk_rx, exit_rx, &output, max_bytes, wait));
|
|
|
|
|
(chunk_tx, exit_tx, recorder, handle)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn data_sizes(sent: &[Sent]) -> Vec<usize> {
|
|
|
|
|
sent.iter().filter_map(|message| match message { Sent::Data(bytes) => Some(bytes.len()), Sent::Exit(_) => None }).collect()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn a_channel_session_sends_raw_bytes_and_no_window_events() {
|
|
|
|
|
let events = Arc::new(Mutex::new(Vec::new()));
|
|
|
|
|
fn small_chunks_within_the_wait_become_one_message() {
|
|
|
|
|
let (chunks, exit, recorder, handle) = start_pump(BATCH_BYTES, Duration::from_secs(5));
|
|
|
|
|
for _ in 0..100 { chunks.send(b"ab".to_vec()).unwrap(); }
|
|
|
|
|
drop(chunks);
|
|
|
|
|
exit.send(Some(0)).unwrap();
|
|
|
|
|
handle.join().unwrap();
|
|
|
|
|
assert_eq!(recorder.take(), vec![Sent::Data(b"ab".repeat(100)), Sent::Exit(Some(0))]);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn output_larger_than_the_limit_becomes_several_messages() {
|
|
|
|
|
let (chunks, exit, recorder, handle) = start_pump(BATCH_BYTES, Duration::from_secs(5));
|
|
|
|
|
let mut expected: Vec<u8> = Vec::new();
|
|
|
|
|
for index in 0..40u8 {
|
|
|
|
|
let chunk = vec![index; 4000];
|
|
|
|
|
expected.extend(&chunk);
|
|
|
|
|
chunks.send(chunk).unwrap();
|
|
|
|
|
}
|
|
|
|
|
// One chunk larger than the limit goes in parts.
|
|
|
|
|
let large = vec![b'x'; BATCH_BYTES + 100];
|
|
|
|
|
expected.extend(&large);
|
|
|
|
|
chunks.send(large).unwrap();
|
|
|
|
|
drop(chunks);
|
|
|
|
|
exit.send(None).unwrap();
|
|
|
|
|
handle.join().unwrap();
|
|
|
|
|
let sent = recorder.take();
|
|
|
|
|
let sizes = data_sizes(&sent);
|
|
|
|
|
assert!(sizes.len() > 1, "{sizes:?}");
|
|
|
|
|
assert!(sizes.iter().all(|&size| size > 0 && size <= BATCH_BYTES), "{sizes:?}");
|
|
|
|
|
let joined: Vec<u8> = sent.iter().flat_map(|message| match message { Sent::Data(bytes) => bytes.clone(), Sent::Exit(_) => Vec::new() }).collect();
|
|
|
|
|
assert_eq!(joined, expected);
|
|
|
|
|
assert_eq!(sent.last(), Some(&Sent::Exit(None)));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn a_chunk_after_a_pause_goes_in_a_new_message() {
|
|
|
|
|
let (chunks, exit, recorder, handle) = start_pump(BATCH_BYTES, Duration::from_millis(20));
|
|
|
|
|
chunks.send(b"first".to_vec()).unwrap();
|
|
|
|
|
thread::sleep(Duration::from_millis(300));
|
|
|
|
|
chunks.send(b"second".to_vec()).unwrap();
|
|
|
|
|
drop(chunks);
|
|
|
|
|
exit.send(Some(1)).unwrap();
|
|
|
|
|
handle.join().unwrap();
|
|
|
|
|
assert_eq!(recorder.take(), vec![Sent::Data(b"first".to_vec()), Sent::Data(b"second".to_vec()), Sent::Exit(Some(1))]);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn the_exit_comes_after_all_output() {
|
|
|
|
|
let (chunks, exit, recorder, handle) = start_pump(16, Duration::from_secs(5));
|
|
|
|
|
// The exit status is ready before the output ends.
|
|
|
|
|
exit.send(Some(9)).unwrap();
|
|
|
|
|
for _ in 0..10 { chunks.send(b"0123456789".to_vec()).unwrap(); }
|
|
|
|
|
drop(chunks);
|
|
|
|
|
handle.join().unwrap();
|
|
|
|
|
let sent = recorder.take();
|
|
|
|
|
assert_eq!(data_sizes(&sent).iter().sum::<usize>(), 100);
|
|
|
|
|
assert!(data_sizes(&sent).iter().all(|&size| size <= 16));
|
|
|
|
|
assert_eq!(sent.iter().position(|message| matches!(message, Sent::Exit(_))), Some(sent.len() - 1));
|
|
|
|
|
assert_eq!(sent.last(), Some(&Sent::Exit(Some(9))));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn a_channel_session_sends_raw_bytes_then_the_json_exit() {
|
|
|
|
|
let received = Arc::new(Mutex::new(Vec::new()));
|
|
|
|
|
let sink = received.clone();
|
|
|
|
|
let channel = Channel::new(move |body| { sink.lock().unwrap().push(body); Ok(()) });
|
|
|
|
|
run_pump(Some(channel), events.clone());
|
|
|
|
|
assert!(events.lock().unwrap().is_empty(), "a channel session must not send pty-data or pty-exit events");
|
|
|
|
|
let (chunk_tx, chunk_rx) = std::sync::mpsc::channel();
|
|
|
|
|
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
|
|
|
|
|
exit_tx.send(Some(3)).unwrap();
|
|
|
|
|
read_chunks(std::io::Cursor::new(b"hello \xce\xbb".to_vec()), chunk_tx);
|
|
|
|
|
pump(chunk_rx, exit_rx, &ChannelOutput(channel), BATCH_BYTES, BATCH_WAIT);
|
|
|
|
|
let received = received.lock().unwrap();
|
|
|
|
|
assert_eq!(received.len(), 2);
|
|
|
|
|
match &received[0] {
|
|
|
|
@@ -470,11 +676,112 @@ mod tests {
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Start a real shell for `owner`. A thread reads its output until EOF.
|
|
|
|
|
fn shell(owner: &str) -> OpenPty {
|
|
|
|
|
let root = std::env::current_dir().unwrap();
|
|
|
|
|
let (session, mut reader, _child) = spawn_shell(&root, 80, 24, None, owner).unwrap();
|
|
|
|
|
thread::spawn(move || {
|
|
|
|
|
let _ = std::io::copy(&mut reader, &mut std::io::sink());
|
|
|
|
|
});
|
|
|
|
|
session
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn ids(pty: &PtyState) -> Vec<String> {
|
|
|
|
|
let mut ids: Vec<String> = pty.inner.lock().unwrap().open.keys().cloned().collect();
|
|
|
|
|
ids.sort();
|
|
|
|
|
ids
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn a_session_without_a_channel_keeps_the_window_events() {
|
|
|
|
|
let events = Arc::new(Mutex::new(Vec::new()));
|
|
|
|
|
run_pump(None, events.clone());
|
|
|
|
|
assert_eq!(*events.lock().unwrap(), vec!["pty-data hello λ".to_owned(), "pty-exit Some(3)".to_owned()]);
|
|
|
|
|
fn only_the_owner_window_can_use_a_session() {
|
|
|
|
|
let pty = PtyState::new();
|
|
|
|
|
pty.inner.lock().unwrap().open.insert("t1".into(), shell("a"));
|
|
|
|
|
assert_eq!(write(&pty, "b", "t1", "\r").unwrap_err().to_string(), NOT_OPEN);
|
|
|
|
|
assert_eq!(resize(&pty, "b", "t1", 100, 40).unwrap_err().to_string(), NOT_OPEN);
|
|
|
|
|
assert!(close(&pty, "b", "t1").unwrap().is_none());
|
|
|
|
|
assert_eq!(ids(&pty), vec!["t1"]);
|
|
|
|
|
// A missing session gives the same results.
|
|
|
|
|
assert_eq!(write(&pty, "a", "t2", "\r").unwrap_err().to_string(), NOT_OPEN);
|
|
|
|
|
assert_eq!(resize(&pty, "a", "t2", 100, 40).unwrap_err().to_string(), NOT_OPEN);
|
|
|
|
|
assert!(close(&pty, "a", "t2").unwrap().is_none());
|
|
|
|
|
write(&pty, "a", "t1", "\r").unwrap();
|
|
|
|
|
resize(&pty, "a", "t1", 100, 40).unwrap();
|
|
|
|
|
let session = close(&pty, "a", "t1").unwrap();
|
|
|
|
|
assert!(session.is_some());
|
|
|
|
|
assert!(ids(&pty).is_empty());
|
|
|
|
|
drop(session);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn a_new_page_closes_the_sessions_of_its_window_only() {
|
|
|
|
|
let pty = PtyState::new();
|
|
|
|
|
let enter = |owner: &str, page: &str| enter_page(&mut pty.inner.lock().unwrap(), owner, page);
|
|
|
|
|
// The first page of each window becomes current.
|
|
|
|
|
assert!(enter("a", "page-1").unwrap().is_empty());
|
|
|
|
|
assert!(enter("b", "page-b").unwrap().is_empty());
|
|
|
|
|
{
|
|
|
|
|
let mut sessions = pty.inner.lock().unwrap();
|
|
|
|
|
sessions.open.insert("a1".into(), shell("a"));
|
|
|
|
|
sessions.open.insert("b1".into(), shell("b"));
|
|
|
|
|
}
|
|
|
|
|
// A second dock of the same page keeps the sessions.
|
|
|
|
|
assert!(enter("a", "page-1").unwrap().is_empty());
|
|
|
|
|
assert_eq!(ids(&pty), vec!["a1", "b1"]);
|
|
|
|
|
// A reload of window "a" closes its sessions. The session of window "b" stays.
|
|
|
|
|
let left = enter("a", "page-2").unwrap();
|
|
|
|
|
assert_eq!(left.iter().map(|session| session.owner.as_str()).collect::<Vec<_>>(), vec!["a"]);
|
|
|
|
|
drop(left);
|
|
|
|
|
assert_eq!(ids(&pty), vec!["b1"]);
|
|
|
|
|
// A late open of the old page is refused and closes nothing.
|
|
|
|
|
pty.inner.lock().unwrap().open.insert("a2".into(), shell("a"));
|
|
|
|
|
assert_eq!(enter("a", "page-1").err().map(|error| error.to_string()).as_deref(), Some(RETIRED_PAGE));
|
|
|
|
|
assert_eq!(ids(&pty), vec!["a2", "b1"]);
|
|
|
|
|
// The window forgets its pages when it closes.
|
|
|
|
|
pty.close_window("a");
|
|
|
|
|
assert_eq!(ids(&pty), vec!["b1"]);
|
|
|
|
|
assert!(!pty.inner.lock().unwrap().pages.contains_key("a"));
|
|
|
|
|
assert!(enter("a", "page-1").unwrap().is_empty());
|
|
|
|
|
pty.close_all();
|
|
|
|
|
assert!(ids(&pty).is_empty());
|
|
|
|
|
assert!(pty.inner.lock().unwrap().pages.is_empty());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn a_window_keeps_a_limited_number_of_retired_pages() {
|
|
|
|
|
let mut sessions = Sessions::default();
|
|
|
|
|
for index in 0..=RETIRED_PAGES + 4 {
|
|
|
|
|
assert!(enter_page(&mut sessions, "a", &format!("page-{index}")).unwrap().is_empty());
|
|
|
|
|
}
|
|
|
|
|
let pages = &sessions.pages["a"];
|
|
|
|
|
assert_eq!(pages.retired.len(), RETIRED_PAGES);
|
|
|
|
|
assert_eq!(pages.current, format!("page-{}", RETIRED_PAGES + 4));
|
|
|
|
|
assert!(enter_page(&mut sessions, "a", &format!("page-{}", RETIRED_PAGES + 3)).is_err());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn page_ids_are_checked() {
|
|
|
|
|
assert!(check_page("0f3c-9a1b").is_ok());
|
|
|
|
|
assert!(check_page(&"a".repeat(64)).is_ok());
|
|
|
|
|
for page in ["", "a b", "../page", "page_1", "λ"] {
|
|
|
|
|
assert!(check_page(page).is_err(), "{page}");
|
|
|
|
|
}
|
|
|
|
|
assert!(check_page(&"a".repeat(65)).is_err());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn running_counts_the_sessions_of_all_windows() {
|
|
|
|
|
let pty = PtyState::new();
|
|
|
|
|
assert_eq!(running(&pty).unwrap(), 0);
|
|
|
|
|
{
|
|
|
|
|
let mut sessions = pty.inner.lock().unwrap();
|
|
|
|
|
sessions.open.insert("a1".into(), shell("a"));
|
|
|
|
|
sessions.open.insert("b1".into(), shell("b"));
|
|
|
|
|
}
|
|
|
|
|
assert_eq!(running(&pty).unwrap(), 2);
|
|
|
|
|
pty.close_window("a");
|
|
|
|
|
assert_eq!(running(&pty).unwrap(), 1);
|
|
|
|
|
pty.close_all();
|
|
|
|
|
assert_eq!(running(&pty).unwrap(), 0);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|