beamterm_renderer/
wasm.rs

1use std::{cell::RefCell, rc::Rc};
2
3use beamterm_data::{FontAtlasData, Glyph};
4use compact_str::CompactString;
5use serde_wasm_bindgen::from_value;
6use unicode_segmentation::UnicodeSegmentation;
7use wasm_bindgen::prelude::*;
8use web_sys::console;
9
10use crate::{
11    gl::{
12        select, CellData, CellQuery as RustCellQuery, FontAtlas, Renderer,
13        SelectionMode as RustSelectionMode, TerminalGrid,
14    },
15    mouse::{DefaultSelectionHandler, TerminalMouseEvent, TerminalMouseHandler},
16};
17
18/// JavaScript wrapper for the terminal renderer
19#[wasm_bindgen]
20#[derive(Debug)]
21pub struct BeamtermRenderer {
22    renderer: Renderer,
23    terminal_grid: Rc<RefCell<TerminalGrid>>,
24    mouse_handler: Option<TerminalMouseHandler>,
25}
26
27/// JavaScript wrapper for cell data
28#[wasm_bindgen]
29#[derive(Debug, Default, serde::Deserialize)]
30pub struct Cell {
31    symbol: CompactString,
32    style: u16,
33    fg: u32,
34    bg: u32,
35}
36
37#[wasm_bindgen]
38#[derive(Debug, Clone, Copy)]
39pub struct CellStyle {
40    fg: u32,
41    bg: u32,
42    style_bits: u16,
43}
44
45#[wasm_bindgen]
46#[derive(Debug, Clone, Copy)]
47pub struct Size {
48    pub width: u16,
49    pub height: u16,
50}
51
52#[wasm_bindgen]
53#[derive(Debug)]
54pub struct Batch {
55    terminal_grid: Rc<RefCell<TerminalGrid>>,
56    gl: web_sys::WebGl2RenderingContext,
57}
58
59/// Selection mode for text selection in the terminal
60#[wasm_bindgen]
61#[derive(Debug, Clone, Copy)]
62pub enum SelectionMode {
63    /// Rectangular block selection
64    Block,
65    /// Linear text flow selection
66    Linear,
67}
68
69/// Type of mouse event
70#[wasm_bindgen]
71#[derive(Debug, Clone, Copy)]
72pub enum MouseEventType {
73    /// Mouse button pressed
74    MouseDown,
75    /// Mouse button released
76    MouseUp,
77    /// Mouse moved
78    MouseMove,
79}
80
81/// Mouse event data with terminal coordinates
82#[wasm_bindgen]
83#[derive(Debug, Clone, Copy)]
84pub struct MouseEvent {
85    /// Type of mouse event
86    pub event_type: MouseEventType,
87    /// Column in terminal grid (0-based)
88    pub col: u16,
89    /// Row in terminal grid (0-based)
90    pub row: u16,
91    /// Mouse button (0=left, 1=middle, 2=right)
92    pub button: i16,
93    /// Whether Ctrl key was pressed
94    pub ctrl_key: bool,
95    /// Whether Shift key was pressed
96    pub shift_key: bool,
97    /// Whether Alt key was pressed
98    pub alt_key: bool,
99}
100
101/// Query for selecting cells in the terminal
102#[wasm_bindgen]
103#[derive(Debug, Clone)]
104pub struct CellQuery {
105    inner: RustCellQuery,
106}
107
108#[wasm_bindgen]
109impl CellQuery {
110    /// Create a new cell query with the specified selection mode
111    #[wasm_bindgen(constructor)]
112    pub fn new(mode: SelectionMode) -> CellQuery {
113        CellQuery { inner: select(mode.into()) }
114    }
115
116    /// Set the starting position for the selection
117    pub fn start(mut self, col: u16, row: u16) -> CellQuery {
118        self.inner = self.inner.start((col, row));
119        self
120    }
121
122    /// Set the ending position for the selection
123    pub fn end(mut self, col: u16, row: u16) -> CellQuery {
124        self.inner = self.inner.end((col, row));
125        self
126    }
127
128    /// Configure whether to trim trailing whitespace from lines
129    #[wasm_bindgen(js_name = "trimTrailingWhitespace")]
130    pub fn trim_trailing_whitespace(mut self, enabled: bool) -> CellQuery {
131        self.inner = self.inner.trim_trailing_whitespace(enabled);
132        self
133    }
134
135    /// Check if the query is empty (no selection range)
136    #[wasm_bindgen(js_name = "isEmpty")]
137    pub fn is_empty(&self) -> bool {
138        self.inner.is_empty()
139    }
140}
141
142#[wasm_bindgen]
143pub fn style() -> CellStyle {
144    CellStyle::new()
145}
146
147#[wasm_bindgen]
148pub fn cell(symbol: &str, style: CellStyle) -> Cell {
149    Cell {
150        symbol: symbol.into(),
151        style: style.style_bits,
152        fg: style.fg,
153        bg: style.bg,
154    }
155}
156
157#[wasm_bindgen]
158impl CellStyle {
159    /// Create a new TextStyle with default (normal) style
160    #[wasm_bindgen(constructor)]
161    pub fn new() -> CellStyle {
162        Default::default()
163    }
164
165    /// Sets the foreground color
166    #[wasm_bindgen]
167    pub fn fg(mut self, color: u32) -> CellStyle {
168        self.fg = color;
169        self
170    }
171
172    /// Sets the background color
173    #[wasm_bindgen]
174    pub fn bg(mut self, color: u32) -> CellStyle {
175        self.bg = color;
176        self
177    }
178
179    /// Add bold style
180    #[wasm_bindgen]
181    pub fn bold(mut self) -> CellStyle {
182        self.style_bits |= Glyph::BOLD_FLAG;
183        self
184    }
185
186    /// Add italic style
187    #[wasm_bindgen]
188    pub fn italic(mut self) -> CellStyle {
189        self.style_bits |= Glyph::ITALIC_FLAG;
190        self
191    }
192
193    /// Add underline effect
194    #[wasm_bindgen]
195    pub fn underline(mut self) -> CellStyle {
196        self.style_bits |= Glyph::UNDERLINE_FLAG;
197        self
198    }
199
200    /// Add strikethrough effect
201    #[wasm_bindgen]
202    pub fn strikethrough(mut self) -> CellStyle {
203        self.style_bits |= Glyph::STRIKETHROUGH_FLAG;
204        self
205    }
206
207    /// Get the combined style bits
208    #[wasm_bindgen(getter)]
209    pub fn bits(&self) -> u16 {
210        self.style_bits
211    }
212}
213
214impl Default for CellStyle {
215    fn default() -> Self {
216        CellStyle {
217            fg: 0xFFFFFF,  // Default foreground color (white)
218            bg: 0x000000,  // Default background color (black)
219            style_bits: 0, // No styles applied
220        }
221    }
222}
223
224#[wasm_bindgen]
225impl Batch {
226    /// Updates a single cell at the given position.
227    #[wasm_bindgen(js_name = "cell")]
228    pub fn cell(&mut self, x: u16, y: u16, cell_data: &Cell) {
229        self.terminal_grid
230            .borrow_mut()
231            .update_cell(x, y, cell_data.as_cell_data());
232    }
233
234    /// Updates a cell by its buffer index.
235    #[wasm_bindgen(js_name = "cellByIndex")]
236    pub fn cell_by_index(&mut self, idx: usize, cell_data: &Cell) {
237        self.terminal_grid
238            .borrow_mut()
239            .update_cell_by_index(idx, cell_data.as_cell_data());
240    }
241
242    /// Updates multiple cells from an array.
243    /// Each element should be [x, y, cellData].
244    #[wasm_bindgen(js_name = "cells")]
245    pub fn cells(&mut self, cells_json: JsValue) -> Result<(), JsValue> {
246        let updates = from_value::<Vec<(u16, u16, Cell)>>(cells_json)
247            .map_err(|e| JsValue::from_str(&e.to_string()));
248
249        match updates {
250            Ok(cells) => {
251                let cell_data = cells
252                    .iter()
253                    .map(|(x, y, data)| (*x, *y, data.as_cell_data()));
254
255                let mut terminal_grid = self.terminal_grid.borrow_mut();
256                terminal_grid
257                    .update_cells_by_position(&self.gl, cell_data)
258                    .map_err(|e| JsValue::from_str(&e.to_string()))
259            },
260            e => e.map(|_| ()),
261        }
262    }
263
264    /// Write text to the terminal
265    #[wasm_bindgen(js_name = "text")]
266    pub fn text(&mut self, x: u16, y: u16, text: &str, style: &CellStyle) -> Result<(), JsValue> {
267        let mut terminal_grid = self.terminal_grid.borrow_mut();
268        let (cols, rows) = terminal_grid.terminal_size();
269
270        if y >= rows {
271            return Ok(()); // oob, ignore
272        }
273
274        for (i, ch) in text.graphemes(true).enumerate() {
275            let current_col = x + i as u16;
276            if current_col >= cols {
277                break;
278            }
279
280            let cell = CellData::new_with_style_bits(ch, style.style_bits, style.fg, style.bg);
281            terminal_grid.update_cell(current_col, y, cell);
282        }
283
284        Ok(())
285    }
286
287    /// Fill a rectangular region
288    #[wasm_bindgen(js_name = "fill")]
289    pub fn fill(
290        &mut self,
291        x: u16,
292        y: u16,
293        width: u16,
294        height: u16,
295        cell_data: &Cell,
296    ) -> Result<(), JsValue> {
297        let mut terminal_grid = self.terminal_grid.borrow_mut();
298        let (cols, rows) = terminal_grid.terminal_size();
299
300        let width = (x + width).min(cols).saturating_sub(x);
301        let height = (y + height).min(rows).saturating_sub(y);
302
303        let fill_cell = cell_data.as_cell_data();
304        for y in y..y + height {
305            for x in x..x + width {
306                terminal_grid.update_cell(x, y, fill_cell);
307            }
308        }
309
310        Ok(())
311    }
312
313    /// Clear the terminal with specified background color
314    #[wasm_bindgen]
315    pub fn clear(&mut self, bg: u32) -> Result<(), JsValue> {
316        let mut terminal_grid = self.terminal_grid.borrow_mut();
317        let (cols, rows) = terminal_grid.terminal_size();
318
319        let clear_cell = CellData::new_with_style_bits(" ", 0, 0xFFFFFF, bg);
320        for y in 0..rows {
321            for x in 0..cols {
322                terminal_grid.update_cell(x, y, clear_cell);
323            }
324        }
325
326        Ok(())
327    }
328
329    /// Synchronize all pending updates to the GPU
330    #[wasm_bindgen]
331    #[deprecated(since = "0.4.0", note = "no-op, flush is now automatic")]
332    #[allow(deprecated)]
333    pub fn flush(&mut self) -> Result<(), JsValue> {
334        Ok(())
335    }
336}
337
338#[wasm_bindgen]
339impl Cell {
340    #[wasm_bindgen(constructor)]
341    pub fn new(symbol: String, style: &CellStyle) -> Cell {
342        Cell {
343            symbol: symbol.into(),
344            style: style.style_bits,
345            fg: style.fg,
346            bg: style.bg,
347        }
348    }
349
350    #[wasm_bindgen(getter)]
351    pub fn symbol(&self) -> String {
352        self.symbol.to_string()
353    }
354
355    #[wasm_bindgen(setter)]
356    pub fn set_symbol(&mut self, symbol: String) {
357        self.symbol = symbol.into();
358    }
359
360    #[wasm_bindgen(getter)]
361    pub fn fg(&self) -> u32 {
362        self.fg
363    }
364
365    #[wasm_bindgen(setter)]
366    pub fn set_fg(&mut self, color: u32) {
367        self.fg = color;
368    }
369
370    #[wasm_bindgen(getter)]
371    pub fn bg(&self) -> u32 {
372        self.bg
373    }
374
375    #[wasm_bindgen(setter)]
376    pub fn set_bg(&mut self, color: u32) {
377        self.bg = color;
378    }
379
380    #[wasm_bindgen(getter)]
381    pub fn style(&self) -> u16 {
382        self.style
383    }
384
385    #[wasm_bindgen(setter)]
386    pub fn set_style(&mut self, style: u16) {
387        self.style = style;
388    }
389}
390
391impl Cell {
392    pub fn as_cell_data(&self) -> CellData<'_> {
393        CellData::new_with_style_bits(&self.symbol, self.style, self.fg, self.bg)
394    }
395}
396
397#[wasm_bindgen]
398impl BeamtermRenderer {
399    /// Create a new terminal renderer
400    #[wasm_bindgen(constructor)]
401    pub fn new(canvas_id: &str) -> Result<BeamtermRenderer, JsValue> {
402        console_error_panic_hook::set_once();
403
404        let renderer = Renderer::create(canvas_id)
405            .map_err(|e| JsValue::from_str(&format!("Failed to create renderer: {e}")))?;
406
407        let gl = renderer.gl();
408        let atlas_data = FontAtlasData::default();
409        let atlas = FontAtlas::load(gl, atlas_data)
410            .map_err(|e| JsValue::from_str(&format!("Failed to load font atlas: {e}")))?;
411
412        let canvas_size = renderer.canvas_size();
413        let terminal_grid = TerminalGrid::new(gl, atlas, canvas_size)
414            .map_err(|e| JsValue::from_str(&format!("Failed to create terminal grid: {e}")))?;
415
416        console::log_1(&"BeamtermRenderer initialized successfully".into());
417        let terminal_grid = Rc::new(RefCell::new(terminal_grid));
418        Ok(BeamtermRenderer { renderer, terminal_grid, mouse_handler: None })
419    }
420
421    /// Enable default mouse selection behavior with built-in copy to clipboard
422    #[wasm_bindgen(js_name = "enableSelection")]
423    pub fn enable_selection(
424        &mut self,
425        mode: SelectionMode,
426        trim_whitespace: bool,
427    ) -> Result<(), JsValue> {
428        // clean up existing mouse handler if present
429        if let Some(old_handler) = self.mouse_handler.take() {
430            old_handler.cleanup();
431        }
432
433        let selection_tracker = self.terminal_grid.borrow().selection_tracker();
434        let handler =
435            DefaultSelectionHandler::new(self.terminal_grid.clone(), mode.into(), trim_whitespace);
436
437        let mouse_handler = TerminalMouseHandler::new(
438            self.renderer.canvas(),
439            self.terminal_grid.clone(),
440            handler.create_event_handler(selection_tracker),
441        )
442        .map_err(|e| JsValue::from_str(&format!("Failed to create mouse handler: {e}")))?;
443
444        self.mouse_handler = Some(mouse_handler);
445        Ok(())
446    }
447
448    /// Set a custom mouse event handler
449    #[wasm_bindgen(js_name = "setMouseHandler")]
450    pub fn set_mouse_handler(&mut self, handler: js_sys::Function) -> Result<(), JsValue> {
451        // Clean up existing mouse handler if present
452        if let Some(old_handler) = self.mouse_handler.take() {
453            old_handler.cleanup();
454        }
455
456        let handler_closure = {
457            let handler = handler.clone();
458            move |event: TerminalMouseEvent, _grid: &TerminalGrid| {
459                let js_event = MouseEvent::from(event);
460                let this = JsValue::null();
461                let args = js_sys::Array::new();
462                args.push(&JsValue::from(js_event));
463
464                if let Err(e) = handler.apply(&this, &args) {
465                    console::error_1(&format!("Mouse handler error: {e:?}").into());
466                }
467            }
468        };
469
470        let mouse_handler = TerminalMouseHandler::new(
471            self.renderer.canvas(),
472            self.terminal_grid.clone(),
473            handler_closure,
474        )
475        .map_err(|e| JsValue::from_str(&format!("Failed to create mouse handler: {e}")))?;
476
477        self.mouse_handler = Some(mouse_handler);
478        Ok(())
479    }
480
481    /// Get selected text based on a cell query
482    #[wasm_bindgen(js_name = "getText")]
483    pub fn get_text(&self, query: &CellQuery) -> String {
484        self.terminal_grid
485            .borrow()
486            .get_text(query.inner)
487            .to_string()
488    }
489
490    /// Copy text to the system clipboard
491    #[wasm_bindgen(js_name = "copyToClipboard")]
492    pub fn copy_to_clipboard(&self, text: &str) {
493        use wasm_bindgen_futures::spawn_local;
494        let text = text.to_string();
495
496        spawn_local(async move {
497            if let Some(window) = web_sys::window() {
498                let clipboard = window.navigator().clipboard();
499                match wasm_bindgen_futures::JsFuture::from(clipboard.write_text(&text)).await {
500                    Ok(_) => {
501                        console::log_1(
502                            &format!("Copied {} characters to clipboard", text.len()).into(),
503                        );
504                    },
505                    Err(err) => {
506                        console::error_1(&format!("Failed to copy to clipboard: {err:?}").into());
507                    },
508                }
509            }
510        });
511    }
512
513    /// Clear any active selection
514    #[wasm_bindgen(js_name = "clearSelection")]
515    pub fn clear_selection(&self) {
516        self.terminal_grid
517            .borrow()
518            .selection_tracker()
519            .clear();
520    }
521
522    /// Check if there is an active selection
523    #[wasm_bindgen(js_name = "hasSelection")]
524    pub fn has_selection(&self) -> bool {
525        self.terminal_grid
526            .borrow()
527            .selection_tracker()
528            .get_query()
529            .is_some()
530    }
531
532    /// Create a new render batch
533    #[wasm_bindgen(js_name = "batch")]
534    pub fn new_render_batch(&mut self) -> Batch {
535        let gl = self.renderer.gl().clone();
536        let terminal_grid = self.terminal_grid.clone();
537        Batch { terminal_grid, gl }
538    }
539
540    /// Get the terminal dimensions in cells
541    #[wasm_bindgen(js_name = "terminalSize")]
542    pub fn terminal_size(&self) -> Size {
543        let (cols, rows) = self.terminal_grid.borrow().terminal_size();
544        Size { width: cols, height: rows }
545    }
546
547    /// Get the cell size in pixels
548    #[wasm_bindgen(js_name = "cellSize")]
549    pub fn cell_size(&self) -> Size {
550        let (width, height) = self.terminal_grid.borrow().cell_size();
551        Size { width: width as u16, height: height as u16 }
552    }
553
554    /// Render the terminal to the canvas
555    #[wasm_bindgen]
556    pub fn render(&mut self) {
557        let mut grid = self.terminal_grid.borrow_mut();
558        let _ = grid.flush_cells(self.renderer.gl());
559
560        self.renderer.begin_frame();
561        self.renderer.render(&*grid);
562        self.renderer.end_frame();
563    }
564
565    /// Resize the terminal to fit new canvas dimensions
566    #[wasm_bindgen]
567    pub fn resize(&mut self, width: i32, height: i32) -> Result<(), JsValue> {
568        self.renderer.resize(width, height);
569
570        let gl = self.renderer.gl();
571        self.terminal_grid
572            .borrow_mut()
573            .resize(gl, (width, height))
574            .map_err(|e| JsValue::from_str(&format!("Failed to resize: {e}")))?;
575
576        // Update mouse handler dimensions if present
577        if let Some(mouse_handler) = &mut self.mouse_handler {
578            let (cols, rows) = self.terminal_grid.borrow().terminal_size();
579            mouse_handler.update_dimensions(cols, rows);
580        }
581
582        Ok(())
583    }
584}
585
586// Convert between Rust and WASM types
587impl From<SelectionMode> for RustSelectionMode {
588    fn from(mode: SelectionMode) -> Self {
589        match mode {
590            SelectionMode::Block => RustSelectionMode::Block,
591            SelectionMode::Linear => RustSelectionMode::Linear,
592        }
593    }
594}
595
596impl From<RustSelectionMode> for SelectionMode {
597    fn from(mode: RustSelectionMode) -> Self {
598        match mode {
599            RustSelectionMode::Block => SelectionMode::Block,
600            RustSelectionMode::Linear => SelectionMode::Linear,
601        }
602    }
603}
604
605impl From<TerminalMouseEvent> for MouseEvent {
606    fn from(event: TerminalMouseEvent) -> Self {
607        use crate::mouse::MouseEventType as RustMouseEventType;
608
609        let event_type = match event.event_type {
610            RustMouseEventType::MouseDown => MouseEventType::MouseDown,
611            RustMouseEventType::MouseUp => MouseEventType::MouseUp,
612            RustMouseEventType::MouseMove => MouseEventType::MouseMove,
613        };
614
615        MouseEvent {
616            event_type,
617            col: event.col,
618            row: event.row,
619            button: event.button(),
620            ctrl_key: event.ctrl_key(),
621            shift_key: event.shift_key(),
622            alt_key: event.alt_key(),
623        }
624    }
625}
626
627/// Initialize the WASM module
628#[wasm_bindgen(start)]
629pub fn main() {
630    console_error_panic_hook::set_once();
631    console::log_1(&"beamterm WASM module loaded".into());
632}