minui 0.7.1

A minimalist framework for building terminal UIs in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
//! Mouse input handling implementation.
//!
//! This module provides comprehensive mouse input functionality using crossterm
//! for cross-platform terminal mouse input handling. It supports mouse movement,
//! clicks, drags, and scroll events.

use crate::{Event, MouseButton, Result};
use crossterm::event::{
    self, Event as CrosstermEvent, MouseButton as CrosstermMouseButton, MouseEvent, MouseEventKind,
};
use std::time::{Duration, Instant};

/// Handles mouse input with configurable polling rates and event tracking.
///
/// `MouseHandler` provides a flexible interface for receiving mouse input in terminal
/// applications. It supports mouse movement tracking, click detection, drag operations,
/// and scroll wheel events.
///
/// # Key Features
///
/// - **Movement Tracking**: Track cursor position within the terminal
/// - **Click Detection**: Handle left, right, and middle mouse button clicks
/// - **Drag Operations**: Support for drag-and-drop interactions
/// - **Scroll Events**: Mouse wheel scrolling support
/// - **Configurable Polling**: Adjustable polling rates for different performance needs
/// - **Cross-platform**: Works consistently across Windows, macOS, and Linux
///
/// # Examples
///
/// ## Basic Mouse Polling
///
/// ```rust
/// use minui::input::MouseHandler;
/// use minui::{Event, MouseButton};
///
/// let mouse = MouseHandler::new();
///
/// // Non-blocking check for mouse input
/// if let Some(event) = mouse.poll()? {
///     match event {
///         Event::MouseClick { x, y, button } => {
///             match button {
///                 MouseButton::Left => println!("Left click at ({}, {})", x, y),
///                 MouseButton::Right => println!("Right click at ({}, {})", x, y),
///                 MouseButton::Middle => println!("Middle click at ({}, {})", x, y),
///                 MouseButton::Other(code) => println!("Button {} click at ({}, {})", code, x, y),
///             }
///         },
///         Event::MouseMove { x, y } => println!("Mouse moved to ({}, {})", x, y),
///         Event::MouseScroll { delta } => {
///             if delta > 0 {
///                 println!("Scrolled up");
///             } else {
///                 println!("Scrolled down");
///             }
///         },
///         _ => {}
///     }
/// }
/// # Ok::<(), minui::Error>(())
/// ```
///
/// ## Drag Detection
///
/// ```rust
/// use minui::input::MouseHandler;
/// use minui::{Event, MouseButton};
///
/// let mut mouse = MouseHandler::new();
/// mouse.enable_drag_detection(true);
///
/// if let Some(event) = mouse.poll()? {
///     match event {
///         Event::MouseClick { x, y, button: MouseButton::Left } => {
///             println!("Click at ({}, {})", x, y);
///         },
///         Event::MouseDrag { x, y, button } => {
///             println!("Dragging with {:?} to ({}, {})", button, x, y);
///         },
///         _ => {}
///     }
/// }
/// # Ok::<(), minui::Error>(())
/// ```
pub struct MouseHandler {
    poll_rate: Duration,
    track_movement: bool,
    drag_detection: bool,
    last_click_pos: Option<(u16, u16)>,
    is_dragging: bool,
    last_scroll_direction: Option<ScrollDirection>,
    scroll_buffer_count: u8,
    invert_scroll_vertical: bool,
    invert_scroll_horizontal: bool,
    click_tracker: ClickTracker,
}

#[derive(Debug, Clone, Copy, PartialEq)]
enum ScrollDirection {
    Vertical,
    Horizontal,
}

/// Tracks click timing and position for double-click detection.
///
/// `ClickTracker` monitors mouse clicks and determines if a click is a double-click
/// based on time interval and position proximity.
///
/// # Examples
///
/// ```rust
/// use minui::input::ClickTracker;
///
/// let mut tracker = ClickTracker::new();
///
/// // Check if a click is a double-click
/// if tracker.is_double_click(10, 5) {
///     println!("Double-click detected at (10, 5)");
/// }
/// ```
pub struct ClickTracker {
    /// Timestamp of the last click
    last_click: Instant,
    /// Position of the last click
    last_pos: (u16, u16),
    /// Maximum time between clicks to be considered a double-click (default: 500ms)
    double_click_threshold: Duration,
    /// Maximum distance between clicks to be considered a double-click (default: 3 pixels)
    double_click_distance: u16,
}

impl ClickTracker {
    /// Creates a new click tracker with default thresholds.
    ///
    /// Defaults:
    /// - 500ms double-click threshold
    /// - 3 cell maximum distance
    pub fn new() -> Self {
        Self {
            last_click: Instant::now() - Duration::from_secs(1), // Initialize in the past
            last_pos: (0, 0),
            double_click_threshold: Duration::from_millis(500),
            double_click_distance: 3,
        }
    }

    /// Sets the maximum time between clicks for double-click detection.
    pub fn with_threshold(mut self, threshold: Duration) -> Self {
        self.double_click_threshold = threshold;
        self
    }

    /// Sets the maximum distance between clicks for double-click detection.
    pub fn with_distance(mut self, distance: u16) -> Self {
        self.double_click_distance = distance;
        self
    }

    /// Checks if a click at the given position is a double-click.
    ///
    /// A double-click is detected if:
    /// - The time since the last click is less than `double_click_threshold`
    /// - The click position is within `double_click_distance` of the last click
    ///
    /// # Returns
    ///
    /// - `true` if this is a double-click
    /// - `false` otherwise
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::input::ClickTracker;
    ///
    /// let mut tracker = ClickTracker::new();
    ///
    /// // First click
    /// assert!(!tracker.is_double_click(10, 5)); // First click is never a double-click
    ///
    /// // Simulate a quick second click
    /// // (in real code, you'd call this from the mouse event handler)
    /// ```
    pub fn is_double_click(&mut self, x: u16, y: u16) -> bool {
        let now = Instant::now();
        let time_diff = now.duration_since(self.last_click);
        let pos_diff_x = if x > self.last_pos.0 {
            x - self.last_pos.0
        } else {
            self.last_pos.0 - x
        };
        let pos_diff_y = if y > self.last_pos.1 {
            y - self.last_pos.1
        } else {
            self.last_pos.1 - y
        };

        let is_double = time_diff < self.double_click_threshold
            && pos_diff_x <= self.double_click_distance
            && pos_diff_y <= self.double_click_distance;

        self.last_click = now;
        self.last_pos = (x, y);

        is_double
    }

    /// Returns the position of the last click.
    pub fn last_position(&self) -> (u16, u16) {
        self.last_pos
    }

    /// Returns the time elapsed since the last click.
    pub fn time_since_last_click(&self) -> Duration {
        self.last_click.elapsed()
    }
}

impl Default for ClickTracker {
    fn default() -> Self {
        Self::new()
    }
}

impl MouseHandler {
    /// Creates a new mouse handler with default settings.
    ///
    /// The handler is initialized with:
    /// - 1ms poll rate for responsive input
    /// - Movement tracking enabled
    /// - Drag detection disabled
    ///
    /// # Returns
    ///
    /// A new `MouseHandler` with default configuration.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::input::MouseHandler;
    ///
    /// let mouse = MouseHandler::new();
    /// # Ok::<(), minui::Error>(())
    /// ```
    pub fn new() -> Self {
        Self {
            poll_rate: Duration::from_millis(1),
            track_movement: true,
            drag_detection: false,
            last_click_pos: None,
            is_dragging: false,
            last_scroll_direction: None,
            scroll_buffer_count: 0,
            invert_scroll_vertical: false,
            invert_scroll_horizontal: false,
            click_tracker: ClickTracker::new(),
        }
    }

    /// Sets the polling rate for mouse input detection.
    ///
    /// The poll rate determines how frequently the handler checks for available input
    /// when using the `poll()` method. Lower values provide more responsive input
    /// at the cost of higher CPU usage.
    ///
    /// # Arguments
    ///
    /// * `milliseconds` - The polling interval in milliseconds
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::input::MouseHandler;
    ///
    /// let mut mouse = MouseHandler::new();
    /// mouse.set_poll_rate(16); // 60 FPS
    /// ```
    pub fn set_poll_rate(&mut self, milliseconds: u64) {
        self.poll_rate = Duration::from_millis(milliseconds);
    }

    /// Returns the current polling rate.
    ///
    /// # Returns
    ///
    /// The current poll rate as a `Duration`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::input::MouseHandler;
    /// use std::time::Duration;
    ///
    /// let mouse = MouseHandler::new();
    /// assert_eq!(mouse.poll_rate(), Duration::from_millis(1));
    /// ```
    pub fn poll_rate(&self) -> Duration {
        self.poll_rate
    }

    /// Enables or disables mouse movement tracking.
    ///
    /// When enabled, the handler will generate `MouseMove` events whenever
    /// the cursor position changes. When disabled, only clicks and scrolls
    /// are tracked, which can reduce event volume.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to track mouse movement
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::input::MouseHandler;
    ///
    /// let mut mouse = MouseHandler::new();
    /// mouse.set_movement_tracking(false); // Only track clicks and scrolls
    /// ```
    pub fn set_movement_tracking(&mut self, enabled: bool) {
        self.track_movement = enabled;
    }

    /// Returns whether movement tracking is enabled.
    ///
    /// # Returns
    ///
    /// `true` if movement tracking is enabled, `false` otherwise.
    pub fn is_movement_tracking_enabled(&self) -> bool {
        self.track_movement
    }

    /// Enables or disables drag detection.
    ///
    /// When enabled, the handler tracks when a mouse button is pressed and
    /// the mouse is subsequently moved, allowing for drag-and-drop operations.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to detect drag operations
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::input::MouseHandler;
    ///
    /// let mut mouse = MouseHandler::new();
    /// mouse.enable_drag_detection(true);
    /// ```
    pub fn enable_drag_detection(&mut self, enabled: bool) {
        self.drag_detection = enabled;
        if !enabled {
            self.is_dragging = false;
            self.last_click_pos = None;
        }
    }

    /// Returns whether drag detection is enabled.
    ///
    /// # Returns
    ///
    /// `true` if drag detection is enabled, `false` otherwise.
    pub fn is_drag_detection_enabled(&self) -> bool {
        self.drag_detection
    }

    /// Returns whether a drag operation is currently in progress.
    ///
    /// This is only meaningful when drag detection is enabled.
    ///
    /// # Returns
    ///
    /// `true` if currently dragging, `false` otherwise.
    pub fn is_dragging(&self) -> bool {
        self.is_dragging
    }

    /// Returns the position where the current drag started (if any).
    ///
    /// # Returns
    ///
    /// - `Some((x, y))` - The starting position of the current drag
    /// - `None` - No drag is in progress
    pub fn drag_start_position(&self) -> Option<(u16, u16)> {
        if self.is_dragging {
            self.last_click_pos
        } else {
            None
        }
    }

    /// Returns a reference to the click tracker for double-click detection.
    ///
    /// This allows you to manually check if a click is a double-click or customize
    /// the double-click thresholds.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::input::MouseHandler;
    ///
    /// let mut mouse = MouseHandler::new();
    ///
    /// // Check for double-click
    /// if mouse.click_tracker().is_double_click(10, 5) {
    ///     println!("Double-click detected!");
    /// }
    /// ```
    pub fn click_tracker(&self) -> &ClickTracker {
        &self.click_tracker
    }

    /// Returns a mutable reference to the click tracker for configuration.
    ///
    /// This allows you to customize double-click thresholds.
    pub fn click_tracker_mut(&mut self) -> &mut ClickTracker {
        &mut self.click_tracker
    }

    /// Sets whether to invert vertical scrolling (natural scrolling).
    ///
    /// When enabled, positive deltas scroll down and negative deltas scroll up,
    /// matching the "natural" scrolling behavior common on trackpads.
    ///
    /// # Arguments
    ///
    /// * `invert` - `true` to enable natural scrolling, `false` for traditional
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::input::MouseHandler;
    ///
    /// let mut mouse = MouseHandler::new();
    /// mouse.set_invert_scroll_vertical(true); // Enable natural scrolling
    /// ```
    pub fn set_invert_scroll_vertical(&mut self, invert: bool) {
        self.invert_scroll_vertical = invert;
    }

    /// Returns whether vertical scrolling is inverted.
    pub fn is_scroll_vertical_inverted(&self) -> bool {
        self.invert_scroll_vertical
    }

    /// Sets whether to invert horizontal scrolling.
    ///
    /// When enabled, positive deltas scroll left and negative deltas scroll right.
    ///
    /// # Arguments
    ///
    /// * `invert` - `true` to invert horizontal scrolling, `false` for normal
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::input::MouseHandler;
    ///
    /// let mut mouse = MouseHandler::new();
    /// mouse.set_invert_scroll_horizontal(true);
    /// ```
    pub fn set_invert_scroll_horizontal(&mut self, invert: bool) {
        self.invert_scroll_horizontal = invert;
    }

    /// Returns whether horizontal scrolling is inverted.
    pub fn is_scroll_horizontal_inverted(&self) -> bool {
        self.invert_scroll_horizontal
    }

    /// Polls for mouse input without blocking.
    ///
    /// This method immediately checks if mouse input is available and returns
    /// the result. It never blocks execution, making it perfect for game loops
    /// and real-time applications.
    ///
    /// # Returns
    ///
    /// - `Ok(Some(Event))` - Mouse input was available and has been converted to an event
    /// - `Ok(None)` - No mouse input is currently available
    /// - `Err(...)` - An error occurred while checking for input
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::input::MouseHandler;
    /// use minui::{Event, MouseButton};
    ///
    /// let mouse = MouseHandler::new();
    ///
    /// match mouse.poll()? {
    ///     Some(Event::MouseClick { x, y, button }) => {
    ///         println!("Click at ({}, {}) with {:?}", x, y, button);
    ///     },
    ///     Some(Event::MouseMove { x, y }) => {
    ///         println!("Mouse at ({}, {})", x, y);
    ///     },
    ///     Some(event) => println!("Other event: {:?}", event),
    ///     None => {}, // No input available
    /// }
    /// # Ok::<(), minui::Error>(())
    /// ```
    pub fn poll(&mut self) -> Result<Option<Event>> {
        if event::poll(self.poll_rate)? {
            if let CrosstermEvent::Mouse(mouse_event) = event::read()? {
                let converted_event = self.convert_mouse_event(mouse_event);

                // Coalesce scroll events to handle fast scroll wheels
                if self.is_scroll_event(&converted_event) {
                    return Ok(Some(self.coalesce_scroll_events(converted_event)?));
                }

                return Ok(Some(converted_event));
            }
        }
        Ok(None)
    }

    /// Waits for mouse input with a timeout.
    ///
    /// This method blocks execution for up to the specified timeout duration,
    /// waiting for mouse input. If input is received within the timeout,
    /// it's converted to an event and returned. If the timeout expires without
    /// input, `None` is returned.
    ///
    /// # Arguments
    ///
    /// * `timeout` - Maximum duration to wait for input
    ///
    /// # Returns
    ///
    /// - `Ok(Some(Event))` - Mouse input was received within the timeout
    /// - `Ok(None)` - Timeout expired without input
    /// - `Err(...)` - An error occurred while waiting for input
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::input::MouseHandler;
    /// use minui::Event;
    /// use std::time::Duration;
    ///
    /// let mut mouse = MouseHandler::new();
    ///
    /// // Wait up to 1 second for mouse input
    /// match mouse.get_input(Duration::from_secs(1))? {
    ///     Some(Event::MouseClick { x, y, .. }) => {
    ///         println!("Got click at ({}, {})", x, y);
    ///     },
    ///     Some(event) => println!("Got event: {:?}", event),
    ///     None => println!("Timeout - no mouse input"),
    /// }
    /// # Ok::<(), minui::Error>(())
    /// ```
    pub fn get_input(&mut self, timeout: Duration) -> Result<Option<Event>> {
        if event::poll(timeout)? {
            if let CrosstermEvent::Mouse(mouse_event) = event::read()? {
                return Ok(Some(self.convert_mouse_event(mouse_event)));
            }
        }
        Ok(None)
    }

    /// Waits indefinitely for mouse input.
    ///
    /// This method blocks execution until mouse input is available.
    /// It will wait forever if necessary.
    ///
    /// # Returns
    ///
    /// - `Ok(Event)` - Mouse input was received and converted to an event
    /// - `Err(...)` - An error occurred while waiting for input
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::input::MouseHandler;
    /// use minui::Event;
    ///
    /// let mut mouse = MouseHandler::new();
    ///
    /// println!("Click anywhere to continue...");
    /// let event = mouse.wait_for_input()?;
    /// println!("Got input: {:?}", event);
    /// # Ok::<(), minui::Error>(())
    /// ```
    pub fn wait_for_input(&mut self) -> Result<Event> {
        loop {
            if let CrosstermEvent::Mouse(mouse_event) = event::read()? {
                return Ok(self.convert_mouse_event(mouse_event));
            }
        }
    }

    /// Converts a crossterm mouse event to a MinUI event.
    ///
    /// This internal method handles the conversion from crossterm's mouse event
    /// format to MinUI's event types, including drag detection logic.
    ///
    /// # Arguments
    ///
    /// * `mouse_event` - The crossterm mouse event to convert
    ///
    /// # Returns
    ///
    /// The corresponding MinUI Event.
    fn convert_mouse_event(&mut self, mouse_event: MouseEvent) -> Event {
        let x = mouse_event.column;
        let y = mouse_event.row;

        match mouse_event.kind {
            MouseEventKind::Down(button) => {
                let minui_button = self.convert_mouse_button(button);

                // Track click position for drag detection
                if self.drag_detection {
                    self.last_click_pos = Some((x, y));
                    self.is_dragging = false;
                }

                Event::MouseClick {
                    x,
                    y,
                    button: minui_button,
                }
            }
            MouseEventKind::Up(button) => {
                let minui_button = self.convert_mouse_button(button);

                // End drag operation
                if self.drag_detection {
                    self.is_dragging = false;
                    self.last_click_pos = None;
                }

                Event::MouseRelease {
                    x,
                    y,
                    button: minui_button,
                }
            }
            MouseEventKind::Drag(button) => {
                let minui_button = self.convert_mouse_button(button);

                // Mark as dragging if drag detection is enabled
                if self.drag_detection && self.last_click_pos.is_some() {
                    self.is_dragging = true;
                }

                Event::MouseDrag {
                    x,
                    y,
                    button: minui_button,
                }
            }
            MouseEventKind::Moved => {
                // Only generate move events if movement tracking is enabled
                if self.track_movement {
                    // Update drag state if drag detection is enabled
                    if self.drag_detection && self.last_click_pos.is_some() {
                        self.is_dragging = true;
                    }

                    Event::MouseMove { x, y }
                } else {
                    Event::Unknown
                }
            }
            MouseEventKind::ScrollDown => self.handle_scroll(ScrollDirection::Vertical, 1),
            MouseEventKind::ScrollUp => self.handle_scroll(ScrollDirection::Vertical, -1),
            MouseEventKind::ScrollLeft => self.handle_scroll(ScrollDirection::Horizontal, 1),
            MouseEventKind::ScrollRight => self.handle_scroll(ScrollDirection::Horizontal, -1),
        }
    }

    /// Converts a crossterm mouse button to a MinUI mouse button.
    ///
    /// # Arguments
    ///
    /// * `button` - The crossterm mouse button to convert
    ///
    /// # Returns
    ///
    /// The corresponding MinUI MouseButton.
    fn convert_mouse_button(&self, button: CrosstermMouseButton) -> MouseButton {
        match button {
            CrosstermMouseButton::Left => MouseButton::Left,
            CrosstermMouseButton::Right => MouseButton::Right,
            CrosstermMouseButton::Middle => MouseButton::Middle,
        }
    }

    /// Handles scroll events with direction buffering to prevent cross-axis noise.
    ///
    /// This maintains a buffer that requires 2 consecutive scroll events in the
    /// opposite direction before switching scroll axes, preventing accidental
    /// cross-axis scrolling.
    fn handle_scroll(&mut self, direction: ScrollDirection, delta: i8) -> Event {
        const BUFFER_THRESHOLD: u8 = 2;

        match self.last_scroll_direction {
            None => {
                // First scroll event, set the direction
                self.last_scroll_direction = Some(direction);
                self.scroll_buffer_count = 0;
                self.emit_scroll_event(direction, delta)
            }
            Some(last_dir) if last_dir == direction => {
                // Same direction, reset buffer and emit
                self.scroll_buffer_count = 0;
                self.emit_scroll_event(direction, delta)
            }
            Some(_) => {
                // Different direction, increment buffer
                self.scroll_buffer_count += 1;

                if self.scroll_buffer_count >= BUFFER_THRESHOLD {
                    // Buffer threshold reached, switch direction
                    self.last_scroll_direction = Some(direction);
                    self.scroll_buffer_count = 0;
                    self.emit_scroll_event(direction, delta)
                } else {
                    // Still in buffer, emit in the previous direction
                    self.emit_scroll_event(self.last_scroll_direction.unwrap(), delta)
                }
            }
        }
    }

    /// Emits the appropriate scroll event for the given direction and delta.
    fn emit_scroll_event(&self, direction: ScrollDirection, delta: i8) -> Event {
        match direction {
            ScrollDirection::Vertical => {
                let final_delta = if self.invert_scroll_vertical {
                    -delta
                } else {
                    delta
                };
                Event::MouseScroll { delta: final_delta }
            }
            ScrollDirection::Horizontal => {
                let final_delta = if self.invert_scroll_horizontal {
                    -delta
                } else {
                    delta
                };
                Event::MouseScrollHorizontal { delta: final_delta }
            }
        }
    }

    /// Checks if an event is a scroll event.
    fn is_scroll_event(&self, event: &Event) -> bool {
        matches!(
            event,
            Event::MouseScroll { .. } | Event::MouseScrollHorizontal { .. }
        )
    }

    /// Coalesces multiple rapid scroll events into a single event.
    ///
    /// This drains the event queue of any additional scroll events in the same
    /// direction, preventing scroll buffer buildup on fast scroll wheels.
    fn coalesce_scroll_events(&mut self, initial_event: Event) -> Result<Event> {
        let mut total_delta = match initial_event {
            Event::MouseScroll { delta } => (delta, 0),
            Event::MouseScrollHorizontal { delta } => (0, delta),
            _ => return Ok(initial_event),
        };

        // Drain any additional pending scroll events
        while event::poll(Duration::from_millis(0))? {
            if let Ok(CrosstermEvent::Mouse(mouse_event)) = event::read() {
                let next_event = self.convert_mouse_event(mouse_event);
                match next_event {
                    Event::MouseScroll { delta } => {
                        total_delta.0 += delta;
                    }
                    Event::MouseScrollHorizontal { delta } => {
                        total_delta.1 += delta;
                    }
                    _ => {
                        // Not a scroll event, we're done coalescing
                        // Note: This event is lost, but that's acceptable for the
                        // improved scroll experience
                        break;
                    }
                }
            } else {
                break;
            }
        }

        // Return the coalesced event
        // Prioritize vertical scroll if both are present
        if total_delta.0 != 0 {
            Ok(Event::MouseScroll {
                delta: total_delta.0,
            })
        } else if total_delta.1 != 0 {
            Ok(Event::MouseScrollHorizontal {
                delta: total_delta.1,
            })
        } else {
            Ok(initial_event)
        }
    }

    /// Converts a crossterm MouseEvent to a MinUI Event.
    ///
    /// This public method allows external code to process mouse events through
    /// the mouse handler, applying drag detection logic if configured.
    ///
    /// # Arguments
    ///
    /// * `mouse_event` - The crossterm mouse event to convert
    ///
    /// # Returns
    ///
    /// The corresponding MinUI Event.
    pub fn process_mouse_event(&mut self, mouse_event: MouseEvent) -> Event {
        self.convert_mouse_event(mouse_event)
    }
}

impl Default for MouseHandler {
    fn default() -> Self {
        Self::new()
    }
}

/// Combined input handler for both keyboard and mouse input.
///
/// This convenience struct allows handling both keyboard and mouse input
/// from a single interface, which is useful for applications that need
/// comprehensive input handling.
///
/// # Examples
///
/// ```rust
/// use minui::input::CombinedInputHandler;
/// use minui::Event;
///
/// let mut input = CombinedInputHandler::new();
///
/// if let Some(event) = input.poll()? {
///     match event {
///         Event::Character(c) => println!("Typed: {}", c),
///         Event::MouseClick { x, y, .. } => println!("Clicked at ({}, {})", x, y),
///         Event::KeyUp => println!("Up arrow pressed"),
///         _ => println!("Other input: {:?}", event),
///     }
/// }
/// # Ok::<(), minui::Error>(())
/// ```
pub struct CombinedInputHandler {
    keyboard: crate::input::KeyboardHandler,
    mouse: MouseHandler,
}

impl CombinedInputHandler {
    /// Creates a new combined input handler.
    ///
    /// Both keyboard and mouse handlers are initialized with their default settings.
    pub fn new() -> Self {
        Self {
            keyboard: crate::input::KeyboardHandler::new(),
            mouse: MouseHandler::new(),
        }
    }

    /// Creates a new combined input handler with common keybinds.
    ///
    /// The keyboard handler is initialized with common keybinds,
    /// and the mouse handler uses default settings.
    pub fn with_common_keybinds() -> Self {
        Self {
            keyboard: crate::input::KeyboardHandler::with_common_keybinds(),
            mouse: MouseHandler::new(),
        }
    }

    /// Returns a mutable reference to the keyboard handler.
    ///
    /// This allows configuration of keyboard-specific settings.
    pub fn keyboard_mut(&mut self) -> &mut crate::input::KeyboardHandler {
        &mut self.keyboard
    }

    /// Returns a mutable reference to the mouse handler.
    ///
    /// This allows configuration of mouse-specific settings.
    pub fn mouse_mut(&mut self) -> &mut MouseHandler {
        &mut self.mouse
    }

    /// Polls for any input (keyboard or mouse) without blocking.
    ///
    /// This method checks both keyboard and mouse input sources and returns
    /// the first available event, prioritizing keyboard input.
    ///
    /// # Returns
    ///
    /// - `Ok(Some(Event))` - Input was available from either source
    /// - `Ok(None)` - No input is currently available
    /// - `Err(...)` - An error occurred while checking for input
    pub fn poll(&mut self) -> Result<Option<Event>> {
        // Check keyboard first
        if let Some(event) = self.keyboard.poll_with_keybinds()? {
            return Ok(Some(event));
        }

        // Then check mouse
        if let Ok(Some(event)) = self.mouse.poll() {
            return Ok(Some(event));
        }
        Ok(None)
    }

    /// Waits for any input (keyboard or mouse) with a timeout.
    ///
    /// This method waits for input from either keyboard or mouse sources
    /// up to the specified timeout.
    ///
    /// # Arguments
    ///
    /// * `timeout` - Maximum duration to wait for input
    ///
    /// # Returns
    ///
    /// - `Ok(Some(Event))` - Input was received within the timeout
    /// - `Ok(None)` - Timeout expired without input
    /// - `Err(...)` - An error occurred while waiting for input
    pub fn get_input(&mut self, timeout: Duration) -> Result<Option<Event>> {
        // Check keyboard first with the timeout
        let keyboard_event = self.keyboard.get_input(timeout)?;
        if keyboard_event != Event::Unknown {
            return Ok(Some(keyboard_event));
        }

        // If keyboard timed out, try mouse with remaining time (simplified to same timeout)
        self.mouse.get_input(timeout)
    }
}

impl Default for CombinedInputHandler {
    fn default() -> Self {
        Self::new()
    }
}