paperos 0.2.0

A programmable editor built on the Runact actor runtime
Documentation
use crate::core::Extension;
use crate::extensions::keymap::Keymap;
use crate::extensions::keymap_registry::KeymapRegistry;
use crossterm::event::{KeyCode, KeyEvent};
use runact::Runtime;
use std::any::Any;

#[cfg(test)]
use crossterm::event::KeyModifiers;

/// InputExtension: default editor keybindings (basic/text-editor mode).
/// Arrow keys move cursor, typing inserts directly, no mode switching.
/// Alt-x (M-x) opens an Emacs-style command prompt for running commands.
/// Vi-style keybindings are provided by ViInputExtension (see vi_input.rs).
#[allow(dead_code)]
pub struct InputExtension {
    active: bool,
    keymap: Keymap,
}

#[allow(dead_code)]
impl InputExtension {
    pub fn new() -> Self {
        let mut keymap = Keymap::new("basic");
        keymap.load_defaults();
        Self {
            active: true,
            keymap,
        }
    }

    pub fn set_active(&mut self, active: bool) {
        self.active = active;
    }

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

    /// Handle a key event. Returns the command string to run, or None.
    /// In Basic mode, arrow keys and printable chars generate commands.
    /// Note: Alt+x is NOT handled here — it's intercepted by render.rs
    /// before reaching this method, making it mode-independent.
    pub fn handle_key(&mut self, key: &KeyEvent) -> Option<String> {
        if !self.active {
            return None;
        }

        // Check keymap first
        if let Some(cmd) = self.keymap.resolve(key) {
            return Some(cmd.to_string());
        }

        // Printable characters not in keymap → insert
        match key.code {
            KeyCode::Char(ch) if !ch.is_control() => Some(format!("insert {}", ch)),
            _ => None,
        }
    }

    /// Get a reference to the keymap (for testing/inspection).
    pub fn keymap(&self) -> &Keymap {
        &self.keymap
    }

    /// Register this extension's default keybindings as a named layer in the
    /// central KeymapRegistry. The extension owns its mode name — the
    /// registry and main.rs never need to know about "basic" or "vi".
    pub fn register_layers(&self, reg: &mut KeymapRegistry) {
        reg.register(self.keymap.to_layer("basic-defaults", 10, "basic"));
    }
}

impl Extension for InputExtension {
    fn name(&self) -> &str {
        "input"
    }

    fn init(&mut self, _runtime: &mut Runtime) -> Result<(), Box<dyn std::error::Error>> {
        Ok(())
    }

    fn shutdown(&mut self, _runtime: &mut Runtime) -> Result<(), Box<dyn std::error::Error>> {
        Ok(())
    }

    fn on_key(&mut self, _ch: char) -> Result<(), Box<dyn std::error::Error>> {
        Ok(())
    }

    fn on_render(&mut self, _runtime: &Runtime) -> Result<(), Box<dyn std::error::Error>> {
        Ok(())
    }

    /// Global bindings: scroll/navigation keys available in all modes.
    /// These are merged into the global layer by main.rs — no hardcoded
    /// key strings in main.rs beyond M-x.
    fn global_bindings(&self) -> Vec<(&'static str, &'static str)> {
        vec![
            ("C-d", "scroll-down"),
            ("C-u", "scroll-up"),
            ("C-f", "page-down"),
            ("C-b", "page-up"),
            ("C-<Left>", "scroll-left"),
            ("C-<Right>", "scroll-right"),
        ]
    }

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

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

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

#[cfg(test)]
mod tests {
    use super::*;

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    fn alt_x() -> KeyEvent {
        KeyEvent::new(KeyCode::Char('x'), KeyModifiers::ALT)
    }

    #[test]
    fn test_basic_mode_arrow_keys() {
        let mut ext = InputExtension::new();
        assert!(ext.is_active());
        assert_eq!(
            ext.handle_key(&key(KeyCode::Left)),
            Some("left".to_string())
        );
        assert_eq!(
            ext.handle_key(&key(KeyCode::Right)),
            Some("right".to_string())
        );
        assert_eq!(ext.handle_key(&key(KeyCode::Up)), Some("up".to_string()));
        assert_eq!(
            ext.handle_key(&key(KeyCode::Down)),
            Some("down".to_string())
        );
    }

    #[test]
    fn test_basic_mode_typing() {
        let mut ext = InputExtension::new();
        assert_eq!(
            ext.handle_key(&key(KeyCode::Char('a'))),
            Some("insert a".to_string())
        );
        assert_eq!(
            ext.handle_key(&key(KeyCode::Char('Z'))),
            Some("insert Z".to_string())
        );
        assert_eq!(
            ext.handle_key(&key(KeyCode::Tab)),
            Some("insert-tab".to_string())
        );
    }

    #[test]
    fn test_basic_mode_control_chars_ignored() {
        let mut ext = InputExtension::new();
        assert!(ext.handle_key(&key(KeyCode::Char('\x01'))).is_none());
        assert!(ext.handle_key(&key(KeyCode::Char('\x1b'))).is_none());
    }

    #[test]
    fn test_alt_x_not_intercepted_by_input() {
        // Alt+x is intercepted by render.rs before reaching input.
        // InputExtension itself processes it as a normal key ('x').
        let mut ext = InputExtension::new();
        assert_eq!(ext.handle_key(&alt_x()), Some("insert x".to_string()));
    }

    #[test]
    fn test_basic_mode_inactive_returns_none() {
        let mut ext = InputExtension::new();
        ext.set_active(false);
        assert!(!ext.is_active());
        assert!(ext.handle_key(&key(KeyCode::Char('a'))).is_none());
        assert!(ext.handle_key(&key(KeyCode::Left)).is_none());
    }

    #[test]
    fn test_basic_mode_special_keys() {
        let mut ext = InputExtension::new();
        assert_eq!(ext.handle_key(&key(KeyCode::Home)), Some("0".to_string()));
        assert_eq!(ext.handle_key(&key(KeyCode::End)), Some("$".to_string()));
        assert_eq!(
            ext.handle_key(&key(KeyCode::Enter)),
            Some("newline".to_string())
        );
        assert_eq!(
            ext.handle_key(&key(KeyCode::Backspace)),
            Some("delete".to_string())
        );
    }
}