egui_simple_term 0.1.0

A small embeddable terminal widget for egui: a colored prompt, line editing, command history, and a scrollable output backlog.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
use crate::{
    CellGroup, Line, Palette,
    utils::{cell_size, visual_rows},
};
use alloc::{format, rc::Rc, string::String, vec, vec::Vec};
use core::sync::atomic::{AtomicU8, Ordering::SeqCst};
use eframe::egui::{
    Align, Align2, Color32, Context, Event, EventFilter, FontId, Id, Key, Painter, Pos2, Rect,
    ScrollArea, Sense, Ui, Vec2, pos2, vec2,
};

static TERM_ID_CNT: AtomicU8 = AtomicU8::new(0);

/// An interactive terminal widget: a prompt, a text input line, a block cursor,
/// and a scrollable backlog of output.
///
/// Create one with [`Terminal::new`], then call [`show`](Self::show) every frame
/// from inside a panel or container. `show` returns the submitted command as
/// [`Option<String>`] whenever the user presses <kbd>Enter</kbd>; handle it and
/// (optionally) write a response with [`writeln_grid`](Self::writeln_grid).
///
/// Key bindings while the terminal has focus:
///
/// | Keys                                          | Action                          |
/// |-----------------------------------------------|---------------------------------|
/// | printable chars, paste                        | insert text at the cursor       |
/// | <kbd>←</kbd> / <kbd>→</kbd>                   | move the cursor                 |
/// | <kbd>Home</kbd> / <kbd>End</kbd>              | jump to start / end of line     |
/// | <kbd>Backspace</kbd> / <kbd>Delete</kbd>      | delete before / at the cursor   |
/// | <kbd>↑</kbd> / <kbd>↓</kbd>                   | previous / next history entry   |
/// | <kbd>Enter</kbd>                              | submit (returned by [`show`](Self::show)) |
///
/// See the [crate-level example](crate#quick-start) for a full usage pattern.
pub struct Terminal {
    id: Id,

    prompt: Rc<[char]>,
    pub palette: Palette,

    grid: Vec<Line>,

    records: Vec<Vec<char>>,
    record_index: usize,

    cursor: usize,
    font_id: FontId,

    cw: f32,
    ch: f32,

    cell_per_row: usize,
}

impl Terminal {
    /// Create a terminal with the given `prompt` and [`Palette`].
    ///
    /// `prompt` is the fixed text shown before the input, e.g. `"> "` or `"$ "`.
    /// The terminal starts empty (no output, empty history).
    pub fn new(prompt: &str, palette: Palette) -> Self {
        let id = TERM_ID_CNT.fetch_add(1, SeqCst);
        let font_id = FontId::monospace(14.);
        Self {
            id: Id::new(format!("egui-simple-term-{}", id)),

            prompt: prompt.chars().collect(),
            palette,

            grid: Vec::new(),

            records: vec![vec![]],
            record_index: 0,

            cursor: 0,
            font_id,

            cw: 0.,
            ch: 0.,

            cell_per_row: 0,
        }
    }

    /// The color used for the block cursor (see [`Palette::cursor_color`]).
    pub fn cursor_color(&self) -> Color32 {
        self.palette.cursor_color
    }

    /// The color used for the prompt (see [`Palette::prompt_color`]).
    pub fn prompt_color(&self) -> Color32 {
        self.palette.prompt_color
    }

    /// The color used for both typed input and output text (see
    /// [`Palette::record_color`]).
    pub fn record_color(&self) -> Color32 {
        self.palette.record_color
    }

    /// The history entry currently being edited (the "draft").
    fn editing(&self) -> &Vec<char> {
        &self.records[self.record_index]
    }

    /// Mutable access to the entry currently being edited.
    fn editing_mut(&mut self) -> &mut Vec<char> {
        &mut self.records[self.record_index]
    }

    /// Remove the character at `i` from the current draft, returning it if in
    /// range.
    fn remove_editing_ch(&mut self, i: usize) -> Option<char> {
        let record = self.editing_mut();
        if i < record.len() {
            Some(record.remove(i))
        } else {
            None
        }
    }

    /// Insert `s` at `i` in the current draft, dropping control characters, and
    /// return how many characters were actually inserted.
    fn insert_editing_str(&mut self, i: usize, s: &str) -> usize {
        let record = self.editing_mut();
        let old_input_len = record.len();
        if i <= old_input_len {
            record.splice(i..i, s.chars().filter(|c| !c.is_control()));
        }
        record.len() - old_input_len
    }

    /// Clear the scrollback — every line written by [`writeln_grid`](Self::writeln_grid).
    ///
    /// The input line and command history are left untouched.
    pub fn clear_grid(&mut self) {
        self.grid.clear();
    }

    /// Append one line of text to the scrollback, drawn in
    /// [`record_color`](Self::record_color).
    ///
    /// Call this to print output in response to a submitted command. Each call
    /// adds one visual line; a newline in `text` is *not* treated specially.
    /// Styled or multi-color output is not yet exposed — see [`Line`] and
    /// [`CellGroup`], the data model this is built on.
    pub fn writeln_grid(&mut self, text: &str) {
        let chars = text.chars().collect::<Rc<_>>();
        let group = CellGroup::no_bg(chars, self.record_color());
        let line = Line::Full(group);
        self.grid.push(line);
    }

    /// Build the [`Line`] for the current input: a prompt segment followed by the
    /// typed text (a single prompt-only segment when the input is empty).
    fn prompt_input_to_line(&self) -> Line {
        let prompt_seg = CellGroup::no_bg(Rc::clone(&self.prompt), self.prompt_color());
        let record = self.editing();
        if record.is_empty() {
            Line::Full(prompt_seg)
        } else {
            let input_seg = CellGroup::no_bg(record.clone().into(), self.record_color());
            Line::Segs([prompt_seg, input_seg].into())
        }
    }

    /// The total size of the scrollable content: full viewport width, and at
    /// least the viewport height, growing downward to fit every line.
    fn grid_size(&self, viewport: Rect) -> Vec2 {
        let record = self.editing();
        let mut row_count = 0;
        for row in &self.grid {
            row_count += visual_rows(row.len(), self.cell_per_row);
        }
        row_count += visual_rows(self.prompt.len() + record.len(), self.cell_per_row);
        vec2(
            viewport.width(),
            viewport.height().max(row_count as f32 * self.ch),
        )
    }

    /// Draw `line` starting at `min`, wrapping at `cell_per_row`, and return how
    /// many visual rows it consumed. Cells whose color is "additive" (egui's
    /// transparent-glow convention) are skipped, so transparent backgrounds stay
    /// invisible.
    fn paint_line(&self, painter: &Painter, line: &Line, min: Pos2, cell_per_row: usize) -> usize {
        let groups = line.as_slice();
        let mut count = 0;

        for &CellGroup { ref chars, fg, bg } in groups {
            let mut rest_chars = &chars[..];
            let mut consume_len;
            loop {
                let (row, col) = (count / cell_per_row, count % cell_per_row);
                consume_len = rest_chars.len().min(cell_per_row - col);
                if consume_len == 0 {
                    break;
                }
                count += consume_len;
                let consume_chars = &rest_chars[..consume_len];
                rest_chars = &rest_chars[consume_len..];
                let left_top = min + vec2(col as f32 * self.cw, row as f32 * self.ch);
                let rect =
                    Rect::from_min_size(left_top, vec2(consume_len as f32 * self.cw, self.ch));
                if !bg.is_additive() {
                    painter.rect_filled(rect, 0., bg);
                }
                if !fg.is_additive() {
                    painter.text(
                        left_top,
                        Align2::LEFT_TOP,
                        consume_chars.iter().collect::<String>(),
                        self.font_id.clone(),
                        fg,
                    );
                }
            }
        }

        visual_rows(count, cell_per_row)
    }

    /// Draw the whole terminal: the backlog, then the input line, then the
    /// cursor (only when `focused`).
    fn paint(&self, painter: &Painter, rect: Rect, focused: bool) {
        let top_left = rect.min;
        let mut row = 0;

        for line in &self.grid {
            row += self.paint_line(
                painter,
                line,
                top_left + vec2(0., row as f32 * self.ch),
                self.cell_per_row,
            );
        }

        let input_line = self.prompt_input_to_line();
        self.paint_line(
            painter,
            &input_line,
            top_left + vec2(0., row as f32 * self.ch),
            self.cell_per_row,
        );

        if focused {
            let idx = self.prompt.len() + self.cursor;
            let col = idx % self.cell_per_row;
            let r = row + idx / self.cell_per_row;
            let rect = Rect::from_min_size(
                pos2(
                    top_left.x + col as f32 * self.cw,
                    top_left.y + r as f32 * self.ch,
                ),
                vec2(self.cw, self.ch),
            );
            painter.rect_filled(rect, 0.0, self.cursor_color());
        }
    }

    /// Whether the terminal currently has keyboard focus.
    ///
    /// Useful for a "let the terminal own the arrow keys while focused" pattern:
    ///
    /// ```no_run
    /// # use egui_simple_term::Terminal;
    /// # fn guard(term: &Terminal, ui: &mut eframe::egui::Ui) {
    /// if !term.has_focus(ui.ctx()) {
    ///     // ...handle arrow keys for the rest of your UI...
    /// }
    /// # }
    /// ```
    pub fn has_focus(&self, ctx: &Context) -> bool {
        ctx.memory(|mem| mem.has_focus(self.id))
    }

    /// Recompute cell width/height from the current font.
    fn update_cell_size(&mut self, ctx: &Context) {
        [self.cw, self.ch] = cell_size(ctx, &self.font_id);
    }

    /// Recompute how many cells fit per row for the given width (at least one).
    fn update_cell_per_row(&mut self, width: f32) {
        self.cell_per_row = ((width / self.cw).floor() as usize).max(1);
    }

    /// While focused, tell egui which keys the terminal consumes so they don't
    /// leak to the rest of the UI (arrow keys are kept; Tab and Escape are not).
    fn set_focus_lock_filter(&self, ctx: &Context) {
        ctx.memory_mut(|mem| {
            mem.set_focus_lock_filter(
                self.id,
                EventFilter {
                    tab: false,
                    horizontal_arrows: true,
                    vertical_arrows: true,
                    escape: false,
                },
            )
        });
    }

    /// Render the terminal and process input. Call this every frame.
    ///
    /// Returns `Some(command)` when the user presses <kbd>Enter</kbd>, where
    /// `command` is the submitted text **without** the prompt. The submitted line
    /// (prompt + text) is automatically added to the scrollback.
    ///
    /// ```no_run
    /// # use eframe::egui;
    /// # use egui_simple_term::{Palette, Terminal};
    /// # struct App { term: Terminal }
    /// # impl eframe::App for App {
    /// #   fn ui(&mut self, ui: &mut egui::Ui, _f: &mut eframe::Frame) {
    ///         if let Some(command) = self.term.show(ui) {
    ///             self.term.writeln_grid(&format!("you typed: {command}"));
    ///         }
    /// #   }
    /// # }
    /// ```
    pub fn show(&mut self, ui: &mut Ui) -> Option<String> {
        let focused = self.has_focus(ui);
        let mut key_pressed = false;
        let mut command = None;
        if focused {
            (key_pressed, command) = self.handle_input(ui);
            self.set_focus_lock_filter(ui);
        }

        ScrollArea::vertical()
            .animated(false)
            .stick_to_bottom(true)
            .auto_shrink([false; 2])
            .show_viewport(ui, |ui, viewport| {
                self.update_cell_size(ui);
                self.update_cell_per_row(viewport.width());

                let size = self.grid_size(viewport);

                let (rect, _) = ui.allocate_exact_size(size, Sense::hover());
                let resp = ui.interact(rect, self.id, Sense::click());
                if resp.clicked() {
                    resp.request_focus();
                }

                let painter = ui.painter_at(rect);
                self.paint(&painter, rect, focused);

                if key_pressed {
                    ui.scroll_to_cursor(Some(Align::BOTTOM));
                }
            });

        command
    }

    /// Move the draft cursor to the previous history entry (end of its text).
    fn cursor_prev_record(&mut self) {
        self.record_index = self.record_index.saturating_sub(1);
        self.cursor = self.editing().len();
    }

    /// Move the draft cursor to the next history entry.
    fn cursor_next_record(&mut self) {
        self.record_index = (self.record_index + 1).min(self.records.len() - 1);
        self.cursor = self.editing().len();
    }

    /// Move the cursor left one cell.
    fn cursor_shl(&mut self) {
        self.cursor = self.cursor.saturating_sub(1);
    }

    /// Move the cursor right one cell.
    fn cursor_shr(&mut self) {
        self.cursor = (self.cursor + 1).min(self.editing().len());
    }

    /// Move the cursor to the start of the line.
    fn cursor_home(&mut self) {
        self.cursor = 0;
    }

    /// Move the cursor to the end of the line.
    fn cursor_end(&mut self) {
        self.cursor = self.editing().len();
    }

    /// Delete the character before the cursor.
    fn cursor_backspace(&mut self) {
        if self.cursor > 0 {
            self.cursor -= 1;
            self.remove_editing_ch(self.cursor);
        }
    }

    /// Delete the character at the cursor.
    fn cursor_delete(&mut self) {
        self.remove_editing_ch(self.cursor);
    }

    /// Insert a string at the cursor and advance the cursor past it.
    fn cursor_insert_str(&mut self, s: &str) {
        let char_count = self.insert_editing_str(self.cursor, s);
        self.cursor += char_count;
    }

    /// Consume this frame's input events, driving the cursor/text edits. Returns
    /// `(key_pressed, submitted_command)`; `key_pressed` triggers auto-scroll.
    fn handle_input(&mut self, ctx: &Context) -> (bool, Option<String>) {
        ctx.input(|st| {
            let mut key_pressed = false;
            let mut command = None;
            for event in &st.events {
                match event {
                    Event::Text(text) | Event::Paste(text) => self.cursor_insert_str(&text),
                    &Event::Key {
                        key,
                        pressed,
                        modifiers,
                        ..
                    } => {
                        if pressed && modifiers.is_none() {
                            key_pressed = true;
                            match key {
                                Key::ArrowUp => self.cursor_prev_record(),
                                Key::ArrowDown => self.cursor_next_record(),
                                Key::ArrowLeft => self.cursor_shl(),
                                Key::ArrowRight => self.cursor_shr(),
                                Key::Backspace => self.cursor_backspace(),
                                Key::Delete => self.cursor_delete(),
                                Key::End => self.cursor_end(),
                                Key::Enter => command = Some(self.submit()),
                                Key::Home => self.cursor_home(),
                                _ => {}
                            };
                        }
                    }
                    _ => {}
                };
            }

            (key_pressed, command)
        })
    }

    /// Commit the current input: echo the line into the scrollback, record it in
    /// history (skipping a duplicate of the immediately-previous entry), and
    /// reset the cursor for the next command. Returns the submitted text.
    fn submit(&mut self) -> String {
        let line = self.prompt_input_to_line();
        self.grid.push(line);
        let command = self.editing().iter().collect();

        if self.records.last().unwrap() != self.editing() {
            *self.records.last_mut().unwrap() = self.editing().clone();
        }

        let (last_record, records) = self.records.split_last().unwrap();
        if !last_record.is_empty() {
            if let Some(last_history) = records.last()
                && last_record == last_history
            {
                self.records.last_mut().unwrap().clear();
            } else {
                self.records.push(Vec::new());
            }
        }

        self.record_index = self.records.len() - 1;
        self.cursor = 0;

        command
    }
}