paperos 0.2.0

A programmable editor built on the Runact actor runtime
Documentation
//! TerminalActor: owns a PTY child process and its TermGrid.
//!
//! The actor runs the child (shell or test command), a reader thread that
//! feeds PTY output through the vte parser into a shared grid, and answers
//! TerminalMessage requests (grid snapshots, status, resize, writes).
//! It is invisible machinery — the visible terminal panel is a BufferActor
//! whose lines hold the grid's text projection.

use super::extension::TermShared;
use super::parser::TermParser;
use portable_pty::{CommandBuilder, NativePtySystem, PtySize, PtySystem};
use runact::{Actor, ActorContext, ActorError};
use std::io::{Read, Write};
use std::sync::Arc;

/// Messages the TerminalActor handles.
pub enum TerminalMessage {
    /// Write bytes to the child's stdin (the PTY master).
    Write(Vec<u8>),
    /// Resize the PTY and the grid.
    Resize { rows: usize, cols: usize },
    /// Request: reply with a Box<TermGrid> snapshot.
    GetGrid,
    /// Request: reply with a Box<TermStatus>.
    GetStatus,
    /// Request: reply with the grid's text projection as a Vec<String>.
    /// This is the buffer-content analogue — it lets TerminalActor stand
    /// in for a BufferActor (GetContent over text_projection).
    GetContent,
    /// Kill the PTY child, tearing the terminal down cleanly.
    Kill,
}

/// Status of the terminal child process.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TermStatus {
    pub exited: bool,
}

/// Actor that owns a PTY child + its grid.
pub struct TerminalActor {
    shared: Arc<TermShared>,
    writer: Box<dyn Write + Send>,
    child: Box<dyn portable_pty::Child + Send + Sync>,
    master: Box<dyn portable_pty::MasterPty + Send>,
}

impl TerminalActor {
    /// Spawn `program` directly in a new PTY with an 80x24 grid.
    pub fn new_with_child(program: &str) -> Result<Self, String> {
        Self::spawn_command(CommandBuilder::new(program), None)
    }

    /// Spawn `sh -c <command>` in a new PTY with an 80x24 grid.
    pub fn new_with_shell_command(command: &str) -> Result<Self, String> {
        let mut cmd = CommandBuilder::new("sh");
        cmd.arg("-c");
        cmd.arg(command);
        Self::spawn_command(cmd, None)
    }

    /// Spawn `sh -c <command>` writing into a caller-owned shared grid
    /// (main.rs / tests use this so the extension and actor share state).
    pub fn with_shared_shell(command: &str, shared: Arc<TermShared>) -> Result<Self, String> {
        let mut cmd = CommandBuilder::new("sh");
        cmd.arg("-c");
        cmd.arg(command);
        Self::spawn_command(cmd, Some(shared))
    }

    fn spawn_command(cmd: CommandBuilder, shared: Option<Arc<TermShared>>) -> Result<Self, String> {
        let pty_system = NativePtySystem {};
        let pair = pty_system
            .openpty(PtySize {
                rows: 24,
                cols: 80,
                pixel_width: 0,
                pixel_height: 0,
            })
            .map_err(|e| format!("openpty: {e}"))?;

        let child = pair
            .slave
            .spawn_command(cmd)
            .map_err(|e| format!("spawn: {e}"))?;

        let reader = pair
            .master
            .try_clone_reader()
            .map_err(|e| format!("clone reader: {e}"))?;
        let writer = pair
            .master
            .take_writer()
            .map_err(|e| format!("take writer: {e}"))?;

        let shared = shared.unwrap_or_else(|| Arc::new(TermShared::new(80, 24)));

        // Reader thread: blocks on PTY output, feeds the grid, marks exit.
        let reader_shared = Arc::clone(&shared);
        std::thread::spawn(move || {
            let mut reader = reader;
            let mut buf = [0u8; 4096];
            loop {
                match reader.read(&mut buf) {
                    Ok(0) => break, // EOF: child closed its end
                    Ok(n) => {
                        let mut grid = reader_shared.grid.write().unwrap();
                        TermParser::new(&mut grid).feed(&buf[..n]);
                    }
                    Err(_) => break,
                }
            }
            *reader_shared.exited.write().unwrap() = true;
        });

        Ok(TerminalActor {
            shared,
            writer,
            child,
            master: pair.master,
        })
    }
}

impl Actor for TerminalActor {
    type Message = TerminalMessage;

    fn handle(
        &mut self,
        message: TerminalMessage,
        context: &mut ActorContext,
    ) -> Result<(), ActorError> {
        match message {
            TerminalMessage::Write(bytes) => {
                self.writer
                    .write_all(&bytes)
                    .and_then(|_| self.writer.flush())
                    .map_err(|e| ActorError::Handler(format!("pty write: {e}")))?;
            }
            TerminalMessage::Resize { rows, cols } => {
                self.master
                    .resize(PtySize {
                        rows: rows as u16,
                        cols: cols as u16,
                        pixel_width: 0,
                        pixel_height: 0,
                    })
                    .map_err(|e| ActorError::Handler(format!("pty resize: {e}")))?;
                self.shared.grid.write().unwrap().resize(cols, rows);
            }
            TerminalMessage::GetGrid => {
                let snapshot = self.shared.grid.read().unwrap().clone();
                context
                    .reply(snapshot)
                    .map_err(|e| ActorError::Handler(e.to_string()))?;
            }
            TerminalMessage::GetStatus => {
                let exited = *self.shared.exited.read().unwrap();
                context
                    .reply(TermStatus { exited })
                    .map_err(|e| ActorError::Handler(e.to_string()))?;
            }
            TerminalMessage::GetContent => {
                let content = self.shared.grid.read().unwrap().text_projection();
                context
                    .reply(content)
                    .map_err(|e| ActorError::Handler(e.to_string()))?;
            }
            TerminalMessage::Kill => {
                let _ = self.child.kill();
                let _ = self.master.try_clone_reader();
                *self.shared.exited.write().unwrap() = true;
            }
        }
        Ok(())
    }
}

impl Drop for TerminalActor {
    fn drop(&mut self) {
        let _ = self.child.kill();
    }
}