turbo-vision 1.0.6

A Rust implementation of the classic Borland Turbo Vision text-mode UI framework
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
// (C) 2025 - Enzo Lombardi

//! DirListBox view - directory tree navigation and selection.
// DirListBox - Directory tree viewer
//
// Matches Borland: TDirListBox (views/tdirlist.cc)
//
// A hierarchical tree view of the directory structure, showing parent
// directories and subdirectories with visual tree indicators.
//
// Features:
// - Hierarchical directory tree display
// - Visual tree structure (├─, └─, │, etc.)
// - Navigate up and down the directory tree
// - Expand/collapse directories
// - Current path tracking
//
// Display format:
//   C:\
//   ├─ Users
//   │ ├─ alice
//   │ └─ bob
//   └─ Program Files

use crate::core::geometry::Rect;
use crate::core::event::{Event, EventType, KB_ENTER};
use crate::core::state::StateFlags;
use crate::terminal::Terminal;
use super::view::View;
use super::list_viewer::{ListViewer, ListViewerState};
use std::path::{Path, PathBuf};
use std::fs;

/// Directory entry in the tree
#[derive(Clone, Debug)]
pub struct DirEntry {
    /// Directory name
    pub name: String,
    /// Full path
    pub path: PathBuf,
    /// Nesting level (0 = root)
    pub level: usize,
    /// Whether this is the last child at its level
    pub is_last: bool,
}

impl DirEntry {
    /// Format with tree characters
    fn display_text(&self, parent_continues: &[bool]) -> String {
        let mut result = String::new();

        // Add vertical lines for parent levels
        for i in 0..self.level {
            if i < parent_continues.len() && parent_continues[i] {
                result.push_str("");
            } else {
                result.push_str("  ");
            }
        }

        // Add branch for current level
        if self.level > 0 {
            if self.is_last {
                result.push_str("└─ ");
            } else {
                result.push_str("├─ ");
            }
        }

        result.push_str(&self.name);
        result
    }
}

/// DirListBox - Hierarchical directory tree viewer
///
/// Matches Borland: TDirListBox
pub struct DirListBox {
    bounds: Rect,
    state: StateFlags,
    list_state: ListViewerState,
    entries: Vec<DirEntry>,
    current_path: PathBuf,
    root_path: PathBuf,
    owner: Option<*const dyn View>,
    owner_type: super::view::OwnerType,
}

impl DirListBox {
    /// Create a new directory list box
    pub fn new(bounds: Rect, path: &Path) -> Self {
        let mut dlb = Self {
            bounds,
            state: 0,
            list_state: ListViewerState::new(),
            entries: Vec::new(),
            current_path: path.to_path_buf(),
            root_path: Self::find_root(path),
            owner: None,
            owner_type: super::view::OwnerType::None,
        };
        dlb.rebuild_tree();
        dlb
    }

    /// Find the root path (drive root on Windows, / on Unix)
    fn find_root(path: &Path) -> PathBuf {
        let mut current = path;
        while let Some(parent) = current.parent() {
            current = parent;
        }
        current.to_path_buf()
    }

    /// Get the currently selected directory path
    pub fn current_path(&self) -> &Path {
        &self.current_path
    }

    /// Get the list viewer state (for scrollbar updates)
    pub fn list_state(&self) -> &ListViewerState {
        &self.list_state
    }

    /// Get the focused directory entry
    pub fn get_focused_entry(&self) -> Option<&DirEntry> {
        let idx = self.list_state.focused?;
        self.entries.get(idx)
    }

    /// Navigate to a different directory
    pub fn change_dir(&mut self, path: &Path) -> std::io::Result<()> {
        if path.is_dir() {
            self.current_path = fs::canonicalize(path)?;
            self.rebuild_tree();
            Ok(())
        } else {
            Err(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                "Not a directory",
            ))
        }
    }

    /// Rebuild the directory tree from root to current path
    fn rebuild_tree(&mut self) {
        self.entries.clear();

        // Build path from root to current directory
        let mut path_components = Vec::new();
        let mut current = self.current_path.clone();

        while current != self.root_path {
            if let Some(name) = current.file_name() {
                path_components.push((name.to_string_lossy().to_string(), current.clone()));
            }
            if let Some(parent) = current.parent() {
                current = parent.to_path_buf();
            } else {
                break;
            }
        }
        path_components.reverse();

        // Add root
        let root_name = self.root_path.to_string_lossy().to_string();
        self.entries.push(DirEntry {
            name: if root_name.is_empty() {
                "/".to_string()
            } else {
                root_name
            },
            path: self.root_path.clone(),
            level: 0,
            is_last: true,
        });

        // Add path components
        for (i, (name, path)) in path_components.iter().enumerate() {
            // Each path component is the only child shown at its level
            self.entries.push(DirEntry {
                name: name.clone(),
                path: path.clone(),
                level: i + 1,
                is_last: true,
            });
        }

        // Add subdirectories of current directory
        if let Ok(entries) = fs::read_dir(&self.current_path) {
            let mut subdirs: Vec<_> = entries
                .filter_map(|e| e.ok())
                .filter_map(|e| {
                    let path = e.path();
                    if path.is_dir() {
                        Some((e.file_name().to_string_lossy().to_string(), path))
                    } else {
                        None
                    }
                })
                .collect();

            subdirs.sort_by(|a, b| a.0.to_lowercase().cmp(&b.0.to_lowercase()));

            let current_level = path_components.len() + 1;
            for (i, (name, path)) in subdirs.iter().enumerate() {
                let is_last = i == subdirs.len() - 1;
                self.entries.push(DirEntry {
                    name: name.clone(),
                    path: path.clone(),
                    level: current_level,
                    is_last,
                });
            }
        }

        // Update list state
        self.list_state.set_range(self.entries.len());

        // Focus the current directory entry
        if let Some(idx) = self.entries.iter().position(|e| e.path == self.current_path) {
            self.list_state.focused = Some(idx);
        } else {
            self.list_state.focused = Some(0);
        }
    }

    /// Enter the focused directory
    pub fn enter_focused_dir(&mut self) -> std::io::Result<()> {
        if let Some(entry) = self.get_focused_entry() {
            let path = entry.path.clone();
            self.change_dir(&path)?;
        }
        Ok(())
    }

    /// Navigate to parent directory
    pub fn parent_dir(&mut self) -> std::io::Result<()> {
        let parent = self.current_path.parent().map(|p| p.to_path_buf());
        if let Some(parent) = parent {
            self.change_dir(&parent)?;
        }
        Ok(())
    }

    /// Get parent continuation flags for rendering
    fn get_parent_continues(&self, entry: &DirEntry) -> Vec<bool> {
        let mut continues = vec![false; entry.level];

        // Find the current entry's index
        let entry_idx = self.entries.iter().position(|e| e.path == entry.path).unwrap_or(0);

        // For each parent level, find the ancestor and check if it's not the last child
        for level in 0..entry.level {
            // Find the ancestor at this level by searching backwards from current entry
            if let Some(ancestor) = self.entries[..=entry_idx]
                .iter()
                .rev()
                .find(|e| e.level == level)
            {
                // Show continuation line if ancestor is not the last child
                continues[level] = !ancestor.is_last;
            }
        }

        continues
    }
}

impl ListViewer for DirListBox {
    fn list_state(&self) -> &ListViewerState {
        &self.list_state
    }

    fn list_state_mut(&mut self) -> &mut ListViewerState {
        &mut self.list_state
    }

    fn get_text(&self, item: usize, _max_len: usize) -> String {
        if let Some(entry) = self.entries.get(item) {
            let continues = self.get_parent_continues(entry);
            entry.display_text(&continues)
        } else {
            String::new()
        }
    }
}

impl View for DirListBox {
    fn bounds(&self) -> Rect {
        self.bounds
    }

    fn set_bounds(&mut self, bounds: Rect) {
        self.bounds = bounds;
    }

    fn draw(&mut self, terminal: &mut Terminal) {
        let width = self.bounds.width_clamped() as usize;
        let height = self.bounds.height_clamped() as usize;

        self.list_state.set_range(self.entries.len());

        // Use direct Attr colors (matching FileList behavior)
        // This ensures consistent appearance in both dialogs and standalone usage
        use crate::core::palette::colors::{LISTBOX_FOCUSED, LISTBOX_NORMAL, LISTBOX_SELECTED};

        let color_normal = if self.is_focused() {
            LISTBOX_FOCUSED // Black on white when focused
        } else {
            LISTBOX_NORMAL // Black on light gray when not focused
        };
        let color_selected = LISTBOX_SELECTED; // White on blue for selected item

        for y in 0..height {
            let item_idx = self.list_state.top_item + y;

            let (text, color) = if item_idx < self.entries.len() {
                let text = self.get_text(item_idx, width);
                let is_selected = self.is_focused() && Some(item_idx) == self.list_state.focused;
                let color = if is_selected {
                    color_selected
                } else {
                    color_normal
                };
                (text, color)
            } else {
                (String::new(), color_normal)
            };

            // Pad with spaces to fill width - all chars drawn with same color
            let padded = format!("{:width$}", text, width = width);

            for (x, ch) in padded.chars().take(width).enumerate() {
                terminal.write_cell(
                    (self.bounds.a.x + x as i16) as u16,
                    (self.bounds.a.y + y as i16) as u16,
                    crate::core::draw::Cell::new(ch, color),
                );
            }
        }
    }

    fn handle_event(&mut self, event: &mut Event) {
        // Handle double-click BEFORE focus check (to allow clicking to focus AND navigate)
        if event.what == EventType::MouseDown {
            use crate::core::event::MB_LEFT_BUTTON;
            if self.bounds.contains(event.mouse.pos) && event.mouse.buttons & MB_LEFT_BUTTON != 0 {
                if event.mouse.double_click && self.is_focused() {
                    // Double-click navigates into directory (only when already focused)
                    let _ = self.enter_focused_dir();
                    event.clear();
                    return;
                }
            }
        }

        if !self.is_focused() {
            return;
        }

        // Use default ListViewer navigation
        self.handle_list_event(event);

        // Handle Enter to navigate into directory
        if event.what == EventType::Keyboard && event.key_code == KB_ENTER {
            let _ = self.enter_focused_dir();
            event.clear();
        }
    }

    fn can_focus(&self) -> bool {
        true
    }

    fn state(&self) -> StateFlags {
        self.state
    }

    fn set_state(&mut self, state: StateFlags) {
        self.state = state;
    }

    fn set_owner(&mut self, owner: *const dyn View) {
        self.owner = Some(owner);
    }

    fn get_owner(&self) -> Option<*const dyn View> {
        self.owner
    }

    fn get_palette(&self) -> Option<crate::core::palette::Palette> {
        use crate::core::palette::{palettes, Palette};
        Some(Palette::from_slice(palettes::CP_LISTBOX))
    }

    fn get_owner_type(&self) -> super::view::OwnerType {
        self.owner_type
    }

    fn set_owner_type(&mut self, owner_type: super::view::OwnerType) {
        self.owner_type = owner_type;
    }
}

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

    #[test]
    fn test_dir_listbox_creation() {
        let bounds = Rect::new(0, 0, 40, 10);
        let path = env::current_dir().unwrap();
        let dlb = DirListBox::new(bounds, &path);

        assert!(dlb.entries.len() > 0, "Should have at least root entry");
        assert_eq!(dlb.current_path(), path.as_path());
    }

    #[test]
    fn test_find_root() {
        let path = env::current_dir().unwrap();
        let root = DirListBox::find_root(&path);

        // Root should have no parent
        assert!(root.parent().is_none());
    }

    #[test]
    fn test_dir_entry_display() {
        let entry = DirEntry {
            name: "subdir".to_string(),
            path: PathBuf::from("/path/to/subdir"),
            level: 1,
            is_last: false,
        };

        let continues = vec![true];
        let text = entry.display_text(&continues);
        assert!(text.contains("├─") || text.contains("└─"));
        assert!(text.contains("subdir"));
    }

    #[test]
    fn test_parent_navigation() {
        let path = env::current_dir().unwrap();
        let bounds = Rect::new(0, 0, 40, 10);
        let mut dlb = DirListBox::new(bounds, &path);

        let original_path = dlb.current_path().to_path_buf();

        // Try to go to parent
        if original_path.parent().is_some() {
            let result = dlb.parent_dir();
            assert!(result.is_ok());
            assert_ne!(dlb.current_path(), original_path.as_path());
        }
    }
}

/// Builder for creating directory list boxes with a fluent API.
pub struct DirListBoxBuilder {
    bounds: Option<Rect>,
    path: Option<PathBuf>,
}

impl DirListBoxBuilder {
    pub fn new() -> Self {
        Self { bounds: None, path: None }
    }

    #[must_use]
    pub fn bounds(mut self, bounds: Rect) -> Self {
        self.bounds = Some(bounds);
        self
    }

    #[must_use]
    pub fn path(mut self, path: impl Into<PathBuf>) -> Self {
        self.path = Some(path.into());
        self
    }

    pub fn build(self) -> DirListBox {
        let bounds = self.bounds.expect("DirListBox bounds must be set");
        let path = self.path.expect("DirListBox path must be set");
        DirListBox::new(bounds, &path)
    }

    pub fn build_boxed(self) -> Box<DirListBox> {
        Box::new(self.build())
    }
}

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