Skip to main content

beamterm_renderer/
terminal.rs

1use std::{cell::RefCell, rc::Rc};
2
3use beamterm_core::GlslVersion;
4use beamterm_data::{DebugSpacePattern, FontAtlasData};
5use compact_str::{CompactString, CompactStringExt, ToCompactString, format_compact};
6use wasm_bindgen::prelude::*;
7
8use crate::{
9    CellData, CursorPosition, Error, FontAtlas, Renderer, SelectionMode, StaticFontAtlas,
10    TerminalGrid, UrlMatch,
11    gl::{CellQuery, ContextLossHandler, DynamicFontAtlas, dynamic_atlas::CanvasGlyphRasterizer},
12    js::device_pixel_ratio,
13    mouse::{
14        DefaultSelectionHandler, MouseEventCallback, MouseSelectOptions, TerminalMouseEvent,
15        TerminalMouseHandler,
16    },
17};
18
19/// High-performance WebGL2 terminal renderer.
20///
21/// `Terminal` encapsulates the complete terminal rendering system, providing a
22/// simplified API over the underlying [`Renderer`] and [`TerminalGrid`] components.
23///
24///  ## Selection and Mouse Input
25///
26/// The renderer supports mouse-driven text selection with automatic clipboard
27/// integration:
28///
29/// ```rust,no_run
30/// // Enable default selection handler
31/// use beamterm_renderer::{SelectionMode, Terminal};
32///
33/// let terminal = Terminal::builder("#canvas")
34///     .default_mouse_input_handler(SelectionMode::Linear, true)
35///     .build().unwrap();
36///
37/// // Or implement custom mouse handling
38/// let terminal = Terminal::builder("#canvas")
39///     .mouse_input_handler(|event, grid| {
40///         // Custom handler logic
41///     })
42///     .build().unwrap();
43///```
44///
45/// # Examples
46///
47/// ```rust,no_run
48/// use beamterm_renderer::{CellData, Terminal};
49///
50/// // Create and render a simple terminal
51/// let mut terminal = Terminal::builder("#canvas").build().unwrap();
52///
53/// // Update cells with content
54/// let cells: Vec<CellData> = unimplemented!();
55/// terminal.update_cells(cells.into_iter()).unwrap();
56///
57/// // Render frame
58/// terminal.render_frame().unwrap();
59///
60/// // Handle window resize
61/// let (new_width, new_height) = (800, 600);
62/// terminal.resize(new_width, new_height).unwrap();
63/// ```
64#[derive(Debug)]
65pub struct Terminal {
66    renderer: Renderer,
67    grid: Rc<RefCell<TerminalGrid>>,
68    mouse_handler: Option<TerminalMouseHandler>,
69    context_loss_handler: Option<ContextLossHandler>,
70    /// Current device pixel ratio for HiDPI rendering
71    current_pixel_ratio: f32,
72}
73
74impl Terminal {
75    /// Creates a new terminal builder with the specified canvas source.
76    ///
77    /// # Parameters
78    /// * `canvas` - Canvas identifier (CSS selector) or `HtmlCanvasElement`
79    ///
80    /// # Examples
81    ///
82    /// ```rust,no_run
83    /// // Using CSS selector
84    /// use web_sys::HtmlCanvasElement;
85    /// use beamterm_renderer::Terminal;
86    ///
87    /// let terminal = Terminal::builder("my-terminal").build().unwrap();
88    ///
89    /// // Using canvas element
90    /// let canvas: &HtmlCanvasElement = unimplemented!("document.get_element_by_id(...)");
91    /// let terminal = Terminal::builder(canvas).build().unwrap();
92    /// ```
93    #[allow(private_bounds)]
94    pub fn builder(canvas: impl Into<CanvasSource>) -> TerminalBuilder {
95        TerminalBuilder::new(canvas.into())
96    }
97
98    /// Updates terminal cell content efficiently.
99    ///
100    /// This method batches all cell updates and uploads them to the GPU in a single
101    /// operation. For optimal performance, collect all changes and update in one call
102    /// rather than making multiple calls for individual cells.
103    ///
104    /// Delegates to [`TerminalGrid::update_cells`].
105    pub fn update_cells<'a>(
106        &mut self,
107        cells: impl Iterator<Item = CellData<'a>>,
108    ) -> Result<(), Error> {
109        Ok(self.grid.borrow_mut().update_cells(cells)?)
110    }
111
112    /// Updates terminal cell content efficiently.
113    ///
114    /// This method batches all cell updates and uploads them to the GPU in a single
115    /// operation. For optimal performance, collect all changes and update in one call
116    /// rather than making multiple calls for individual cells.
117    ///
118    /// Delegates to [`TerminalGrid::update_cells_by_position`].
119    pub fn update_cells_by_position<'a>(
120        &mut self,
121        cells: impl Iterator<Item = (u16, u16, CellData<'a>)>,
122    ) -> Result<(), Error> {
123        Ok(self
124            .grid
125            .borrow_mut()
126            .update_cells_by_position(cells)?)
127    }
128
129    pub fn update_cells_by_index<'a>(
130        &mut self,
131        cells: impl Iterator<Item = (usize, CellData<'a>)>,
132    ) -> Result<(), Error> {
133        Ok(self
134            .grid
135            .borrow_mut()
136            .update_cells_by_index(cells)?)
137    }
138
139    /// Returns the glow rendering context.
140    pub fn gl(&self) -> &glow::Context {
141        self.renderer.gl()
142    }
143
144    /// Resizes the terminal to fit new canvas dimensions.
145    ///
146    /// This method updates both the renderer viewport and terminal grid to match
147    /// the new canvas size. The terminal dimensions (in cells) are automatically
148    /// recalculated based on the cell size from the font atlas.
149    ///
150    /// Combines [`Renderer::resize`] and [`TerminalGrid::resize`] operations.
151    pub fn resize(&mut self, width: i32, height: i32) -> Result<(), Error> {
152        self.renderer.resize(width, height);
153        // Use physical size for grid layout
154        let (w, h) = self.renderer.physical_size();
155        self.grid
156            .borrow_mut()
157            .resize(self.renderer.gl(), (w, h), self.current_pixel_ratio)?;
158
159        Ok(())
160    }
161
162    /// Returns the terminal dimensions in cells.
163    pub fn terminal_size(&self) -> beamterm_data::TerminalSize {
164        self.grid.borrow().terminal_size()
165    }
166
167    /// Returns the total number of cells in the terminal grid.
168    pub fn cell_count(&self) -> usize {
169        self.grid.borrow().cell_count()
170    }
171
172    /// Returns the size of the canvas in pixels.
173    pub fn canvas_size(&self) -> (i32, i32) {
174        self.renderer.canvas_size()
175    }
176
177    /// Returns the size of each cell in pixels.
178    pub fn cell_size(&self) -> beamterm_data::CellSize {
179        self.grid.borrow().cell_size()
180    }
181
182    /// Returns a reference to the HTML canvas element used for rendering.
183    pub fn canvas(&self) -> &web_sys::HtmlCanvasElement {
184        self.renderer.canvas()
185    }
186
187    /// Returns a reference to the underlying renderer.
188    pub fn renderer(&self) -> &Renderer {
189        &self.renderer
190    }
191
192    /// Returns a reference to the terminal grid.
193    pub fn grid(&self) -> Rc<RefCell<TerminalGrid>> {
194        self.grid.clone()
195    }
196
197    /// Replaces the current font atlas with a new static atlas.
198    ///
199    /// All existing cell content is preserved and translated to the new atlas.
200    /// The grid will be resized if the new atlas has different cell dimensions.
201    ///
202    /// # Parameters
203    /// * `atlas_data` - Binary atlas data loaded from a `.atlas` file
204    ///
205    /// # Example
206    /// ```rust,ignore
207    /// use beamterm_renderer::{Terminal, FontAtlasData};
208    ///
209    /// let mut terminal = Terminal::builder("#canvas").build().unwrap();
210    ///
211    /// // Load and apply a new static atlas
212    /// let atlas_data = FontAtlasData::from_binary(&atlas_bytes).unwrap();
213    /// terminal.replace_with_static_atlas(atlas_data).unwrap();
214    /// ```
215    pub fn replace_with_static_atlas(&mut self, atlas_data: FontAtlasData) -> Result<(), Error> {
216        let gl = self.renderer.gl();
217        let atlas = StaticFontAtlas::load(gl, atlas_data)?;
218        self.grid
219            .borrow_mut()
220            .replace_atlas(gl, atlas.into());
221
222        Ok(())
223    }
224
225    /// Replaces the current font atlas with a new dynamic atlas.
226    ///
227    /// The dynamic atlas rasterizes glyphs on-demand using the browser's Canvas API,
228    /// enabling runtime font selection. All existing cell content is preserved and
229    /// translated to the new atlas.
230    ///
231    /// # Parameters
232    /// * `font_family` - Font family names in priority order (e.g., `&["JetBrains Mono", "Hack"]`)
233    /// * `font_size` - Font size in pixels
234    ///
235    /// # Example
236    /// ```rust,no_run
237    /// use beamterm_renderer::Terminal;
238    ///
239    /// let mut terminal = Terminal::builder("#canvas").build().unwrap();
240    ///
241    /// // Switch to a different font at runtime
242    /// terminal.replace_with_dynamic_atlas(&["Fira Code", "Hack"], 15.0).unwrap();
243    /// ```
244    pub fn replace_with_dynamic_atlas(
245        &mut self,
246        font_family: &[&str],
247        font_size: f32,
248    ) -> Result<(), Error> {
249        let gl = self.renderer.gl();
250        let pixel_ratio = device_pixel_ratio();
251        let font_family_css = font_family
252            .iter()
253            .map(|&s| format_compact!("'{s}'"))
254            .join_compact(", ");
255        let effective_font_size = font_size * pixel_ratio;
256        let rasterizer = CanvasGlyphRasterizer::new(&font_family_css, effective_font_size)
257            .map_err(|e| Error::Rasterization(e.to_string()))?;
258        let atlas = DynamicFontAtlas::new(gl, rasterizer, font_size, pixel_ratio)?;
259        self.grid
260            .borrow_mut()
261            .replace_atlas(gl, atlas.into());
262
263        Ok(())
264    }
265
266    /// Returns the textual content of the specified cell selection.
267    pub fn get_text(&self, selection: CellQuery) -> CompactString {
268        self.grid.borrow().get_text(selection)
269    }
270
271    /// Detects an HTTP/HTTPS URL at or around the given cell position.
272    ///
273    /// Scans left from the cursor to find a URL scheme (`http://` or `https://`),
274    /// then scans right to find the URL end. Handles trailing punctuation and
275    /// unbalanced parentheses (e.g., Wikipedia URLs).
276    ///
277    /// Returns `None` if no URL is found at the cursor position.
278    ///
279    /// **Note:** Only detects URLs within a single row. URLs that wrap across
280    /// multiple lines are not supported.
281    pub fn find_url_at(&self, cursor: CursorPosition) -> Option<UrlMatch> {
282        let grid = self.grid.borrow();
283        beamterm_core::find_url_at_cursor(cursor, &grid)
284    }
285
286    /// Renders the current terminal state to the canvas.
287    ///
288    /// This method performs the complete render pipeline: frame setup, grid rendering,
289    /// and frame finalization. Call this after updating terminal content to display
290    /// the changes.
291    ///
292    /// If a WebGL context loss occurred and the context has been restored by the browser,
293    /// this method will automatically recreate all GPU resources before rendering.
294    /// The terminal's cell content is preserved during this process.
295    ///
296    /// Combines [`Renderer::begin_frame`], [`Renderer::render`], and [`Renderer::end_frame`].
297    pub fn render_frame(&mut self) -> Result<(), Error> {
298        if self.needs_gl_reinit() {
299            self.restore_context()?;
300        }
301
302        // skip rendering if context is currently lost (waiting for restoration)
303        if self.is_context_lost() {
304            return Ok(());
305        }
306
307        // Check for device pixel ratio changes (HiDPI display switching)
308        let raw_dpr = device_pixel_ratio();
309        if (raw_dpr - self.current_pixel_ratio).abs() > f32::EPSILON {
310            self.handle_pixel_ratio_change(raw_dpr)?;
311        }
312
313        self.grid
314            .borrow_mut()
315            .flush_cells(self.renderer.gl())?;
316
317        self.renderer.begin_frame();
318        self.renderer.render(&*self.grid.borrow())?;
319        self.renderer.end_frame();
320        Ok(())
321    }
322
323    /// Handles a change in device pixel ratio.
324    ///
325    /// Callers should verify the ratio has changed before calling this method.
326    fn handle_pixel_ratio_change(&mut self, raw_pixel_ratio: f32) -> Result<(), Error> {
327        self.current_pixel_ratio = raw_pixel_ratio;
328        let gl = self.renderer.gl();
329
330        // Update atlas (sets cell_scale for static, re-rasterizes for dynamic)
331        self.grid
332            .borrow_mut()
333            .atlas_mut()
334            .update_pixel_ratio(gl, raw_pixel_ratio)?;
335
336        // Always use exact DPR for canvas sizing
337        self.renderer.set_pixel_ratio(raw_pixel_ratio);
338
339        // Resize to apply the new pixel ratio
340        let (w, h) = self.renderer.logical_size();
341        self.resize(w, h)
342    }
343
344    /// Returns a sorted list of all glyphs that were requested but not found in the font atlas.
345    pub fn missing_glyphs(&self) -> Vec<CompactString> {
346        let mut glyphs: Vec<_> = self
347            .grid
348            .borrow()
349            .atlas()
350            .glyph_tracker()
351            .missing_glyphs()
352            .into_iter()
353            .collect();
354        glyphs.sort();
355        glyphs
356    }
357
358    /// Checks if the WebGL context has been lost.
359    ///
360    /// Returns `true` if the context is lost and waiting for restoration.
361    fn is_context_lost(&self) -> bool {
362        if let Some(handler) = &self.context_loss_handler {
363            handler.is_context_lost()
364        } else {
365            self.renderer.is_context_lost()
366        }
367    }
368
369    /// Restores all GPU resources after a WebGL context loss.
370    ///
371    /// # Returns
372    /// * `Ok(())` - All resources successfully restored
373    /// * `Err(Error)` - Failed to restore context or recreate resources
374    fn restore_context(&mut self) -> Result<(), Error> {
375        self.renderer.restore_context()?;
376
377        let gl = self.renderer.gl();
378
379        self.grid
380            .borrow_mut()
381            .recreate_atlas_texture(gl)?;
382        self.grid
383            .borrow_mut()
384            .recreate_resources(gl, &GlslVersion::Es300)?;
385        self.grid.borrow_mut().flush_cells(gl)?;
386
387        if let Some(handler) = &self.context_loss_handler {
388            handler.clear_context_rebuild_needed();
389        }
390
391        // re-apply current pixel ratio after context restoration
392        // (display may have changed during context loss)
393        let dpr = device_pixel_ratio();
394        if (dpr - self.current_pixel_ratio).abs() > f32::EPSILON {
395            self.handle_pixel_ratio_change(dpr)?;
396        } else {
397            // even if DPR unchanged, renderer state was reset - reapply it
398            self.renderer.set_pixel_ratio(dpr);
399            let (w, h) = self.renderer.logical_size();
400            self.renderer.resize(w, h);
401        }
402
403        Ok(())
404    }
405
406    /// Checks if the terminal needs to restore GPU resources after a context loss.
407    fn needs_gl_reinit(&self) -> bool {
408        self.context_loss_handler
409            .as_ref()
410            .map(ContextLossHandler::context_pending_rebuild)
411            .unwrap_or(false)
412    }
413
414    /// Returns the current device pixel ratio.
415    pub fn current_pixel_ratio(&self) -> f32 {
416        self.current_pixel_ratio
417    }
418
419    /// Enables mouse-based text selection with the given options.
420    ///
421    /// Replaces any existing mouse handler. Creates a [`DefaultSelectionHandler`]
422    /// and a [`TerminalMouseHandler`] attached to this terminal's canvas.
423    pub fn enable_mouse_selection(&mut self, options: MouseSelectOptions) -> Result<(), Error> {
424        // clean up existing mouse handler if present
425        if let Some(old_handler) = self.mouse_handler.take() {
426            old_handler.cleanup();
427        }
428
429        let selection_tracker = self.grid.borrow().selection_tracker();
430        let handler = DefaultSelectionHandler::new(self.grid.clone(), options);
431
432        let mut mouse_handler = TerminalMouseHandler::new(
433            self.renderer.canvas(),
434            self.grid.clone(),
435            handler.create_event_handler(selection_tracker),
436        )?;
437        mouse_handler.default_input_handler = Some(handler);
438        self.mouse_handler = Some(mouse_handler);
439        Ok(())
440    }
441
442    /// Sets a custom mouse event callback.
443    ///
444    /// Replaces any existing mouse handler. The callback receives
445    /// [`TerminalMouseEvent`] and a reference to the [`TerminalGrid`].
446    pub fn set_mouse_callback(
447        &mut self,
448        callback: impl FnMut(TerminalMouseEvent, &TerminalGrid) + 'static,
449    ) -> Result<(), Error> {
450        // clean up existing mouse handler if present
451        if let Some(old_handler) = self.mouse_handler.take() {
452            old_handler.cleanup();
453        }
454
455        let mouse_handler =
456            TerminalMouseHandler::new(self.renderer.canvas(), self.grid.clone(), callback)?;
457        self.mouse_handler = Some(mouse_handler);
458        Ok(())
459    }
460
461    /// Clears any active text selection.
462    pub fn clear_selection(&self) {
463        self.grid.borrow().selection_tracker().clear();
464    }
465
466    /// Returns whether there is an active text selection.
467    pub fn has_selection(&self) -> bool {
468        self.grid
469            .borrow()
470            .selection_tracker()
471            .get_query()
472            .is_some()
473    }
474
475    /// Exposes this terminal instance to the browser console for debugging.
476    ///
477    /// After calling this method, you can access the terminal from the console:
478    /// ```javascript
479    /// // In browser console:
480    /// window.__beamterm_debug.getMissingGlyphs();
481    /// ```
482    ///
483    /// Note: This creates a live reference that will show current missing glyphs
484    /// each time you call it.
485    fn expose_to_console(&self) {
486        let debug_api = TerminalDebugApi { grid: self.grid.clone() };
487
488        let window = web_sys::window().expect("no window");
489        js_sys::Reflect::set(
490            &window,
491            &"__beamterm_debug".into(),
492            &JsValue::from(debug_api),
493        )
494        .unwrap();
495
496        web_sys::console::log_1(
497            &"Terminal debugging API exposed at window.__beamterm_debug".into(),
498        );
499    }
500}
501
502/// Canvas source for terminal initialization.
503///
504/// Supports both CSS selector strings and direct `HtmlCanvasElement` references
505/// for flexible terminal creation.
506#[derive(Debug)]
507enum CanvasSource {
508    /// CSS selector string for canvas lookup (e.g., "#terminal", "canvas").
509    Id(CompactString),
510    /// Direct reference to an existing canvas element.
511    Element(web_sys::HtmlCanvasElement),
512}
513
514/// Builder for configuring and creating a [`Terminal`].
515///
516/// Provides a fluent API for terminal configuration with sensible defaults.
517/// The terminal will use the default embedded font atlas unless explicitly configured.
518///
519/// # Examples
520///
521/// ```rust,no_run
522/// // Simple terminal with default configuration
523/// use beamterm_renderer::{FontAtlasData, Terminal};
524///
525/// let terminal = Terminal::builder("#canvas").build().unwrap();
526///
527/// // Terminal with custom font atlas
528/// let atlas = FontAtlasData::from_binary(unimplemented!(".atlas data")).unwrap();
529/// let terminal = Terminal::builder("#canvas")
530///     .font_atlas(atlas)
531///     .fallback_glyph("X".into())
532///     .build().unwrap();
533/// ```
534pub struct TerminalBuilder {
535    canvas: CanvasSource,
536    atlas_kind: AtlasKind,
537    fallback_glyph: Option<CompactString>,
538    input_handler: Option<InputHandler>,
539    canvas_padding_color: u32,
540    enable_debug_api: bool,
541    auto_resize_canvas_css: bool,
542}
543
544#[derive(Debug)]
545enum AtlasKind {
546    Static(Option<FontAtlasData>),
547    Dynamic {
548        font_size: f32,
549        font_family: Vec<CompactString>,
550    },
551    DebugDynamic {
552        font_size: f32,
553        font_family: Vec<CompactString>,
554        debug_space_pattern: DebugSpacePattern,
555    },
556}
557
558impl TerminalBuilder {
559    /// Creates a new terminal builder with the specified canvas source.
560    fn new(canvas: CanvasSource) -> Self {
561        TerminalBuilder {
562            canvas,
563            atlas_kind: AtlasKind::Static(None),
564            fallback_glyph: None,
565            input_handler: None,
566            canvas_padding_color: 0x000000,
567            enable_debug_api: false,
568            auto_resize_canvas_css: true,
569        }
570    }
571
572    /// Sets a custom static font atlas for the terminal.
573    ///
574    /// By default, the terminal uses an embedded font atlas. Use this method
575    /// to provide a custom atlas with different fonts, sizes, or character sets.
576    ///
577    /// Static atlases are pre-generated using the `beamterm-atlas` CLI tool and
578    /// loaded from binary `.atlas` files. They provide consistent rendering but
579    /// require the character set to be known at build time.
580    ///
581    /// For dynamic glyph rasterization at runtime, see [`dynamic_font_atlas`](Self::dynamic_font_atlas).
582    #[must_use]
583    pub fn font_atlas(mut self, atlas: FontAtlasData) -> Self {
584        self.atlas_kind = AtlasKind::Static(Some(atlas));
585        self
586    }
587
588    /// Configures the terminal to use a dynamic font atlas.
589    ///
590    /// Unlike static atlases, the dynamic atlas rasterizes glyphs on-demand using
591    /// the browser's Canvas API. This enables:
592    /// - Runtime font selection without pre-generation
593    /// - Support for any system font available in the browser
594    /// - Automatic handling of unpredictable Unicode content
595    ///
596    /// # Parameters
597    /// * `font_family` - Font family names in priority order (e.g., `&["JetBrains Mono", "Fira Code"]`)
598    /// * `font_size` - Font size in pixels
599    ///
600    /// For pre-generated atlases with fixed character sets, see [`font_atlas`](Self::font_atlas).
601    #[must_use]
602    pub fn dynamic_font_atlas(mut self, font_family: &[&str], font_size: f32) -> Self {
603        self.atlas_kind = AtlasKind::Dynamic {
604            font_family: font_family.iter().map(|&s| s.into()).collect(),
605            font_size,
606        };
607        self
608    }
609
610    /// Configures the terminal to use a dynamic font atlas with debug space pattern.
611    ///
612    /// This is the same as [`dynamic_font_atlas`](Self::dynamic_font_atlas), but replaces
613    /// the space glyph with a checkered pattern for validating pixel-perfect rendering.
614    ///
615    /// # Parameters
616    /// * `font_family` - Font family names in priority order
617    /// * `font_size` - Font size in pixels
618    /// * `pattern` - The checkered pattern to use (1px or 2x2 pixels)
619    #[must_use]
620    pub fn debug_dynamic_font_atlas(
621        mut self,
622        font_family: &[&str],
623        font_size: f32,
624        pattern: DebugSpacePattern,
625    ) -> Self {
626        self.atlas_kind = AtlasKind::DebugDynamic {
627            font_family: font_family.iter().map(|&s| s.into()).collect(),
628            font_size,
629            debug_space_pattern: pattern,
630        };
631        self
632    }
633
634    /// Sets the fallback glyph for missing characters.
635    ///
636    /// When a character is not found in the font atlas, this glyph will be
637    /// displayed instead. Defaults to a space character if not specified.
638    #[must_use]
639    pub fn fallback_glyph(mut self, glyph: &str) -> Self {
640        self.fallback_glyph = Some(glyph.into());
641        self
642    }
643
644    /// Sets the background color for the canvas area outside the terminal grid.
645    ///
646    /// When the canvas dimensions don't align perfectly with the terminal cell grid,
647    /// there may be unused pixels around the edges. This color fills those padding
648    /// areas to maintain a consistent appearance.
649    #[must_use]
650    pub fn canvas_padding_color(mut self, color: u32) -> Self {
651        self.canvas_padding_color = color;
652        self
653    }
654
655    /// Enables the debug API that will be exposed to the browser console.
656    ///
657    /// When enabled, a debug API will be available at `window.__beamterm_debug`
658    /// with methods like `getMissingGlyphs()` for inspecting the terminal state.
659    #[must_use]
660    pub fn enable_debug_api(mut self) -> Self {
661        self.enable_debug_api = true;
662        self
663    }
664
665    /// Controls whether the renderer automatically updates the canvas CSS
666    /// `width` and `height` style properties on resize.
667    ///
668    /// Set to `false` when external CSS (flexbox, grid, percentages) controls the
669    /// canvas dimensions, such as in responsive layouts.
670    ///
671    /// When `true` (the default), the renderer sets `style.width` and `style.height`
672    /// to match the logical size. When `false`, the canvas CSS size is left unchanged.
673    #[must_use]
674    pub fn auto_resize_canvas_css(mut self, enabled: bool) -> Self {
675        self.auto_resize_canvas_css = enabled;
676        self
677    }
678
679    /// Sets a callback for handling terminal mouse input events.
680    #[must_use]
681    pub fn mouse_input_handler<F>(mut self, callback: F) -> Self
682    where
683        F: FnMut(TerminalMouseEvent, &TerminalGrid) + 'static,
684    {
685        self.input_handler = Some(InputHandler::Mouse(Box::new(callback)));
686        self
687    }
688
689    /// Enables mouse-based text selection with automatic clipboard copying.
690    ///
691    /// When enabled, users can click and drag to select text in the terminal.
692    /// Selected text is automatically copied to the clipboard on mouse release.
693    ///
694    /// # Example
695    /// ```rust,no_run
696    /// use beamterm_renderer::{Terminal, SelectionMode};
697    /// use beamterm_renderer::mouse::{MouseSelectOptions, ModifierKeys};
698    ///
699    /// let terminal = Terminal::builder("#canvas")
700    ///     .mouse_selection_handler(
701    ///         MouseSelectOptions::new()
702    ///             .selection_mode(SelectionMode::Linear)
703    ///             .require_modifier_keys(ModifierKeys::SHIFT)
704    ///             .trim_trailing_whitespace(true)
705    ///     )
706    ///     .build()
707    ///     .unwrap();
708    /// ```
709    #[must_use]
710    pub fn mouse_selection_handler(mut self, configuration: MouseSelectOptions) -> Self {
711        self.input_handler = Some(InputHandler::CopyOnSelect(configuration));
712        self
713    }
714
715    /// Sets a default selection handler for mouse input events. Left
716    /// button selects text, it copies the selected text to the clipboard
717    /// on mouse release.
718    #[deprecated(
719        since = "0.13.0",
720        note = "Use `mouse_selection_handler` with `MouseSelectOptions` instead"
721    )]
722    pub fn default_mouse_input_handler(
723        self,
724        selection_mode: SelectionMode,
725        trim_trailing_whitespace: bool,
726    ) -> Self {
727        let options = MouseSelectOptions::new()
728            .selection_mode(selection_mode)
729            .trim_trailing_whitespace(trim_trailing_whitespace);
730
731        self.mouse_selection_handler(options)
732    }
733
734    /// Builds the terminal with the configured options.
735    pub fn build(self) -> Result<Terminal, Error> {
736        // setup renderer
737        let mut renderer = Self::create_renderer(self.canvas, self.auto_resize_canvas_css)?
738            .canvas_padding_color(self.canvas_padding_color);
739
740        // Always use exact DPR for canvas sizing (physical pixels)
741        // Cell scaling is handled separately by each atlas type
742        let raw_pixel_ratio = device_pixel_ratio();
743        renderer.set_pixel_ratio(raw_pixel_ratio);
744        let (w, h) = renderer.logical_size();
745        renderer.resize(w, h);
746
747        // load font atlas
748        let gl = renderer.gl();
749        let atlas: FontAtlas = match self.atlas_kind {
750            AtlasKind::Static(atlas_data) => {
751                StaticFontAtlas::load(gl, atlas_data.unwrap_or_default())?.into()
752            },
753            AtlasKind::Dynamic { font_family, font_size } => {
754                let rasterizer =
755                    create_canvas_rasterizer(&font_family, font_size, raw_pixel_ratio)?;
756                DynamicFontAtlas::new(gl, rasterizer, font_size, raw_pixel_ratio)?.into()
757            },
758            AtlasKind::DebugDynamic { font_family, font_size, debug_space_pattern } => {
759                let rasterizer =
760                    create_canvas_rasterizer(&font_family, font_size, raw_pixel_ratio)?;
761                DynamicFontAtlas::with_debug_spaces(
762                    gl,
763                    rasterizer,
764                    font_size,
765                    raw_pixel_ratio,
766                    Some(debug_space_pattern),
767                )?
768                .into()
769            },
770        };
771
772        // create terminal grid with physical canvas size
773        let canvas_size = renderer.physical_size();
774        let mut grid =
775            TerminalGrid::new(gl, atlas, canvas_size, raw_pixel_ratio, &GlslVersion::Es300)?;
776        if let Some(fallback) = self.fallback_glyph {
777            grid.set_fallback_glyph(&fallback)
778        };
779        let grid = Rc::new(RefCell::new(grid));
780
781        // Set up context loss handler for automatic recovery
782        let context_loss_handler = ContextLossHandler::new(renderer.canvas()).ok();
783
784        // initialize mouse handler if needed
785        let selection = grid.borrow().selection_tracker();
786
787        match self.input_handler {
788            None => Ok(Terminal {
789                renderer,
790                grid,
791                mouse_handler: None,
792                context_loss_handler,
793                current_pixel_ratio: raw_pixel_ratio,
794            }),
795            Some(InputHandler::CopyOnSelect(select)) => {
796                let handler = DefaultSelectionHandler::new(grid.clone(), select);
797
798                let mut mouse_input = TerminalMouseHandler::new(
799                    renderer.canvas(),
800                    grid.clone(),
801                    handler.create_event_handler(selection),
802                )?;
803                mouse_input.default_input_handler = Some(handler);
804
805                Ok(Terminal {
806                    renderer,
807                    grid,
808                    mouse_handler: Some(mouse_input),
809                    context_loss_handler,
810                    current_pixel_ratio: raw_pixel_ratio,
811                })
812            },
813            Some(InputHandler::Mouse(callback)) => {
814                let mouse_input =
815                    TerminalMouseHandler::new(renderer.canvas(), grid.clone(), callback)?;
816                Ok(Terminal {
817                    renderer,
818                    grid,
819                    mouse_handler: Some(mouse_input),
820                    context_loss_handler,
821                    current_pixel_ratio: raw_pixel_ratio,
822                })
823            },
824        }
825        .inspect(|terminal| {
826            if self.enable_debug_api {
827                terminal.expose_to_console();
828            }
829        })
830    }
831
832    fn create_renderer(canvas: CanvasSource, auto_resize_css: bool) -> Result<Renderer, Error> {
833        let renderer = match canvas {
834            CanvasSource::Id(id) => Renderer::create(&id, auto_resize_css)?,
835            CanvasSource::Element(element) => {
836                Renderer::create_with_canvas(element, auto_resize_css)?
837            },
838        };
839        Ok(renderer)
840    }
841}
842
843enum InputHandler {
844    Mouse(MouseEventCallback),
845    CopyOnSelect(MouseSelectOptions),
846}
847
848/// Debug API exposed to browser console for terminal inspection.
849#[wasm_bindgen]
850pub struct TerminalDebugApi {
851    grid: Rc<RefCell<TerminalGrid>>,
852}
853
854#[wasm_bindgen]
855impl TerminalDebugApi {
856    /// Returns an array of glyphs that were requested but not found in the font atlas.
857    #[wasm_bindgen(js_name = "getMissingGlyphs")]
858    pub fn get_missing_glyphs(&self) -> js_sys::Array {
859        let missing_set = self
860            .grid
861            .borrow()
862            .atlas()
863            .glyph_tracker()
864            .missing_glyphs();
865        let mut missing: Vec<_> = missing_set.into_iter().collect();
866        missing.sort();
867
868        let js_array = js_sys::Array::new();
869        for glyph in missing {
870            js_array.push(&JsValue::from_str(&glyph));
871        }
872        js_array
873    }
874
875    /// Returns the terminal size in cells as an object with `cols` and `rows` fields.
876    #[wasm_bindgen(js_name = "getTerminalSize")]
877    pub fn get_terminal_size(&self) -> JsValue {
878        let ts = self.grid.borrow().terminal_size();
879        let obj = js_sys::Object::new();
880
881        js_sys::Reflect::set(&obj, &"cols".into(), &JsValue::from(ts.cols)).unwrap();
882        js_sys::Reflect::set(&obj, &"rows".into(), &JsValue::from(ts.rows)).unwrap();
883
884        obj.into()
885    }
886
887    /// Returns the canvas size in pixels as an object with `width` and `height` fields.
888    #[wasm_bindgen(js_name = "getCanvasSize")]
889    pub fn get_canvas_size(&self) -> JsValue {
890        let (width, height) = self.grid.borrow().canvas_size();
891        let obj = js_sys::Object::new();
892
893        js_sys::Reflect::set(&obj, &"width".into(), &JsValue::from(width)).unwrap();
894        js_sys::Reflect::set(&obj, &"height".into(), &JsValue::from(height)).unwrap();
895
896        obj.into()
897    }
898
899    /// Returns the number of glyphs available in the font atlas.
900    #[wasm_bindgen(js_name = "getGlyphCount")]
901    pub fn get_glyph_count(&self) -> u32 {
902        self.grid.borrow().atlas().glyph_count()
903    }
904
905    /// Returns the base glyph ID for a given symbol, or null if not found.
906    #[wasm_bindgen(js_name = "getBaseGlyphId")]
907    pub fn get_base_glyph_id(&self, symbol: &str) -> Option<u16> {
908        self.grid.borrow_mut().base_glyph_id(symbol)
909    }
910
911    /// Returns the symbol for a given glyph ID, or null if not found.
912    #[wasm_bindgen(js_name = "getSymbol")]
913    pub fn get_symbol(&self, glyph_id: u16) -> Option<String> {
914        self.grid
915            .borrow()
916            .atlas()
917            .get_symbol(glyph_id)
918            .map(|s| s.to_string())
919    }
920
921    /// Returns the cell size in pixels as an object with `width` and `height` fields.
922    #[wasm_bindgen(js_name = "getCellSize")]
923    pub fn get_cell_size(&self) -> JsValue {
924        let cs = self.grid.borrow().atlas().cell_size();
925        let obj = js_sys::Object::new();
926
927        js_sys::Reflect::set(&obj, &"width".into(), &JsValue::from(cs.width)).unwrap();
928        js_sys::Reflect::set(&obj, &"height".into(), &JsValue::from(cs.height)).unwrap();
929
930        obj.into()
931    }
932
933    #[wasm_bindgen(js_name = "getAtlasLookup")]
934    pub fn get_symbol_lookup(&self) -> js_sys::Array {
935        let grid = self.grid.borrow();
936        let atlas = grid.atlas();
937
938        let mut glyphs: Vec<(u16, CompactString)> = Vec::new();
939        atlas.for_each_symbol(&mut |glyph_id, symbol| {
940            glyphs.push((glyph_id, symbol.to_compact_string()));
941        });
942
943        glyphs.sort();
944
945        let js_array = js_sys::Array::new();
946        for (glyph_id, symbol) in glyphs.iter() {
947            let obj = js_sys::Object::new();
948            js_sys::Reflect::set(&obj, &"glyph_id".into(), &JsValue::from(*glyph_id)).unwrap();
949            js_sys::Reflect::set(&obj, &"symbol".into(), &JsValue::from(symbol.as_str())).unwrap();
950
951            js_array.push(&obj.into());
952        }
953        js_array
954    }
955}
956
957impl<'a> From<&'a str> for CanvasSource {
958    fn from(id: &'a str) -> Self {
959        CanvasSource::Id(id.into())
960    }
961}
962
963impl From<web_sys::HtmlCanvasElement> for CanvasSource {
964    fn from(element: web_sys::HtmlCanvasElement) -> Self {
965        CanvasSource::Element(element)
966    }
967}
968
969impl<'a> From<&'a web_sys::HtmlCanvasElement> for CanvasSource {
970    fn from(value: &'a web_sys::HtmlCanvasElement) -> Self {
971        value.clone().into()
972    }
973}
974
975fn create_canvas_rasterizer(
976    font_family: &[CompactString],
977    font_size: f32,
978    pixel_ratio: f32,
979) -> Result<CanvasGlyphRasterizer, Error> {
980    let font_family_css = font_family
981        .iter()
982        .map(|s| format_compact!("'{s}'"))
983        .join_compact(", ");
984    let effective_font_size = font_size * pixel_ratio;
985    CanvasGlyphRasterizer::new(&font_family_css, effective_font_size)
986}