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.borrow_mut().update_cell(x, y, cell_data.as_cell_data());
230    }
231
232    /// Updates a cell by its buffer index.
233    #[wasm_bindgen(js_name = "cellByIndex")]
234    pub fn cell_by_index(&mut self, idx: usize, cell_data: &Cell) {
235        self.terminal_grid
236            .borrow_mut()
237            .update_cell_by_index(idx, cell_data.as_cell_data());
238    }
239
240    /// Updates multiple cells from an array.
241    /// Each element should be [x, y, cellData].
242    #[wasm_bindgen(js_name = "cells")]
243    pub fn cells(&mut self, cells_json: JsValue) -> Result<(), JsValue> {
244        let updates = from_value::<Vec<(u16, u16, Cell)>>(cells_json)
245            .map_err(|e| JsValue::from_str(&e.to_string()));
246
247        match updates {
248            Ok(cells) => {
249                let cell_data = cells.iter().map(|(x, y, data)| (*x, *y, data.as_cell_data()));
250
251                let mut terminal_grid = self.terminal_grid.borrow_mut();
252                terminal_grid
253                    .update_cells_by_position(&self.gl, cell_data)
254                    .map_err(|e| JsValue::from_str(&e.to_string()))
255            },
256            e => e.map(|_| ()),
257        }
258    }
259
260    /// Write text to the terminal
261    #[wasm_bindgen(js_name = "text")]
262    pub fn text(&mut self, x: u16, y: u16, text: &str, style: &CellStyle) -> Result<(), JsValue> {
263        let mut terminal_grid = self.terminal_grid.borrow_mut();
264        let (cols, rows) = terminal_grid.terminal_size();
265
266        if y >= rows {
267            return Ok(()); // oob, ignore
268        }
269
270        for (i, ch) in text.graphemes(true).enumerate() {
271            let current_col = x + i as u16;
272            if current_col >= cols {
273                break;
274            }
275
276            let cell = CellData::new_with_style_bits(ch, style.style_bits, style.fg, style.bg);
277            terminal_grid.update_cell(current_col, y, cell);
278        }
279
280        Ok(())
281    }
282
283    /// Fill a rectangular region
284    #[wasm_bindgen(js_name = "fill")]
285    pub fn fill(
286        &mut self,
287        x: u16,
288        y: u16,
289        width: u16,
290        height: u16,
291        cell_data: &Cell,
292    ) -> Result<(), JsValue> {
293        let mut terminal_grid = self.terminal_grid.borrow_mut();
294        let (cols, rows) = terminal_grid.terminal_size();
295
296        let width = (x + width).min(cols).saturating_sub(x);
297        let height = (y + height).min(rows).saturating_sub(y);
298
299        let fill_cell = cell_data.as_cell_data();
300        for y in y..y + height {
301            for x in x..x + width {
302                terminal_grid.update_cell(x, y, fill_cell);
303            }
304        }
305
306        Ok(())
307    }
308
309    /// Clear the terminal with specified background color
310    #[wasm_bindgen]
311    pub fn clear(&mut self, bg: u32) -> Result<(), JsValue> {
312        let mut terminal_grid = self.terminal_grid.borrow_mut();
313        let (cols, rows) = terminal_grid.terminal_size();
314
315        let clear_cell = CellData::new_with_style_bits(" ", 0, 0xFFFFFF, bg);
316        for y in 0..rows {
317            for x in 0..cols {
318                terminal_grid.update_cell(x, y, clear_cell);
319            }
320        }
321
322        Ok(())
323    }
324
325    /// Synchronize all pending updates to the GPU
326    #[wasm_bindgen]
327    #[deprecated(since = "0.4.0", note = "no-op, flush is now automatic")]
328    #[allow(deprecated)]
329    pub fn flush(&mut self) -> Result<(), JsValue> {
330        Ok(())
331    }
332}
333
334#[wasm_bindgen]
335impl Cell {
336    #[wasm_bindgen(constructor)]
337    pub fn new(symbol: String, style: &CellStyle) -> Cell {
338        Cell {
339            symbol: symbol.into(),
340            style: style.style_bits,
341            fg: style.fg,
342            bg: style.bg,
343        }
344    }
345
346    #[wasm_bindgen(getter)]
347    pub fn symbol(&self) -> String {
348        self.symbol.to_string()
349    }
350
351    #[wasm_bindgen(setter)]
352    pub fn set_symbol(&mut self, symbol: String) {
353        self.symbol = symbol.into();
354    }
355
356    #[wasm_bindgen(getter)]
357    pub fn fg(&self) -> u32 {
358        self.fg
359    }
360
361    #[wasm_bindgen(setter)]
362    pub fn set_fg(&mut self, color: u32) {
363        self.fg = color;
364    }
365
366    #[wasm_bindgen(getter)]
367    pub fn bg(&self) -> u32 {
368        self.bg
369    }
370
371    #[wasm_bindgen(setter)]
372    pub fn set_bg(&mut self, color: u32) {
373        self.bg = color;
374    }
375
376    #[wasm_bindgen(getter)]
377    pub fn style(&self) -> u16 {
378        self.style
379    }
380
381    #[wasm_bindgen(setter)]
382    pub fn set_style(&mut self, style: u16) {
383        self.style = style;
384    }
385}
386
387impl Cell {
388    pub fn as_cell_data(&self) -> CellData {
389        CellData::new_with_style_bits(&self.symbol, self.style, self.fg, self.bg)
390    }
391}
392
393#[wasm_bindgen]
394impl BeamtermRenderer {
395    /// Create a new terminal renderer
396    #[wasm_bindgen(constructor)]
397    pub fn new(canvas_id: &str) -> Result<BeamtermRenderer, JsValue> {
398        console_error_panic_hook::set_once();
399
400        let renderer = Renderer::create(canvas_id)
401            .map_err(|e| JsValue::from_str(&format!("Failed to create renderer: {e}")))?;
402
403        let gl = renderer.gl();
404        let atlas_data = FontAtlasData::default();
405        let atlas = FontAtlas::load(gl, atlas_data)
406            .map_err(|e| JsValue::from_str(&format!("Failed to load font atlas: {e}")))?;
407
408        let canvas_size = renderer.canvas_size();
409        let terminal_grid = TerminalGrid::new(gl, atlas, canvas_size)
410            .map_err(|e| JsValue::from_str(&format!("Failed to create terminal grid: {e}")))?;
411
412        console::log_1(&"BeamtermRenderer initialized successfully".into());
413        let terminal_grid = Rc::new(RefCell::new(terminal_grid));
414        Ok(BeamtermRenderer {
415            renderer,
416            terminal_grid,
417            mouse_handler: None,
418        })
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.borrow().get_text(query.inner).to_string()
485    }
486
487    /// Copy text to the system clipboard
488    #[wasm_bindgen(js_name = "copyToClipboard")]
489    pub fn copy_to_clipboard(&self, text: &str) {
490        use wasm_bindgen_futures::spawn_local;
491        let text = text.to_string();
492
493        spawn_local(async move {
494            if let Some(window) = web_sys::window() {
495                let clipboard = window.navigator().clipboard();
496                match wasm_bindgen_futures::JsFuture::from(clipboard.write_text(&text)).await {
497                    Ok(_) => {
498                        console::log_1(
499                            &format!("Copied {} characters to clipboard", text.len()).into(),
500                        );
501                    },
502                    Err(err) => {
503                        console::error_1(&format!("Failed to copy to clipboard: {err:?}").into());
504                    },
505                }
506            }
507        });
508    }
509
510    /// Clear any active selection
511    #[wasm_bindgen(js_name = "clearSelection")]
512    pub fn clear_selection(&self) {
513        self.terminal_grid.borrow().selection_tracker().clear();
514    }
515
516    /// Check if there is an active selection
517    #[wasm_bindgen(js_name = "hasSelection")]
518    pub fn has_selection(&self) -> bool {
519        self.terminal_grid.borrow().selection_tracker().get_query().is_some()
520    }
521
522    /// Create a new render batch
523    #[wasm_bindgen(js_name = "batch")]
524    pub fn new_render_batch(&mut self) -> Batch {
525        let gl = self.renderer.gl().clone();
526        let terminal_grid = self.terminal_grid.clone();
527        Batch { terminal_grid, gl }
528    }
529
530    /// Get the terminal dimensions in cells
531    #[wasm_bindgen(js_name = "terminalSize")]
532    pub fn terminal_size(&self) -> Size {
533        let (cols, rows) = self.terminal_grid.borrow().terminal_size();
534        Size { width: cols, height: rows }
535    }
536
537    /// Get the cell size in pixels
538    #[wasm_bindgen(js_name = "cellSize")]
539    pub fn cell_size(&self) -> Size {
540        let (width, height) = self.terminal_grid.borrow().cell_size();
541        Size {
542            width: width as u16,
543            height: height as u16,
544        }
545    }
546
547    /// Render the terminal to the canvas
548    #[wasm_bindgen]
549    pub fn render(&mut self) {
550        let mut grid = self.terminal_grid.borrow_mut();
551        let _ = grid.flush_cells(self.renderer.gl());
552
553        self.renderer.begin_frame();
554        self.renderer.render(&*grid);
555        self.renderer.end_frame();
556    }
557
558    /// Resize the terminal to fit new canvas dimensions
559    #[wasm_bindgen]
560    pub fn resize(&mut self, width: i32, height: i32) -> Result<(), JsValue> {
561        self.renderer.resize(width, height);
562
563        console::log_1(&format!("Resizing terminal to {width}x{height}").into());
564
565        let gl = self.renderer.gl();
566        self.terminal_grid
567            .borrow_mut()
568            .resize(gl, (width, height))
569            .map_err(|e| JsValue::from_str(&format!("Failed to resize: {e}")))?;
570
571        // Update mouse handler dimensions if present
572        if let Some(mouse_handler) = &self.mouse_handler {
573            let (cols, rows) = self.terminal_grid.borrow().terminal_size();
574            mouse_handler.update_dimensions(cols, rows);
575        }
576
577        Ok(())
578    }
579}
580
581// Convert between Rust and WASM types
582impl From<SelectionMode> for RustSelectionMode {
583    fn from(mode: SelectionMode) -> Self {
584        match mode {
585            SelectionMode::Block => RustSelectionMode::Block,
586            SelectionMode::Linear => RustSelectionMode::Linear,
587        }
588    }
589}
590
591impl From<RustSelectionMode> for SelectionMode {
592    fn from(mode: RustSelectionMode) -> Self {
593        match mode {
594            RustSelectionMode::Block => SelectionMode::Block,
595            RustSelectionMode::Linear => SelectionMode::Linear,
596        }
597    }
598}
599
600impl From<TerminalMouseEvent> for MouseEvent {
601    fn from(event: TerminalMouseEvent) -> Self {
602        use crate::mouse::MouseEventType as RustMouseEventType;
603
604        let event_type = match event.event_type {
605            RustMouseEventType::MouseDown => MouseEventType::MouseDown,
606            RustMouseEventType::MouseUp => MouseEventType::MouseUp,
607            RustMouseEventType::MouseMove => MouseEventType::MouseMove,
608        };
609
610        MouseEvent {
611            event_type,
612            col: event.col,
613            row: event.row,
614            button: event.button,
615            ctrl_key: event.ctrl_key,
616            shift_key: event.shift_key,
617            alt_key: event.alt_key,
618        }
619    }
620}
621
622/// Initialize the WASM module
623#[wasm_bindgen(start)]
624pub fn main() {
625    console_error_panic_hook::set_once();
626    console::log_1(&"beamterm WASM module loaded".into());
627}