bevy_terminal 0.2.0

A terminal scene model and renderer built on Bevy text, UI, and the render world
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
//! Renderer configuration and the pieces shared by the compact renderer.

use bevy::{
    ecs::schedule::SystemSet,
    prelude::*,
    text::{
        ComputedTextBlock, FontCx, FontHinting, FontSource, FontStyle, FontWeight, LayoutCx,
        LetterSpacing, LineHeight, TextPipeline,
    },
};

use crate::{
    TerminalSnapshot,
    color::{TerminalTheme, dim},
    scene::{StyleFlags, TerminalCell},
};

mod batch;

pub use batch::{
    Presentation, Terminal, TerminalNode, TerminalPlugin, TerminalResized, TerminalStats,
    TerminalTexture,
};

/// Visual shape used for the terminal cursor.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum CursorStyle {
    /// A translucent rectangle covering the entire cell.
    #[default]
    Block,
    /// A two-logical-pixel bar at the cell's left edge.
    Bar,
    /// A two-logical-pixel line at the cell's bottom edge.
    Underline,
}

/// Cursor appearance.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CursorConfig {
    /// Cursor shape.
    pub style: CursorStyle,
    /// Cursor overlay color.
    pub color: Color,
    /// Cursor blink frequency; `None` disables blinking.
    pub blink_hz: Option<f32>,
}

impl Default for CursorConfig {
    fn default() -> Self {
        Self {
            style: CursorStyle::Block,
            color: Color::srgba(0.82, 0.88, 1.0, 0.48),
            blink_hz: Some(1.0),
        }
    }
}

/// Text blink frequencies; `None` disables the corresponding attribute.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BlinkConfig {
    /// Frequency of [`StyleFlags::SLOW_BLINK`].
    pub slow_hz: Option<f32>,
    /// Frequency of [`StyleFlags::RAPID_BLINK`].
    pub rapid_hz: Option<f32>,
}

impl Default for BlinkConfig {
    fn default() -> Self {
        Self {
            slow_hz: Some(1.0),
            rapid_hz: Some(3.0),
        }
    }
}

impl BlinkConfig {
    /// Disables text blinking entirely.
    pub const NONE: Self = Self {
        slow_hz: None,
        rapid_hz: None,
    };
}

/// The font faces used for regular, bold, italic and bold-italic text.
///
/// Missing faces fall back in the order bold-italic → bold → italic → regular
/// with the corresponding weight/style requested from the fallback face.
#[derive(Clone, Debug, PartialEq)]
pub struct FontFaces {
    /// Regular text. The generic monospace family enables system fallback.
    pub regular: FontSource,
    /// Optional face for bold text.
    pub bold: Option<FontSource>,
    /// Optional face for italic text.
    pub italic: Option<FontSource>,
    /// Optional face for text that is both bold and italic.
    pub bold_italic: Option<FontSource>,
}

impl FontFaces {
    /// Uses `regular` for every style, relying on the family's own weight and
    /// style axes.
    #[must_use]
    pub fn regular(regular: impl Into<FontSource>) -> Self {
        Self {
            regular: regular.into(),
            bold: None,
            italic: None,
            bold_italic: None,
        }
    }

    /// Returns the face used for the given weight and style.
    #[must_use]
    pub fn select(&self, bold: bool, italic: bool) -> &FontSource {
        match (bold, italic) {
            (true, true) => self
                .bold_italic
                .as_ref()
                .or(self.bold.as_ref())
                .or(self.italic.as_ref()),
            (true, false) => self.bold.as_ref(),
            (false, true) => self.italic.as_ref(),
            (false, false) => None,
        }
        .unwrap_or(&self.regular)
    }
}

impl Default for FontFaces {
    fn default() -> Self {
        Self::regular(FontSource::Monospace)
    }
}

impl<T: Into<FontSource>> From<T> for FontFaces {
    fn from(regular: T) -> Self {
        Self::regular(regular)
    }
}

/// How the rasterized font size is chosen.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum FontSizing {
    /// Measure the regular font's advance width by shaping it and pick the
    /// font size at which one glyph advance equals `cell_size.x`, so
    /// box-drawing and block glyphs designed to fill their advance tile the
    /// grid without seams. Nothing about the font is assumed; the measurement
    /// is repeated whenever fonts or the configuration change. Assumes a
    /// monospaced primary font.
    #[default]
    FitCellWidth,
    /// Use exactly this size in logical pixels.
    Px(f32),
}

/// Number of probe glyphs shaped by [`measure_advance`].
const PROBE_GLYPHS: usize = 100;
/// Font size in logical pixels used to shape the probe run.
const PROBE_FONT_SIZE: f32 = 64.0;
/// Font size used while [`FontSizing::FitCellWidth`] has not been measured yet.
const UNMEASURED_FONT_SIZE: f32 = 16.0;

/// Measures the average advance of the regular font at [`PROBE_FONT_SIZE`] by
/// shaping a run of `0` glyphs; returns `None` until the font can be shaped.
fn measure_advance(
    faces: &FontFaces,
    fonts: &Assets<Font>,
    text_pipeline: &mut TextPipeline,
    font_cx: &mut FontCx,
    layout_cx: &mut LayoutCx,
) -> Option<f32> {
    // A font asset is only usable once Bevy has registered it with the font
    // context (which assigns its alias); measuring before that would shape a
    // fallback font. Report "not yet" so the caller retries next frame.
    if let FontSource::Handle(handle) = &faces.regular
        && fonts
            .get(handle.id())
            .is_none_or(|font| font.alias.is_empty())
    {
        return None;
    }
    let font = TextFont {
        font: faces.regular.clone(),
        font_size: PROBE_FONT_SIZE.into(),
        ..default()
    };
    let probe = "0".repeat(PROBE_GLYPHS);
    let mut computed = ComputedTextBlock::default();
    let measure = text_pipeline
        .create_text_measure(
            Entity::PLACEHOLDER,
            fonts,
            std::iter::once((
                Entity::PLACEHOLDER,
                0,
                probe.as_str(),
                &font,
                Color::WHITE,
                LineHeight::Px(PROBE_FONT_SIZE),
                LetterSpacing::default(),
            )),
            1.0,
            &TextLayout::new(Justify::Left, LineBreak::NoWrap),
            &mut computed,
            font_cx,
            layout_cx,
            Vec2::new(f32::MAX, f32::MAX),
            20.0,
        )
        .ok()?;
    let advance = measure.max.x / PROBE_GLYPHS as f32;
    (advance.is_finite() && advance > 0.0).then_some(advance)
}

/// Returns the logical font size to rasterize with, given a measured advance.
fn effective_font_size(config: &TerminalRenderConfig, measured_advance: Option<f32>) -> f32 {
    match (config.font_size, measured_advance) {
        (FontSizing::Px(size), _) => size.max(1.0),
        (FontSizing::FitCellWidth, Some(advance)) => {
            (config.cell_size.x * PROBE_FONT_SIZE / advance).max(1.0)
        }
        (FontSizing::FitCellWidth, None) => UNMEASURED_FONT_SIZE,
    }
}

/// Selects the physical resolution used by the renderer.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum TerminalRenderScale {
    /// Match the primary window's physical-to-logical scale factor when the
    /// terminal is presented through Bevy UI. Headless rendering uses `1.0`.
    #[default]
    Automatic,
    /// Rasterize at an explicit physical-to-logical scale factor.
    ///
    /// Values that are non-finite or less than or equal to zero fall back to
    /// `1.0`; valid values are clamped to `1.0..=8.0`. A custom UI or camera
    /// should use the same scale factor so the resulting texture maps
    /// one-to-one onto physical display pixels.
    Fixed(f32),
}

/// Configuration for converting terminal cells into rendered geometry and text.
///
/// `cell_size` is intentionally explicit. Bevy can shape several fallback
/// fonts in one run, so there is no single font metric that is guaranteed to
/// describe every Unicode glyph. Text runs are anchored to cell coordinates to
/// prevent this from causing cumulative drift.
#[derive(Clone, Debug, PartialEq)]
pub struct TerminalRenderConfig {
    /// Width and height of one terminal cell in Bevy logical pixels.
    pub cell_size: Vec2,
    /// Font faces for regular, bold, italic and bold-italic text.
    pub font: FontFaces,
    /// How the font size is chosen.
    pub font_size: FontSizing,
    /// Glyph rasterization hinting.
    ///
    /// Defaults to [`FontHinting::Disabled`]: hinted rasterization snaps the
    /// font to whole-pixel sizes, so a font sized to fill the cell width
    /// exactly (see [`FontSizing::FitCellWidth`]) is rendered a fraction too
    /// narrow or wide and adjacent block/box glyphs show seams on displays
    /// whose scale factor makes the physical font size fractional. Unhinted
    /// rasterization keeps the measured metrics exact.
    pub font_hinting: FontHinting,
    /// Physical raster scale.
    pub render_scale: TerminalRenderScale,
    /// Terminal color theme.
    pub theme: TerminalTheme,
    /// Cursor appearance.
    pub cursor: CursorConfig,
    /// Text blink rates.
    pub blink: BlinkConfig,
}

impl Default for TerminalRenderConfig {
    fn default() -> Self {
        Self {
            cell_size: Vec2::new(11.0, 20.0),
            font: FontFaces::default(),
            font_size: FontSizing::FitCellWidth,
            font_hinting: FontHinting::Disabled,
            render_scale: TerminalRenderScale::Automatic,
            theme: TerminalTheme::default(),
            cursor: CursorConfig::default(),
            blink: BlinkConfig::default(),
        }
    }
}

/// Public system set for ordering application systems around terminal syncing.
#[derive(Clone, Debug, Hash, Eq, PartialEq, SystemSet)]
pub enum TerminalSystems {
    /// Initializes newly spawned [`Terminal`] entities and cleans up removed ones.
    Setup,
    /// Copies the latest surface state into the renderer and builds the frame's scene.
    Sync,
}

fn text_font(faces: &FontFaces, font_size: f32, style: &ResolvedStyle) -> TextFont {
    TextFont {
        font: faces.select(style.bold, style.italic).clone(),
        font_size: font_size.into(),
        weight: if style.bold {
            FontWeight::BOLD
        } else {
            FontWeight::NORMAL
        },
        style: if style.italic {
            FontStyle::Italic
        } else {
            FontStyle::Normal
        },
        ..default()
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
struct PixelGeometry {
    x: f32,
    y: f32,
    width: f32,
    height: f32,
}

/// Returns the number of columns rendered for the cell at `column`.
///
/// A wide anchor claims its declared span, clipped to the row and to the run of
/// explicit continuation cells that actually follow it, so a wide glyph can
/// never paint over a neighbor that has since been overwritten.
fn cell_span(cells: &[TerminalCell], column: usize) -> usize {
    let declared = usize::from(cells[column].columns()).min(cells.len() - column);
    let mut span = 1;
    while span < declared && cells[column + span].is_continuation() {
        span += 1;
    }
    span
}

fn cursor_should_be_visible(snapshot: &TerminalSnapshot) -> bool {
    let size = snapshot.size();
    let position = snapshot.cursor_position();
    snapshot.cursor_visible() && position.x < size.width && position.y < size.height
}

fn blink_hidden(elapsed: f32, frequency_hz: Option<f32>) -> bool {
    frequency_hz.is_some_and(|frequency_hz| {
        frequency_hz.is_finite()
            && frequency_hz > 0.0
            && (elapsed * frequency_hz * 2.0).floor() as u64 % 2 == 1
    })
}

#[derive(Clone, Debug, PartialEq)]
struct ResolvedStyle {
    foreground: Color,
    background: Color,
    underline: Color,
    bold: bool,
    italic: bool,
    underlined: bool,
    crossed_out: bool,
    slow_blink: bool,
    rapid_blink: bool,
    hidden: bool,
}

impl ResolvedStyle {
    fn new(cell: &TerminalCell, theme: &TerminalTheme) -> Self {
        let mut foreground = theme.foreground(cell.style.foreground);
        let mut background = theme.background(cell.style.background);
        if cell.style.has(StyleFlags::REVERSED) {
            std::mem::swap(&mut foreground, &mut background);
        }
        let mut underline = theme.resolve(cell.style.underline, foreground);
        if cell.style.has(StyleFlags::DIM) {
            foreground = dim(foreground, background);
            underline = dim(underline, background);
        }
        if cell.style.has(StyleFlags::HIDDEN) {
            foreground = background;
            underline = background;
        }
        Self {
            foreground,
            background,
            underline,
            bold: cell.style.has(StyleFlags::BOLD),
            italic: cell.style.has(StyleFlags::ITALIC),
            underlined: cell.style.has(StyleFlags::UNDERLINED),
            crossed_out: cell.style.has(StyleFlags::CROSSED_OUT),
            slow_blink: cell.style.has(StyleFlags::SLOW_BLINK),
            rapid_blink: cell.style.has(StyleFlags::RAPID_BLINK),
            hidden: cell.style.has(StyleFlags::HIDDEN),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::scene::{TerminalColor, TerminalStyle};

    #[test]
    fn styles_resolve_reverse_hidden_dim_and_decorations() {
        let theme = TerminalTheme::default();
        let mut cell = TerminalCell::new("X").with_style(
            TerminalStyle::new()
                .fg(TerminalColor::RED)
                .bg(TerminalColor::BLUE)
                .with(
                    StyleFlags::REVERSED
                        | StyleFlags::DIM
                        | StyleFlags::UNDERLINED
                        | StyleFlags::CROSSED_OUT
                        | StyleFlags::BOLD
                        | StyleFlags::ITALIC,
                ),
        );
        let style = ResolvedStyle::new(&cell, &theme);
        assert_eq!(style.background, theme.ansi[1]);
        assert_ne!(style.foreground, theme.ansi[4]);
        assert!(style.bold && style.italic && style.underlined && style.crossed_out);

        cell.style.flags.insert(StyleFlags::HIDDEN);
        let hidden = ResolvedStyle::new(&cell, &theme);
        assert_eq!(hidden.foreground, hidden.background);
        assert!(hidden.hidden);

        let reversed = TerminalCell::new("X").with_style(
            TerminalStyle::new()
                .fg(TerminalColor::RED)
                .bg(TerminalColor::BLUE)
                .with(StyleFlags::REVERSED | StyleFlags::UNDERLINED),
        );
        let reversed = ResolvedStyle::new(&reversed, &theme);
        assert_eq!(reversed.foreground, theme.ansi[4]);
        assert_eq!(reversed.underline, reversed.foreground);
    }

    #[test]
    fn font_faces_fall_back_in_order() {
        let regular = FontSource::from("regular");
        let bold = FontSource::from("bold");
        let italic = FontSource::from("italic");
        let bold_italic = FontSource::from("bold italic");

        let only_regular = FontFaces::regular(regular.clone());
        assert_eq!(only_regular.select(true, true), &regular);
        assert_eq!(FontFaces::from(regular.clone()), only_regular);

        let with_bold = FontFaces {
            bold: Some(bold.clone()),
            ..only_regular.clone()
        };
        assert_eq!(with_bold.select(true, false), &bold);
        assert_eq!(with_bold.select(true, true), &bold);
        assert_eq!(with_bold.select(false, true), &regular);

        let with_italic = FontFaces {
            italic: Some(italic.clone()),
            ..only_regular.clone()
        };
        assert_eq!(with_italic.select(true, true), &italic);

        let complete = FontFaces {
            regular: regular.clone(),
            bold: Some(bold.clone()),
            italic: Some(italic.clone()),
            bold_italic: Some(bold_italic.clone()),
        };
        assert_eq!(complete.select(false, false), &regular);
        assert_eq!(complete.select(true, false), &bold);
        assert_eq!(complete.select(false, true), &italic);
        assert_eq!(complete.select(true, true), &bold_italic);

        let theme = TerminalTheme::default();
        let cell = TerminalCell::new("X")
            .with_style(TerminalStyle::new().with(StyleFlags::BOLD | StyleFlags::ITALIC));
        let font = text_font(&complete, 18.0, &ResolvedStyle::new(&cell, &theme));
        assert_eq!(font.font, bold_italic);
        assert_eq!(font.weight, FontWeight::BOLD);
        assert_eq!(font.style, FontStyle::Italic);
    }

    #[test]
    fn font_size_selection_uses_measured_advance_or_explicit_pixels() {
        let config = TerminalRenderConfig {
            cell_size: Vec2::new(11.0, 20.0),
            ..default()
        };
        // A font whose advance is 0.6 em measures 38.4 px at the 64 px probe.
        let fitted = effective_font_size(&config, Some(38.4));
        assert!((fitted - 11.0 / 0.6).abs() < 1e-3);
        assert_eq!(effective_font_size(&config, None), UNMEASURED_FONT_SIZE);
        let explicit = TerminalRenderConfig {
            font_size: FontSizing::Px(18.0),
            ..config
        };
        assert_eq!(effective_font_size(&explicit, Some(38.4)), 18.0);
        assert_eq!(effective_font_size(&explicit, None), 18.0);
    }

    #[test]
    fn wide_cells_span_only_their_continuations() {
        let wide = TerminalCell::wide("", 2);
        let cells = [
            wide.clone(),
            TerminalCell::continuation_of(&wide),
            TerminalCell::new("A"),
        ];
        assert_eq!(cell_span(&cells, 0), 2);
        assert_eq!(cell_span(&cells, 2), 1);
        let overwritten = [wide.clone(), TerminalCell::new("B")];
        assert_eq!(cell_span(&overwritten, 0), 1);
        let clipped = [wide];
        assert_eq!(cell_span(&clipped, 0), 1);
    }

    #[test]
    fn blink_phase_alternates_at_twice_the_frequency() {
        assert!(!blink_hidden(0.1, Some(1.0)));
        assert!(blink_hidden(0.6, Some(1.0)));
        assert!(!blink_hidden(0.6, None));
        assert!(!blink_hidden(0.6, Some(0.0)));
    }
}