turbo-vision 1.1.0

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
// (C) 2025 - Enzo Lombardi

//! Status line data structures - declarative status bar building with command-based visibility.
// Borland-compatible status line data structures
// Matches the original Turbo Vision TStatusItem, TStatusDef architecture
//
// This module provides data structures for building status lines in a declarative way,
// matching Borland's approach while being Rust-idiomatic.

use crate::core::command::CommandId;
use crate::core::event::KeyCode;

/// Status line item - displays text and responds to keyboard shortcuts
///
/// Matches Borland: TStatusItem
///
/// In Borland, TStatusItem is a linked list node with a `next` pointer.
/// In Rust, we use Vec for type safety, but provide builder methods
/// that match Borland's ergonomics.
#[derive(Clone, Debug)]
pub struct StatusItem {
    /// Display text (use ~x~ to mark accelerator key)
    pub text: String,
    /// Keyboard shortcut
    pub key_code: KeyCode,
    /// Command to execute when clicked or shortcut pressed
    pub command: CommandId,
}

impl StatusItem {
    /// Create a new status item
    ///
    /// Matches Borland: `TStatusItem(text, keyCode, command)`
    ///
    /// # Example
    /// ```ignore
    /// let item = StatusItem::new("~F1~ Help", KB_F1, CM_HELP);
    /// ```
    pub fn new(text: &str, key_code: KeyCode, command: CommandId) -> Self {
        Self {
            text: text.to_string(),
            key_code,
            command,
        }
    }

    /// Extract the accelerator key from the text (character between ~ marks)
    pub fn get_accelerator(&self) -> Option<char> {
        let mut chars = self.text.chars();
        while let Some(ch) = chars.next() {
            if ch == '~' {
                // Next char is the accelerator
                if let Some(accel) = chars.next() {
                    return Some(accel.to_ascii_lowercase());
                }
            }
        }
        None
    }
}

/// Builder for creating status items with a fluent API.
///
/// # Examples
///
/// ```ignore
/// use turbo_vision::core::status_data::StatusItemBuilder;
///
/// let item = StatusItemBuilder::new()
///     .text("~F1~ Help")
///     .key_code(0x3B00)
///     .command(100)
///     .build();
/// ```
pub struct StatusItemBuilder {
    text: Option<String>,
    key_code: KeyCode,
    command: CommandId,
}

impl StatusItemBuilder {
    /// Creates a new StatusItemBuilder with default values.
    pub fn new() -> Self {
        Self {
            text: None,
            key_code: 0,
            command: 0,
        }
    }

    /// Sets the status item text (required).
    /// Use ~x~ to mark the accelerator key.
    #[must_use]
    pub fn text(mut self, text: impl Into<String>) -> Self {
        self.text = Some(text.into());
        self
    }

    /// Sets the keyboard shortcut key code.
    #[must_use]
    pub fn key_code(mut self, key_code: KeyCode) -> Self {
        self.key_code = key_code;
        self
    }

    /// Sets the command to execute.
    #[must_use]
    pub fn command(mut self, command: CommandId) -> Self {
        self.command = command;
        self
    }

    /// Builds the StatusItem.
    ///
    /// # Panics
    ///
    /// Panics if required fields (text) are not set.
    pub fn build(self) -> StatusItem {
        let text = self.text.expect("StatusItem text must be set");
        StatusItem {
            text,
            key_code: self.key_code,
            command: self.command,
        }
    }
}

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

/// Status line definition - defines which items are visible for a command set range
///
/// Matches Borland: TStatusDef
///
/// In Borland, TStatusDef is a linked list node with:
/// - `min`, `max`: command range for which this def is active
/// - `items`: pointer to first item in linked list
/// - `next`: pointer to next status def
///
/// In Rust, we use Vec for type safety and provide convenient builders.
#[derive(Clone, Debug)]
pub struct StatusDef {
    /// Minimum command ID for which this definition is active
    pub min: u16,
    /// Maximum command ID for which this definition is active
    pub max: u16,
    /// Status items to display
    pub items: Vec<StatusItem>,
}

impl StatusDef {
    /// Create a new status definition
    ///
    /// Matches Borland: `TStatusDef(min, max, items)`
    ///
    /// # Example
    /// ```ignore
    /// let def = StatusDef::new(0, 0xFFFF, vec![
    ///     StatusItem::new("~F1~ Help", KB_F1, CM_HELP),
    ///     StatusItem::new("~Alt+X~ Exit", KB_ALT_X, CM_QUIT),
    /// ]);
    /// ```
    pub fn new(min: u16, max: u16, items: Vec<StatusItem>) -> Self {
        Self { min, max, items }
    }

    /// Create a status definition for all command ranges (default)
    ///
    /// Matches Borland: `TStatusDef(0, 0xFFFF, items)`
    pub fn default_range(items: Vec<StatusItem>) -> Self {
        Self {
            min: 0,
            max: 0xFFFF,
            items,
        }
    }

    /// Check if this definition applies to the given command set
    ///
    /// In Borland, the status line checks which definition's range
    /// matches the currently focused view's command set.
    pub fn applies_to(&self, command_set: u16) -> bool {
        command_set >= self.min && command_set <= self.max
    }

    /// Add an item to this definition
    pub fn add(&mut self, item: StatusItem) {
        self.items.push(item);
    }

    /// Get the number of items
    pub fn len(&self) -> usize {
        self.items.len()
    }

    /// Check if definition has no items
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }
}

/// Builder for creating status definitions with a fluent API.
///
/// # Examples
///
/// ```ignore
/// use turbo_vision::core::status_data::{StatusDefBuilder, StatusItem};
///
/// let def = StatusDefBuilder::new()
///     .range(0, 100)
///     .add_item(StatusItem::new("~F1~ Help", 0x3B00, 100))
///     .add_item(StatusItem::new("~F2~ Save", 0x3C00, 101))
///     .build();
/// ```
pub struct StatusDefBuilder {
    min: u16,
    max: u16,
    items: Vec<StatusItem>,
}

impl StatusDefBuilder {
    /// Creates a new StatusDefBuilder with default values (full range: 0-0xFFFF).
    pub fn new() -> Self {
        Self {
            min: 0,
            max: 0xFFFF,
            items: Vec::new(),
        }
    }

    /// Sets the command range (default: 0-0xFFFF).
    #[must_use]
    pub fn range(mut self, min: u16, max: u16) -> Self {
        self.min = min;
        self.max = max;
        self
    }

    /// Sets the minimum command ID.
    #[must_use]
    pub fn min(mut self, min: u16) -> Self {
        self.min = min;
        self
    }

    /// Sets the maximum command ID.
    #[must_use]
    pub fn max(mut self, max: u16) -> Self {
        self.max = max;
        self
    }

    /// Adds a status item to the definition.
    #[must_use]
    pub fn add_item(mut self, item: StatusItem) -> Self {
        self.items.push(item);
        self
    }

    /// Sets all items at once.
    #[must_use]
    pub fn items(mut self, items: Vec<StatusItem>) -> Self {
        self.items = items;
        self
    }

    /// Builds the StatusDef.
    pub fn build(self) -> StatusDef {
        StatusDef {
            min: self.min,
            max: self.max,
            items: self.items,
        }
    }
}

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

/// Status line configuration - collection of status definitions
///
/// Matches Borland: linked list of TStatusDef
///
/// In Borland, status defs are linked via `next` pointers.
/// In Rust, we use Vec for type safety.
#[derive(Clone, Debug)]
pub struct StatusLine {
    /// Status definitions (evaluated in order)
    pub defs: Vec<StatusDef>,
}

impl StatusLine {
    /// Create a new status line configuration
    pub fn new(defs: Vec<StatusDef>) -> Self {
        Self { defs }
    }

    /// Create a status line with a single default definition
    pub fn single(items: Vec<StatusItem>) -> Self {
        Self {
            defs: vec![StatusDef::default_range(items)],
        }
    }

    /// Get the status definition that applies to the given command set
    ///
    /// Matches Borland: TStatusLine::update() logic
    pub fn get_def_for(&self, command_set: u16) -> Option<&StatusDef> {
        // Return first matching definition (Borland behavior)
        self.defs.iter().find(|def| def.applies_to(command_set))
    }

    /// Add a status definition
    pub fn add_def(&mut self, def: StatusDef) {
        self.defs.push(def);
    }
}

/// Builder for constructing status line configurations fluently
///
/// This provides a Borland-style builder API while being Rust-idiomatic.
///
/// # Example (Borland-style)
/// ```ignore
/// let status = StatusLineBuilder::new()
///     .add_def(0, 0xFFFF, vec![
///         StatusItem::new("~F1~ Help", KB_F1, CM_HELP),
///         StatusItem::new("~Alt+X~ Exit", KB_ALT_X, CM_QUIT),
///     ])
///     .build();
/// ```
pub struct StatusLineBuilder {
    defs: Vec<StatusDef>,
}

impl StatusLineBuilder {
    /// Create a new status line builder
    pub fn new() -> Self {
        Self {
            defs: Vec::new(),
        }
    }

    /// Add a status definition with command range
    ///
    /// Matches Borland: `TStatusDef(min, max, items)`
    pub fn add_def(mut self, min: u16, max: u16, items: Vec<StatusItem>) -> Self {
        self.defs.push(StatusDef::new(min, max, items));
        self
    }

    /// Add a default status definition (applies to all command sets)
    pub fn add_default_def(mut self, items: Vec<StatusItem>) -> Self {
        self.defs.push(StatusDef::default_range(items));
        self
    }

    /// Build the status line configuration
    pub fn build(self) -> StatusLine {
        StatusLine::new(self.defs)
    }
}

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

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

    #[test]
    fn test_status_def() {
        let def = StatusDef::new(0, 100, vec![
            StatusItem::new("~F1~ Help", 0x3B00, 100),
            StatusItem::new("~Alt+X~ Exit", 0x2D00, 101),
        ]);

        assert!(def.applies_to(50));
        assert!(def.applies_to(0));
        assert!(def.applies_to(100));
        assert!(!def.applies_to(101));
        assert_eq!(def.len(), 2);
    }

    #[test]
    fn test_status_line_builder() {
        let status = StatusLineBuilder::new()
            .add_def(0, 100, vec![
                StatusItem::new("~F1~ Help", 0x3B00, 100),
                StatusItem::new("~F2~ Save", 0x3C00, 101),
            ])
            .add_def(101, 200, vec![
                StatusItem::new("~F1~ Help", 0x3B00, 100),
                StatusItem::new("~Esc~ Cancel", 0x011B, 102),
            ])
            .build();

        assert_eq!(status.defs.len(), 2);

        let def1 = status.get_def_for(50);
        assert!(def1.is_some());
        assert_eq!(def1.unwrap().len(), 2);

        let def2 = status.get_def_for(150);
        assert!(def2.is_some());
        assert_eq!(def2.unwrap().len(), 2);
    }

    #[test]
    fn test_accelerator() {
        let item = StatusItem::new("~F1~ Help", 0x3B00, 100);
        assert_eq!(item.get_accelerator(), Some('f'));
    }
}