beamterm-renderer 1.0.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
//! Mouse input handling for the beamterm terminal renderer.
//!
//! This module provides mouse event handling infrastructure for the terminal,
//! including coordinate conversion from pixel space to terminal grid space,
//! text selection with automatic clipboard integration, and customizable
//! event handling.
//!
//! # Architecture
//!
//! The mouse handling system consists of:
//! - [`TerminalMouseHandler`] - Main event handler that attaches to a canvas
//! - [`TerminalMouseEvent`] - Mouse events translated to terminal coordinates
//! - [`DefaultSelectionHandler`] - Built-in text selection implementation
//! - Internal state tracking for selection operations
//!
//! # Example
//!
//! ```rust,no_run
//! use beamterm_renderer::{Terminal, SelectionMode};
//! use beamterm_renderer::mouse::{MouseSelectOptions, ModifierKeys};
//!
//! // Enable selection with Shift+Click
//! 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();
//!
//! // Or provide custom mouse handling
//! let terminal = Terminal::builder("#canvas")
//!     .mouse_input_handler(|event, grid| {
//!         println!("Mouse event at ({}, {})", event.col, event.row);
//!     })
//!     .build().unwrap();
//! ```

use std::{
    cell::RefCell,
    fmt::{Debug, Formatter},
    rc::Rc,
};

use bitflags::bitflags;
use wasm_bindgen::{JsCast, closure::Closure};

use crate::{Error, SelectionMode, TerminalGrid, gl::SelectionTracker, select};

/// Type alias for boxed mouse event callback functions.
///
/// Callbacks are invoked synchronously in the browser's event loop
pub type MouseEventCallback = Box<dyn FnMut(TerminalMouseEvent, &TerminalGrid) + 'static>;

/// Internal type for shared event handler wrapped in Rc<RefCell>.
type EventHandler = Rc<RefCell<dyn FnMut(TerminalMouseEvent, &TerminalGrid) + 'static>>;

/// All mouse event types this handler listens to.
const MOUSE_EVENTS: &[&str] =
    &["mousedown", "mouseup", "mousemove", "click", "mouseenter", "mouseleave"];

/// Handles mouse input events for a terminal grid.
///
/// Converts browser mouse events into terminal grid coordinates and manages
/// event handlers for mouse interactions. Maintains terminal dimensions for
/// accurate coordinate mapping.
pub struct TerminalMouseHandler {
    /// The canvas element this handler is attached to.
    canvas: web_sys::HtmlCanvasElement,
    /// Unified closure for all mouse events.
    on_mouse_event: Closure<dyn FnMut(web_sys::MouseEvent)>,
    /// Optional default selection handler.
    pub(crate) default_input_handler: Option<DefaultSelectionHandler>,
}

/// Mouse event data with terminal cell coordinates.
///
/// Represents a mouse event translated from pixel coordinates to terminal
/// grid coordinates, including modifier key states.`col` and `row` are 0-based
/// terminal grid coordinates
#[derive(Debug, Clone, Copy)]
pub struct TerminalMouseEvent {
    /// Type of mouse event (down, up, or move).
    pub event_type: MouseEventType,
    /// Column in the terminal grid (0-based).
    pub col: u16,
    /// Row in the terminal grid (0-based).
    pub row: u16,
    /// Mouse button pressed (0 = left, 1 = middle, 2 = right).
    button: i16,
    /// All modifier that were pressed during the event.
    modifier_keys: ModifierKeys,
}

impl TerminalMouseEvent {
    /// Returns the mouse button pressed during the event.
    #[must_use]
    pub fn button(&self) -> i16 {
        self.button
    }

    /// Returns whether the Ctrl key was pressed during the event.
    #[must_use]
    pub fn ctrl_key(&self) -> bool {
        self.modifier_keys.contains(ModifierKeys::CONTROL)
    }

    /// Returns whether the Shift key was pressed during the event.
    #[must_use]
    pub fn shift_key(&self) -> bool {
        self.modifier_keys.contains(ModifierKeys::SHIFT)
    }

    /// Returns whether the Alt key was pressed during the event.
    #[must_use]
    pub fn alt_key(&self) -> bool {
        self.modifier_keys.contains(ModifierKeys::ALT)
    }

    /// Returns whether the Meta key was pressed during the event.
    ///
    /// This is the Command key on macOS or the Windows key on Windows.
    #[must_use]
    pub fn meta_key(&self) -> bool {
        self.modifier_keys.contains(ModifierKeys::META)
    }

    /// Returns whether the pressed modifiers exactly match the specified set.
    ///
    /// Returns `true` only if the modifier keys pressed during the event
    /// are exactly equal to `mods`—no more, no less.
    #[must_use]
    pub fn has_exact_modifiers(&self, mods: ModifierKeys) -> bool {
        self.modifier_keys == mods
    }
}

/// Types of mouse events that can occur.
#[derive(Debug, Clone, Copy, PartialEq)]
#[repr(u8)]
pub enum MouseEventType {
    /// Mouse button was pressed.
    MouseDown = 0,
    /// Mouse button was released.
    MouseUp = 1,
    /// Mouse moved while over the terminal.
    MouseMove = 2,
    /// Mouse button was clicked (pressed and released).
    Click = 3,
    /// Mouse cursor entered the terminal area.
    MouseEnter = 4,
    /// Mouse cursor left the terminal area.
    MouseLeave = 5,
}

impl MouseEventType {
    /// Converts a browser event type string to a MouseEventType.
    fn from_event_type(event_type: &str) -> Option<Self> {
        match event_type {
            "mousedown" => Some(Self::MouseDown),
            "mouseup" => Some(Self::MouseUp),
            "mousemove" => Some(Self::MouseMove),
            "click" => Some(Self::Click),
            "mouseenter" => Some(Self::MouseEnter),
            "mouseleave" => Some(Self::MouseLeave),
            _ => None,
        }
    }
}

/// Configuration options for mouse-based text selection.
///
/// Use the builder pattern to configure selection behavior:
///
/// ```rust,no_run
/// use beamterm_renderer::mouse::{MouseSelectOptions, ModifierKeys};
/// use beamterm_renderer::SelectionMode;
///
/// let options = MouseSelectOptions::new()
///     .selection_mode(SelectionMode::Block)
///     .require_modifier_keys(ModifierKeys::SHIFT)
///     .trim_trailing_whitespace(true);
/// ```
#[derive(Clone, Debug, Copy, Default)]
pub struct MouseSelectOptions {
    selection_mode: SelectionMode,
    require_modifier_keys: ModifierKeys,
    trim_trailing_whitespace: bool,
}

impl MouseSelectOptions {
    /// Creates a new `MouseSelectOptions` with default settings.
    ///
    /// Defaults:
    /// - Selection mode: `Block`
    /// - Required modifier keys: none
    /// - Trim trailing whitespace: `false`
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the selection mode (Linear or Block).
    ///
    /// - `Linear`: Selects text following the natural reading order
    /// - `Block`: Selects a rectangular region of cells
    #[must_use]
    pub fn selection_mode(mut self, mode: SelectionMode) -> Self {
        self.selection_mode = mode;
        self
    }

    /// Sets modifier keys that must be held for selection to activate.
    ///
    /// When set, mouse selection only begins if the specified modifier
    /// keys are pressed during the initial click. Use `ModifierKeys::empty()`
    /// to allow selection without any modifiers (the default).
    ///
    /// # Example
    /// ```rust,no_run
    /// use beamterm_renderer::mouse::{MouseSelectOptions, ModifierKeys};
    ///
    /// // Require Shift+Click to start selection
    /// let options = MouseSelectOptions::new()
    ///     .require_modifier_keys(ModifierKeys::SHIFT);
    ///
    /// // Require Ctrl+Shift+Click
    /// let options = MouseSelectOptions::new()
    ///     .require_modifier_keys(ModifierKeys::CONTROL | ModifierKeys::SHIFT);
    /// ```
    #[must_use]
    pub fn require_modifier_keys(mut self, require_modifier_keys: ModifierKeys) -> Self {
        self.require_modifier_keys = require_modifier_keys;
        self
    }

    /// Sets whether to trim trailing whitespace from selected text.
    ///
    /// When enabled, trailing spaces at the end of each line are removed
    /// from the copied text.
    #[must_use]
    pub fn trim_trailing_whitespace(mut self, trim: bool) -> Self {
        self.trim_trailing_whitespace = trim;
        self
    }
}

impl TerminalMouseHandler {
    /// Creates a new mouse handler for the given canvas and terminal grid.
    ///
    /// Sets up mouse event listeners on the canvas and converts pixel coordinates
    /// to terminal cell coordinates before invoking the provided event handler.
    ///
    /// # Arguments
    /// * `canvas` - The HTML canvas element to attach mouse listeners to
    /// * `grid` - The terminal grid for coordinate calculations
    /// * `event_handler` - Callback invoked for each mouse event
    ///
    /// # Errors
    /// Returns `Error::Callback` if event listeners cannot be attached to the canvas.
    ///
    /// # Example
    /// ```rust,no_run
    /// use beamterm_renderer::mouse::TerminalMouseHandler;
    /// use std::{cell::RefCell, rc::Rc};
    ///
    /// let canvas = unimplemented!("canvas");
    /// let grid: Rc<RefCell<()>> = unimplemented!("TerminalGrid");
    ///
    /// // In real code, this would be TerminalGrid
    /// // let handler = TerminalMouseHandler::new(
    /// //     &canvas,
    /// //     grid.clone(),
    /// //     |event, grid| {
    /// //         println!("Click at ({}, {})", event.col, event.row);
    /// //     }
    /// // ).unwrap();
    /// ```
    pub fn new<F>(
        canvas: &web_sys::HtmlCanvasElement,
        grid: Rc<RefCell<TerminalGrid>>,
        event_handler: F,
    ) -> Result<Self, Error>
    where
        F: FnMut(TerminalMouseEvent, &TerminalGrid) + 'static,
    {
        Self::new_internal(canvas, grid, Box::new(event_handler))
    }

    /// Internal constructor that accepts a boxed event handler.
    ///
    /// # Implementation Details
    /// - Wraps handler in Rc<RefCell> for sharing between event closures
    /// - Caches terminal metrics for fast coordinate conversion
    /// - Creates three closures (one per event type) that share the handler
    #[allow(clippy::needless_pass_by_value)] // Rc pass-by-value is idiomatic for shared ownership
    fn new_internal(
        canvas: &web_sys::HtmlCanvasElement,
        grid: Rc<RefCell<TerminalGrid>>,
        event_handler: MouseEventCallback,
    ) -> Result<Self, Error> {
        // Wrap the handler in Rc<RefCell> for sharing between closures
        let shared_handler = Rc::new(RefCell::new(event_handler));

        // Create pixel-to-cell coordinate converter that reads live grid state.
        // This ensures correct coordinate mapping even after DPR/zoom changes,
        let grid_for_coords = grid.clone();
        let pixel_to_cell = move |event: &web_sys::MouseEvent| -> Option<(u16, u16)> {
            let g = grid_for_coords.try_borrow().ok()?;
            let ts = g.terminal_size();
            let (cell_width, cell_height) = g.css_cell_size();

            let col = (event.offset_x() as f32 / cell_width).floor() as u16;
            let row = (event.offset_y() as f32 / cell_height).floor() as u16;

            if col < ts.cols && row < ts.rows { Some((col, row)) } else { None }
        };

        // Create unified event handler
        let on_mouse_event =
            create_mouse_event_closure(grid.clone(), shared_handler, pixel_to_cell);

        // Attach event listeners for all mouse event types
        for event_type in MOUSE_EVENTS {
            canvas
                .add_event_listener_with_callback(
                    event_type,
                    on_mouse_event.as_ref().unchecked_ref(),
                )
                .map_err(|_| Error::Callback(format!("Failed to add {event_type} listener")))?;
        }

        Ok(Self {
            canvas: canvas.clone(),
            on_mouse_event,
            default_input_handler: None,
        })
    }

    /// Removes all event listeners from the canvas.
    ///
    /// Called automatically on drop. Safe to call multiple times.
    pub fn cleanup(&self) {
        for event_type in MOUSE_EVENTS {
            let _ = self.canvas.remove_event_listener_with_callback(
                event_type,
                self.on_mouse_event.as_ref().unchecked_ref(),
            );
        }
    }
}

/// Default mouse selection handler with clipboard integration.
///
/// Provides text selection functionality with automatic clipboard copying
/// on selection completion. Supports both linear (text flow) and block
/// (rectangular) selection modes.
///
/// # Features
/// - Click and drag to select text
/// - Automatic clipboard copy on mouse release
/// - Configurable selection modes (Linear/Block)
/// - Optional trailing whitespace trimming
pub(crate) struct DefaultSelectionHandler {
    /// Current selection state machine.
    selection_state: Rc<RefCell<SelectionState>>,
    /// Terminal grid reference for text extraction.
    grid: Rc<RefCell<TerminalGrid>>,
    /// Selection mode (Linear or Block).
    options: MouseSelectOptions,
}

impl DefaultSelectionHandler {
    /// Creates a new selection handler for the given terminal grid.
    ///
    /// # Arguments
    /// * `grid` - Terminal grid for text extraction
    /// * `query_mode` - Selection mode (Linear follows text flow, Block is rectangular)
    /// * `trim_trailing_whitespace` - Whether to remove trailing spaces from selected text
    pub(crate) fn new(grid: Rc<RefCell<TerminalGrid>>, options: MouseSelectOptions) -> Self {
        Self {
            grid,
            selection_state: Rc::new(RefCell::new(SelectionState::Idle)),
            options,
        }
    }

    /// Creates the mouse event handler closure for this selection handler.
    ///
    /// Returns a boxed closure that handles mouse events, tracks selection state,
    /// and copies selected text to the clipboard on completion.
    ///
    /// # Arguments
    /// * `active_selection` - Selection tracker for visual feedback
    ///
    /// # Algorithm
    /// 1. MouseDown: Begin new selection or replace existing
    /// 2. MouseMove: Update selection end point if selecting
    /// 3. MouseUp: Complete selection and copy to clipboard
    ///
    /// Repeated single-cell clicks cancel selection rather than selecting one cell.
    pub fn create_event_handler(&self, active_selection: SelectionTracker) -> MouseEventCallback {
        let selection_state = self.selection_state.clone();
        let query_mode = self.options.selection_mode;
        let trim_trailing = self.options.trim_trailing_whitespace;
        let require_modifier_keys = self.options.require_modifier_keys;

        Box::new(move |event: TerminalMouseEvent, grid: &TerminalGrid| {
            let mut state = selection_state.borrow_mut();

            // update mouse selection state based on the event type.
            match event.event_type {
                MouseEventType::MouseDown if event.button == 0 => {
                    // if modifier keys are required, ensure they are pressed
                    if !event.has_exact_modifiers(require_modifier_keys) {
                        return;
                    }

                    // note: if there's an existing selection in progress, it
                    // means that the cursor left the terminal (canvas) area
                    // while a previous selection was ongoing. if so, we do
                    // nothing and await the MouseUp event.

                    // mouse down always begins a new *potential* selection
                    if state.is_complete() {
                        // the existing (completed) selection is replaced with
                        // a new selection which will be canceled if the mouse
                        // up event is fired on the same cell.
                        state.maybe_selecting(event.col, event.row);
                    } else if state.is_idle() {
                        // begins a new selection from a blank state
                        state.begin_selection(event.col, event.row);
                    }

                    let query = select(query_mode)
                        .start((event.col, event.row))
                        .trim_trailing_whitespace(trim_trailing);

                    active_selection.set_query(query);
                },
                MouseEventType::MouseMove if state.is_selecting() => {
                    state.update_selection(event.col, event.row);
                    active_selection.update_selection_end((event.col, event.row));
                },
                MouseEventType::MouseUp if event.button == 0 => {
                    // at this point, we're either at:
                    // a) the user has finished making the selection
                    // b) the selection was canceled by a click inside a single cell
                    if let Some((_start, _end)) = state.complete_selection(event.col, event.row) {
                        active_selection.update_selection_end((event.col, event.row));

                        // hash the selected content and store it with the query;
                        // this allows us to clear the selection if the content changes
                        let query = active_selection.query();
                        active_selection.set_content_hash(grid.hash_cells(query));

                        let selected_text = grid.get_text(active_selection.query());
                        crate::js::copy_to_clipboard(selected_text);
                    } else {
                        state.clear();
                        active_selection.clear();
                    }
                },
                _ => {}, // ignore non-left button events
            }
        })
    }
}

/// Internal state machine for tracking mouse selection operations.
///
/// Manages the lifecycle of a selection from initial click through dragging
/// to final release. Handles edge cases like single-cell clicks that should
/// cancel rather than select.
///
/// # State Transitions
/// ```text
///        ┌──────────┐
///    ┌──▶│   Idle   │
///    │   └────┬─────┘
///    │        │ begin_selection
///    │        ▼
///    │   ┌──────────┐
///    │   │Selecting │◀────────────┐
///    │   └────┬─────┘             │
///    │        │ complete_selection│
///    │        ▼                   │
///    │   ┌──────────┐             │
///    │   │ Complete │             │
///    │   └────┬─────┘             │
///    │        │ maybe_selecting   │
///    │        ▼                   │
///    │   ┌──────────────┐         │
///    └───│MaybeSelecting│─────────┘
/// mouse  └──────────────┘  update_selection
///   up       
///          
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
enum SelectionState {
    /// No selection in progress.
    Idle,
    /// Active selection with start point and current cursor position.
    Selecting { start: (u16, u16), current: Option<(u16, u16)> },
    /// MouseDown in a cell while selection exists.
    /// Will become Selecting on MouseMove or Idle on MouseUp.
    MaybeSelecting { start: (u16, u16) },
    /// Selection completed, contains start and end coordinates.
    Complete { start: (u16, u16), end: (u16, u16) },
}

impl SelectionState {
    /// Begins a new selection from idle state.
    ///
    /// # Panics
    /// Panics if called when not in Idle state (debug only).
    fn begin_selection(&mut self, col: u16, row: u16) {
        debug_assert!(matches!(self, SelectionState::Idle));
        *self = SelectionState::Selecting { start: (col, row), current: None };
    }

    /// Updates selection end point during drag.
    ///
    /// Transitions MaybeSelecting to Selecting if needed.
    fn update_selection(&mut self, col: u16, row: u16) {
        use SelectionState::*;

        match self {
            Selecting { current, .. } => {
                *current = Some((col, row));
            },
            MaybeSelecting { start } => {
                if (col, row) != *start {
                    *self = Selecting { start: *start, current: Some((col, row)) };
                }
            },
            _ => {},
        }
    }

    /// Completes the selection on mouse release.
    ///
    /// # Returns
    /// - `Some((start, end))` if selection completed
    /// - `None` if selection was canceled (single cell click)
    fn complete_selection(&mut self, col: u16, row: u16) -> Option<((u16, u16), (u16, u16))> {
        match self {
            SelectionState::Selecting { start, .. } => {
                let result = Some((*start, (col, row)));
                *self = SelectionState::Complete { start: *start, end: (col, row) };
                result
            },
            _ => None,
        }
    }

    /// Clears the selection state back to idle.
    fn clear(&mut self) {
        *self = SelectionState::Idle;
    }

    /// Checks if currently in selecting state.
    fn is_selecting(&self) -> bool {
        matches!(
            self,
            SelectionState::Selecting { .. } | SelectionState::MaybeSelecting { .. }
        )
    }

    fn is_idle(&self) -> bool {
        matches!(self, SelectionState::Idle)
    }

    /// Begins potential new selection while one exists.
    ///
    /// Used when clicking while a selection is complete.
    fn maybe_selecting(&mut self, col: u16, row: u16) {
        *self = SelectionState::MaybeSelecting { start: (col, row) };
    }

    /// Checks if a selection has been completed.
    fn is_complete(&self) -> bool {
        matches!(self, SelectionState::Complete { .. })
    }
}

/// Creates a closure that handles browser mouse events and converts them to terminal events.
///
/// Wraps the event handler with coordinate conversion and terminal event creation logic.
/// Handles all mouse event types (mousedown, mouseup, mousemove, click, mouseenter, mouseleave).
fn create_mouse_event_closure(
    grid: Rc<RefCell<TerminalGrid>>,
    event_handler: EventHandler,
    pixel_to_cell: impl Fn(&web_sys::MouseEvent) -> Option<(u16, u16)> + 'static,
) -> Closure<dyn FnMut(web_sys::MouseEvent)> {
    Closure::wrap(Box::new(move |event: web_sys::MouseEvent| {
        // Determine event type from browser event
        let Some(event_type) = MouseEventType::from_event_type(&event.type_()) else {
            return;
        };

        // For enter/exit events, we don't need valid cell coordinates
        let (col, row) = match event_type {
            MouseEventType::MouseEnter | MouseEventType::MouseLeave => {
                // Use (0, 0) for enter/leave events as they may occur outside the grid
                (0, 0)
            },
            _ => {
                // For other events, require valid cell coordinates
                match pixel_to_cell(&event) {
                    Some(coords) => coords,
                    None => return,
                }
            },
        };

        let modifiers = {
            let mut mods = ModifierKeys::empty();
            if event.ctrl_key() {
                mods |= ModifierKeys::CONTROL;
            }
            if event.shift_key() {
                mods |= ModifierKeys::SHIFT;
            }
            if event.alt_key() {
                mods |= ModifierKeys::ALT;
            }
            if event.meta_key() {
                mods |= ModifierKeys::META;
            }
            mods
        };

        let terminal_event = TerminalMouseEvent {
            event_type,
            col,
            row,
            button: event.button(),
            modifier_keys: modifiers,
        };
        let grid_ref = grid.borrow();
        event_handler.borrow_mut()(terminal_event, &grid_ref);
    }) as Box<dyn FnMut(_)>)
}

impl Drop for TerminalMouseHandler {
    /// Automatically removes event listeners when handler is dropped.
    fn drop(&mut self) {
        self.cleanup();
    }
}

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

impl Debug for DefaultSelectionHandler {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let ts = self.grid.borrow().terminal_size();
        write!(
            f,
            "DefaultSelectionHandler {{ options: {:?}, grid: {}x{} }}",
            self.options, ts.cols, ts.rows
        )
    }
}

bitflags! {
    /// Keyboard modifier keys that can be held during mouse events.
    ///
    /// Flags can be combined using bitwise OR:
    ///
    /// ```rust,no_run
    /// use beamterm_renderer::mouse::ModifierKeys;
    ///
    /// let ctrl_shift = ModifierKeys::CONTROL | ModifierKeys::SHIFT;
    /// ```
    #[derive(Default, Debug, Clone, Copy, Eq, PartialEq)]
    pub struct ModifierKeys : u8 {
        /// The Control key (Ctrl on Windows/Linux).
        const CONTROL = 0b0000_0001;
        /// The Shift key.
        const SHIFT   = 0b0000_0010;
        /// The Alt key (Option on macOS).
        const ALT     = 0b0000_0100;
        /// The Meta key (Command on macOS, Windows key on Windows).
        const META    = 0b0000_1000;
    }
}