w3resource

Create Interactive Terminal UIs in Rust


Rust TUI: Building Terminal-Based User Interfaces

Rust TUI (Text User Interface) allows developers to create interactive, text-based interfaces directly in the terminal. These interfaces are ideal for command-line applications, dashboards, or lightweight tools that don't require graphical environments. Rust offers several libraries for TUI development, such as tui-rs and crossterm, which simplify creating terminal-based UIs.


Why use Rust for TUI Development?

  • Performance: Rust's low-level access ensures snappy terminal applications.
  • Safety: Memory safety and concurrency make applications robust.
  • Ecosystem: Libraries like tui-rs provide high-level abstractions for complex UIs.
  • Cross-Platform: Rust ensures consistent behavior across different operating systems.

Popular Libraries for Rust TUI

    1. tui-rs:

    • Provides high-level abstractions for layout, widgets, and rendering.
    • Integrates well with crossterm for terminal manipulation.

    2. crossterm:

    • Focuses on low-level terminal interactions like cursor control and event handling.
    • Ideal for those who want granular control.

    3. ratatui (a tui-rs fork):

    • A modern version of tui-rs with enhanced features and bug fixes.

Example: Building a Simple TUI with tui-rs

Step 1: Add Dependencies to Cargo.toml

Code:

[dependencies]
tui = "0.19"           # TUI library for layouts and widgets
crossterm = "0.25"     # Crossterm for terminal management

Step 2: Write the Code

Code:

use crossterm::event::{self, Event, KeyCode}; // Import terminal event handling
use crossterm::terminal::{disable_raw_mode, enable_raw_mode}; // For raw terminal mode
use std::io::{self, stdout}; // Input-output handling
use tui::backend::{CrosstermBackend, Backend}; // TUI backend for rendering
use tui::layout::{Layout, Constraint, Direction}; // For arranging UI components
use tui::widgets::{Block, Borders, Paragraph}; // Widgets for the UI
use tui::Terminal; // Terminal rendering

fn main() -> Result<(), io::Error> {
    // Enable raw mode for better terminal control
    enable_raw_mode()?;

    // Create a terminal backend with Crossterm
    let stdout = stdout();
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    // Application logic: keep running until 'q' is pressed
    loop {
        // Draw the UI
        terminal.draw(|f| {
            // Create a vertical layout with 2 sections
            let chunks = Layout::default()
                .direction(Direction::Vertical)
                .constraints([Constraint::Percentage(50), Constraint::Percentage(50)].as_ref())
                .split(f.size());

            // Create a block with borders
            let block = Block::default()
                .title("Block 1")
                .borders(Borders::ALL);

            let paragraph = Paragraph::new("Press 'q' to quit").block(Block::default().borders(Borders::ALL));

            // Render the widgets in their respective chunks
            f.render_widget(block, chunks[0]);
            f.render_widget(paragraph, chunks[1]);
        })?;

        // Handle key events
        if let Event::Key(key) = event::read()? {
            if key.code == KeyCode::Char('q') {
                break; // Exit the loop on 'q'
            }
        }
    }

    // Restore terminal to normal mode
    disable_raw_mode()?;
    Ok(())
}

Explanation

    1. Setup:

    • enable_raw_mode: Switches the terminal to raw mode for precise control.
    • CrosstermBackend: Provides backend for tui-rs.

    2. Layout:

    • Layout: Splits the terminal into sections using percentages or fixed sizes.
    • Block: Adds borders and titles to sections.

    3. Widgets:

    • Paragraph: Displays text in a section.

    4. Event Handling:

    • Listens for key presses using crossterm::event. The app exits when 'q' is pressed.

    5. Cleanup:

    • disable_raw_mode: Restores the terminal to its normal state after exiting.

Output:

When you run this program, the terminal will display two sections. The top block will have a title Block 1, and the bottom section will display the text Press 'q' to quit.


Advanced Features

    1. Dynamic Layouts: Adjust sizes and directions dynamically based on terminal size.

    2. Interactive Widgets: Add progress bars, input fields, or graphs.

    3. Multi-threading: Use Rust's concurrency features to handle background tasks.


When to Use Rust TUI

  • CLI Tools: Enhance command-line utilities with interactive interfaces.
  • Dashboards: Display real-time data in a visually appealing manner.
  • Minimalist Applications: Create lightweight tools without requiring graphical dependencies.

Rust Language Questions, Answers, and Code Snippets Collection.



Follow us on Facebook and Twitter for latest update.