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

//! PictureValidator - validates and formats input using picture mask patterns.
// Picture Mask Validator (TPXPictureValidator)
//
// Validates and formats input according to a picture mask.
// Borland's TPXPictureValidator from validate.h and tvalidat.cc
//
// Mask Characters:
// - # : Digit (0-9)
// - @ : Alpha (A-Z, a-z)
// - ! : Any character
// - * : Optional character (makes following characters optional)
// - Literal characters : Must match exactly
//
// Examples:
// - "(###) ###-####" : Phone number (555) 123-4567
// - "##/##/####"     : Date 12/25/2023
// - "@@@@-####"      : Code ABCD-1234
// - "###*-####"      : Optional dash 123-4567 or 1234567
//
// Reference: Borland Turbo Vision tvalidat.cc, validate.h

use crate::views::validator::{Validator, ValidatorRef};
use std::cell::RefCell;
use std::rc::Rc;

/// Picture mask validator for formatted input
pub struct PictureValidator {
    /// Picture mask string
    mask: String,
    /// Whether to auto-format as user types
    auto_format: bool,
}

impl PictureValidator {
    /// Create a new picture validator with the given mask
    ///
    /// # Example
    /// ```
    /// use turbo_vision::views::picture_validator::PictureValidator;
    ///
    /// // Phone number mask
    /// let validator = PictureValidator::new("(###) ###-####");
    ///
    /// // Date mask
    /// let validator = PictureValidator::new("##/##/####");
    /// ```
    pub fn new(mask: &str) -> Self {
        PictureValidator {
            mask: mask.to_string(),
            auto_format: true,
        }
    }

    /// Create a new picture validator without auto-formatting
    pub fn new_no_format(mask: &str) -> Self {
        PictureValidator {
            mask: mask.to_string(),
            auto_format: false,
        }
    }

    /// Get the mask string
    pub fn mask(&self) -> &str {
        &self.mask
    }

    /// Set whether to auto-format input
    pub fn set_auto_format(&mut self, auto_format: bool) {
        self.auto_format = auto_format;
    }

    /// Check if a character is valid for the given mask position
    fn is_valid_char_for_mask(&self, ch: char, mask_ch: char) -> bool {
        match mask_ch {
            '#' => ch.is_ascii_digit(),
            '@' => ch.is_ascii_alphabetic(),
            '!' => true,
            '*' => true, // Optional marker - accept anything
            _ => ch == mask_ch, // Literal must match
        }
    }

    /// Format input according to the mask
    ///
    /// Returns the formatted string, filling in literal characters from the mask.
    pub fn format(&self, input: &str) -> String {
        let mut result = String::new();
        let mut input_chars = input.chars().filter(|&c| !c.is_whitespace());
        let mask_chars: Vec<char> = self.mask.chars().collect();
        let mut optional = false;

        for &mask_ch in &mask_chars {
            if mask_ch == '*' {
                optional = true;
                continue;
            }

            match mask_ch {
                '#' | '@' | '!' => {
                    // Field character - consume from input
                    if let Some(ch) = input_chars.next() {
                        if self.is_valid_char_for_mask(ch, mask_ch) {
                            result.push(ch);
                        } else if optional {
                            // Invalid in optional section - stop
                            break;
                        } else {
                            // Invalid character for required field
                            // Skip it and try next
                            continue;
                        }
                    } else if optional {
                        // No more input and we're in optional section - done
                        break;
                    } else {
                        // Required field but no more input - incomplete
                        break;
                    }
                }
                _ => {
                    // Literal character - add to result
                    result.push(mask_ch);
                }
            }
        }

        result
    }

    /// Check if input matches the mask completely
    fn matches_mask(&self, input: &str) -> bool {
        let mask_chars: Vec<char> = self.mask.chars().collect();
        let input_chars: Vec<char> = input.chars().collect();
        let mut mask_idx = 0;
        let mut input_idx = 0;
        let mut optional = false;

        while mask_idx < mask_chars.len() {
            let mask_ch = mask_chars[mask_idx];

            if mask_ch == '*' {
                optional = true;
                mask_idx += 1;
                continue;
            }

            match mask_ch {
                '#' | '@' | '!' => {
                    // Field character - must match input
                    if input_idx >= input_chars.len() {
                        return optional; // OK if optional section
                    }

                    let input_ch = input_chars[input_idx];
                    if !self.is_valid_char_for_mask(input_ch, mask_ch) {
                        return false;
                    }

                    input_idx += 1;
                }
                _ => {
                    // Literal character - must match exactly
                    if input_idx >= input_chars.len() {
                        return optional;
                    }

                    if input_chars[input_idx] != mask_ch {
                        return false;
                    }

                    input_idx += 1;
                }
            }

            mask_idx += 1;
        }

        // All input consumed?
        input_idx == input_chars.len()
    }
}

impl Validator for PictureValidator {
    fn is_valid(&self, input: &str) -> bool {
        if input.is_empty() {
            return true; // Empty is valid (might be required by parent)
        }

        self.matches_mask(input)
    }

    fn is_valid_input(&self, input: &str, _append: bool) -> bool {
        if input.is_empty() {
            return true;
        }

        // For auto-format mode, check if the formatted version is valid
        if self.auto_format {
            let formatted = self.format(input);
            return !formatted.is_empty();
        }

        // For non-auto-format, check if it's on track to match the mask
        let mask_chars: Vec<char> = self.mask.chars().collect();
        let input_chars: Vec<char> = input.chars().collect();
        let mut mask_idx = 0;
        let mut input_idx = 0;
        let mut _optional = false;

        while input_idx < input_chars.len() && mask_idx < mask_chars.len() {
            let mask_ch = mask_chars[mask_idx];

            if mask_ch == '*' {
                _optional = true;
                mask_idx += 1;
                continue;
            }

            match mask_ch {
                '#' | '@' | '!' => {
                    if !self.is_valid_char_for_mask(input_chars[input_idx], mask_ch) {
                        return false;
                    }
                    input_idx += 1;
                }
                _ => {
                    // Literal must match
                    if input_chars[input_idx] != mask_ch {
                        return false;
                    }
                    input_idx += 1;
                }
            }

            mask_idx += 1;
        }

        true // Partial input is valid
    }

    fn error(&self) {
        // In a full implementation, this would show a message box
        // For now, just a no-op (the InputLine will handle visual feedback)
    }

    fn valid(&self, input: &str) -> bool {
        if self.is_valid(input) {
            true
        } else {
            self.error();
            false
        }
    }
}

/// Helper function to create a ValidatorRef for a PictureValidator
pub fn picture_validator(mask: &str) -> ValidatorRef {
    Rc::new(RefCell::new(PictureValidator::new(mask)))
}

/// Builder for creating picture validators with a fluent API.
///
/// # Examples
///
/// ```ignore
/// use turbo_vision::views::picture_validator::PictureValidatorBuilder;
///
/// // Create a phone number validator with auto-formatting
/// let validator = PictureValidatorBuilder::new()
///     .mask("(###) ###-####")
///     .build();
///
/// // Create a date validator without auto-formatting
/// let validator = PictureValidatorBuilder::new()
///     .mask("##/##/####")
///     .auto_format(false)
///     .build();
/// ```
pub struct PictureValidatorBuilder {
    mask: Option<String>,
    auto_format: bool,
}

impl PictureValidatorBuilder {
    /// Creates a new PictureValidatorBuilder with default values.
    pub fn new() -> Self {
        Self {
            mask: None,
            auto_format: true,
        }
    }

    /// Sets the picture mask pattern (required).
    ///
    /// Mask characters:
    /// - `#` : Digit (0-9)
    /// - `@` : Alpha (A-Z, a-z)
    /// - `!` : Any character
    /// - `*` : Optional character marker
    /// - Other : Literal characters
    #[must_use]
    pub fn mask(mut self, mask: impl Into<String>) -> Self {
        self.mask = Some(mask.into());
        self
    }

    /// Sets whether to auto-format input (default: true).
    #[must_use]
    pub fn auto_format(mut self, auto_format: bool) -> Self {
        self.auto_format = auto_format;
        self
    }

    /// Builds the PictureValidator.
    ///
    /// # Panics
    ///
    /// Panics if required fields (mask) are not set.
    pub fn build(self) -> PictureValidator {
        let mask = self.mask.expect("PictureValidator mask must be set");

        PictureValidator {
            mask,
            auto_format: self.auto_format,
        }
    }

    /// Builds the PictureValidator as a ValidatorRef.
    pub fn build_ref(self) -> ValidatorRef {
        Rc::new(RefCell::new(self.build()))
    }
}

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

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

    #[test]
    fn test_phone_number_mask() {
        let validator = PictureValidator::new("(###) ###-####");

        // Valid complete input
        assert!(validator.is_valid("(555) 123-4567"));

        // Invalid - wrong format
        assert!(!validator.is_valid("555-123-4567"));
        assert!(!validator.is_valid("(abc) def-ghij"));
    }

    #[test]
    fn test_date_mask() {
        let validator = PictureValidator::new("##/##/####");

        // Valid dates
        assert!(validator.is_valid("12/25/2023"));
        assert!(validator.is_valid("01/01/2000"));

        // Invalid dates
        assert!(!validator.is_valid("12-25-2023")); // Wrong separator
        assert!(!validator.is_valid("1/1/2023"));   // Missing leading zeros
    }

    #[test]
    fn test_format_phone_number() {
        let validator = PictureValidator::new("(###) ###-####");

        // Format digits only
        assert_eq!(validator.format("5551234567"), "(555) 123-4567");
        assert_eq!(validator.format("555 123 4567"), "(555) 123-4567");
    }

    #[test]
    fn test_format_date() {
        let validator = PictureValidator::new("##/##/####");

        assert_eq!(validator.format("12252023"), "12/25/2023");
        assert_eq!(validator.format("01012000"), "01/01/2000");
    }

    #[test]
    fn test_alpha_mask() {
        let validator = PictureValidator::new("@@@@-####");

        assert!(validator.is_valid("ABCD-1234"));
        assert!(!validator.is_valid("1234-ABCD")); // Wrong order
    }

    #[test]
    fn test_optional_section() {
        let validator = PictureValidator::new("###*-####");

        // With optional dash
        assert!(validator.is_valid("123-4567"));
        // Without optional dash (not fully supported yet)
        // This test shows the current limitation
    }

    #[test]
    fn test_any_character_mask() {
        let validator = PictureValidator::new("!!!-!!!!");

        assert!(validator.is_valid("abc-123d"));
        assert!(validator.is_valid("XYZ-ABCD"));
    }

    #[test]
    fn test_partial_input_validation() {
        let validator = PictureValidator::new("(###) ###-####");

        // Partial inputs should be valid during typing
        assert!(validator.is_valid_input("(5", false));
        assert!(validator.is_valid_input("(55", false));
        assert!(validator.is_valid_input("(555", false));
        assert!(validator.is_valid_input("(555) ", false));
        assert!(validator.is_valid_input("(555) 1", false));
    }

    #[test]
    fn test_empty_input() {
        let validator = PictureValidator::new("##/##/####");
        assert!(validator.is_valid("")); // Empty is valid
    }

    #[test]
    fn test_validator_trait() {
        let validator = PictureValidator::new("(###) ###-####");
        assert!(validator.valid("(555) 123-4567"));
        assert!(!validator.valid("invalid"));
    }

    #[test]
    fn test_picture_validator_builder() {
        let validator = PictureValidatorBuilder::new()
            .mask("##/##/####")
            .build();

        assert!(validator.is_valid("12/25/2023"));
        assert_eq!(validator.mask(), "##/##/####");
    }

    #[test]
    fn test_picture_validator_builder_no_format() {
        let validator = PictureValidatorBuilder::new()
            .mask("(###) ###-####")
            .auto_format(false)
            .build();

        assert!(validator.is_valid("(555) 123-4567"));
    }
}