ombre: Add readline implementation

e0a580f0d94bbfc8d33bc9c85cb39715d5fa1d84
Alexis Sellier committed ago 1 parent 28f47f40
Cargo.lock +3 -2
81 81
 "wasm-bindgen",
82 82
]
83 83
84 84
[[package]]
85 85
name = "libc"
86 -
version = "0.2.150"
86 +
version = "0.2.169"
87 87
source = "registry+https://github.com/rust-lang/crates.io-index"
88 -
checksum = "89d92a4743f9a61002fae18374ed11e7973f530cb3a3255fb354818118b2203c"
88 +
checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a"
89 89
90 90
[[package]]
91 91
name = "log"
92 92
version = "0.4.20"
93 93
source = "registry+https://github.com/rust-lang/crates.io-index"
125 125
name = "ombre"
126 126
version = "0.6.6"
127 127
dependencies = [
128 128
 "glfw",
129 129
 "glow",
130 +
 "libc",
130 131
 "log",
131 132
 "nonempty",
132 133
 "ombre",
133 134
 "ombre-derive",
134 135
 "termcolor",
ombre/Cargo.toml +8 -1
6 6
keywords = ["graphics", "gamedev", "game"]
7 7
categories = ["graphics", "rendering", "game-development"]
8 8
authors = ["cloudhead <self@cloudhead.io>"]
9 9
10 10
[features]
11 -
default = ["glfw", "color-logging"]
11 +
default = ["readline", "ui", "glfw", "color-logging"]
12 12
color-logging = ["termcolor"]
13 +
readline = ["libc"]
13 14
derive = ["ombre-derive"]
14 15
paint = ["derive"]
15 16
ui = ["paint", "derive"]
16 17
17 18
[dependencies]
18 19
glfw = { version = "0.58.0", optional = true }
19 20
glow = { version = "0.16.0" }
21 +
libc = { version = "0.2.169", optional = true }
20 22
log = { version = "0.4.20", features = ["std"] }
21 23
ombre-derive = { version = "0.1.0", path = "../ombre-derive", optional = true }
22 24
nonempty = { version = "0.10.0" }
23 25
termcolor = { version = "1.4.0", optional = true }
24 26
26 28
workspace = true
27 29
28 30
[dev-dependencies]
29 31
ombre = { version = "0.6.6", features = ["derive", "ui"], path = "." }
30 32
33 +
[[bin]]
34 +
name = "repl"
35 +
path = "src/bin/repl.rs"
36 +
required-features = ["readline"]
37 +
31 38
[[example]]
32 39
name = "paint-basic"
33 40
path = "examples/paint/basic.rs"
34 41
35 42
[[example]]
ombre/src/bin/repl.rs +6 -16
1 -
use std::io::{self, Write};
1 +
use std::io;
2 2
3 3
use ombre::lisp::*;
4 +
use ombre::readline;
4 5
5 6
pub fn run() -> io::Result<()> {
6 7
    let mut env = Env::default();
7 -
    let mut stdout = io::stdout().lock();
8 -
    let stdin = io::stdin();
9 -
    let mut input = String::new();
8 +
    let mut rl = readline::Readline::new()?;
10 9
11 -
    loop {
12 -
        stdout.write_all(b"> ")?;
13 -
        stdout.flush()?;
14 -
        input.clear();
15 -
16 -
        if stdin.read_line(&mut input)? == 0 {
17 -
            // Ctrl-D.
18 -
            eprintln!();
19 -
            break;
20 -
        }
21 -
        match Parser::new(Scanner::new(&input)).next() {
10 +
    while let Some(input) = rl.readline("> ")? {
11 +
        match Parser::new(Scanner::new(input)).next() {
22 12
            Some(Ok(expr)) => {
23 13
                match Evaluator::new([Ok::<_, parser::Error>(expr)].into_iter()).eval(&mut env) {
24 14
                    Ok(result) => println!("{result}"),
25 15
                    Err(e) => eprintln!("Error: {e}"),
26 16
                }
31 21
    }
32 22
    Ok(())
33 23
}
34 24
35 25
fn main() -> io::Result<()> {
36 -
    println!("Ombre REPL (Ctrl-D to exit)");
26 +
    println!("Ombre REPL (Ctrl-C to exit)");
37 27
    run()
38 28
}
ombre/src/lib.rs +2 -0
16 16
pub mod lenses;
17 17
pub mod lisp;
18 18
pub mod logger;
19 19
pub mod math;
20 20
pub mod platform;
21 +
#[cfg(feature = "readline")]
22 +
pub mod readline;
21 23
pub mod rng;
22 24
pub mod runtime;
23 25
pub mod string;
24 26
pub mod text;
25 27
#[cfg(feature = "ui")]
ombre/src/readline.rs added +294 -0
1 +
//! A line editing library for handling user input.
2 +
//!
3 +
//! This module provides a line editor with:
4 +
//! * History navigation (up/down arrows)
5 +
//! * Cursor movement (left/right arrows)
6 +
//! * Basic line editing (backspace, delete)
7 +
//! * Raw mode terminal handling
8 +
//! * ANSI escape sequence support
9 +
#![warn(missing_docs, clippy::unwrap_used)]
10 +
use libc;
11 +
use std::io;
12 +
use std::io::{Read, Stdin, Stdout, Write};
13 +
14 +
mod cursor;
15 +
use cursor::Cursor;
16 +
17 +
// Special characters.
18 +
const CTRL_A: u8 = 1;
19 +
const CTRL_C: u8 = 3;
20 +
const CTRL_D: u8 = 4;
21 +
const CTRL_E: u8 = 5;
22 +
const ENTER: u8 = 13;
23 +
const NEWLINE: u8 = 10;
24 +
const BACKSPACE: u8 = 127;
25 +
const DELETE: u8 = 8;
26 +
const ESC: u8 = 27;
27 +
28 +
// ANSI escape sequences.
29 +
const CLEAR_LINE: &str = "\r\x1b[0K";
30 +
const CLEAR_SCREEN_FROM_CURSOR: &str = "\x1b[J";
31 +
32 +
/// Maintains editing state and terminal configuration.
33 +
pub struct Readline {
34 +
    /// Original terminal settings to restore on drop.
35 +
    previous: libc::termios,
36 +
    /// Saved current line when navigating history.
37 +
    current_line: Option<String>,
38 +
    /// Cached stdout handle.
39 +
    stdout: Stdout,
40 +
    /// Cached stdin handle.
41 +
    stdin: Stdin,
42 +
    /// Current input buffer.
43 +
    buffer: String,
44 +
    /// History of previously entered lines.
45 +
    history: Vec<String>,
46 +
    /// Current position in history when navigating.
47 +
    history_pos: Option<usize>,
48 +
    /// Current cursor position in the buffer.
49 +
    cursor_pos: usize,
50 +
}
51 +
52 +
impl Readline {
53 +
    /// Creates a new [`Readline`] instance.
54 +
    ///
55 +
    /// Initializes terminal settings and internal buffers.
56 +
    /// Returns error if terminal settings cannot be retrieved.
57 +
    pub fn new() -> io::Result<Self> {
58 +
        let mut previous = unsafe { std::mem::zeroed() };
59 +
        if unsafe { libc::tcgetattr(libc::STDIN_FILENO, &mut previous) } != 0 {
60 +
            return Err(io::Error::last_os_error());
61 +
        }
62 +
        // Configure raw mode.
63 +
        let mut raw = previous;
64 +
        raw.c_lflag &= !(libc::ECHO | libc::ICANON | libc::IEXTEN | libc::ISIG);
65 +
        raw.c_iflag &= !(libc::IXON | libc::ICRNL);
66 +
        raw.c_oflag &= !(libc::OPOST);
67 +
        raw.c_cc[libc::VMIN] = 1;
68 +
        raw.c_cc[libc::VTIME] = 0;
69 +
70 +
        // Apply raw mode settings.
71 +
        if unsafe { libc::tcsetattr(libc::STDIN_FILENO, libc::TCSAFLUSH, &raw) } != 0 {
72 +
            return Err(io::Error::last_os_error());
73 +
        }
74 +
75 +
        Ok(Readline {
76 +
            buffer: String::with_capacity(1024),
77 +
            previous,
78 +
            history: Vec::new(),
79 +
            history_pos: None,
80 +
            current_line: None,
81 +
            stdout: io::stdout(),
82 +
            stdin: io::stdin(),
83 +
            cursor_pos: 0,
84 +
        })
85 +
    }
86 +
87 +
    /// Adds a line to the history.
88 +
    ///
89 +
    /// Only non-empty lines are added. Duplicate consecutive entries are ignored.
90 +
    pub fn add_history(&mut self, line: String) {
91 +
        if line.trim().is_empty() {
92 +
            return;
93 +
        }
94 +
        if let Some(last) = self.history.last() {
95 +
            if last == &line {
96 +
                return;
97 +
            }
98 +
        }
99 +
        self.history.push(line);
100 +
    }
101 +
102 +
    /// Reads a line of input from the user.
103 +
    ///
104 +
    /// Displays the given prompt and handles user input until submission.
105 +
    /// Returns None if `Ctrl-C` or `Ctrl-D` is pressed.
106 +
    pub fn readline(&mut self, prompt: &str) -> io::Result<Option<&str>> {
107 +
        // Start at beginning of line and clear.
108 +
        write!(self.stdout, "{}{}", CLEAR_LINE, prompt)?;
109 +
110 +
        self.stdout.flush()?;
111 +
        self.buffer.clear();
112 +
113 +
        let mut buf = [0u8; 4];
114 +
        self.cursor_pos = 0;
115 +
        self.history_pos = None;
116 +
        self.current_line = None;
117 +
118 +
        loop {
119 +
            match self.stdin.read(&mut buf[..1]) {
120 +
                Ok(0) => {
121 +
                    if self.buffer.is_empty() {
122 +
                        return Ok(None);
123 +
                    }
124 +
                    break;
125 +
                }
126 +
                Ok(_) => {}
127 +
                Err(e) => return Err(e),
128 +
            }
129 +
            match self.handle_keypress(&mut buf, prompt)? {
130 +
                KeyAction::Exit => return Ok(None),
131 +
                KeyAction::Submit => break,
132 +
                KeyAction::Continue => continue,
133 +
            }
134 +
        }
135 +
        self.add_history(self.buffer.clone());
136 +
137 +
        Ok(Some(&self.buffer))
138 +
    }
139 +
}
140 +
141 +
#[derive(Debug)]
142 +
enum KeyAction {
143 +
    Exit,
144 +
    Submit,
145 +
    Continue,
146 +
}
147 +
148 +
impl Readline {
149 +
    /// Move to start of line and clear everything after cursor.
150 +
    /// Then, move cursor back to position if needed.
151 +
    fn refresh_line(&mut self, prompt: &str) -> io::Result<()> {
152 +
        write!(self.stdout, "{}{}{}", CLEAR_LINE, prompt, self.buffer)?;
153 +
        if self.cursor_pos < self.buffer.len() {
154 +
            write!(
155 +
                self.stdout,
156 +
                "{}",
157 +
                Cursor::left(self.buffer.len() - self.cursor_pos)
158 +
            )?;
159 +
        }
160 +
        self.stdout.flush()
161 +
    }
162 +
163 +
    fn handle_keypress(&mut self, buf: &mut [u8; 4], prompt: &str) -> io::Result<KeyAction> {
164 +
        match buf[0] {
165 +
            ESC => {
166 +
                // Read the next two bytes of the escape sequence.
167 +
                self.stdin.read_exact(&mut buf[1..3])?;
168 +
                match &buf[..3] {
169 +
                    [ESC, b'[', 51] => {
170 +
                        // Delete key sends `ESC[3~`.
171 +
                        self.stdin.read_exact(&mut buf[3..4])?; // Read the trailing '~'
172 +
                        if self.cursor_pos < self.buffer.len() {
173 +
                            self.buffer.remove(self.cursor_pos);
174 +
                            self.refresh_line(prompt)?;
175 +
                        }
176 +
                    }
177 +
                    [ESC, b'[', 65] => self.handle_up_arrow(prompt)?,
178 +
                    [ESC, b'[', 66] => self.handle_down_arrow(prompt)?,
179 +
                    [ESC, b'[', 67] => self.handle_right_arrow()?,
180 +
                    [ESC, b'[', 68] => self.handle_left_arrow()?,
181 +
                    _ => {}
182 +
                }
183 +
                Ok(KeyAction::Continue)
184 +
            }
185 +
            CTRL_A => {
186 +
                if self.cursor_pos > 0 {
187 +
                    write!(self.stdout, "{}", Cursor::left(self.cursor_pos))?;
188 +
                    self.stdout.flush()?;
189 +
                    self.cursor_pos = 0;
190 +
                }
191 +
                Ok(KeyAction::Continue)
192 +
            }
193 +
            CTRL_E => {
194 +
                let remaining = self.buffer.len() - self.cursor_pos;
195 +
                if remaining > 0 {
196 +
                    write!(self.stdout, "{}", Cursor::right(remaining))?;
197 +
                    self.stdout.flush()?;
198 +
                    self.cursor_pos = self.buffer.len();
199 +
                }
200 +
                Ok(KeyAction::Continue)
201 +
            }
202 +
            CTRL_C | CTRL_D => {
203 +
                write!(
204 +
                    self.stdout,
205 +
                    "{}\r\n{}",
206 +
                    CLEAR_SCREEN_FROM_CURSOR, CLEAR_LINE
207 +
                )?;
208 +
                self.stdout.flush()?;
209 +
                Ok(KeyAction::Exit)
210 +
            }
211 +
            ENTER | NEWLINE => {
212 +
                write!(self.stdout, "\r\n")?; // Just move to next line without clearing
213 +
                self.stdout.flush()?;
214 +
                Ok(KeyAction::Submit)
215 +
            }
216 +
            BACKSPACE | DELETE => {
217 +
                if self.cursor_pos > 0 {
218 +
                    self.buffer.remove(self.cursor_pos - 1);
219 +
                    self.cursor_pos -= 1;
220 +
                    self.refresh_line(prompt)?;
221 +
                }
222 +
                Ok(KeyAction::Continue)
223 +
            }
224 +
            c if c.is_ascii() && !c.is_ascii_control() => {
225 +
                self.buffer.insert(self.cursor_pos, c as char);
226 +
                self.cursor_pos += 1;
227 +
                self.refresh_line(prompt)?;
228 +
                Ok(KeyAction::Continue)
229 +
            }
230 +
            _ => Ok(KeyAction::Continue),
231 +
        }
232 +
    }
233 +
234 +
    fn handle_up_arrow(&mut self, prompt: &str) -> io::Result<()> {
235 +
        if self.history_pos.is_none() {
236 +
            self.current_line = Some(self.buffer.clone());
237 +
        }
238 +
        self.history_pos = match self.history_pos {
239 +
            Some(pos) if pos > 0 => Some(pos - 1),
240 +
            None if !self.history.is_empty() => Some(self.history.len() - 1),
241 +
            other => other,
242 +
        };
243 +
244 +
        if let Some(pos) = self.history_pos {
245 +
            if pos < self.history.len() {
246 +
                self.buffer = self.history[pos].clone();
247 +
                self.cursor_pos = self.buffer.len();
248 +
                self.refresh_line(prompt)?;
249 +
            }
250 +
        }
251 +
        Ok(())
252 +
    }
253 +
254 +
    fn handle_down_arrow(&mut self, prompt: &str) -> io::Result<()> {
255 +
        if let Some(pos) = self.history_pos {
256 +
            if pos + 1 < self.history.len() {
257 +
                self.history_pos = Some(pos + 1);
258 +
                self.buffer = self.history[pos + 1].clone();
259 +
            } else {
260 +
                self.history_pos = None;
261 +
                self.buffer = self.current_line.take().unwrap_or_default();
262 +
            }
263 +
            self.cursor_pos = self.buffer.len();
264 +
            self.refresh_line(prompt)?;
265 +
        }
266 +
        Ok(())
267 +
    }
268 +
269 +
    fn handle_right_arrow(&mut self) -> io::Result<()> {
270 +
        if self.cursor_pos < self.buffer.len() {
271 +
            self.cursor_pos += 1;
272 +
            write!(self.stdout, "{}", Cursor::right(1))?;
273 +
            self.stdout.flush()?;
274 +
        }
275 +
        Ok(())
276 +
    }
277 +
278 +
    fn handle_left_arrow(&mut self) -> io::Result<()> {
279 +
        if self.cursor_pos > 0 {
280 +
            self.cursor_pos -= 1;
281 +
            write!(self.stdout, "{}", Cursor::left(1))?;
282 +
            self.stdout.flush()?;
283 +
        }
284 +
        Ok(())
285 +
    }
286 +
}
287 +
288 +
impl Drop for Readline {
289 +
    fn drop(&mut self) {
290 +
        unsafe {
291 +
            libc::tcsetattr(libc::STDIN_FILENO, libc::TCSAFLUSH, &self.previous);
292 +
        }
293 +
    }
294 +
}
ombre/src/readline/cursor.rs added +24 -0
1 +
//! ANSI escape sequences for cursor movement.
2 +
3 +
/// Utilities for cursor movement in the terminal.
4 +
pub struct Cursor;
5 +
6 +
impl Cursor {
7 +
    /// Generates an ANSI escape sequence to move the cursor `n` positions to the left.
8 +
    /// Returns an empty string if n is 0.
9 +
    pub fn left(n: usize) -> String {
10 +
        if n == 0 {
11 +
            return String::new();
12 +
        }
13 +
        format!("\x1b[{n}D")
14 +
    }
15 +
16 +
    /// Generates an ANSI escape sequence to move the cursor `n` positions to the right.
17 +
    /// Returns an empty string if n is 0.
18 +
    pub fn right(n: usize) -> String {
19 +
        if n == 0 {
20 +
            return String::new();
21 +
        }
22 +
        format!("\x1b[{n}C")
23 +
    }
24 +
}