minui 0.3.0

A minimalist Rust framework for TUIs and terminal games.
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
//! # Terminal Window
//!
//! The [`Window`] trait provides the drawing interface, and [`TerminalWindow`] is the
//! main implementation that handles the actual terminal. It manages buffered rendering,
//! input handling, and automatic cleanup.
//!
//! ## Features
//!
//! - Cross-platform terminal control (Windows, macOS, Linux)
//! - Buffered rendering for smooth updates
//! - Full color support (RGB, ANSI, named colors)
//! - Keyboard and mouse input handling
//! - Automatic terminal state restoration
//!
//! ## Basic Usage
//!
//! ```rust
//! use minui::{TerminalWindow, Window, ColorPair, Color};
//!
//! let mut window = TerminalWindow::new()?;
//!
//! // Write text
//! window.write_str(0, 0, "Hello, World!")?;
//!
//! // Write colored text
//! let colors = ColorPair::new(Color::Yellow, Color::Blue);
//! window.write_str_colored(1, 0, "Colored text!", colors)?;
//!
//! // Get terminal size
//! let (width, height) = window.get_size();
//!
//! // Handle input
//! if let Some(event) = window.poll_input()? {
//!     // Process the event
//! }
//! # Ok::<(), minui::Error>(())
//! ```

use crate::input::{KeyboardHandler, MouseHandler};
use crate::render::buffer::Buffer;
use crate::{ColorPair, Error, Event, Result};
use crossterm::{
    cursor,
    event::{self, DisableMouseCapture, EnableMouseCapture, Event as CrosstermEvent},
    execute,
    style::{self, SetBackgroundColor, SetForegroundColor},
    terminal::{self, disable_raw_mode, enable_raw_mode},
};
use std::io::{Write, stdout};
use std::time::Duration;

/// The core drawing interface for all UI components.
///
/// Provides methods for writing text, colors, clearing areas, and getting terminal dimensions.
/// Coordinates start at (0, 0) in the top-left corner.
pub trait Window {
    /// Writes a string to the window at the specified coordinates.
    ///
    /// This method draws text using the terminal's default colors. The text
    /// is drawn starting at position (x, y) using terminal character coordinates.
    ///
    /// # Arguments
    ///
    /// * `y` - The row position (0-indexed from top)
    /// * `x` - The column position (0-indexed from left)
    /// * `s` - The string to write
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` on success, or an error if the coordinates are out of bounds
    /// or if the write operation fails.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::{TerminalWindow, Window};
    ///
    /// let mut window = TerminalWindow::new()?;
    /// window.write_str(0, 0, "Hello, World!")?;
    /// # Ok::<(), minui::Error>(())
    /// ```
    fn write_str(&mut self, y: u16, x: u16, s: &str) -> Result<()>;

    /// Writes a colored string to the window at the specified coordinates.
    ///
    /// This method draws text with custom foreground and background colors.
    /// The text is drawn starting at position (x, y) using terminal character coordinates.
    ///
    /// # Arguments
    ///
    /// * `y` - The row position (0-indexed from top)
    /// * `x` - The column position (0-indexed from left)
    /// * `s` - The string to write
    /// * `colors` - The color pair defining foreground and background colors
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` on success, or an error if the coordinates are out of bounds
    /// or if the write operation fails.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::{TerminalWindow, Window, Color, ColorPair};
    ///
    /// let mut window = TerminalWindow::new()?;
    /// let colors = ColorPair::new(Color::Red, Color::Yellow);
    /// window.write_str_colored(1, 0, "Colored text!", colors)?;
    /// # Ok::<(), minui::Error>(())
    /// ```
    fn write_str_colored(&mut self, y: u16, x: u16, s: &str, colors: ColorPair) -> Result<()>;

    /// Returns the dimensions of the window as (width, height).
    ///
    /// The dimensions represent the number of character positions available
    /// in the terminal window.
    ///
    /// # Returns
    ///
    /// A tuple containing (width, height) in terminal character units.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::{TerminalWindow, Window};
    ///
    /// let window = TerminalWindow::new()?;
    /// let (width, height) = window.get_size();
    /// println!("Terminal is {} columns by {} rows", width, height);
    /// # Ok::<(), minui::Error>(())
    /// ```
    fn get_size(&self) -> (u16, u16);

    /// Clears the entire window.
    ///
    /// This method fills the entire window with spaces, effectively clearing
    /// all visible content. The cursor position is not affected.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` on success, or an error if the clear operation fails.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::{TerminalWindow, Window};
    ///
    /// let mut window = TerminalWindow::new()?;
    /// window.write_str(0, 0, "This will be cleared")?;
    /// window.clear_screen()?; // Screen is now blank
    /// # Ok::<(), minui::Error>(())
    /// ```
    fn clear_screen(&mut self) -> Result<()>;

    /// Clears a single line in the window.
    ///
    /// This method fills the specified line with spaces, clearing all content
    /// on that row.
    ///
    /// # Arguments
    ///
    /// * `y` - The row to clear (0-indexed from top)
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` on success, or an error if the line is out of bounds
    /// or if the clear operation fails.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::{TerminalWindow, Window};
    ///
    /// let mut window = TerminalWindow::new()?;
    /// window.write_str(5, 0, "This line will be cleared")?;
    /// window.clear_line(5)?; // Line 5 is now blank
    /// # Ok::<(), minui::Error>(())
    /// ```
    fn clear_line(&mut self, y: u16) -> Result<()>;

    /// Clears a rectangular area within the window.
    ///
    /// This method clears all content within the rectangle defined by the
    /// two corner points. The coordinates can be provided in any order.
    ///
    /// # Arguments
    ///
    /// * `y1` - First corner row coordinate
    /// * `x1` - First corner column coordinate
    /// * `y2` - Second corner row coordinate
    /// * `x2` - Second corner column coordinate
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` on success, or an error if any coordinates are out of bounds
    /// or if the clear operation fails.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::{TerminalWindow, Window};
    ///
    /// let mut window = TerminalWindow::new()?;
    /// // Clear a 10x5 rectangle starting at (2, 1)
    /// window.clear_area(1, 2, 5, 11)?;
    /// # Ok::<(), minui::Error>(())
    /// ```
    fn clear_area(&mut self, y1: u16, x1: u16, y2: u16, x2: u16) -> Result<()>;
}

/// A terminal window implementation using crossterm for cross-platform terminal control.
///
/// `TerminalWindow` provides a complete terminal-based window with buffered rendering,
/// input handling, and automatic terminal state management. It uses crossterm internally
/// for cross-platform compatibility.
///
/// # Features
///
/// - **Buffered Rendering**: All drawing operations are buffered and only sent to the
///   terminal when explicitly flushed or when auto-flush is enabled
/// - **Alternate Screen**: Uses the terminal's alternate screen buffer to avoid
///   disrupting the user's terminal session
/// - **Input Handling**: Integrated keyboard and mouse input processing with multiple
///   input modes (blocking, non-blocking, timeout-based)
/// - **Automatic Cleanup**: Properly restores terminal state when dropped
/// - **Color Support**: Full support for RGB, ANSI, and named colors
///
/// # Coordinate System
///
/// - (0, 0) is the top-left corner
/// - X coordinates increase to the right
/// - Y coordinates increase downward
/// - All coordinates are in terminal character units
///
/// # Examples
///
/// ## Basic Usage
///
/// ```rust
/// use minui::{TerminalWindow, Window};
///
/// let mut window = TerminalWindow::new()?;
/// let (width, height) = window.get_size();
///
/// // Draw a border around the terminal
/// let border = "+";
/// for x in 0..width {
///     window.write_str(0, x, border)?; // Top border
///     window.write_str(height - 1, x, border)?; // Bottom border
/// }
/// for y in 0..height {
///     window.write_str(y, 0, border)?; // Left border
///     window.write_str(y, width - 1, border)?; // Right border
/// }
/// # Ok::<(), minui::Error>(())
/// ```
///
/// ## Manual Flush Control
///
/// ```rust
/// use minui::TerminalWindow;
///
/// let mut window = TerminalWindow::new()?;
/// window.set_auto_flush(false); // Disable automatic flushing
///
/// // Multiple operations without terminal updates
/// window.write_str(0, 0, "Line 1")?;
/// window.write_str(1, 0, "Line 2")?;
/// window.write_str(2, 0, "Line 3")?;
///
/// // All changes rendered at once
/// window.flush()?;
/// # Ok::<(), minui::Error>(())
/// ```
pub struct TerminalWindow {
    width: u16,
    height: u16,
    buffer: Buffer,
    auto_flush: bool,
    keyboard: KeyboardHandler,
    mouse: MouseHandler,
}

impl TerminalWindow {
    /// Creates a new terminal window with full-screen access.
    ///
    /// This constructor initializes a terminal window by:
    /// - Enabling raw mode for direct input handling
    /// - Switching to the alternate screen buffer
    /// - Hiding the cursor
    /// - Clearing the screen
    /// - Setting up internal buffers and input handlers
    ///
    /// The window will automatically restore the terminal state when dropped.
    ///
    /// # Returns
    ///
    /// Returns a new `TerminalWindow` instance, or an error if terminal
    /// initialization fails.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::TerminalWindow;
    ///
    /// let window = TerminalWindow::new()?;
    /// // Terminal is now in full-screen mode with raw input
    /// # Ok::<(), minui::Error>(())
    /// ```
    pub fn new() -> Result<Self> {
        enable_raw_mode()?;

        let (cols, rows) = terminal::size()?;

        execute!(
            stdout(),
            terminal::EnterAlternateScreen, // Use separate screen buffer
            terminal::Clear(terminal::ClearType::All),
            cursor::Hide,
            cursor::MoveTo(0, 0),
            EnableMouseCapture // Enable mouse event capture
        )?;

        Ok(Self {
            width: cols,
            height: rows,
            buffer: Buffer::new(cols, rows),
            auto_flush: true,
            keyboard: KeyboardHandler::new(),
            mouse: MouseHandler::new(),
        })
    }

    /// Immediately clears the entire terminal screen.
    ///
    /// This method bypasses the internal buffer and directly clears the terminal.
    /// It's different from `clear_screen()` which uses the buffered approach.
    /// Use this for immediate clearing operations.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` on success, or an error if the clear operation fails.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::TerminalWindow;
    ///
    /// let window = TerminalWindow::new()?;
    /// window.clear()?; // Screen cleared immediately
    /// # Ok::<(), minui::Error>(())
    /// ```
    pub fn clear(&self) -> Result<()> {
        execute!(
            stdout(),
            terminal::Clear(terminal::ClearType::All),
            cursor::MoveTo(0, 0)
        )?;
        Ok(())
    }

    /// Gets input with a default 100ms timeout.
    ///
    /// This is a convenience method that waits up to 100ms for user input.
    /// If no input is available within the timeout, it returns a timeout error.
    ///
    /// # Returns
    ///
    /// Returns the input `Event` if available within 100ms, or an error if
    /// no input is received or if an input error occurs.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::{TerminalWindow, Event};
    ///
    /// let window = TerminalWindow::new()?;
    /// match window.get_input() {
    ///     Ok(Event::Character(c)) => println!("Got character: {}", c),
    ///     Ok(event) => println!("Got event: {:?}", event),
    ///     Err(_) => println!("No input within 100ms"),
    /// }
    /// # Ok::<(), minui::Error>(())
    /// ```
    pub fn get_input(&self) -> Result<Event> {
        self.keyboard.get_input(Duration::from_millis(100))
    }

    /// Gets input with a custom timeout duration.
    ///
    /// This method waits up to the specified duration for user input.
    /// Use this when you need precise control over input timing.
    ///
    /// # Arguments
    ///
    /// * `timeout` - Maximum duration to wait for input
    ///
    /// # Returns
    ///
    /// Returns the input `Event` if available within the timeout, or an error if
    /// no input is received or if an input error occurs.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::TerminalWindow;
    /// use std::time::Duration;
    ///
    /// let window = TerminalWindow::new()?;
    ///
    /// // Wait up to 2 seconds for input
    /// match window.get_input_timeout(Duration::from_secs(2)) {
    ///     Ok(event) => println!("Received: {:?}", event),
    ///     Err(_) => println!("No input within 2 seconds"),
    /// }
    /// # Ok::<(), minui::Error>(())
    /// ```
    pub fn get_input_timeout(&mut self, timeout: Duration) -> Result<Event> {
        // Use crossterm's unified event system to handle both keyboard and mouse
        if event::poll(timeout)? {
            match event::read()? {
                CrosstermEvent::Key(key_event) => Ok(self.keyboard.process_key_event(key_event)),
                CrosstermEvent::Mouse(mouse_event) => {
                    Ok(self.mouse.process_mouse_event(mouse_event))
                }
                CrosstermEvent::Resize(cols, rows) => Ok(Event::Resize {
                    width: cols,
                    height: rows,
                }),
                _ => Ok(Event::Unknown),
            }
        } else {
            Ok(Event::Unknown)
        }
    }

    /// Waits indefinitely for user input.
    ///
    /// This method blocks until user input is available. Use this when you
    /// need to wait for user interaction without any time constraints.
    ///
    /// # Returns
    ///
    /// Returns the input `Event` when available, or an error if an input error occurs.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::{TerminalWindow, Event};
    ///
    /// let window = TerminalWindow::new()?;
    ///
    /// println!("Press any key to continue...");
    /// let event = window.wait_for_input()?;
    /// println!("You pressed: {:?}", event);
    /// # Ok::<(), minui::Error>(())
    /// ```
    pub fn wait_for_input(&mut self) -> Result<Event> {
        // Use crossterm's unified event system to handle both keyboard and mouse
        loop {
            match event::read()? {
                CrosstermEvent::Key(key_event) => {
                    return Ok(self.keyboard.process_key_event(key_event));
                }
                CrosstermEvent::Mouse(mouse_event) => {
                    return Ok(self.mouse.process_mouse_event(mouse_event));
                }
                CrosstermEvent::Resize(cols, rows) => {
                    return Ok(Event::Resize {
                        width: cols,
                        height: rows,
                    });
                }
                _ => continue,
            }
        }
    }

    /// Polls for input without blocking.
    ///
    /// This method immediately returns whether input is available or not.
    /// Use this for non-blocking input checking in game loops or real-time applications.
    ///
    /// # Returns
    ///
    /// Returns `Some(Event)` if input is immediately available, `None` if no input
    /// is available, or an error if an input error occurs.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::TerminalWindow;
    ///
    /// let window = TerminalWindow::new()?;
    ///
    /// loop {
    ///     if let Some(event) = window.poll_input()? {
    ///         println!("Got immediate input: {:?}", event);
    ///         break;
    ///     }
    ///     // Do other work...
    ///     std::thread::sleep(std::time::Duration::from_millis(16));
    /// }
    /// # Ok::<(), minui::Error>(())
    /// ```
    pub fn poll_input(&mut self) -> Result<Option<Event>> {
        // Check mouse input first (more interactive)
        if let Some(event) = self.mouse.poll()? {
            return Ok(Some(event));
        }
        // Then check keyboard input
        self.keyboard.poll()
    }

    /// Gets a reference to the keyboard handler for advanced configuration.
    ///
    /// This provides access to the underlying keyboard handler for advanced
    /// input configuration and monitoring.
    ///
    /// # Returns
    ///
    /// Returns a reference to the internal `KeyboardHandler`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::TerminalWindow;
    ///
    /// let window = TerminalWindow::new()?;
    /// let keyboard = window.keyboard();
    /// // Use keyboard for advanced operations
    /// # Ok::<(), minui::Error>(())
    /// ```
    pub fn keyboard(&self) -> &KeyboardHandler {
        &self.keyboard
    }

    /// Gets a mutable reference to the keyboard handler for configuration changes.
    ///
    /// This provides mutable access to the underlying keyboard handler for
    /// configuration modifications.
    ///
    /// # Returns
    ///
    /// Returns a mutable reference to the internal `KeyboardHandler`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::TerminalWindow;
    ///
    /// let mut window = TerminalWindow::new()?;
    /// let keyboard = window.keyboard_mut();
    /// // Configure keyboard settings
    /// # Ok::<(), minui::Error>(())
    /// ```
    pub fn keyboard_mut(&mut self) -> &mut KeyboardHandler {
        &mut self.keyboard
    }

    /// Gets a reference to the mouse handler for advanced configuration.
    ///
    /// This provides access to the underlying mouse handler for advanced
    /// input configuration and monitoring.
    ///
    /// # Returns
    ///
    /// Returns a reference to the internal `MouseHandler`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::TerminalWindow;
    ///
    /// let window = TerminalWindow::new()?;
    /// let mouse = window.mouse();
    /// // Use mouse for advanced operations
    /// # Ok::<(), minui::Error>(())
    /// ```
    pub fn mouse(&self) -> &MouseHandler {
        &self.mouse
    }

    /// Gets a mutable reference to the mouse handler for configuration changes.
    ///
    /// This provides mutable access to the underlying mouse handler for
    /// configuration modifications.
    ///
    /// # Returns
    ///
    /// Returns a mutable reference to the internal `MouseHandler`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::TerminalWindow;
    ///
    /// let mut window = TerminalWindow::new()?;
    /// let mouse = window.mouse_mut();
    /// mouse.enable_drag_detection(true);
    /// # Ok::<(), minui::Error>(())
    /// ```
    pub fn mouse_mut(&mut self) -> &mut MouseHandler {
        &mut self.mouse
    }

    /// Controls automatic buffer flushing behavior.
    ///
    /// When auto-flush is enabled (default), all drawing operations immediately
    /// update the terminal. When disabled, you must manually call `flush()` to
    /// render buffered changes.
    ///
    /// Disabling auto-flush can improve performance when making many drawing
    /// operations, as it allows batching multiple changes into a single render.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to enable automatic flushing after each drawing operation
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::{TerminalWindow, Window};
    ///
    /// let mut window = TerminalWindow::new()?;
    ///
    /// // Disable auto-flush for better performance
    /// window.set_auto_flush(false);
    ///
    /// // Multiple operations are buffered
    /// window.write_str(0, 0, "Line 1")?;
    /// window.write_str(1, 0, "Line 2")?;
    /// window.write_str(2, 0, "Line 3")?;
    ///
    /// // Render all changes at once
    /// window.flush()?;
    /// # Ok::<(), minui::Error>(())
    /// ```
    pub fn set_auto_flush(&mut self, enabled: bool) {
        self.auto_flush = enabled;
    }

    /// Manually flushes all buffered drawing operations to the terminal.
    ///
    /// This method processes all pending changes in the internal buffer and
    /// renders them to the terminal. It optimizes rendering by:
    /// - Only updating changed areas
    /// - Minimizing color change operations
    /// - Batching cursor movements
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` on successful flush, or an error if rendering fails.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::{TerminalWindow, Window};
    ///
    /// let mut window = TerminalWindow::new()?;
    /// window.set_auto_flush(false);
    ///
    /// // Buffer some operations
    /// window.write_str(0, 0, "Buffered text 1")?;
    /// window.write_str(1, 0, "Buffered text 2")?;
    ///
    /// // Nothing is visible yet
    /// window.flush()?; // Now both lines appear
    /// # Ok::<(), minui::Error>(())
    /// ```
    pub fn flush(&mut self) -> Result<()> {
        let changes = self.buffer.process_changes();
        let mut last_colors = None;

        for change in changes {
            // Move the cursor to the correct position for the change
            execute!(stdout(), cursor::MoveTo(change.x, change.y))?;

            if change.colors != last_colors {
                if let Some(colors) = change.colors {
                    // Set the foreground and background colors
                    execute!(
                        stdout(),
                        SetForegroundColor(colors.fg.to_crossterm()),
                        SetBackgroundColor(colors.bg.to_crossterm())
                    )?;
                } else {
                    // If there are no colors, reset to the default
                    execute!(stdout(), style::ResetColor)?;
                }
                last_colors = change.colors;
            }

            // Print the text for the change
            execute!(stdout(), style::Print(&change.text))?;
        }

        // Reset the color at the end of the flush
        execute!(stdout(), style::ResetColor)?;
        stdout().flush()?;
        Ok(())
    }
}

impl Window for TerminalWindow {
    fn write_str(&mut self, y: u16, x: u16, s: &str) -> Result<()> {
        if y >= self.height || x >= self.width {
            return Err(Error::OutOfBoundsError {
                x,
                y,
                width: self.width,
                height: self.height,
            });
        }

        self.buffer.write_str(y, x, s, None)?;

        if self.auto_flush {
            self.flush()?;
        }
        Ok(())
    }

    fn write_str_colored(&mut self, y: u16, x: u16, s: &str, colors: ColorPair) -> Result<()> {
        if y >= self.height || x >= self.width {
            return Err(Error::OutOfBoundsError {
                x,
                y,
                width: self.width,
                height: self.height,
            });
        }

        self.buffer.write_str(y, x, s, Some(colors))?;

        if self.auto_flush {
            self.flush()?;
        }
        Ok(())
    }

    fn get_size(&self) -> (u16, u16) {
        (self.width, self.height)
    }

    fn clear_screen(&mut self) -> Result<()> {
        self.buffer.clear();

        if self.auto_flush {
            self.flush()?;
        }
        Ok(())
    }

    fn clear_line(&mut self, y: u16) -> Result<()> {
        if y >= self.height {
            return Err(Error::LineOutOfBoundsError {
                y,
                height: self.height,
            });
        }

        self.buffer.clear_line(y)?;

        if self.auto_flush {
            self.flush()?;
        }
        Ok(())
    }

    fn clear_area(&mut self, y1: u16, x1: u16, y2: u16, x2: u16) -> Result<()> {
        // Validate all coordinates are within bounds
        if x1 >= self.width || x2 >= self.width || y1 >= self.height || y2 >= self.height {
            return Err(Error::BoxOutOfBoundsError {
                x1,
                y1,
                x2,
                y2,
                width: self.width,
                height: self.height,
            });
        }

        let (start_y, end_y) = if y1 <= y2 { (y1, y2) } else { (y2, y1) };
        let (start_x, end_x) = if x1 <= x2 { (x1, x2) } else { (x2, x1) };

        // Clear the area in the buffer
        for y in start_y..=end_y {
            let spaces = " ".repeat((end_x - start_x + 1) as usize);
            self.buffer.write_str(y, start_x, &spaces, None)?;
        }

        if self.auto_flush {
            self.flush()?;
        }
        Ok(())
    }
}

impl Drop for TerminalWindow {
    fn drop(&mut self) {
        let _ = disable_raw_mode();
        let _ = execute!(
            stdout(),
            DisableMouseCapture, // Disable mouse event capture
            style::ResetColor,
            terminal::Clear(terminal::ClearType::All),
            cursor::MoveTo(0, 0),
            cursor::Show,
            terminal::LeaveAlternateScreen
        );
        let _ = self.flush();
    }
}