paperos 0.2.0

A programmable editor built on the Runact actor runtime
Documentation
//! TerminalExtension: the visible half of the terminal.
//!
//! Owns the terminal panel's rendering (via the render-claim mechanism),
//! encodes keys to PTY bytes in Terminal mode, syncs the grid's text
//! projection into the "terminal" BufferActor, and exposes the
//! `terminal` / `terminal-send` commands.

use super::actor::TerminalMessage;
use super::grid::TermGrid;
use crate::core::runtime::CommandHandler;
use crate::extensions::panel_registry::PanelRegistry;
use crate::extensions::vi_input::{EditorMode, ViInputExtension};
use runact::{ActorId, Runtime};
use std::sync::{Arc, RwLock};

/// Shared grid + exit flag, owned jointly by the extension and the
/// TerminalActor's reader thread.
pub struct TermShared {
    pub grid: RwLock<TermGrid>,
    pub exited: RwLock<bool>,
}

/// Scrollback history retained above the visible area.
pub const SCROLLBACK_CAP: usize = 10_000;

impl TermShared {
    pub fn new(cols: usize, rows: usize) -> Self {
        TermShared {
            grid: RwLock::new(TermGrid::scrollback(cols, rows, SCROLLBACK_CAP)),
            exited: RwLock::new(false),
        }
    }
}

/// The terminal extension state.
pub struct TerminalExtension {
    /// The TerminalActor running the PTY child.
    actor: ActorId,
    /// Shared grid (same handle the actor's reader thread writes to).
    shared: Arc<TermShared>,
    /// Panel registry — for looking up the "terminal" panel buffer.
    panels: Option<Arc<RwLock<PanelRegistry>>>,
    /// vi input — for reading the current mode in on_key.
    vi_input: Option<Arc<RwLock<ViInputExtension>>>,
}

impl TerminalExtension {
    pub fn new(actor: ActorId, shared: Arc<TermShared>) -> Self {
        TerminalExtension {
            actor,
            shared,
            panels: None,
            vi_input: None,
        }
    }

    /// Wire the panel registry (main.rs, before the event loop).
    pub fn set_panels(&mut self, panels: Arc<RwLock<PanelRegistry>>) {
        self.panels = Some(panels);
    }

    /// Wire the vi input extension (mode source for key encoding).
    pub fn set_vi_input(&mut self, vi: Arc<RwLock<ViInputExtension>>) {
        self.vi_input = Some(vi);
    }

    /// The TerminalActor's ActorId — for direct message traffic (Kill, etc.).
    pub fn actor_id(&self) -> ActorId {
        self.actor
    }

    /// Current grid snapshot (cheap clone under read lock).
    pub fn grid(&self) -> TermGrid {
        self.shared.grid.read().unwrap().clone()
    }

    /// Scroll the terminal viewport by `delta` rows (positive = into
    /// history). Local — nothing is written to the PTY.
    pub fn scroll_viewport(&self, delta: i64) {
        self.shared.grid.write().unwrap().scroll_viewport(delta);
    }

    /// Write raw bytes to the PTY child via the actor. User input snaps
    /// the viewport to the live view (you type, you follow the output).
    pub fn write(&self, runtime: &Runtime, bytes: &[u8]) {
        self.shared.grid.write().unwrap().reset_viewport();
        let _ = runtime.send(self.actor, TerminalMessage::Write(bytes.to_vec()));
    }

    /// Sync the grid's text projection into the "terminal" panel buffer.
    /// Keeps the invariant: buffer lines describe what is on screen.
    pub fn sync_projection(&self, runtime: &Runtime) {
        let Some(panels) = self.panels.as_ref() else {
            return;
        };
        let Ok(panels) = panels.read() else {
            return;
        };
        let Some(id) = panels.get("terminal") else {
            return;
        };
        let projection = self.shared.grid.read().unwrap().text_projection();
        let content = projection.join("\n");
        let _ = runtime.send(id, crate::core::BufferMessage::LoadContent(content));
    }

    /// Handle a crossterm key in Terminal mode: encode and write to PTY.
    /// Returns true if the key was consumed (terminal mode active).
    pub fn handle_key(&self, key: crossterm::event::KeyEvent, runtime: &Runtime) -> bool {
        let in_terminal = self
            .vi_input
            .as_ref()
            .map(|vi| {
                vi.read()
                    .map(|v| v.mode() == EditorMode::Terminal)
                    .unwrap_or(false)
            })
            .unwrap_or(false);
        if !in_terminal {
            return false;
        }
        // The minibuffer owns the keyboard while it is active (M-x).
        // Keys must reach it, never the PTY.
        if self
            .panels
            .as_ref()
            .map(|p| p.read().map(|r| r.minibuffer_active()).unwrap_or(false))
            .unwrap_or(false)
        {
            return false;
        }
        // PageUp/PageDown scroll the viewport locally (history paging).
        match key.code {
            crossterm::event::KeyCode::PageUp => {
                self.scroll_viewport(self.page_rows());
                return true;
            }
            crossterm::event::KeyCode::PageDown => {
                self.scroll_viewport(-self.page_rows());
                return true;
            }
            _ => {}
        }
        // Editor escape hatches never reach the PTY: Alt+<anything> is
        // editor command space (M-x, M-n, ...), and Esc exits Terminal
        // mode. Return false so the event loop routes them through the
        // normal keymap path.
        if key.modifiers.contains(crossterm::event::KeyModifiers::ALT) {
            return false;
        }
        if key.code == crossterm::event::KeyCode::Esc {
            return false;
        }
        // Any other key: snap to the live view first, then encode.
        self.shared.grid.write().unwrap().reset_viewport();
        if let Some(bytes) = encode_key(key) {
            self.write(runtime, &bytes);
        }
        true
    }

    /// Rows per PageUp/PageDown: half the visible height (minimum 1).
    fn page_rows(&self) -> i64 {
        let rows = self.shared.grid.read().unwrap().rows() as i64;
        (rows / 2).max(1)
    }

    /// Draw the terminal grid into `area` (called by the render
    /// extension when the "terminal" panel is claimed and focused).
    pub fn draw(&self, f: &mut ratatui::Frame, area: ratatui::layout::Rect) {
        use ratatui::text::Span;
        use ratatui::widgets::Paragraph;

        let grid = self.grid();
        let cursor_row = grid.cursor_in_view();
        let ccol = grid.cursor().1;

        let lines: Vec<ratatui::text::Line> = (0..grid.rows())
            .map(|r| {
                let mut spans: Vec<Span> = Vec::new();
                let mut col = 0usize;
                while col < grid.cols() {
                    let Some(cell) = grid.cell(r, col) else {
                        break;
                    };
                    let mut style = cell.style;
                    // Terminal cursor: reverse video on the cursor cell
                    // (only when the viewport shows it).
                    if cursor_row == Some(r) && col == ccol {
                        style = style
                            .fg(ratatui::style::Color::Black)
                            .bg(cell.style.fg.unwrap_or(ratatui::style::Color::White));
                    }
                    spans.push(Span::styled(cell.ch.to_string(), style));
                    col += 1;
                }
                ratatui::text::Line::from(spans)
            })
            .collect();

        let paragraph = Paragraph::new(lines);
        f.render_widget(paragraph, area);
    }
}

/// Encode a crossterm key to the bytes a terminal program expects.
pub fn encode_key(key: crossterm::event::KeyEvent) -> Option<Vec<u8>> {
    use crossterm::event::{KeyCode, KeyModifiers};

    // Only react to Press (not Repeat/Release) — matches event loop rules.
    if !matches!(key.kind, crossterm::event::KeyEventKind::Press) {
        return None;
    }

    let bytes = match key.code {
        KeyCode::Enter => b"\r".to_vec(),
        KeyCode::Tab => b"\t".to_vec(),
        KeyCode::BackTab => b"\x1b[Z".to_vec(),
        KeyCode::Backspace => b"\x7f".to_vec(),
        KeyCode::Esc => b"\x1b".to_vec(),
        KeyCode::Left => b"\x1b[D".to_vec(),
        KeyCode::Right => b"\x1b[C".to_vec(),
        KeyCode::Up => b"\x1b[A".to_vec(),
        KeyCode::Down => b"\x1b[B".to_vec(),
        KeyCode::Home => b"\x1b[H".to_vec(),
        KeyCode::End => b"\x1b[F".to_vec(),
        KeyCode::PageUp => b"\x1b[5~".to_vec(),
        KeyCode::PageDown => b"\x1b[6~".to_vec(),
        KeyCode::Delete => b"\x1b[3~".to_vec(),
        KeyCode::Insert => b"\x1b[2~".to_vec(),
        KeyCode::Char(ch) => {
            if key.modifiers.contains(KeyModifiers::CONTROL) {
                // Ctrl-A..Ctrl-Z map to 0x01..0x1a (ch is lowercase-ish).
                let c = ch.to_ascii_lowercase();
                if c.is_ascii_lowercase() {
                    vec![c as u8 - b'a' + 1]
                } else if c == ' ' {
                    b"\x00".to_vec()
                } else {
                    return None;
                }
            } else if key.modifiers.contains(KeyModifiers::ALT) {
                let mut v = b"\x1b".to_vec();
                v.push(ch as u8);
                v
            } else {
                // crossterm already provides the shifted/uppercase char.
                ch.to_string().into_bytes()
            }
        }
        _ => return None,
    };
    Some(bytes)
}

/// `terminal-send <text>` command handler — writes text (plus \r) to
/// the PTY via the extension. Text is a single argument (splitn(2)).
pub struct TerminalSendCommand {
    ext: Arc<RwLock<TerminalExtension>>,
}

impl TerminalSendCommand {
    pub fn new(ext: Arc<RwLock<TerminalExtension>>) -> Self {
        TerminalSendCommand { ext }
    }
}

impl CommandHandler for TerminalSendCommand {
    fn handle(
        &mut self,
        args: &[String],
        runtime: &Runtime,
        _buffer: Option<ActorId>,
    ) -> Result<Option<String>, Box<dyn std::error::Error>> {
        // args[0] is the command name; args[1] the argument (run_command
        // convention — see buffer_commands.rs / file.rs).
        let text = args.get(1).cloned().unwrap_or_default();
        if text.is_empty() {
            return Ok(Some("usage: terminal-send <text>".to_string()));
        }
        let ext = self.ext.read().map_err(|e| e.to_string())?;
        ext.write(runtime, text.as_bytes());
        ext.write(runtime, b"\r");
        Ok(None)
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }
}