beamterm-renderer 0.18.0

High-performance WebGL2 terminal renderer for beamterm, targeting sub-millisecond render times in web browsers
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
use std::{cell::RefCell, rc::Rc};

use beamterm_core::GlslVersion;
use beamterm_data::{DebugSpacePattern, FontAtlasData};
use compact_str::{CompactString, CompactStringExt, ToCompactString, format_compact};
use wasm_bindgen::prelude::*;

use crate::{
    CellData, CursorPosition, Error, FontAtlas, Renderer, SelectionMode, StaticFontAtlas,
    TerminalGrid, UrlMatch,
    gl::{CellQuery, ContextLossHandler, DynamicFontAtlas, dynamic_atlas::CanvasGlyphRasterizer},
    js::device_pixel_ratio,
    mouse::{
        DefaultSelectionHandler, MouseEventCallback, MouseSelectOptions, TerminalMouseEvent,
        TerminalMouseHandler,
    },
};

/// High-performance WebGL2 terminal renderer.
///
/// `Terminal` encapsulates the complete terminal rendering system, providing a
/// simplified API over the underlying [`Renderer`] and [`TerminalGrid`] components.
///
///  ## Selection and Mouse Input
///
/// The renderer supports mouse-driven text selection with automatic clipboard
/// integration:
///
/// ```rust,no_run
/// // Enable default selection handler
/// use beamterm_renderer::{SelectionMode, Terminal};
///
/// let terminal = Terminal::builder("#canvas")
///     .default_mouse_input_handler(SelectionMode::Linear, true)
///     .build().unwrap();
///
/// // Or implement custom mouse handling
/// let terminal = Terminal::builder("#canvas")
///     .mouse_input_handler(|event, grid| {
///         // Custom handler logic
///     })
///     .build().unwrap();
///```
///
/// # Examples
///
/// ```rust,no_run
/// use beamterm_renderer::{CellData, Terminal};
///
/// // Create and render a simple terminal
/// let mut terminal = Terminal::builder("#canvas").build().unwrap();
///
/// // Update cells with content
/// let cells: Vec<CellData> = unimplemented!();
/// terminal.update_cells(cells.into_iter()).unwrap();
///
/// // Render frame
/// terminal.render_frame().unwrap();
///
/// // Handle window resize
/// let (new_width, new_height) = (800, 600);
/// terminal.resize(new_width, new_height).unwrap();
/// ```
#[derive(Debug)]
pub struct Terminal {
    renderer: Renderer,
    grid: Rc<RefCell<TerminalGrid>>,
    mouse_handler: Option<TerminalMouseHandler>,
    context_loss_handler: Option<ContextLossHandler>,
    /// Current device pixel ratio for HiDPI rendering
    current_pixel_ratio: f32,
}

impl Terminal {
    /// Creates a new terminal builder with the specified canvas source.
    ///
    /// # Parameters
    /// * `canvas` - Canvas identifier (CSS selector) or `HtmlCanvasElement`
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// // Using CSS selector
    /// use web_sys::HtmlCanvasElement;
    /// use beamterm_renderer::Terminal;
    ///
    /// let terminal = Terminal::builder("my-terminal").build().unwrap();
    ///
    /// // Using canvas element
    /// let canvas: &HtmlCanvasElement = unimplemented!("document.get_element_by_id(...)");
    /// let terminal = Terminal::builder(canvas).build().unwrap();
    /// ```
    #[allow(private_bounds)]
    pub fn builder(canvas: impl Into<CanvasSource>) -> TerminalBuilder {
        TerminalBuilder::new(canvas.into())
    }

    /// Updates terminal cell content efficiently.
    ///
    /// This method batches all cell updates and uploads them to the GPU in a single
    /// operation. For optimal performance, collect all changes and update in one call
    /// rather than making multiple calls for individual cells.
    ///
    /// Delegates to [`TerminalGrid::update_cells`].
    pub fn update_cells<'a>(
        &mut self,
        cells: impl Iterator<Item = CellData<'a>>,
    ) -> Result<(), Error> {
        Ok(self.grid.borrow_mut().update_cells(cells)?)
    }

    /// Updates terminal cell content efficiently.
    ///
    /// This method batches all cell updates and uploads them to the GPU in a single
    /// operation. For optimal performance, collect all changes and update in one call
    /// rather than making multiple calls for individual cells.
    ///
    /// Delegates to [`TerminalGrid::update_cells_by_position`].
    pub fn update_cells_by_position<'a>(
        &mut self,
        cells: impl Iterator<Item = (u16, u16, CellData<'a>)>,
    ) -> Result<(), Error> {
        Ok(self
            .grid
            .borrow_mut()
            .update_cells_by_position(cells)?)
    }

    pub fn update_cells_by_index<'a>(
        &mut self,
        cells: impl Iterator<Item = (usize, CellData<'a>)>,
    ) -> Result<(), Error> {
        Ok(self
            .grid
            .borrow_mut()
            .update_cells_by_index(cells)?)
    }

    /// Returns the glow rendering context.
    pub fn gl(&self) -> &glow::Context {
        self.renderer.gl()
    }

    /// Resizes the terminal to fit new canvas dimensions.
    ///
    /// This method updates both the renderer viewport and terminal grid to match
    /// the new canvas size. The terminal dimensions (in cells) are automatically
    /// recalculated based on the cell size from the font atlas.
    ///
    /// Combines [`Renderer::resize`] and [`TerminalGrid::resize`] operations.
    pub fn resize(&mut self, width: i32, height: i32) -> Result<(), Error> {
        self.renderer.resize(width, height);
        // Use physical size for grid layout
        let (w, h) = self.renderer.physical_size();
        self.grid
            .borrow_mut()
            .resize(self.renderer.gl(), (w, h), self.current_pixel_ratio)?;

        Ok(())
    }

    /// Returns the terminal dimensions in cells.
    pub fn terminal_size(&self) -> beamterm_data::TerminalSize {
        self.grid.borrow().terminal_size()
    }

    /// Returns the total number of cells in the terminal grid.
    pub fn cell_count(&self) -> usize {
        self.grid.borrow().cell_count()
    }

    /// Returns the size of the canvas in pixels.
    pub fn canvas_size(&self) -> (i32, i32) {
        self.renderer.canvas_size()
    }

    /// Returns the size of each cell in pixels.
    pub fn cell_size(&self) -> beamterm_data::CellSize {
        self.grid.borrow().cell_size()
    }

    /// Returns a reference to the HTML canvas element used for rendering.
    pub fn canvas(&self) -> &web_sys::HtmlCanvasElement {
        self.renderer.canvas()
    }

    /// Returns a reference to the underlying renderer.
    pub fn renderer(&self) -> &Renderer {
        &self.renderer
    }

    /// Returns a reference to the terminal grid.
    pub fn grid(&self) -> Rc<RefCell<TerminalGrid>> {
        self.grid.clone()
    }

    /// Replaces the current font atlas with a new static atlas.
    ///
    /// All existing cell content is preserved and translated to the new atlas.
    /// The grid will be resized if the new atlas has different cell dimensions.
    ///
    /// # Parameters
    /// * `atlas_data` - Binary atlas data loaded from a `.atlas` file
    ///
    /// # Example
    /// ```rust,ignore
    /// use beamterm_renderer::{Terminal, FontAtlasData};
    ///
    /// let mut terminal = Terminal::builder("#canvas").build().unwrap();
    ///
    /// // Load and apply a new static atlas
    /// let atlas_data = FontAtlasData::from_binary(&atlas_bytes).unwrap();
    /// terminal.replace_with_static_atlas(atlas_data).unwrap();
    /// ```
    pub fn replace_with_static_atlas(&mut self, atlas_data: FontAtlasData) -> Result<(), Error> {
        let gl = self.renderer.gl();
        let atlas = StaticFontAtlas::load(gl, atlas_data)?;
        self.grid
            .borrow_mut()
            .replace_atlas(gl, atlas.into());

        Ok(())
    }

    /// Replaces the current font atlas with a new dynamic atlas.
    ///
    /// The dynamic atlas rasterizes glyphs on-demand using the browser's Canvas API,
    /// enabling runtime font selection. All existing cell content is preserved and
    /// translated to the new atlas.
    ///
    /// # Parameters
    /// * `font_family` - Font family names in priority order (e.g., `&["JetBrains Mono", "Hack"]`)
    /// * `font_size` - Font size in pixels
    ///
    /// # Example
    /// ```rust,no_run
    /// use beamterm_renderer::Terminal;
    ///
    /// let mut terminal = Terminal::builder("#canvas").build().unwrap();
    ///
    /// // Switch to a different font at runtime
    /// terminal.replace_with_dynamic_atlas(&["Fira Code", "Hack"], 15.0).unwrap();
    /// ```
    pub fn replace_with_dynamic_atlas(
        &mut self,
        font_family: &[&str],
        font_size: f32,
    ) -> Result<(), Error> {
        let gl = self.renderer.gl();
        let pixel_ratio = device_pixel_ratio();
        let font_family_css = font_family
            .iter()
            .map(|&s| format_compact!("'{s}'"))
            .join_compact(", ");
        let effective_font_size = font_size * pixel_ratio;
        let rasterizer = CanvasGlyphRasterizer::new(&font_family_css, effective_font_size)
            .map_err(|e| Error::Rasterization(e.to_string()))?;
        let atlas = DynamicFontAtlas::new(gl, rasterizer, font_size, pixel_ratio)?;
        self.grid
            .borrow_mut()
            .replace_atlas(gl, atlas.into());

        Ok(())
    }

    /// Returns the textual content of the specified cell selection.
    pub fn get_text(&self, selection: CellQuery) -> CompactString {
        self.grid.borrow().get_text(selection)
    }

    /// Detects an HTTP/HTTPS URL at or around the given cell position.
    ///
    /// Scans left from the cursor to find a URL scheme (`http://` or `https://`),
    /// then scans right to find the URL end. Handles trailing punctuation and
    /// unbalanced parentheses (e.g., Wikipedia URLs).
    ///
    /// Returns `None` if no URL is found at the cursor position.
    ///
    /// **Note:** Only detects URLs within a single row. URLs that wrap across
    /// multiple lines are not supported.
    pub fn find_url_at(&self, cursor: CursorPosition) -> Option<UrlMatch> {
        let grid = self.grid.borrow();
        beamterm_core::find_url_at_cursor(cursor, &grid)
    }

    /// Renders the current terminal state to the canvas.
    ///
    /// This method performs the complete render pipeline: frame setup, grid rendering,
    /// and frame finalization. Call this after updating terminal content to display
    /// the changes.
    ///
    /// If a WebGL context loss occurred and the context has been restored by the browser,
    /// this method will automatically recreate all GPU resources before rendering.
    /// The terminal's cell content is preserved during this process.
    ///
    /// Combines [`Renderer::begin_frame`], [`Renderer::render`], and [`Renderer::end_frame`].
    pub fn render_frame(&mut self) -> Result<(), Error> {
        if self.needs_gl_reinit() {
            self.restore_context()?;
        }

        // skip rendering if context is currently lost (waiting for restoration)
        if self.is_context_lost() {
            return Ok(());
        }

        // Check for device pixel ratio changes (HiDPI display switching)
        let raw_dpr = device_pixel_ratio();
        if (raw_dpr - self.current_pixel_ratio).abs() > f32::EPSILON {
            self.handle_pixel_ratio_change(raw_dpr)?;
        }

        self.grid
            .borrow_mut()
            .flush_cells(self.renderer.gl())?;

        self.renderer.begin_frame();
        self.renderer.render(&*self.grid.borrow())?;
        self.renderer.end_frame();
        Ok(())
    }

    /// Handles a change in device pixel ratio.
    ///
    /// Callers should verify the ratio has changed before calling this method.
    fn handle_pixel_ratio_change(&mut self, raw_pixel_ratio: f32) -> Result<(), Error> {
        self.current_pixel_ratio = raw_pixel_ratio;
        let gl = self.renderer.gl();

        // Update atlas (sets cell_scale for static, re-rasterizes for dynamic)
        self.grid
            .borrow_mut()
            .atlas_mut()
            .update_pixel_ratio(gl, raw_pixel_ratio)?;

        // Always use exact DPR for canvas sizing
        self.renderer.set_pixel_ratio(raw_pixel_ratio);

        // Resize to apply the new pixel ratio
        let (w, h) = self.renderer.logical_size();
        self.resize(w, h)
    }

    /// Returns a sorted list of all glyphs that were requested but not found in the font atlas.
    pub fn missing_glyphs(&self) -> Vec<CompactString> {
        let mut glyphs: Vec<_> = self
            .grid
            .borrow()
            .atlas()
            .glyph_tracker()
            .missing_glyphs()
            .into_iter()
            .collect();
        glyphs.sort();
        glyphs
    }

    /// Checks if the WebGL context has been lost.
    ///
    /// Returns `true` if the context is lost and waiting for restoration.
    fn is_context_lost(&self) -> bool {
        if let Some(handler) = &self.context_loss_handler {
            handler.is_context_lost()
        } else {
            self.renderer.is_context_lost()
        }
    }

    /// Restores all GPU resources after a WebGL context loss.
    ///
    /// # Returns
    /// * `Ok(())` - All resources successfully restored
    /// * `Err(Error)` - Failed to restore context or recreate resources
    fn restore_context(&mut self) -> Result<(), Error> {
        self.renderer.restore_context()?;

        let gl = self.renderer.gl();

        self.grid
            .borrow_mut()
            .recreate_atlas_texture(gl)?;
        self.grid
            .borrow_mut()
            .recreate_resources(gl, &GlslVersion::Es300)?;
        self.grid.borrow_mut().flush_cells(gl)?;

        if let Some(handler) = &self.context_loss_handler {
            handler.clear_context_rebuild_needed();
        }

        // re-apply current pixel ratio after context restoration
        // (display may have changed during context loss)
        let dpr = device_pixel_ratio();
        if (dpr - self.current_pixel_ratio).abs() > f32::EPSILON {
            self.handle_pixel_ratio_change(dpr)?;
        } else {
            // even if DPR unchanged, renderer state was reset - reapply it
            self.renderer.set_pixel_ratio(dpr);
            let (w, h) = self.renderer.logical_size();
            self.renderer.resize(w, h);
        }

        Ok(())
    }

    /// Checks if the terminal needs to restore GPU resources after a context loss.
    fn needs_gl_reinit(&self) -> bool {
        self.context_loss_handler
            .as_ref()
            .map(ContextLossHandler::context_pending_rebuild)
            .unwrap_or(false)
    }

    /// Returns the current device pixel ratio.
    pub fn current_pixel_ratio(&self) -> f32 {
        self.current_pixel_ratio
    }

    /// Enables mouse-based text selection with the given options.
    ///
    /// Replaces any existing mouse handler. Creates a [`DefaultSelectionHandler`]
    /// and a [`TerminalMouseHandler`] attached to this terminal's canvas.
    pub fn enable_mouse_selection(&mut self, options: MouseSelectOptions) -> Result<(), Error> {
        // clean up existing mouse handler if present
        if let Some(old_handler) = self.mouse_handler.take() {
            old_handler.cleanup();
        }

        let selection_tracker = self.grid.borrow().selection_tracker();
        let handler = DefaultSelectionHandler::new(self.grid.clone(), options);

        let mut mouse_handler = TerminalMouseHandler::new(
            self.renderer.canvas(),
            self.grid.clone(),
            handler.create_event_handler(selection_tracker),
        )?;
        mouse_handler.default_input_handler = Some(handler);
        self.mouse_handler = Some(mouse_handler);
        Ok(())
    }

    /// Sets a custom mouse event callback.
    ///
    /// Replaces any existing mouse handler. The callback receives
    /// [`TerminalMouseEvent`] and a reference to the [`TerminalGrid`].
    pub fn set_mouse_callback(
        &mut self,
        callback: impl FnMut(TerminalMouseEvent, &TerminalGrid) + 'static,
    ) -> Result<(), Error> {
        // clean up existing mouse handler if present
        if let Some(old_handler) = self.mouse_handler.take() {
            old_handler.cleanup();
        }

        let mouse_handler =
            TerminalMouseHandler::new(self.renderer.canvas(), self.grid.clone(), callback)?;
        self.mouse_handler = Some(mouse_handler);
        Ok(())
    }

    /// Clears any active text selection.
    pub fn clear_selection(&self) {
        self.grid.borrow().selection_tracker().clear();
    }

    /// Returns whether there is an active text selection.
    pub fn has_selection(&self) -> bool {
        self.grid
            .borrow()
            .selection_tracker()
            .get_query()
            .is_some()
    }

    /// Exposes this terminal instance to the browser console for debugging.
    ///
    /// After calling this method, you can access the terminal from the console:
    /// ```javascript
    /// // In browser console:
    /// window.__beamterm_debug.getMissingGlyphs();
    /// ```
    ///
    /// Note: This creates a live reference that will show current missing glyphs
    /// each time you call it.
    fn expose_to_console(&self) {
        let debug_api = TerminalDebugApi { grid: self.grid.clone() };

        let window = web_sys::window().expect("no window");
        js_sys::Reflect::set(
            &window,
            &"__beamterm_debug".into(),
            &JsValue::from(debug_api),
        )
        .unwrap();

        web_sys::console::log_1(
            &"Terminal debugging API exposed at window.__beamterm_debug".into(),
        );
    }
}

/// Canvas source for terminal initialization.
///
/// Supports both CSS selector strings and direct `HtmlCanvasElement` references
/// for flexible terminal creation.
#[derive(Debug)]
enum CanvasSource {
    /// CSS selector string for canvas lookup (e.g., "#terminal", "canvas").
    Id(CompactString),
    /// Direct reference to an existing canvas element.
    Element(web_sys::HtmlCanvasElement),
}

/// Builder for configuring and creating a [`Terminal`].
///
/// Provides a fluent API for terminal configuration with sensible defaults.
/// The terminal will use the default embedded font atlas unless explicitly configured.
///
/// # Examples
///
/// ```rust,no_run
/// // Simple terminal with default configuration
/// use beamterm_renderer::{FontAtlasData, Terminal};
///
/// let terminal = Terminal::builder("#canvas").build().unwrap();
///
/// // Terminal with custom font atlas
/// let atlas = FontAtlasData::from_binary(unimplemented!(".atlas data")).unwrap();
/// let terminal = Terminal::builder("#canvas")
///     .font_atlas(atlas)
///     .fallback_glyph("X".into())
///     .build().unwrap();
/// ```
pub struct TerminalBuilder {
    canvas: CanvasSource,
    atlas_kind: AtlasKind,
    fallback_glyph: Option<CompactString>,
    input_handler: Option<InputHandler>,
    canvas_padding_color: u32,
    enable_debug_api: bool,
    auto_resize_canvas_css: bool,
}

#[derive(Debug)]
enum AtlasKind {
    Static(Option<FontAtlasData>),
    Dynamic {
        font_size: f32,
        font_family: Vec<CompactString>,
    },
    DebugDynamic {
        font_size: f32,
        font_family: Vec<CompactString>,
        debug_space_pattern: DebugSpacePattern,
    },
}

impl TerminalBuilder {
    /// Creates a new terminal builder with the specified canvas source.
    fn new(canvas: CanvasSource) -> Self {
        TerminalBuilder {
            canvas,
            atlas_kind: AtlasKind::Static(None),
            fallback_glyph: None,
            input_handler: None,
            canvas_padding_color: 0x000000,
            enable_debug_api: false,
            auto_resize_canvas_css: true,
        }
    }

    /// Sets a custom static font atlas for the terminal.
    ///
    /// By default, the terminal uses an embedded font atlas. Use this method
    /// to provide a custom atlas with different fonts, sizes, or character sets.
    ///
    /// Static atlases are pre-generated using the `beamterm-atlas` CLI tool and
    /// loaded from binary `.atlas` files. They provide consistent rendering but
    /// require the character set to be known at build time.
    ///
    /// For dynamic glyph rasterization at runtime, see [`dynamic_font_atlas`](Self::dynamic_font_atlas).
    #[must_use]
    pub fn font_atlas(mut self, atlas: FontAtlasData) -> Self {
        self.atlas_kind = AtlasKind::Static(Some(atlas));
        self
    }

    /// Configures the terminal to use a dynamic font atlas.
    ///
    /// Unlike static atlases, the dynamic atlas rasterizes glyphs on-demand using
    /// the browser's Canvas API. This enables:
    /// - Runtime font selection without pre-generation
    /// - Support for any system font available in the browser
    /// - Automatic handling of unpredictable Unicode content
    ///
    /// # Parameters
    /// * `font_family` - Font family names in priority order (e.g., `&["JetBrains Mono", "Fira Code"]`)
    /// * `font_size` - Font size in pixels
    ///
    /// For pre-generated atlases with fixed character sets, see [`font_atlas`](Self::font_atlas).
    #[must_use]
    pub fn dynamic_font_atlas(mut self, font_family: &[&str], font_size: f32) -> Self {
        self.atlas_kind = AtlasKind::Dynamic {
            font_family: font_family.iter().map(|&s| s.into()).collect(),
            font_size,
        };
        self
    }

    /// Configures the terminal to use a dynamic font atlas with debug space pattern.
    ///
    /// This is the same as [`dynamic_font_atlas`](Self::dynamic_font_atlas), but replaces
    /// the space glyph with a checkered pattern for validating pixel-perfect rendering.
    ///
    /// # Parameters
    /// * `font_family` - Font family names in priority order
    /// * `font_size` - Font size in pixels
    /// * `pattern` - The checkered pattern to use (1px or 2x2 pixels)
    #[must_use]
    pub fn debug_dynamic_font_atlas(
        mut self,
        font_family: &[&str],
        font_size: f32,
        pattern: DebugSpacePattern,
    ) -> Self {
        self.atlas_kind = AtlasKind::DebugDynamic {
            font_family: font_family.iter().map(|&s| s.into()).collect(),
            font_size,
            debug_space_pattern: pattern,
        };
        self
    }

    /// Sets the fallback glyph for missing characters.
    ///
    /// When a character is not found in the font atlas, this glyph will be
    /// displayed instead. Defaults to a space character if not specified.
    #[must_use]
    pub fn fallback_glyph(mut self, glyph: &str) -> Self {
        self.fallback_glyph = Some(glyph.into());
        self
    }

    /// Sets the background color for the canvas area outside the terminal grid.
    ///
    /// When the canvas dimensions don't align perfectly with the terminal cell grid,
    /// there may be unused pixels around the edges. This color fills those padding
    /// areas to maintain a consistent appearance.
    #[must_use]
    pub fn canvas_padding_color(mut self, color: u32) -> Self {
        self.canvas_padding_color = color;
        self
    }

    /// Enables the debug API that will be exposed to the browser console.
    ///
    /// When enabled, a debug API will be available at `window.__beamterm_debug`
    /// with methods like `getMissingGlyphs()` for inspecting the terminal state.
    #[must_use]
    pub fn enable_debug_api(mut self) -> Self {
        self.enable_debug_api = true;
        self
    }

    /// Controls whether the renderer automatically updates the canvas CSS
    /// `width` and `height` style properties on resize.
    ///
    /// Set to `false` when external CSS (flexbox, grid, percentages) controls the
    /// canvas dimensions, such as in responsive layouts.
    ///
    /// When `true` (the default), the renderer sets `style.width` and `style.height`
    /// to match the logical size. When `false`, the canvas CSS size is left unchanged.
    #[must_use]
    pub fn auto_resize_canvas_css(mut self, enabled: bool) -> Self {
        self.auto_resize_canvas_css = enabled;
        self
    }

    /// Sets a callback for handling terminal mouse input events.
    #[must_use]
    pub fn mouse_input_handler<F>(mut self, callback: F) -> Self
    where
        F: FnMut(TerminalMouseEvent, &TerminalGrid) + 'static,
    {
        self.input_handler = Some(InputHandler::Mouse(Box::new(callback)));
        self
    }

    /// Enables mouse-based text selection with automatic clipboard copying.
    ///
    /// When enabled, users can click and drag to select text in the terminal.
    /// Selected text is automatically copied to the clipboard on mouse release.
    ///
    /// # Example
    /// ```rust,no_run
    /// use beamterm_renderer::{Terminal, SelectionMode};
    /// use beamterm_renderer::mouse::{MouseSelectOptions, ModifierKeys};
    ///
    /// let terminal = Terminal::builder("#canvas")
    ///     .mouse_selection_handler(
    ///         MouseSelectOptions::new()
    ///             .selection_mode(SelectionMode::Linear)
    ///             .require_modifier_keys(ModifierKeys::SHIFT)
    ///             .trim_trailing_whitespace(true)
    ///     )
    ///     .build()
    ///     .unwrap();
    /// ```
    #[must_use]
    pub fn mouse_selection_handler(mut self, configuration: MouseSelectOptions) -> Self {
        self.input_handler = Some(InputHandler::CopyOnSelect(configuration));
        self
    }

    /// Sets a default selection handler for mouse input events. Left
    /// button selects text, it copies the selected text to the clipboard
    /// on mouse release.
    #[deprecated(
        since = "0.13.0",
        note = "Use `mouse_selection_handler` with `MouseSelectOptions` instead"
    )]
    pub fn default_mouse_input_handler(
        self,
        selection_mode: SelectionMode,
        trim_trailing_whitespace: bool,
    ) -> Self {
        let options = MouseSelectOptions::new()
            .selection_mode(selection_mode)
            .trim_trailing_whitespace(trim_trailing_whitespace);

        self.mouse_selection_handler(options)
    }

    /// Builds the terminal with the configured options.
    pub fn build(self) -> Result<Terminal, Error> {
        // setup renderer
        let mut renderer = Self::create_renderer(self.canvas, self.auto_resize_canvas_css)?
            .canvas_padding_color(self.canvas_padding_color);

        // Always use exact DPR for canvas sizing (physical pixels)
        // Cell scaling is handled separately by each atlas type
        let raw_pixel_ratio = device_pixel_ratio();
        renderer.set_pixel_ratio(raw_pixel_ratio);
        let (w, h) = renderer.logical_size();
        renderer.resize(w, h);

        // load font atlas
        let gl = renderer.gl();
        let atlas: FontAtlas = match self.atlas_kind {
            AtlasKind::Static(atlas_data) => {
                StaticFontAtlas::load(gl, atlas_data.unwrap_or_default())?.into()
            },
            AtlasKind::Dynamic { font_family, font_size } => {
                let rasterizer =
                    create_canvas_rasterizer(&font_family, font_size, raw_pixel_ratio)?;
                DynamicFontAtlas::new(gl, rasterizer, font_size, raw_pixel_ratio)?.into()
            },
            AtlasKind::DebugDynamic { font_family, font_size, debug_space_pattern } => {
                let rasterizer =
                    create_canvas_rasterizer(&font_family, font_size, raw_pixel_ratio)?;
                DynamicFontAtlas::with_debug_spaces(
                    gl,
                    rasterizer,
                    font_size,
                    raw_pixel_ratio,
                    Some(debug_space_pattern),
                )?
                .into()
            },
        };

        // create terminal grid with physical canvas size
        let canvas_size = renderer.physical_size();
        let mut grid =
            TerminalGrid::new(gl, atlas, canvas_size, raw_pixel_ratio, &GlslVersion::Es300)?;
        if let Some(fallback) = self.fallback_glyph {
            grid.set_fallback_glyph(&fallback)
        };
        let grid = Rc::new(RefCell::new(grid));

        // Set up context loss handler for automatic recovery
        let context_loss_handler = ContextLossHandler::new(renderer.canvas()).ok();

        // initialize mouse handler if needed
        let selection = grid.borrow().selection_tracker();

        match self.input_handler {
            None => Ok(Terminal {
                renderer,
                grid,
                mouse_handler: None,
                context_loss_handler,
                current_pixel_ratio: raw_pixel_ratio,
            }),
            Some(InputHandler::CopyOnSelect(select)) => {
                let handler = DefaultSelectionHandler::new(grid.clone(), select);

                let mut mouse_input = TerminalMouseHandler::new(
                    renderer.canvas(),
                    grid.clone(),
                    handler.create_event_handler(selection),
                )?;
                mouse_input.default_input_handler = Some(handler);

                Ok(Terminal {
                    renderer,
                    grid,
                    mouse_handler: Some(mouse_input),
                    context_loss_handler,
                    current_pixel_ratio: raw_pixel_ratio,
                })
            },
            Some(InputHandler::Mouse(callback)) => {
                let mouse_input =
                    TerminalMouseHandler::new(renderer.canvas(), grid.clone(), callback)?;
                Ok(Terminal {
                    renderer,
                    grid,
                    mouse_handler: Some(mouse_input),
                    context_loss_handler,
                    current_pixel_ratio: raw_pixel_ratio,
                })
            },
        }
        .inspect(|terminal| {
            if self.enable_debug_api {
                terminal.expose_to_console();
            }
        })
    }

    fn create_renderer(canvas: CanvasSource, auto_resize_css: bool) -> Result<Renderer, Error> {
        let renderer = match canvas {
            CanvasSource::Id(id) => Renderer::create(&id, auto_resize_css)?,
            CanvasSource::Element(element) => {
                Renderer::create_with_canvas(element, auto_resize_css)?
            },
        };
        Ok(renderer)
    }
}

enum InputHandler {
    Mouse(MouseEventCallback),
    CopyOnSelect(MouseSelectOptions),
}

/// Debug API exposed to browser console for terminal inspection.
#[wasm_bindgen]
pub struct TerminalDebugApi {
    grid: Rc<RefCell<TerminalGrid>>,
}

#[wasm_bindgen]
impl TerminalDebugApi {
    /// Returns an array of glyphs that were requested but not found in the font atlas.
    #[wasm_bindgen(js_name = "getMissingGlyphs")]
    pub fn get_missing_glyphs(&self) -> js_sys::Array {
        let missing_set = self
            .grid
            .borrow()
            .atlas()
            .glyph_tracker()
            .missing_glyphs();
        let mut missing: Vec<_> = missing_set.into_iter().collect();
        missing.sort();

        let js_array = js_sys::Array::new();
        for glyph in missing {
            js_array.push(&JsValue::from_str(&glyph));
        }
        js_array
    }

    /// Returns the terminal size in cells as an object with `cols` and `rows` fields.
    #[wasm_bindgen(js_name = "getTerminalSize")]
    pub fn get_terminal_size(&self) -> JsValue {
        let ts = self.grid.borrow().terminal_size();
        let obj = js_sys::Object::new();

        js_sys::Reflect::set(&obj, &"cols".into(), &JsValue::from(ts.cols)).unwrap();
        js_sys::Reflect::set(&obj, &"rows".into(), &JsValue::from(ts.rows)).unwrap();

        obj.into()
    }

    /// Returns the canvas size in pixels as an object with `width` and `height` fields.
    #[wasm_bindgen(js_name = "getCanvasSize")]
    pub fn get_canvas_size(&self) -> JsValue {
        let (width, height) = self.grid.borrow().canvas_size();
        let obj = js_sys::Object::new();

        js_sys::Reflect::set(&obj, &"width".into(), &JsValue::from(width)).unwrap();
        js_sys::Reflect::set(&obj, &"height".into(), &JsValue::from(height)).unwrap();

        obj.into()
    }

    /// Returns the number of glyphs available in the font atlas.
    #[wasm_bindgen(js_name = "getGlyphCount")]
    pub fn get_glyph_count(&self) -> u32 {
        self.grid.borrow().atlas().glyph_count()
    }

    /// Returns the base glyph ID for a given symbol, or null if not found.
    #[wasm_bindgen(js_name = "getBaseGlyphId")]
    pub fn get_base_glyph_id(&self, symbol: &str) -> Option<u16> {
        self.grid.borrow_mut().base_glyph_id(symbol)
    }

    /// Returns the symbol for a given glyph ID, or null if not found.
    #[wasm_bindgen(js_name = "getSymbol")]
    pub fn get_symbol(&self, glyph_id: u16) -> Option<String> {
        self.grid
            .borrow()
            .atlas()
            .get_symbol(glyph_id)
            .map(|s| s.to_string())
    }

    /// Returns the cell size in pixels as an object with `width` and `height` fields.
    #[wasm_bindgen(js_name = "getCellSize")]
    pub fn get_cell_size(&self) -> JsValue {
        let cs = self.grid.borrow().atlas().cell_size();
        let obj = js_sys::Object::new();

        js_sys::Reflect::set(&obj, &"width".into(), &JsValue::from(cs.width)).unwrap();
        js_sys::Reflect::set(&obj, &"height".into(), &JsValue::from(cs.height)).unwrap();

        obj.into()
    }

    #[wasm_bindgen(js_name = "getAtlasLookup")]
    pub fn get_symbol_lookup(&self) -> js_sys::Array {
        let grid = self.grid.borrow();
        let atlas = grid.atlas();

        let mut glyphs: Vec<(u16, CompactString)> = Vec::new();
        atlas.for_each_symbol(&mut |glyph_id, symbol| {
            glyphs.push((glyph_id, symbol.to_compact_string()));
        });

        glyphs.sort();

        let js_array = js_sys::Array::new();
        for (glyph_id, symbol) in glyphs.iter() {
            let obj = js_sys::Object::new();
            js_sys::Reflect::set(&obj, &"glyph_id".into(), &JsValue::from(*glyph_id)).unwrap();
            js_sys::Reflect::set(&obj, &"symbol".into(), &JsValue::from(symbol.as_str())).unwrap();

            js_array.push(&obj.into());
        }
        js_array
    }
}

impl<'a> From<&'a str> for CanvasSource {
    fn from(id: &'a str) -> Self {
        CanvasSource::Id(id.into())
    }
}

impl From<web_sys::HtmlCanvasElement> for CanvasSource {
    fn from(element: web_sys::HtmlCanvasElement) -> Self {
        CanvasSource::Element(element)
    }
}

impl<'a> From<&'a web_sys::HtmlCanvasElement> for CanvasSource {
    fn from(value: &'a web_sys::HtmlCanvasElement) -> Self {
        value.clone().into()
    }
}

fn create_canvas_rasterizer(
    font_family: &[CompactString],
    font_size: f32,
    pixel_ratio: f32,
) -> Result<CanvasGlyphRasterizer, Error> {
    let font_family_css = font_family
        .iter()
        .map(|s| format_compact!("'{s}'"))
        .join_compact(", ");
    let effective_font_size = font_size * pixel_ratio;
    CanvasGlyphRasterizer::new(&font_family_css, effective_font_size)
}