paperos 0.2.0

A programmable editor built on the Runact actor runtime
Documentation
use crate::core::{BufferActor, BufferMessage};
use runact::{ActorId, Runtime};
use std::collections::HashMap;

/// Manages panel buffers and minibuffer state.
/// Does NOT own Runtime — callers pass &Runtime or &mut Runtime as needed.
pub struct PanelRegistry {
    panels: HashMap<String, ActorId>,
    /// Panel name -> owning extension name. A claimed panel's rendering
    /// is owned by that extension (drawn via its render hook), NOT the
    /// plain-lines default. One renderer per panel — second claim errors.
    render_claims: HashMap<String, String>,
    minibuffer: String,
    minibuffer_active: bool,
    /// Fuzzy-match candidates shown in the minibuffer command list.
    /// Updated as the user types in M-x mode.
    candidates: Vec<String>,
    /// Scroll offset within the candidate list (visible window).
    candidate_scroll: usize,
    /// Statusline format template. Tokens: %m mode, %f file, %l line,
    /// %c col, %( modified marker " [+]". Default preserves the classic
    /// " MODE | file | l:c [+] " layout.
    statusline_format: String,
}

impl Default for PanelRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl PanelRegistry {
    #[allow(dead_code)]
    pub fn new() -> Self {
        Self {
            panels: HashMap::new(),
            render_claims: HashMap::new(),
            minibuffer: String::new(),
            minibuffer_active: false,
            candidates: Vec::new(),
            candidate_scroll: 0,
            statusline_format: " %m | %f | %l:%c%( ".to_string(),
        }
    }

    /// Set the statusline format template (statusline.format config).
    /// Tokens: %m mode, %f file, %l line, %c col, %( modified marker.
    pub fn set_statusline_format(&mut self, format: String) {
        self.statusline_format = format;
    }

    /// Register an existing panel actor.
    #[allow(dead_code)]
    pub fn register_panel(&mut self, kind: &str, id: ActorId) {
        self.panels.insert(kind.to_string(), id);
    }

    /// Spawn a new panel buffer and register it.
    #[allow(dead_code)]
    pub fn create_panel(&mut self, runtime: &mut Runtime, kind: &str) -> ActorId {
        let actor = BufferActor::new_read_only();
        let id = runtime.spawn(actor).expect("failed to spawn panel buffer");
        self.panels.insert(kind.to_string(), id);
        id
    }

    #[allow(dead_code)]
    pub fn get(&self, kind: &str) -> Option<ActorId> {
        self.panels.get(kind).copied()
    }

    /// Claim rendering of a named panel for an extension. First claim
    /// wins; a second claim on the same panel is an error (one renderer
    /// per panel). The renderer never dispatches on panel names — the
    /// extension volunteers.
    pub fn claim_render(&mut self, panel: &str, ext_name: &str) -> Result<(), String> {
        if let Some(owner) = self.render_claims.get(panel) {
            if owner != ext_name {
                return Err(format!("panel '{panel}' already claimed by '{owner}'"));
            }
            return Ok(());
        }
        self.render_claims
            .insert(panel.to_string(), ext_name.to_string());
        Ok(())
    }

    /// Whether a panel's rendering is claimed by an extension.
    /// (Used by acceptance tests and future claim-aware render paths.)
    #[allow(dead_code)]
    pub fn is_claimed(&self, panel: &str) -> bool {
        self.render_claims.contains_key(panel)
    }

    pub fn send(&self, runtime: &Runtime, kind: &str, msg: BufferMessage) -> Result<(), String> {
        if let Some(id) = self.panels.get(kind) {
            runtime.send(*id, msg).map_err(|e| e.to_string())
        } else {
            Err(format!("Panel not found: {}", kind))
        }
    }

    pub fn get_lines(&self, runtime: &Runtime, kind: &str) -> Vec<String> {
        if let Some(id) = self.panels.get(kind) {
            if let Ok(handle) = runtime.request(*id, BufferMessage::GetContent) {
                if let Ok(reply) = handle.recv_timeout(std::time::Duration::from_millis(100)) {
                    if let Ok(content) = reply.downcast::<String>() {
                        return crate::core::buffer::content_to_lines(&content);
                    }
                }
            }
        }
        Vec::new()
    }

    pub fn echo(&self, runtime: &Runtime, msg: impl Into<String>) {
        let _ = self.send(runtime, "echo", BufferMessage::Echo(msg.into()));
    }

    #[allow(dead_code)]
    pub fn echo_clear(&self, runtime: &Runtime) {
        let _ = self.send(runtime, "echo", BufferMessage::Clear);
    }

    #[allow(dead_code)]
    pub fn update_status(
        &self,
        runtime: &Runtime,
        mode: &str,
        file_name: &str,
        row: usize,
        col: usize,
        modified: bool,
    ) {
        // Expand tokens: %m mode, %f file, %l line, %c col, %( marker.
        let marker = if modified { " [+]" } else { "" };
        let mut status = String::with_capacity(self.statusline_format.len() + 16);
        let mut chars = self.statusline_format.chars().peekable();
        while let Some(ch) = chars.next() {
            if ch == '%' {
                match chars.next() {
                    Some('m') => status.push_str(mode),
                    Some('f') => status.push_str(file_name),
                    Some('l') => status.push_str(&row.to_string()),
                    Some('c') => status.push_str(&col.to_string()),
                    Some('(') => status.push_str(marker),
                    Some('%') => status.push('%'),
                    Some(other) => {
                        status.push('%');
                        status.push(other);
                    }
                    None => status.push('%'),
                }
            } else {
                status.push(ch);
            }
        }
        let _ = self.send(runtime, "statusbar", BufferMessage::Clear);
        let _ = self.send(runtime, "statusbar", BufferMessage::Echo(status));
    }

    pub fn minibuffer_push(&mut self, ch: char) {
        self.minibuffer.push(ch);
    }

    pub fn minibuffer_backspace(&mut self) {
        self.minibuffer.pop();
    }

    pub fn minibuffer_content(&self) -> &str {
        &self.minibuffer
    }

    pub fn minibuffer_clear(&mut self) {
        self.minibuffer.clear();
    }

    pub fn minibuffer_active(&self) -> bool {
        self.minibuffer_active
    }

    pub fn set_minibuffer_active(&mut self, active: bool) {
        self.minibuffer_active = active;
        if !active {
            self.candidates.clear();
            self.candidate_scroll = 0;
        }
    }

    /// Set the current M-x command match candidates (shown in a scrollable
    /// list below the input line).
    pub fn set_candidates(&mut self, candidates: Vec<String>) {
        self.candidates = candidates;
        self.candidate_scroll = 0;
    }

    /// Scroll the candidate list by `delta` lines (keeps it in range).
    pub fn scroll_candidates(&mut self, delta: isize) {
        let max = self.candidates.len().saturating_sub(1);
        let new = self.candidate_scroll as isize + delta;
        self.candidate_scroll = new.clamp(0, max as isize) as usize;
    }

    /// Number of candidate entries currently stored.
    pub fn candidate_count(&self) -> usize {
        self.candidates.len()
    }

    /// Visible slice of candidates starting from the scroll offset.
    pub fn visible_candidates(&self, max_rows: usize) -> &[String] {
        let len = self.candidates.len();
        let end = (self.candidate_scroll + max_rows).min(len);
        let start = self.candidate_scroll.min(end);
        &self.candidates[start..end]
    }
}