term39 0.6.0

A modern, retro-styled terminal multiplexer inspired by Norton Disk Doctor (MS-DOS)
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
use crate::charset::Charset;
use crate::theme::Theme;
use crate::video_buffer::{self, Cell, VideoBuffer};
use crossterm::style::Color;

/// Prompt types with different visual styles (similar to Bootstrap alerts)
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PromptType {
    #[allow(dead_code)]
    Info, // Blue theme
    #[allow(dead_code)]
    Success, // Green theme
    #[allow(dead_code)]
    Warning, // Yellow theme
    Danger, // Red theme
}

impl PromptType {
    /// Get the background color for this prompt type
    pub fn background_color(&self, theme: &Theme) -> Color {
        match self {
            PromptType::Info => theme.prompt_info_bg,
            PromptType::Success => theme.prompt_success_bg,
            PromptType::Warning => theme.prompt_warning_bg,
            PromptType::Danger => theme.prompt_danger_bg,
        }
    }

    /// Get the foreground color for this prompt type
    pub fn foreground_color(&self, theme: &Theme) -> Color {
        match self {
            PromptType::Info => theme.prompt_info_fg,
            PromptType::Success => theme.prompt_success_fg,
            PromptType::Warning => theme.prompt_warning_fg,
            PromptType::Danger => theme.prompt_danger_fg,
        }
    }
}

/// Button in a prompt
#[derive(Clone, Debug)]
pub struct PromptButton {
    pub text: String,
    pub action: PromptAction,
    pub is_primary: bool, // Primary buttons have attractive colors, secondary are muted
}

/// Action to take when a button is clicked
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PromptAction {
    Confirm,
    Cancel,
    #[allow(dead_code)]
    Custom(u32),
}

impl PromptButton {
    /// Create a new button
    pub fn new(text: String, action: PromptAction, is_primary: bool) -> Self {
        Self {
            text,
            action,
            is_primary,
        }
    }

    /// Get button colors based on whether it's primary
    pub fn colors(&self, prompt_type: PromptType, theme: &Theme) -> (Color, Color) {
        if self.is_primary {
            // Primary button: attractive colors based on prompt type
            match prompt_type {
                PromptType::Info => (
                    theme.dialog_button_primary_info_fg,
                    theme.dialog_button_primary_info_bg,
                ),
                PromptType::Success => (
                    theme.dialog_button_primary_success_fg,
                    theme.dialog_button_primary_success_bg,
                ),
                PromptType::Warning => (
                    theme.dialog_button_primary_warning_fg,
                    theme.dialog_button_primary_warning_bg,
                ),
                PromptType::Danger => (
                    theme.dialog_button_primary_danger_fg,
                    theme.dialog_button_primary_danger_bg,
                ),
            }
        } else {
            // Secondary button: muted colors
            (
                theme.dialog_button_secondary_fg,
                theme.dialog_button_secondary_bg,
            )
        }
    }

    /// Get the rendered width of the button (includes brackets and spaces)
    pub fn width(&self) -> u16 {
        // Format: [ Text ]
        self.text.len() as u16 + 4
    }
}

/// Text alignment for prompt messages
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TextAlign {
    #[allow(dead_code)]
    Left,
    Center,
}

/// A modal prompt dialog (no title bar, centered on screen)
pub struct Prompt {
    pub prompt_type: PromptType,
    pub message: String,
    pub buttons: Vec<PromptButton>,
    pub width: u16,
    pub height: u16,
    pub x: u16,
    pub y: u16,
    pub selected_button_index: usize, // Index of currently selected button for keyboard navigation
    pub text_align: TextAlign,        // Text alignment for the message
}

impl Prompt {
    /// Create a new prompt (auto-sized and centered) with center alignment
    pub fn new(
        prompt_type: PromptType,
        message: String,
        buttons: Vec<PromptButton>,
        buffer_width: u16,
        buffer_height: u16,
    ) -> Self {
        Self::new_with_alignment(
            prompt_type,
            message,
            buttons,
            buffer_width,
            buffer_height,
            TextAlign::Center,
        )
    }

    /// Create a new prompt (auto-sized and centered) with custom alignment
    pub fn new_with_alignment(
        prompt_type: PromptType,
        message: String,
        buttons: Vec<PromptButton>,
        buffer_width: u16,
        buffer_height: u16,
        text_align: TextAlign,
    ) -> Self {
        // Calculate dimensions
        let message_lines: Vec<&str> = message.lines().collect();

        // Strip color codes when calculating width
        let max_message_width = message_lines
            .iter()
            .map(|line| Self::strip_color_codes(line).len())
            .max()
            .unwrap_or(0) as u16;

        // Calculate total button width (with spacing)
        let total_button_width: u16 = buttons.iter().map(|b| b.width()).sum::<u16>()
            + (buttons.len().saturating_sub(1)) as u16 * 2; // 2 spaces between buttons

        // Width is max of message width and button width, plus padding
        let content_width = max_message_width.max(total_button_width);
        let width = content_width + 6; // 2 for padding on each side + 2 for borders

        // Height: message lines + padding + button row
        let height = message_lines.len() as u16 + 6; // 1 top padding + message + 1 padding + buttons + 1 padding + borders

        // Center on screen
        let x = (buffer_width.saturating_sub(width)) / 2;
        let y = (buffer_height.saturating_sub(height)) / 2;

        // Find the first primary button as default selection, or use first button
        let selected_button_index = buttons.iter().position(|b| b.is_primary).unwrap_or(0);

        Self {
            prompt_type,
            message,
            buttons,
            width,
            height,
            x,
            y,
            selected_button_index,
            text_align,
        }
    }

    /// Strip color codes from a string for length calculation
    fn strip_color_codes(s: &str) -> String {
        let mut result = String::new();
        let mut chars = s.chars();
        while let Some(ch) = chars.next() {
            if ch == '{' {
                // Skip until we find '}'
                for next in chars.by_ref() {
                    if next == '}' {
                        break;
                    }
                }
            } else {
                result.push(ch);
            }
        }
        result
    }

    /// Parse color code and return the corresponding Color
    fn parse_color_code(code: &str) -> Option<Color> {
        match code {
            "Y" | "y" => Some(Color::Yellow),
            "C" | "c" => Some(Color::Cyan),
            "W" | "w" => Some(Color::White),
            "G" | "g" => Some(Color::Green),
            "R" | "r" => Some(Color::Red),
            "M" | "m" => Some(Color::Magenta),
            "B" | "b" => Some(Color::Blue),
            "DG" | "dg" => Some(Color::DarkGrey),
            _ => None,
        }
    }

    /// Render the prompt to the video buffer
    pub fn render(&self, buffer: &mut VideoBuffer, charset: &Charset, theme: &Theme) {
        let bg_color = self.prompt_type.background_color(theme);
        let default_fg_color = self.prompt_type.foreground_color(theme);

        // Fill the entire prompt area with the background color (no borders)
        for y in 0..self.height {
            for x in 0..self.width {
                buffer.set(
                    self.x + x,
                    self.y + y,
                    Cell::new(' ', default_fg_color, bg_color),
                );
            }
        }

        // Render message (with alignment and color support)
        let message_lines: Vec<&str> = self.message.lines().collect();
        let message_start_y = self.y + 2; // Leave space at top

        for (i, line) in message_lines.iter().enumerate() {
            let line_y = message_start_y + i as u16;

            // Calculate line_x based on alignment
            let stripped_line = Self::strip_color_codes(line);
            let line_x = match self.text_align {
                TextAlign::Center => {
                    self.x + (self.width.saturating_sub(stripped_line.len() as u16)) / 2
                }
                TextAlign::Left => self.x + 3, // 3 spaces from left edge
            };

            // Render line with color code parsing
            let mut current_x = line_x;
            let mut current_color = default_fg_color;
            let mut chars = line.chars();

            while let Some(ch) = chars.next() {
                if ch == '{' {
                    // Collect color code
                    let mut code = String::new();
                    for next in chars.by_ref() {
                        if next == '}' {
                            // Apply color if valid
                            if let Some(color) = Self::parse_color_code(&code) {
                                current_color = color;
                            }
                            break;
                        }
                        code.push(next);
                    }
                } else {
                    // Render character with current color
                    buffer.set(current_x, line_y, Cell::new(ch, current_color, bg_color));
                    current_x += 1;
                }
            }
        }

        // Render buttons (centered, at bottom)
        let button_y = self.y + self.height - 2;
        let total_button_width: u16 = self.buttons.iter().map(|b| b.width()).sum::<u16>()
            + (self.buttons.len().saturating_sub(1)) as u16 * 2; // 2 spaces between buttons

        let mut button_x = self.x + (self.width.saturating_sub(total_button_width)) / 2;

        for (index, button) in self.buttons.iter().enumerate() {
            let (button_fg, button_bg) = button.colors(self.prompt_type, theme);
            let is_selected = index == self.selected_button_index;

            // Render selection indicator before button
            if is_selected {
                // Add ">" indicator before selected button (1 cell to the left)
                if button_x > self.x {
                    buffer.set(
                        button_x - 1,
                        button_y,
                        Cell::new('>', default_fg_color, bg_color),
                    );
                }
            }

            // Render button: [ Text ]
            buffer.set(button_x, button_y, Cell::new('[', button_fg, button_bg));
            button_x += 1;
            buffer.set(button_x, button_y, Cell::new(' ', button_fg, button_bg));
            button_x += 1;

            for ch in button.text.chars() {
                buffer.set(button_x, button_y, Cell::new(ch, button_fg, button_bg));
                button_x += 1;
            }

            buffer.set(button_x, button_y, Cell::new(' ', button_fg, button_bg));
            button_x += 1;
            buffer.set(button_x, button_y, Cell::new(']', button_fg, button_bg));
            button_x += 1;

            // Render selection indicator after button
            if is_selected {
                buffer.set(
                    button_x,
                    button_y,
                    Cell::new('<', default_fg_color, bg_color),
                );
            }

            // Add spacing between buttons
            button_x += 2;
        }

        // Render shadow
        video_buffer::render_shadow(
            buffer,
            self.x,
            self.y,
            self.width,
            self.height,
            charset,
            theme,
        );
    }

    /// Check if a click is on a button, return the action if so
    pub fn handle_click(&self, x: u16, y: u16) -> Option<PromptAction> {
        let button_y = self.y + self.height - 2;

        // Only process clicks on the button row
        if y != button_y {
            return None;
        }

        let total_button_width: u16 = self.buttons.iter().map(|b| b.width()).sum::<u16>()
            + (self.buttons.len().saturating_sub(1)) as u16 * 2;

        let mut button_x = self.x + (self.width.saturating_sub(total_button_width)) / 2;

        for button in &self.buttons {
            let button_width = button.width();
            let button_end = button_x + button_width;

            if x >= button_x && x < button_end {
                return Some(button.action);
            }

            button_x = button_end + 2; // Move to next button (with spacing)
        }

        None
    }

    /// Check if point is within prompt bounds
    pub fn contains_point(&self, x: u16, y: u16) -> bool {
        x >= self.x && x < self.x + self.width && y >= self.y && y < self.y + self.height
    }

    /// Move selection to the next button (right/tab)
    pub fn select_next_button(&mut self) {
        if !self.buttons.is_empty() {
            self.selected_button_index = (self.selected_button_index + 1) % self.buttons.len();
        }
    }

    /// Move selection to the previous button (left/shift+tab)
    pub fn select_previous_button(&mut self) {
        if !self.buttons.is_empty() {
            self.selected_button_index = if self.selected_button_index == 0 {
                self.buttons.len() - 1
            } else {
                self.selected_button_index - 1
            };
        }
    }

    /// Get the action of the currently selected button
    pub fn get_selected_action(&self) -> Option<PromptAction> {
        self.buttons
            .get(self.selected_button_index)
            .map(|b| b.action)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_prompt_creation() {
        let buttons = vec![
            PromptButton::new("Yes".to_string(), PromptAction::Confirm, true),
            PromptButton::new("No".to_string(), PromptAction::Cancel, false),
        ];

        let prompt = Prompt::new(
            PromptType::Danger,
            "Are you sure?".to_string(),
            buttons,
            80,
            24,
        );

        assert_eq!(prompt.prompt_type, PromptType::Danger);
        assert_eq!(prompt.buttons.len(), 2);
    }

    #[test]
    fn test_button_width() {
        let button = PromptButton::new("OK".to_string(), PromptAction::Confirm, true);
        assert_eq!(button.width(), 6); // "[ OK ]"
    }
}