turbo-vision 2.4.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
# Turbo Vision - Rust TUI Library

<p align="center">
  <a href="https://ai.enzolombardi.net/"><img src="https://img.shields.io/badge/built%20with-AI-D97757?style=flat-square&labelColor=101010&logo=anthropic&logoColor=white" alt="Built with AI — part of Enzo Lombardi's AI portfolio"></a>
</p>


<img src="https://raw.githubusercontent.com/aovestdipaperino/turbo-vision-4-rust/main/logo.png" alt="Turbo Vision Logo" width="384" align="right" />

A Rust implementation of the classic Borland Turbo Vision text user interface framework.

**Version 2.0.0 - PRODUCTION READY** ✅

Based on
kloczek Borland Turbo Vision C++ port [here](https://github.com/kloczek/tvision)

Other C++ implementations:
- [Magiblot Turbo Vision for C++]https://github.com/magiblot/tvision
- [Borland Original Turbo Vision 2.0.3 code]http://www.sigala.it/sergio/tvision/source/tv2orig.zip

This port achieves **100% API parity** with
kloczek port of Borland Turbo Vision C++. All features from the original framework have been implemented. While the codebase is complete and production-ready, it may contain bugs. Please report any issues you encounter!

## Screenshots

### Showcase: Multiple Windows

The showcase demo with Calculator, Calendar, ASCII Table, and Puzzle windows demonstrating overlapping window management, z-ordering, and shadows.

![Showcase](screenshots/showcase-v2.png)

### Code Editor

A full-featured text editor (`pascal_ide`) editing its own source code, with menu bar, status line, and scrollable editing area.

![Code Editor](screenshots/code-editor-v2.png)

### Help Window

Context-sensitive help system (F1) with scrollable content, rendered over the editor window.

![Help Window](screenshots/help-window-v2.png)

### File System Tree

A tree view widget displaying a hierarchical file system with expandable/collapsible directories, keyboard navigation, and selection highlighting.

![File System Tree](screenshots/file-tree-v2.png)

### File Chooser Dialog

The built-in file dialog with directory navigation, file list, and keyboard/mouse support.

![File Dialog](screenshots/file-dialog-v2.png)

## Features

- **Complete UI Component Set**: Windows, dialogs, buttons, input fields, menus, status bars, scrollbars
- **Z-Order Management**: Click any non-modal window to bring it to the front
- **Modal Dialog Support**: Modal dialogs block interaction with background windows
- **Borland-Accurate Styling**: Menu borders and shadows match original Borland Turbo Vision
- **Scrollable Views**: Built-in scrollbar support with keyboard navigation
- **Text Viewer**: Ready-to-use scrollable text viewer with line numbers
- **Event-Driven Architecture**:
  - Three-phase event processing (PreProcess → Focused → PostProcess)
  - Event re-queuing for deferred processing
  - Owner-aware broadcast system to prevent echo back to sender
- **Mouse Support**: Full mouse support for buttons, menus, status bar, dialog close buttons, scroll wheel, and double-click detection
- **Window Dragging and Resizing**: Drag windows by title bar, resize by bottom-right corner
- **Flexible Layout System**: Geometry primitives with absolute and relative positioning
- **Color Support**: 16-color palette with Borland-accurate attribute system and context-aware remapping
- **Text Styling**: Bold, dim, italic, underline, reverse, and strikethrough attributes — composable via `Attr::new(fg, bg).bold().italic()`, emitted as real SGR codes on the terminal and in ANSI dumps (see `cargo run --example text_styling`)
- **Editor Selection**: Stream selection (Shift+arrows / drag) plus rectangular **block selection** with columnar copy/cut and single-step undo, switched with the global block-edit mode (`Application::set_block_edit_mode`, `CM_TOGGLE_BLOCK_MODE`) rather than a modifier key; `CM_SELECT_ALL` command and Ctrl+A select all content of the focused window
- **Cross-Platform**: Built on crossterm for wide terminal compatibility
- **SSH Support**: Optional SSH backend to serve TUI applications over SSH connections
- **Modal Dialogs**: Built-in support for modal dialog execution
- **Focus Management**: Tab navigation and keyboard shortcuts
- **Screen Capture**: F12 saves an ASCII (ANSI) dump of the whole screen; Ctrl+F12 saves a PNG screenshot. Programmatic dumps of screen/views/regions via `dump_screen`/`dump_region`/`dump_to_file`

## Quick Start

```rust
use turbo_vision::prelude::*;

fn main() -> turbo_vision::core::error::Result<()> {
    // Create a window
    let mut dialog = turbo_vision::views::dialog::DialogBuilder::new().bounds(Rect::new(10, 5, 50, 15)).title("My First Dialog").build();

    // Create a button and add it to the window
    let button = turbo_vision::views::button::Button::new(Rect::new(26, 6, 36, 8), "Quit", turbo_vision::core::command::CM_OK, true);
    dialog.add(Box::new(button));

    // Create the application and add the dialog to its desktop
    let mut app = Application::new()?;
    app.desktop.add(Box::new(dialog));

    // Event loop
    app.running = true;
    while app.running {
        app.desktop.draw(&mut app.terminal);
        app.terminal.flush()?;
        if let Ok(Some(mut event)) = app.terminal.poll_event(std::time::Duration::from_millis(50)) {
            app.desktop.handle_event(&mut event);
            if event.command == CM_OK {
                // Handle button click
                app.running = false;
            }
        }
    }
    Ok(())
}
```

**Tip**: Capture the screen at any time —
- **F12** saves an ASCII (ANSI-colored) dump of the whole screen to `screen-YYYYMMDD-HHMMSS.ans` (view it with `cat` or `less -R`).
- **Ctrl+F12** saves a PNG screenshot of the whole screen to `screenshot-YYYYMMDD-HHMMSS.png`.

For programmatic use, see `Terminal::dump_screen(path)`, `Terminal::dump_region(...)`, and `Terminal::save_screenshot_png(path)`.

## Palette System

The color palette system accurately replicates Borland Turbo Vision's behavior:

- **Context-Aware Remapping**: Views automatically remap colors based on their container (Dialog, Window, or Desktop)
- **Owner Type Support**: Each view tracks its owner type for correct palette inheritance
- **Borland-Accurate Colors**: All UI elements (menus, buttons, labels, dialogs) match original Borland colors
- **Runtime Customization**: Change the entire application palette at runtime with `app.set_palette()` for custom themes

The palette system uses a three-level mapping chain:
1. View palette (e.g., Button, Label) → indices 1-31
2. Container palette (Dialog/Window) → remaps to indices 32-63
3. Application palette → final RGB colors

### Custom Palettes and Theming

You can customize the entire application palette at runtime to create custom themes:

```rust
// Create a custom palette (63 bytes, each encoding foreground << 4 | background)
let dark_palette = vec![/* 63 color bytes */];

// Set the palette - redraw happens automatically!
app.set_palette(Some(dark_palette));

// Reset to default Borland palette
app.set_palette(None);
```

See `examples/palette_themes_demo.rs` for a complete example with multiple themes.

## Module Overview

- **core**: Fundamental types (geometry, events, drawing, colors)
- **terminal**: Terminal I/O abstraction layer
- **views**: UI components (dialogs, buttons, menus, etc.)
- **app**: Application framework and event loop

## Documentation

This project includes extensive documentation for different audiences and use cases. Here's a recommended reading order based on your goals:

### 🚀 New to Turbo Vision? Start Here

If you're new to Turbo Vision frameworks, follow this path:

1. **Quick Start** (above) - Get a minimal example running
2. **[Examples Overview]examples/README.md** - Browse 30+ working examples
   ```bash
   cargo run --example showcase    # Comprehensive feature showcase
   cargo run --bin pascal_ide     # Full-featured text editor
   ```
3. **[User Guide - Chapter 1]docs/user-guide/Chapter-01-Stepping-into-Turbo-Vision.md** - Learn the basics
4. **[User Guide - Chapter 2]docs/user-guide/Chapter-02-Responding-to-Commands.md** - Handle events and commands
5. **[User Guide - Chapter 3]docs/user-guide/Chapter-03-Adding-Windows.md** - Create your first window

**Continue with**: Chapters 4-18 in the [User Guide](docs/user-guide/) for comprehensive coverage of all features.

### 🎯 Building Your First App

For practical application development:

1. **[Custom Application Example]docs/CUSTOM-APPLICATION-RUST-EXAMPLE.md** - Complete walkthrough
2. **[Biorhythm Calculator Tutorial]docs/BIORHYTHM-CALCULATOR-TUTORIAL.md** - Build a real app step-by-step
3. **[examples/showcase.rs]examples/showcase.rs** - Study the comprehensive demo
4. **[pascal_ide source]demo/pascal_ide.rs** - See a production-ready editor

### 🔧 Coming from Borland/C++ Turbo Vision?

If you're familiar with Borland Turbo Vision:

1. **[Architecture Overview]docs/user-guide/Chapter-07-Architecture-Overview.md** - Understand Rust adaptations
2. **[Rust Implementation Reference]docs/RUST-IMPLEMENTATION-REFERENCE.md** - Technical details
3. **[Turbo Vision Design]docs/TURBO-VISION-DESIGN.md** - Complete design document

**Key Differences**: The Rust port uses composition over inheritance, but maintains the same event loop patterns, drawing system, and API structure as Borland's original.

### 📚 Feature-Specific Guides

When you need specific functionality:

- **Palette & Colors**: [Palette System]docs/PALETTE-SYSTEM.md, [Borland Palette Chart]docs/BORLAND-PALETTE-CHART.md, [Chapter 14]docs/user-guide/Chapter-14-Palettes-and-Color-Selection.md
- **Event Handling**: [Chapter 9 - Event-Driven Programming]docs/user-guide/Chapter-09-Event-Driven-Programming.md
- **Forms & Input**: [Chapter 5 - Data Entry Forms]docs/user-guide/Chapter-05-Creating-Data-Entry-Forms.md, [Chapter 13 - Validation]docs/user-guide/Chapter-13-Data-Validation.md
- **Text Editing**: [Chapter 15 - Editor and Text Views]docs/user-guide/Chapter-15-Editor-and-Text-Views.md
- **Collections & Lists**: [Chapter 6 - Managing Data Collections]docs/user-guide/Chapter-06-Managing-Data-Collections.md
- **Persistence**: [Serialization Guide]docs/SERIALIZATION-PERSISTENCE.md, [Quick Reference]docs/SERIALIZATION-QUICK-REFERENCE.md
- **Application Structure**: [Chapter 10 - Application Objects]docs/user-guide/Chapter-10-Application-Objects.md
- **Windows & Dialogs**: [Chapter 11 - Window and Dialog Box Objects]docs/user-guide/Chapter-11-Window-and-Dialog-Box-Objects.md

### 📖 API Reference

For API lookups and function signatures:

- **[Documentation Index]docs/DOCUMENTATION-INDEX.md** - Master index of all documentation
- **[Rust API Catalog]docs/RUST-API-CATALOG.md** - Complete API listing
- **[API Catalog Index]docs/RUST-API-CATALOGUE-INDEX.md** - Quick reference guide
- **Inline Docs**: Run `cargo doc --open` for generated documentation

### 🛠️ Contributing to the Project

If you want to modify or extend the codebase:

1. **[Rust Coding Guidelines]docs/RUST-CODING-GUIDELINES.md** - Code style and best practices
2. **[Chapter 8 - Views and Groups]docs/user-guide/Chapter-08-Views-and-Groups.md** - Understanding the view hierarchy
3. Study existing tests in `src/views/*/tests` modules

### 📂 Complete Documentation Structure

```
docs/
├── DOCUMENTATION-INDEX.md              # Master index
├── RUST-CODING-GUIDELINES.md          # Code style guide
├── CUSTOM-APPLICATION-RUST-EXAMPLE.md  # Complete app walkthrough
├── BIORHYTHM-CALCULATOR-TUTORIAL.md    # Step-by-step tutorial
├── PALETTE-SYSTEM.md                   # Color system explained
├── BORLAND-PALETTE-CHART.md            # Color reference
├── RUST-API-CATALOG.md                 # API reference
├── TURBO-VISION-DESIGN.md              # Complete design document
├── SERIALIZATION-PERSISTENCE.md         # Saving/loading data
└── user-guide/                         # 18-chapter comprehensive guide
    ├── Chapter-01-Stepping-into-Turbo-Vision.md
    ├── Chapter-02-Responding-to-Commands.md
    ├── ... (Chapters 3-17)
    └── Chapter-18-Resources.md

examples/
├── README.md                           # Examples index with descriptions
├── showcase.rs                         # Comprehensive demo
├── biorhythm.rs                        # Complete calculator app
└── ... (30+ more examples)

demo/
└── pascal_ide.rs                      # Production text editor
```

### 🔗 Quick Links

- **Start Coding**: [Quick Start]#quick-start[Examples]examples/README.md
- **Learn Concepts**: [User Guide Chapter 1]docs/user-guide/Chapter-01-Stepping-into-Turbo-Vision.md
- **Build an App**: [Custom Application Example]docs/CUSTOM-APPLICATION-RUST-EXAMPLE.md
- **Get Help**: [Documentation Index]docs/DOCUMENTATION-INDEX.md
- **Report Issues**: [GitHub Issues]https://github.com/aovestdipaperino/turbo-vision-4-rust/issues



## Status

Currently implements:
- ✅ Core drawing and event system
- ✅ Dialog boxes with frames and close buttons
- ✅ Buttons with keyboard shortcuts
- ✅ Static text labels (with centered text support)
- ✅ Input fields
- ✅ Menu bar with dropdowns and keyboard shortcut display
- ✅ Status line with hot spots (hover highlighting, context-sensitive hints)
- ✅ Desktop manager
- ✅ Scrollbars (vertical and horizontal)
- ✅ Scroller base class for scrollable views
- ✅ Indicator (position display)
- ✅ Text viewer with scrolling
- ✅ CheckBoxes and RadioButtons (single, or multi-item clusters with one bitmask value)
- ✅ ListBoxes (single selection, or multi-select with Space and Shift+click)
- ✅ Memo (multi-line text editor)
- ✅ ProgressBar (determinate and marquee, three glyph styles)
- ✅ ComboBox (read-only field with a drop-down list)
- ✅ Spinner (numeric field with steppers, range-clamped)
- ✅ Table (grid with header row, sized columns, cell focus)
- ✅ TabbedPane (enclosed tabs over a stack of pages)
- ✅ SplitPane (two panes with a draggable divider)
- ✅ Tooltip (hover hints for a dialog's controls)
- ✅ Mouse support (buttons, menus, status bar, close buttons, hover effects, listbox clicks, scroll wheel, double-click detection)
- ✅ Window dragging and resizing (drag by title bar, resize from bottom-right corner with minimum size constraints)
- ✅ Window closing (non-modal windows close with close button, modal dialogs convert to cancel)
- ✅ File Dialog (fully functional with mouse/keyboard support and directory navigation)
- ✅ ANSI Dump for debugging (dump screen/views to text files with colors)
- ✅ Input Validators (FilterValidator, RangeValidator with hex/octal, LookupValidator)
- ✅ Editor with search/replace and file I/O (load_file, save_file, save_as)
- ✅ EditWindow (ready-to-use editor window wrapper)
- ✅ OS Clipboard integration (cross-platform with arboard)
- ✅ Help System (markdown-based with HelpFile, HelpViewer, HelpWindow, HelpContext)
- ✅ SSH TUI Bridge (optional feature for serving TUI apps over SSH)

## SSH Support

Turbo Vision can serve TUI applications over SSH connections, enabling remote terminal access to your application. This is useful for admin consoles, monitoring dashboards, and tools that need to be accessed remotely.

### Enabling SSH Support

SSH support is behind a feature flag. Enable it in your `Cargo.toml`:

```toml
[dependencies]
turbo-vision = { version = "2.3", features = ["ssh"] }
```

Or build with the feature:

```bash
cargo build --features ssh
```

### Quick Example

```rust
use turbo_vision::prelude::*;
use turbo_vision::terminal::{Backend, SshBackend, SshSessionBuilder};
use turbo_vision::ssh::{SshServer, SshServerConfig};
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = SshServerConfig::default();
    let server = SshServer::new(config)?;

    server.run("0.0.0.0:2222", |backend| {
        // Create Terminal with SSH backend
        let terminal = Terminal::with_backend(backend).unwrap();
        run_your_tui_app(terminal);
    }).await?;

    Ok(())
}
```

### Running the Example

```bash
# Start the SSH server
cargo run --example ssh_server --features ssh

# Connect from another terminal
ssh -p 2222 user@localhost
# Password: any (accepts any password in the example)
```

### Architecture

The SSH support uses a Backend trait abstraction:

- **Backend trait**: Abstracts terminal I/O operations
- **CrosstermBackend**: Default implementation for local terminals
- **SshBackend**: Implementation for SSH channel I/O
- **InputParser**: Converts raw terminal bytes to turbo-vision events

This allows the same TUI application to run locally or over SSH with no code changes.

## Architecture

This implementation closely follows Borland Turbo Vision's architecture, adapted for Rust:

- **Event Loop**: Located in `Group` (matching Borland's `TGroup::execute()`), not in individual views
- **Modal Dialogs**: Use Borland's `endModal()` pattern to exit event loops
- **View Hierarchy**: Composition-based design (`Window` contains `Group`, `Dialog` wraps `Window`)
- **Drawing**: Event-driven redraws with Borland's `drawUnderRect` pattern for efficient updates
- **Event System**:
  - Three-phase processing (PreProcess → Focused → PostProcess) matching Borland's `TGroup::handleEvent()`
  - Event re-queuing via `Terminal::put_event()` matching Borland's `TProgram::putEvent()`
  - Owner-aware broadcasts via `Group::broadcast()` matching Borland's `message(owner, ...)` pattern

## Project Statistics

```
===============================================================================
 Language            Files        Lines         Code     Comments       Blanks
===============================================================================
 Rust                  125        37315        28029         3557         5729
 |- Markdown           102         4695          332         3604          759
 (Total)                          42010        28361         7161         6488
===============================================================================
```

Generated with [tokei](https://github.com/XAMPPRocky/tokei) - includes inline documentation

**226 unit tests** - all passing ✅

## Star History

<a href="https://www.star-history.com/#aovestdipaperino/turbo-vision-4-rust&Date">
 <picture>
   <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=aovestdipaperino/turbo-vision-4-rust&type=Date&theme=dark" />
   <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=aovestdipaperino/turbo-vision-4-rust&type=Date" />
   <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=aovestdipaperino/turbo-vision-4-rust&type=Date" />
 </picture>
</a>

## License

MIT License - see [LICENSE](LICENSE) file for details.