turbo-vision 2.2.1

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
501
502
503
504
505
// (C) 2025 - Enzo Lombardi

//! HelpWindow view - window container for displaying context-sensitive help.
// HelpWindow - Help display window
//
// Matches Borland: THelpWindow (help.h)
//
// A window containing a HelpViewer with navigation and topic selection.

use super::help_file::HelpFile;
use super::help_viewer::HelpViewer;
use super::view::View;
use super::window::Window;
use crate::core::command::{CM_CANCEL, CommandId};
use crate::core::event::{
    Event, EventType, KB_ALT_F1, KB_BACKSPACE, KB_ENTER, KB_ESC, MB_LEFT_BUTTON,
};
use crate::core::geometry::{Point, Rect};
use crate::core::state::StateFlags;
use crate::terminal::Terminal;
use std::cell::RefCell;
use std::rc::Rc;

/// Wrapper that allows HelpViewer to be shared between window and HelpWindow
struct SharedHelpViewer(Rc<RefCell<HelpViewer>>);

impl View for SharedHelpViewer {
    fn bounds(&self) -> Rect {
        self.0.borrow().bounds()
    }

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

    fn draw(&mut self, terminal: &mut Terminal) {
        self.0.borrow_mut().draw(terminal);
    }

    fn handle_event(&mut self, event: &mut Event) {
        self.0.borrow_mut().handle_event(event);
    }

    fn can_focus(&self) -> bool {
        self.0.borrow().can_focus()
    }

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

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

    fn get_palette(&self) -> Option<crate::core::palette::Palette> {
        self.0.borrow().get_palette()
    }
}

/// History entry storing topic ID with scroll state for restoration.
struct HistoryEntry {
    topic_id: String,
    delta: Point,
    selected: usize,
}

/// HelpWindow - Window containing help viewer
///
/// Matches Borland: THelpWindow (parent-child hierarchy)
pub struct HelpWindow {
    window: Window,
    viewer: Rc<RefCell<HelpViewer>>, // Shared reference for API access
    help_file: Rc<RefCell<HelpFile>>,
    /// Topic history for back/forward navigation
    history: Vec<HistoryEntry>,
    /// Current position in history
    history_pos: usize,
}

impl HelpWindow {
    /// Create a new help window
    ///
    /// Matches Borland: THelpWindow constructor creates TWindow and inserts THelpViewer as child
    /// Uses cyan window palette (cHelpWindow) for the classic help window appearance
    pub fn new(bounds: Rect, title: &str, help_file: Rc<RefCell<HelpFile>>) -> Self {
        let mut window = Window::new_for_help(bounds, title);

        // Viewer fills the window interior
        let viewer_bounds = Rect::new(1, 1, bounds.width() - 2, bounds.height() - 2);
        let viewer = Rc::new(RefCell::new(
            HelpViewer::new(viewer_bounds).with_scrollbar(),
        ));

        // Insert viewer as a child of window (matches Borland's window->insert(viewer))
        window.add(Box::new(SharedHelpViewer(Rc::clone(&viewer))));

        Self {
            window,
            viewer,
            help_file,
            history: Vec::new(),
            history_pos: 0,
        }
    }

    /// Show a topic by ID
    /// Does not add to history (use switchToTopic for navigation with history)
    pub fn show_topic(&mut self, topic_id: &str) -> bool {
        let help = self.help_file.borrow();
        if let Some(topic) = help.get_topic(topic_id) {
            self.viewer.borrow_mut().set_topic(topic);
            true
        } else {
            false
        }
    }

    /// Show the default topic
    pub fn show_default_topic(&mut self) {
        let help = self.help_file.borrow();
        if let Some(topic) = help.get_default_topic() {
            self.viewer.borrow_mut().set_topic(topic);
        }
    }

    /// Get the current topic ID
    pub fn current_topic(&self) -> Option<String> {
        self.viewer.borrow().current_topic().map(|s| s.to_string())
    }

    /// Get a cloned Rc to the viewer for advanced access
    pub fn viewer_rc(&self) -> Rc<RefCell<HelpViewer>> {
        Rc::clone(&self.viewer)
    }

    /// Get reference to the help file
    pub fn help_file(&self) -> &Rc<RefCell<HelpFile>> {
        &self.help_file
    }

    /// Switch to a topic (with history tracking)
    /// Matches Borland: THelpViewer::switchToTopic()
    /// This is the method to use for hyperlink navigation
    pub fn switch_to_topic(&mut self, topic_id: &str) -> bool {
        let help = self.help_file.borrow();
        if help.get_topic(topic_id).is_none() {
            return false;
        }
        drop(help);

        // Truncate future history if not at the end
        if self.history_pos < self.history.len() {
            self.history.truncate(self.history_pos);
        }

        // Save current topic + scroll state to history before switching
        if let Some(current) = self.viewer.borrow().current_topic().map(|s| s.to_string()) {
            let (delta, selected) = self.viewer.borrow().get_scroll_state();
            self.history.push(HistoryEntry {
                topic_id: current,
                delta,
                selected,
            });
        }

        let success = self.show_topic(topic_id);
        if success {
            self.history_pos = self.history.len();
        }
        success
    }

    /// Navigate back in history
    /// Returns true if navigation occurred
    pub fn go_back(&mut self) -> bool {
        if self.history_pos > 0 {
            self.history_pos -= 1;
            let entry = &self.history[self.history_pos];
            let topic_id = entry.topic_id.clone();
            let delta = entry.delta;
            let selected = entry.selected;
            self.show_topic(&topic_id);
            self.viewer.borrow_mut().set_scroll_state(delta, selected);
            true
        } else {
            false
        }
    }

    /// Navigate forward in history
    /// Returns true if navigation occurred
    pub fn go_forward(&mut self) -> bool {
        if self.history_pos < self.history.len() {
            let entry = &self.history[self.history_pos];
            let topic_id = entry.topic_id.clone();
            let delta = entry.delta;
            let selected = entry.selected;
            self.history_pos += 1;
            self.show_topic(&topic_id);
            self.viewer.borrow_mut().set_scroll_state(delta, selected);
            true
        } else {
            false
        }
    }

    /// Check if we can go back
    pub fn can_go_back(&self) -> bool {
        self.history_pos > 0
    }

    /// Check if we can go forward
    pub fn can_go_forward(&self) -> bool {
        self.history_pos < self.history.len()
    }

    /// Create and show a topic selection dialog
    /// Matches Borland: THelpViewer::makeSelectTopic()
    /// Returns the selected topic ID, or None if cancelled
    pub fn make_select_topic(&self) -> Option<String> {
        // Get all available topics from help file
        let help = self.help_file.borrow();
        let topics = help.get_topic_ids();

        if topics.is_empty() {
            return None;
        }

        // For now, return the first topic as a placeholder
        // TODO: Show a proper selection dialog (ListBox in a Dialog)
        // This would require access to Application to show modal dialog
        Some(topics[0].clone())
    }

    /// Execute the help window modally
    pub fn execute(&mut self, app: &mut crate::app::Application) -> CommandId {
        self.window.execute(app)
    }

    /// End the modal event loop
    pub fn end_modal(&mut self, command: CommandId) {
        self.window.end_modal(command);
    }
}

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

    fn set_bounds(&mut self, bounds: Rect) {
        self.window.set_bounds(bounds);
        // Update viewer bounds to match window interior (ABSOLUTE coordinates)
        // The viewer needs absolute screen coordinates, not relative to window
        let viewer_bounds = Rect::new(
            bounds.a.x + 1,
            bounds.a.y + 1,
            bounds.b.x - 1,
            bounds.b.y - 1,
        );
        self.viewer.borrow_mut().set_bounds(viewer_bounds);
    }

    fn draw(&mut self, terminal: &mut Terminal) {
        // Window draws itself and all children (including viewer)
        self.window.draw(terminal);
    }

    fn handle_event(&mut self, event: &mut Event) {
        match event.what {
            EventType::Keyboard => {
                match event.key_code {
                    KB_ESC => {
                        // ESC closes the help window
                        self.window.end_modal(CM_CANCEL);
                        event.clear();
                        return;
                    }
                    KB_ENTER => {
                        // Follow selected link
                        // Matches Borland: THelpViewer::handleEvent() kbEnter (help.cc:189-194)
                        let target = self
                            .viewer
                            .borrow()
                            .get_selected_target()
                            .map(|s| s.to_string());
                        if let Some(target) = target {
                            self.switch_to_topic(&target);
                            event.clear();
                            return;
                        }
                    }
                    KB_ALT_F1 | KB_BACKSPACE => {
                        // Go back in history
                        // Matches Borland: THelpViewer::handleEvent() kbAltF1 (help.cc:195-200)
                        // Also supports Backspace as an intuitive alternative
                        self.go_back();
                        event.clear();
                        return;
                    }
                    _ => {}
                }
            }
            EventType::MouseDown => {
                if event.mouse.buttons & MB_LEFT_BUTTON != 0 {
                    // Let the window (and viewer) handle the click first
                    self.window.handle_event(event);

                    // If a link was clicked, follow it
                    let target = self
                        .viewer
                        .borrow()
                        .get_selected_target()
                        .map(|s| s.to_string());
                    if let Some(target) = target {
                        // Check if click was actually on a cross-ref
                        let mouse_pos = event.mouse.pos;
                        let hit = self
                            .viewer
                            .borrow()
                            .get_cross_ref_at_public(mouse_pos.x, mouse_pos.y);
                        if hit > 0 {
                            self.switch_to_topic(&target);
                        }
                    }
                    event.clear();
                    return;
                }
            }
            _ => {}
        }

        // Window handles events and dispatches to children (including viewer)
        self.window.handle_event(event);
    }

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

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

    fn set_state(&mut self, state: StateFlags) {
        self.window.set_state(state);
        self.viewer.borrow_mut().set_state(state);
    }

    fn get_palette(&self) -> Option<crate::core::palette::Palette> {
        self.window.get_palette()
    }

    fn options(&self) -> u16 {
        self.window.options()
    }

    fn set_options(&mut self, options: u16) {
        self.window.set_options(options);
    }

    fn get_end_state(&self) -> crate::core::command::CommandId {
        self.window.get_end_state()
    }

    fn set_end_state(&mut self, command: crate::core::command::CommandId) {
        self.window.set_end_state(command);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    fn create_test_help_file() -> (NamedTempFile, Rc<RefCell<HelpFile>>) {
        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, "# Test Topic {{#test}}").unwrap();
        writeln!(file, "").unwrap();
        writeln!(file, "This is test content.").unwrap();
        file.flush().unwrap();

        let help = HelpFile::new(file.path().to_str().unwrap()).unwrap();
        (file, Rc::new(RefCell::new(help)))
    }

    #[test]
    fn test_help_window_creation() {
        let (_file, help) = create_test_help_file();
        let bounds = Rect::new(10, 5, 70, 20);
        let window = HelpWindow::new(bounds, "Help", help);

        assert_eq!(window.bounds(), bounds);
    }

    #[test]
    fn test_show_topic() {
        let (_file, help) = create_test_help_file();
        let bounds = Rect::new(10, 5, 70, 20);
        let mut window = HelpWindow::new(bounds, "Help", help);

        assert!(window.show_topic("test"));
        assert_eq!(window.current_topic(), Some("test".to_string()));
    }

    #[test]
    fn test_show_default_topic() {
        let (_file, help) = create_test_help_file();
        let bounds = Rect::new(10, 5, 70, 20);
        let mut window = HelpWindow::new(bounds, "Help", help);

        window.show_default_topic();
        assert_eq!(window.current_topic(), Some("test".to_string()));
    }

    #[test]
    fn test_show_nonexistent_topic() {
        let (_file, help) = create_test_help_file();
        let bounds = Rect::new(10, 5, 70, 20);
        let mut window = HelpWindow::new(bounds, "Help", help);

        assert!(!window.show_topic("nonexistent"));
    }

    #[test]
    fn test_help_window_options_delegation() {
        use crate::core::state::{OF_SELECTABLE, OF_TILEABLE, OF_TOP_SELECT};

        let (_file, help) = create_test_help_file();
        let bounds = Rect::new(10, 5, 70, 20);
        let window = HelpWindow::new(bounds, "Help", help);

        let options = window.options();
        assert_ne!(
            options, 0,
            "HelpWindow should delegate options() to inner window"
        );
        assert!(
            (options & OF_SELECTABLE) != 0,
            "HelpWindow should have OF_SELECTABLE"
        );
        assert!(
            (options & OF_TOP_SELECT) != 0,
            "HelpWindow should have OF_TOP_SELECT for click-to-focus"
        );
        assert!(
            (options & OF_TILEABLE) != 0,
            "HelpWindow should have OF_TILEABLE"
        );
    }
}

/// Builder for creating help windows with a fluent API.
pub struct HelpWindowBuilder {
    bounds: Option<Rect>,
    title: Option<String>,
    help_file: Option<Rc<RefCell<HelpFile>>>,
}

impl HelpWindowBuilder {
    pub fn new() -> Self {
        Self {
            bounds: None,
            title: None,
            help_file: None,
        }
    }

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

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

    #[must_use]
    pub fn help_file(mut self, help_file: Rc<RefCell<HelpFile>>) -> Self {
        self.help_file = Some(help_file);
        self
    }

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

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

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