minui 0.4.1

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
//! # Common Widget Utilities
//!
//! A collection of shared types, utilities, and building blocks used across all MinUI
//! widgets. This module provides the foundational components that enable consistent
//! visual styling and drawing operations throughout the widget system, including
//! comprehensive border character sets and window view management for constrained
//! rendering within specific areas.
//!
//! ## Features
//!
//! - **Rich border styles**: Unicode and ASCII-compatible border character sets
//! - **Flexible styling**: Support for single-line, double-line, and custom borders
//! - **Window constraints**: Bounded drawing areas for contained widget rendering
//! - **Cross-platform compatibility**: ASCII fallbacks for terminal compatibility
//! - **Consistent theming**: Standardized visual elements across all widgets
//! - **Drawing optimization**: Efficient rendering within specified boundaries
//!
//! ## Key Components
//!
//! ### BorderChars
//! Comprehensive character sets for drawing borders, frames, and decorative elements.
//! Provides predefined styles for different visual aesthetics and terminal capabilities.
//!
//! ### WindowView
//! A constrained view system that enables widgets to draw within specific rectangular
//! areas while automatically handling boundary clipping and coordinate translation.
//!
//! ## Visual Border Styles
//!
//! ```text
//! Single Line:              Double Line:              ASCII Compatible:
//! ┌─────────────────┐       ╔═══════════════════╗     +-------------------+
//! │     Content     │       ║      Content      ║     |      Content      |
//! ├─────────────────┤       ╠═══════════════════╣     +-------------------+
//! │   More Content  │       ║   More Content    ║     |   More Content    |
//! └─────────────────┘       ╚═══════════════════╝     +-------------------+
//! ```
//!
//! ## Basic Usage
//!
//! ```rust
//! use minui::{BorderChars, Panel};
//!
//! // Apply different border styles to widgets
//! let elegant_panel = Panel::new(30, 8)
//!     .with_header("Elegant Design")
//!     .with_header_style(BorderChars::single_line())
//!     .with_body_style(BorderChars::single_line());
//!
//! let bold_panel = Panel::new(30, 8)
//!     .with_header("Bold Design")
//!     .with_header_style(BorderChars::double_line())
//!     .with_body_style(BorderChars::double_line());
//!
//! let compatible_panel = Panel::new(30, 8)
//!     .with_header("Compatible Design")
//!     .with_header_style(BorderChars::ascii())
//!     .with_body_style(BorderChars::ascii());
//! ```
//!
//! ## Advanced Border Customization
//!
//! ```rust
//! use minui::{BorderChars, Panel};
//!
//! // Create custom border characters
//! let custom_border = BorderChars {
//!     top_left: '╭',
//!     top_right: '╮',
//!     bottom_left: '╰',
//!     bottom_right: '╯',
//!     horizontal: '─',
//!     vertical: '│',
//!     intersect: '┼',
//!     intersect_left: '┤',
//!     intersect_right: '├',
//!     intersect_top: '┴',
//!     intersect_bottom: '┬',
//! };
//!
//! // Use custom borders in widgets
//! let rounded_panel = Panel::new(25, 6)
//!     .with_header_style(custom_border)
//!     .with_body_style(custom_border);
//! ```
//!
//! ## Window View Usage
//! ## Constrained Drawing with WindowView
//!
//! ```rust
//! use minui::widgets::WindowView;
//! # use minui::{TerminalWindow, Window};
//! # let mut window = TerminalWindow::new().unwrap();
//!
//! // Create a constrained drawing area
//! let view = WindowView::new(&mut window, 10, 5, 40, 15);
//! // All drawing operations within this view are automatically
//! // clipped to the specified rectangular bounds
//! ```
//!
//! Common utilities form the foundation of MinUI's consistent visual design,
//! enabling widgets to share styling elements while maintaining flexibility
//! for custom appearances and cross-platform terminal compatibility.

use crate::{ColorPair, Result, Window};

/// Character sets for drawing borders, boxes, and frames.
///
/// `BorderChars` defines all the characters needed to draw complete borders
/// around widgets. It includes corner pieces, edges, and intersection characters
/// for creating complex layouts.
///
/// The struct provides predefined character sets for different visual styles:
/// - Unicode single-line borders (┌┐└┘─│)
/// - Unicode double-line borders (╔╗╚╝═║)
/// - ASCII-compatible borders (++-|)
///
/// # Examples
///
/// ```rust
/// use minui::BorderChars;
///
/// // Create different border styles
/// let elegant = BorderChars::single_line();
/// let bold = BorderChars::double_line();
/// let compatible = BorderChars::ascii();
///
/// // Use in widget creation
/// // let panel = Panel::new(20, 10)
/// //     .with_border_style(elegant);
/// ```
#[derive(Debug, Clone, Copy)]
pub struct BorderChars {
    /// Top-left corner character
    pub top_left: char,
    /// Top-right corner character
    pub top_right: char,
    /// Bottom-left corner character
    pub bottom_left: char,
    /// Bottom-right corner character
    pub bottom_right: char,
    /// Horizontal line character
    pub horizontal: char,
    /// Vertical line character
    pub vertical: char,
    /// Four-way intersection character
    pub intersect: char,
    /// Left T-junction character
    pub intersect_left: char,
    /// Right T-junction character
    pub intersect_right: char,
    /// Top T-junction character
    pub intersect_top: char,
    /// Bottom T-junction character
    pub intersect_bottom: char,
}

impl BorderChars {
    /// Creates a single-line Unicode border character set.
    ///
    /// This provides elegant thin borders using Unicode box-drawing characters.
    /// The style works well for modern terminals and provides a clean, professional look.
    ///
    /// Characters used: ┌┐└┘─│┼├┤┬┴
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::BorderChars;
    ///
    /// let border = BorderChars::single_line();
    /// assert_eq!(border.top_left, '┌');
    /// assert_eq!(border.horizontal, '─');
    /// ```
    pub const fn single_line() -> Self {
        Self {
            top_left: '',
            top_right: '',
            bottom_left: '',
            bottom_right: '',
            horizontal: '',
            vertical: '',
            intersect: '',
            intersect_left: '',
            intersect_right: '',
            intersect_top: '',
            intersect_bottom: '',
        }
    }

    /// Creates a double-line Unicode border character set.
    ///
    /// This provides bold, prominent borders using Unicode double-line box-drawing characters.
    /// The style is ideal for highlighting important sections or creating strong visual separation.
    ///
    /// Characters used: ╔╗╚╝═║╬╠╣╦╩
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::BorderChars;
    ///
    /// let border = BorderChars::double_line();
    /// assert_eq!(border.top_left, '╔');
    /// assert_eq!(border.horizontal, '═');
    /// ```
    pub const fn double_line() -> Self {
        Self {
            top_left: '',
            top_right: '',
            bottom_left: '',
            bottom_right: '',
            horizontal: '',
            vertical: '',
            intersect: '',
            intersect_left: '',
            intersect_right: '',
            intersect_top: '',
            intersect_bottom: '',
        }
    }

    /// Creates an ASCII-compatible border character set.
    ///
    /// This provides basic borders using only ASCII characters, ensuring compatibility
    /// with all terminals and text environments. While less visually appealing than
    /// Unicode alternatives, it works everywhere.
    ///
    /// Characters used: + (corners and intersections), - (horizontal), | (vertical)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::BorderChars;
    ///
    /// let border = BorderChars::ascii();
    /// assert_eq!(border.top_left, '+');
    /// assert_eq!(border.horizontal, '-');
    /// assert_eq!(border.vertical, '|');
    /// ```
    pub const fn ascii() -> Self {
        Self {
            top_left: '+',
            top_right: '+',
            bottom_left: '+',
            bottom_right: '+',
            horizontal: '-',
            vertical: '|',
            intersect: '+',
            intersect_left: '+',
            intersect_right: '+',
            intersect_top: '+',
            intersect_bottom: '+',
        }
    }
}

/// A constrained view of a window that provides bounded drawing operations.
///
/// `WindowView` acts as a "clipping rectangle" that restricts drawing operations
/// to a specific area within a larger window. This is essential for container widgets
/// that need to ensure their child widgets don't draw outside their boundaries.
///
/// All drawing operations are automatically translated and clipped:
/// - Coordinates are offset by the view's position
/// - Out-of-bounds operations are silently ignored
/// - The view appears as a complete window to child widgets
///
/// # Use Cases
///
/// - **Container Widgets**: Panels and containers use views to constrain child drawing
/// - **Scrolling**: Views can be used to implement scrollable content areas
/// - **Layout Management**: Complex layouts can use views for precise positioning
///
/// # Examples
///
/// ```rust
/// use minui::widgets::WindowView;
/// use minui::{TerminalWindow, Window};
/// # let mut window = TerminalWindow::new().unwrap();
///
/// // Create a view within a larger window
/// // let mut view = WindowView {
/// //     window: &mut main_window,
/// //     x_offset: 10,   // Start 10 columns from left
/// //     y_offset: 5,    // Start 5 rows from top
/// //     width: 20,      // 20 columns wide
/// //     height: 10,     // 10 rows tall
/// // };
///
/// // Drawing at (0, 0) in the view actually draws at (10, 5) in the main window
/// // view.write_str(0, 0, "Hello");
/// ```
pub struct WindowView<'a> {
    /// Reference to the underlying window
    pub window: &'a mut dyn Window,

    /// Horizontal offset from the parent window's origin (in parent window coordinates)
    pub x_offset: u16,
    /// Vertical offset from the parent window's origin (in parent window coordinates)
    pub y_offset: u16,

    /// Horizontal scroll offset applied to coordinates within this view.
    ///
    /// A scroll offset shifts the *content* left/up, which means drawing at (0,0) in the view
    /// targets the parent window at (x_offset - scroll_x, y_offset - scroll_y), with clipping.
    pub scroll_x: u16,
    /// Vertical scroll offset applied to coordinates within this view.
    pub scroll_y: u16,

    /// Width of the constrained drawing area
    pub width: u16,
    /// Height of the constrained drawing area
    pub height: u16,
}

impl<'a> Window for WindowView<'a> {
    fn write_str(&mut self, y: u16, x: u16, s: &str) -> Result<()> {
        if y >= self.height || x >= self.width {
            return Ok(()); // Silently skip out-of-bounds writes
        }

        // Apply scroll by shifting the content origin.
        // If the caller draws into scrolled-off space, skip safely.
        let local_x = match x.checked_sub(self.scroll_x) {
            Some(v) => v,
            None => return Ok(()),
        };
        let local_y = match y.checked_sub(self.scroll_y) {
            Some(v) => v,
            None => return Ok(()),
        };

        if local_y < self.height && local_x < self.width {
            // IMPORTANT: Clip the string to the view's remaining width.
            // Without this, writes can spill outside the view and corrupt neighboring UI
            // (especially visible after resizes).
            let max_cells = self.width.saturating_sub(local_x);
            let clipped =
                crate::text::clip_to_cells(s, max_cells, crate::text::TabPolicy::SingleCell);

            self.window
                .write_str(local_y + self.y_offset, local_x + self.x_offset, &clipped)
        } else {
            Ok(())
        }
    }

    fn write_str_colored(&mut self, y: u16, x: u16, s: &str, colors: ColorPair) -> Result<()> {
        if y >= self.height || x >= self.width {
            return Ok(()); // Silently skip out-of-bounds writes
        }

        let local_x = match x.checked_sub(self.scroll_x) {
            Some(v) => v,
            None => return Ok(()),
        };
        let local_y = match y.checked_sub(self.scroll_y) {
            Some(v) => v,
            None => return Ok(()),
        };

        if local_y < self.height && local_x < self.width {
            // IMPORTANT: Clip the string to the view's remaining width.
            let max_cells = self.width.saturating_sub(local_x);
            let clipped =
                crate::text::clip_to_cells(s, max_cells, crate::text::TabPolicy::SingleCell);

            self.window.write_str_colored(
                local_y + self.y_offset,
                local_x + self.x_offset,
                &clipped,
                colors,
            )
        } else {
            Ok(())
        }
    }

    fn flush(&mut self) -> Result<()> {
        self.window.flush()
    }

    fn set_cursor_position(&mut self, x: u16, y: u16) -> Result<()> {
        self.window.set_cursor_position(x, y)
    }

    fn show_cursor(&mut self, show: bool) -> Result<()> {
        self.window.show_cursor(show)
    }

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

    fn clear_screen(&mut self) -> Result<()> {
        if self.width == 0 || self.height == 0 {
            return Ok(());
        }

        self.window.clear_area(
            self.y_offset,
            self.x_offset,
            self.y_offset + self.height - 1,
            self.x_offset + self.width - 1,
        )
    }

    fn clear_line(&mut self, y: u16) -> Result<()> {
        if self.width == 0 || self.height == 0 {
            return Ok(());
        }

        if y < self.height {
            self.window.clear_area(
                self.y_offset + y,
                self.x_offset,
                self.y_offset + y,
                self.x_offset + self.width - 1,
            )
        } else {
            Ok(())
        }
    }

    fn clear_area(&mut self, y1: u16, x1: u16, y2: u16, x2: u16) -> Result<()> {
        if self.width == 0 || self.height == 0 {
            return Ok(());
        }

        if x1 >= self.width || x2 >= self.width || y1 >= self.height || y2 >= self.height {
            return Ok(());
        }

        let parent_x1 = self.x_offset + x1;
        let parent_x2 = self.x_offset + x2.min(self.width - 1);
        let parent_y1 = self.y_offset + y1;
        let parent_y2 = self.y_offset + y2.min(self.height - 1);

        self.window
            .clear_area(parent_y1, parent_x1, parent_y2, parent_x2)
    }
}