beamterm-core 1.0.0

Platform-agnostic OpenGL terminal renderer using glow
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
use std::{collections::HashSet, fmt::Debug};

use compact_str::CompactString;

use crate::Error;

/// Prevents external implementations of the [`Atlas`] trait.
///
/// This module is not part of the public API.
#[doc(hidden)]
pub mod sealed {
    /// Sealed marker trait. Cannot be implemented outside of beamterm crates.
    pub trait Sealed {}
}

pub type SlotId = u16;
/// Bitmask for extracting the base glyph slot from a styled glyph ID.
///
/// Both static and dynamic atlases use 13 bits (0x1FFF) for texture addressing.
/// The emoji flag lives above this mask: bit 12 for static atlas (naturally part
/// of slot address for emoji at slots >= 4096), bit 15 for dynamic atlas.
pub(crate) const GLYPH_SLOT_MASK: u32 = 0x1FFF;

/// Trait defining the interface for font atlases.
///
/// This trait is **sealed** and cannot be implemented outside of beamterm crates.
///
/// Methods that may mutate internal state (glyph resolution, cache updates,
/// texture uploads) take `&mut self`. Read-only accessors take `&self`.
pub trait Atlas: sealed::Sealed {
    /// Returns the glyph identifier for the given key and style bits.
    ///
    /// May mutate internal state (e.g., LRU promotion in dynamic atlases,
    /// recording missing glyphs in static atlases).
    fn get_glyph_id(&mut self, key: &str, style_bits: u16) -> Option<u16>;

    /// Returns the base glyph identifier for the given key.
    ///
    /// May mutate internal state (e.g., LRU promotion, missing glyph tracking).
    fn get_base_glyph_id(&mut self, key: &str) -> Option<u16>;

    /// Returns the height of the atlas in pixels.
    fn cell_size(&self) -> beamterm_data::CellSize;

    /// Binds the font atlas texture to the currently active texture unit.
    fn bind(&self, gl: &glow::Context);

    /// Returns the underline configuration
    fn underline(&self) -> beamterm_data::LineDecoration;

    /// Returns the strikethrough configuration
    fn strikethrough(&self) -> beamterm_data::LineDecoration;

    /// Returns the symbol for the given glyph ID, if it exists
    fn get_symbol(&self, glyph_id: u16) -> Option<CompactString>;

    /// Returns the ASCII character for the given glyph ID, if it represents an ASCII char.
    ///
    /// This is an optimized path for URL detection that avoids string allocation.
    fn get_ascii_char(&self, glyph_id: u16) -> Option<char>;

    /// Returns a reference to the glyph tracker for accessing missing glyphs.
    fn glyph_tracker(&self) -> &GlyphTracker;

    /// Returns the number of glyphs currently in the atlas.
    fn glyph_count(&self) -> u32;

    /// Flushes any pending glyph data to the GPU texture.
    ///
    /// For dynamic atlases, this rasterizes and uploads queued glyphs that were
    /// allocated during [`resolve_glyph_slot`] calls. Must be called after the
    /// atlas texture is bound and before rendering.
    ///
    /// For static atlases, this is a no-op since all glyphs are pre-loaded.
    ///
    /// # Errors
    /// Returns an error if texture upload fails.
    fn flush(&mut self, gl: &glow::Context) -> Result<(), Error>;

    /// Recreates the GPU texture after a context loss.
    ///
    /// This clears the cache - glyphs will be re-rasterized on next access.
    ///
    /// # Errors
    /// Returns an error if GPU texture creation fails.
    fn recreate_texture(&mut self, gl: &glow::Context) -> Result<(), Error>;

    /// Iterates over all glyph ID to symbol mappings.
    ///
    /// Calls the provided closure for each (glyph_id, symbol) pair in the atlas.
    /// This is used for debugging and exposing the atlas contents to JavaScript.
    fn for_each_symbol(&self, f: &mut dyn FnMut(u16, &str));

    /// Resolves a glyph to its texture slot.
    ///
    /// For static atlases, performs a lookup and returns `None` if not found.
    ///
    /// For dynamic atlases, allocates a slot if missing and queues for upload.
    /// The slot is immediately valid, but [`flush`] must be called before
    /// rendering to populate the texture.
    fn resolve_glyph_slot(&mut self, key: &str, style_bits: u16) -> Option<GlyphSlot>;

    /// Returns the bit position used for emoji detection in the fragment shader.
    ///
    /// The glyph ID encodes the base slot index (bits 0-12, masked by `0x1FFF`)
    /// plus effect/flag bits above that. The emoji bit tells the shader to use
    /// texture color (emoji) vs foreground color (regular text).
    ///
    /// - **`StaticFontAtlas`** returns `12`: emoji are at slots >= 4096, so bit 12
    ///   is naturally set in their slot address.
    /// - **`DynamicFontAtlas`** returns `15`: emoji flag is stored in bit 15,
    ///   outside the 13-bit slot mask, leaving bits 13-14 for underline/strikethrough.
    fn emoji_bit(&self) -> u32;

    /// Deletes the GPU texture resources associated with this atlas.
    ///
    /// This method must be called before dropping the atlas to properly clean up
    /// GPU resources. Failing to call this will leak GPU memory.
    fn delete(&self, gl: &glow::Context);

    /// Updates the pixel ratio for HiDPI rendering.
    ///
    /// Returns the effective pixel ratio that should be used for viewport scaling.
    /// Each atlas implementation decides how to handle the ratio:
    ///
    /// - **Static atlas**: Returns exact ratio, no internal work needed
    /// - **Dynamic atlas**: Returns exact ratio, reinitializes with scaled font size
    ///
    /// # Errors
    /// Returns an error if GPU texture recreation fails during reinitialization.
    fn update_pixel_ratio(&mut self, gl: &glow::Context, pixel_ratio: f32) -> Result<f32, Error>;

    /// Returns the cell scale factor for layout calculations at the given DPR.
    ///
    /// This determines how cells from `cell_size()` should be scaled for layout:
    ///
    /// - **Static atlas**: Returns snapped scale values (0.5, 1.0, 2.0, 3.0, etc.)
    ///   to avoid arbitrary fractional scaling of pre-rasterized glyphs.
    ///   DPR <= 0.5 snaps to 0.5, otherwise rounds to nearest integer (minimum 1.0).
    /// - **Dynamic atlas**: Returns `1.0` - glyphs are re-rasterized at the exact DPR,
    ///   so `cell_size()` already returns the correctly-scaled physical size
    ///
    /// # Contract
    ///
    /// - Return value is always >= 0.5
    /// - The effective cell size for layout is `cell_size() * cell_scale_for_dpr(dpr)`
    /// - Static atlases use snapped scaling to preserve glyph sharpness
    /// - Dynamic atlases handle DPR internally via re-rasterization
    fn cell_scale_for_dpr(&self, pixel_ratio: f32) -> f32;

    /// Returns the texture cell size in physical pixels (for fragment shader calculations).
    ///
    /// This is used for computing padding fractions in the shader, which need to be
    /// based on the actual texture dimensions rather than logical layout dimensions.
    ///
    /// - **Static atlas**: Same as `cell_size()` (texture is at fixed resolution)
    /// - **Dynamic atlas**: Physical cell size (before dividing by pixel_ratio)
    fn texture_cell_size(&self) -> beamterm_data::CellSize;
}

/// Type-erased wrapper around any [`Atlas`] implementation.
pub struct FontAtlas {
    inner: Box<dyn Atlas>,
}

impl<A: Atlas + 'static> From<A> for FontAtlas {
    fn from(atlas: A) -> Self {
        FontAtlas::new(atlas)
    }
}

impl Debug for FontAtlas {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FontAtlas")
            .finish_non_exhaustive()
    }
}

impl FontAtlas {
    /// Wraps an atlas implementation in a type-erased container.
    pub fn new(inner: impl Atlas + 'static) -> Self {
        Self { inner: Box::new(inner) }
    }

    /// Returns the styled glyph ID for the given symbol.
    pub fn get_glyph_id(&mut self, key: &str, style_bits: u16) -> Option<u16> {
        self.inner.get_glyph_id(key, style_bits)
    }

    /// Returns the unstyled base glyph ID for the given symbol.
    pub fn get_base_glyph_id(&mut self, key: &str) -> Option<u16> {
        self.inner.get_base_glyph_id(key)
    }

    /// Returns the cell dimensions used for grid layout.
    #[must_use]
    pub fn cell_size(&self) -> beamterm_data::CellSize {
        self.inner.cell_size()
    }

    /// Binds the atlas texture for rendering.
    pub fn bind(&self, gl: &glow::Context) {
        self.inner.bind(gl);
    }

    /// Returns underline position and thickness metadata.
    #[must_use]
    pub fn underline(&self) -> beamterm_data::LineDecoration {
        self.inner.underline()
    }

    /// Returns strikethrough position and thickness metadata.
    #[must_use]
    pub fn strikethrough(&self) -> beamterm_data::LineDecoration {
        self.inner.strikethrough()
    }

    /// Returns the symbol string for the given glyph ID.
    #[must_use]
    pub fn get_symbol(&self, glyph_id: u16) -> Option<CompactString> {
        self.inner.get_symbol(glyph_id)
    }

    /// Returns the ASCII character for the given glyph ID, if applicable.
    #[must_use]
    pub fn get_ascii_char(&self, glyph_id: u16) -> Option<char> {
        self.inner.get_ascii_char(glyph_id)
    }

    /// Returns a reference to the glyph usage tracker.
    #[must_use]
    pub fn glyph_tracker(&self) -> &GlyphTracker {
        self.inner.glyph_tracker()
    }

    /// Returns the total number of allocated glyphs.
    #[must_use]
    pub fn glyph_count(&self) -> u32 {
        self.inner.glyph_count()
    }

    /// Recreates the GPU texture after a context loss.
    ///
    /// # Errors
    /// Returns an error if GPU texture creation fails.
    pub fn recreate_texture(&mut self, gl: &glow::Context) -> Result<(), Error> {
        self.inner.recreate_texture(gl)
    }

    /// Iterates over all glyph ID to symbol mappings.
    pub fn for_each_symbol(&self, f: &mut dyn FnMut(u16, &str)) {
        self.inner.for_each_symbol(f);
    }

    /// Resolves a symbol to its glyph slot classification.
    pub fn resolve_glyph_slot(&mut self, key: &str, style_bits: u16) -> Option<GlyphSlot> {
        self.inner.resolve_glyph_slot(key, style_bits)
    }

    /// Flushes pending glyph data to the GPU texture.
    ///
    /// # Errors
    /// Returns an error if texture upload fails.
    pub fn flush(&mut self, gl: &glow::Context) -> Result<(), Error> {
        self.inner.flush(gl)
    }

    pub(crate) fn emoji_bit(&self) -> u32 {
        self.inner.emoji_bit()
    }

    pub(crate) fn space_glyph_id(&mut self) -> u16 {
        self.get_glyph_id(" ", 0x0)
            .expect("space glyph exists in every font atlas")
    }

    /// Deletes the GPU texture resources associated with this atlas.
    pub fn delete(&self, gl: &glow::Context) {
        self.inner.delete(gl);
    }

    /// Updates the pixel ratio for HiDPI rendering.
    ///
    /// Returns the effective pixel ratio to use for viewport scaling.
    ///
    /// # Errors
    /// Returns an error if GPU texture recreation fails during reinitialization.
    pub fn update_pixel_ratio(
        &mut self,
        gl: &glow::Context,
        pixel_ratio: f32,
    ) -> Result<f32, Error> {
        self.inner.update_pixel_ratio(gl, pixel_ratio)
    }

    /// Returns the cell scale factor for layout calculations.
    #[must_use]
    pub fn cell_scale_for_dpr(&self, pixel_ratio: f32) -> f32 {
        self.inner.cell_scale_for_dpr(pixel_ratio)
    }

    /// Returns the texture cell size in physical pixels.
    #[must_use]
    pub fn texture_cell_size(&self) -> beamterm_data::CellSize {
        self.inner.texture_cell_size()
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
/// Classifies a glyph's texture slot by width category.
pub enum GlyphSlot {
    /// Single-width glyph slot.
    Normal(SlotId),
    /// Double-width glyph slot (CJK characters).
    Wide(SlotId),
    /// Emoji glyph slot (occupies two consecutive texture slots).
    Emoji(SlotId),
}

impl GlyphSlot {
    /// Returns the underlying slot ID.
    #[must_use]
    pub fn slot_id(&self) -> SlotId {
        match *self {
            GlyphSlot::Normal(id) | GlyphSlot::Wide(id) | GlyphSlot::Emoji(id) => id,
        }
    }

    /// Returns a new slot with the given style bits applied.
    #[must_use]
    pub fn with_styling(self, style_bits: u16) -> Self {
        use GlyphSlot::*;
        match self {
            Normal(id) => Normal(id | style_bits),
            Wide(id) => Wide(id | style_bits),
            Emoji(id) => Emoji(id | style_bits),
        }
    }

    /// Returns true if this is a double-width glyph (emoji or wide CJK).
    #[must_use]
    pub fn is_double_width(&self) -> bool {
        matches!(self, GlyphSlot::Wide(_) | GlyphSlot::Emoji(_))
    }
}

/// Tracks glyphs that were requested but not found in the font atlas.
#[derive(Debug, Default)]
pub struct GlyphTracker {
    missing: HashSet<CompactString>,
}

impl GlyphTracker {
    /// Creates a new empty glyph tracker.
    #[must_use]
    pub fn new() -> Self {
        Self { missing: HashSet::new() }
    }

    /// Records a glyph as missing.
    pub fn record_missing(&mut self, glyph: &str) {
        self.missing.insert(glyph.into());
    }

    /// Returns a copy of all missing glyphs.
    #[must_use]
    pub fn missing_glyphs(&self) -> HashSet<CompactString> {
        self.missing.clone()
    }

    /// Clears all tracked missing glyphs.
    pub fn clear(&mut self) {
        self.missing.clear();
    }

    /// Returns the number of unique missing glyphs.
    #[must_use]
    pub fn len(&self) -> usize {
        self.missing.len()
    }

    /// Returns true if no glyphs are missing.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.missing.is_empty()
    }
}

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

    #[test]
    fn test_glyph_tracker() {
        let mut tracker = GlyphTracker::new();

        // Initially empty
        assert!(tracker.is_empty());
        assert_eq!(tracker.len(), 0);

        // Record some missing glyphs
        tracker.record_missing("\u{1F3AE}");
        tracker.record_missing("\u{1F3AF}");
        tracker.record_missing("\u{1F3AE}"); // Duplicate

        assert!(!tracker.is_empty());
        assert_eq!(tracker.len(), 2); // Only unique glyphs

        // Check the missing glyphs
        let missing = tracker.missing_glyphs();
        assert!(missing.contains(&CompactString::new("\u{1F3AE}")));
        assert!(missing.contains(&CompactString::new("\u{1F3AF}")));

        // Clear and verify
        tracker.clear();
        assert!(tracker.is_empty());
        assert_eq!(tracker.len(), 0);
    }
}