Skip to main content

TerminalApp

Struct TerminalApp 

Source
pub struct TerminalApp {
    pub stdout_handle: Stdout,
    pub command_history: Vec<String>,
    pub current_input: String,
    pub history_index: Option<usize>,
    pub last_ctrl_c: Option<Instant>,
    pub should_exit: bool,
    pub app_name: String,
    pub raw_mode_enabled: bool,
    /* private fields */
}
Expand description

Main terminal application structure managing state and input/output.

TerminalApp provides a complete terminal interface with:

  • Command history navigation
  • Cursor management
  • Colored logging support
  • Non-blocking input handling
  • Tab completion support

Fields§

§stdout_handle: Stdout

Handle to stdout for terminal operations

§command_history: Vec<String>

Command history for up/down navigation

§current_input: String

Current input buffer

§history_index: Option<usize>

Index in command history (None = not browsing history)

§last_ctrl_c: Option<Instant>

Timestamp of last Ctrl+C press for double-tap detection

§should_exit: bool

A flag used to exit the application.

§app_name: String

Application name, could be set to any valid text your like.

§raw_mode_enabled: bool

Whether raw mode is enabled

Implementations§

Source§

impl TerminalApp

Source

pub fn new() -> Self

Creates a new terminal application instance with default settings.

Some attributes are allowed to be modified later, like app_name.

Source

pub fn enable_tab_completion(&mut self)

Enables tab completion and initializes the completion tree.

Source

pub fn is_tab_completion_enabled(&self) -> bool

Checks if tab completion is currently enabled.

Source

pub fn register_tab_completions(&mut self, context: &str, completions: &[&str])

Registers completions for a given context.

§Arguments
  • context - The input prefix that triggers these completions (empty string for root)
  • completions - List of completion texts
§Examples
use daemon_console_lite::TerminalApp;

let mut app = TerminalApp::new();
app.enable_tab_completion();
app.register_tab_completions("!config", &["start", "stop", "restart"]);
Source

pub fn register_tab_completions_with_desc( &mut self, context: &str, items: &[(&str, &str)], )

Registers completions with descriptions.

§Arguments
  • context - The input prefix that triggers these completions
  • items - List of (text, description) tuples
Source

pub fn add_tab_completion( &mut self, context: &str, text: &str, description: Option<&str>, )

Adds a single completion item to an existing context.

§Arguments
  • context - The context to add to
  • text - Completion text
  • description - Optional description
Source

pub async fn init_terminal( &mut self, startup_message: &str, ) -> Result<(), Box<dyn Error>>

Initializes the terminal with raw mode and displays startup messages.

§Arguments
  • startup_message - Message to display on startup
§Errors

Returns an error if terminal initialization fails.

Source

pub async fn process_event( &mut self, event: Event, ) -> Result<bool, Box<dyn Error>>

Processes a single terminal event and returns whether the app should quit.

§Arguments
  • event - Terminal event to process
§Returns

Ok(true) if the application should exit, Ok(false) otherwise

§Errors

Returns an error if event processing fails.

Source

pub async fn shutdown_terminal( &mut self, exit_message: &str, ) -> Result<(), Box<dyn Error>>

Shuts down the terminal and displays exit messages.

§Arguments
  • exit_message - Message to display on exit
§Errors

Returns an error if terminal shutdown fails.

Source

pub async fn read_input(&mut self) -> Result<Option<String>, Box<dyn Error>>

Waits for and returns the next user input event.

This method processes terminal events in a non-blocking manner and returns when the user presses Enter with non-empty input or when a quit signal is received.

§Returns
  • Ok(Some(String)) - User entered a non-empty string
  • Ok(None) - User should exit (Ctrl+C, Ctrl+D, or should_exit flag set)
§Errors

Returns an error if terminal event processing fails.

§Examples
use daemon_console_lite::TerminalApp;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut app = TerminalApp::new();
    app.init_terminal("Welcome!").await?;

    while let Some(input) = app.read_input().await? {
        app.info(&format!("You entered: {}", input));
    }

    app.shutdown_terminal("Goodbye!").await?;
    Ok(())
}
Source

pub async fn run( &mut self, startup_message: &str, exit_message: &str, ) -> Result<(), Box<dyn Error>>

Simple convenience method that runs a basic input loop.

For more control, use init_terminal(), read_input(), and shutdown_terminal() separately.

§Arguments
  • startup_message - Optional message to display on startup
  • exit_message - Optional message to display on exit
§Errors

Returns an error if terminal initialization or event handling fails.

Source

pub fn clear_input_line(&mut self)

Clears the current input line and completion hints if rendered.

If hints_rendered is true, this clears both the input line and the line below it containing completion hints. Otherwise, only the current line is cleared.

Source

pub fn print_log_entry(&mut self, log_line: &str)

Prints a log entry while preserving the input line.

Clears the input line, outputs the log message, then re-renders the input line on a new line without clearing first.

Source

pub async fn handle_ctrl_d(&mut self) -> Result<bool, Box<dyn Error>>

Handles Ctrl+D key press to exit the application.

Clears the input line and completions before returning true to signal exit.

Source

pub async fn handle_ctrl_c(&mut self) -> Result<(bool, String), Box<dyn Error>>

Handles Ctrl+C key press with double-press confirmation.

  • First press (with input): clears input and completions
  • First press (no input): prompts for confirmation
  • Second press within 5 seconds: exits application

Returns (should_quit, message_to_display).

Source

pub async fn handle_enter_key( &mut self, input_prefix: &str, ) -> Result<(bool, Option<String>), Box<dyn Error>>

Handles Enter key press to submit input.

If input is non-empty, adds it to history, echoes it with the prefix, clears the input state, and returns the input string. If empty, just clears and re-renders the input line.

Returns (should_exit, optional_input_string).

Source

pub fn info(&mut self, message: &str)

Log info-level messages.

This method ensures proper terminal line management by clearing the current input line, printing the log message, and then re-rendering the input line.

§Arguments
  • message - The message content to be logged.
§Examples
use daemon_console_lite::TerminalApp;

fn needless_main() {
    let mut app = TerminalApp::new();
    app.info("Application started successfully!");
    app.info("Running tasks...");
}
Source

pub fn debug(&mut self, message: &str)

Log debug-level messages.

§Examples
use daemon_console_lite::TerminalApp;

fn needless_main() {
    let mut app = TerminalApp::new();
    app.debug("Debugging information...");
    app.debug("Debugging more...");
}
Source

pub fn warn(&mut self, message: &str)

Log warn-level messages.

§Examples
use daemon_console_lite::TerminalApp;

fn needless_main() {
    let mut app = TerminalApp::new();
    app.warn("You get a warning!");
    app.warn("Continue running...");
}
Source

pub fn error(&mut self, message: &str)

Log error-level messages.

§Examples
use daemon_console_lite::TerminalApp;

fn needless_main() {
    let mut app = TerminalApp::new();
    app.error("An error occurred!");
    app.error("Failed to run tasks.");
}
Source

pub fn critical(&mut self, message: &str)

Log critical-level messages.

§Examples
use daemon_console_lite::TerminalApp;

fn needless_main() {
    let mut app = TerminalApp::new();
    app.critical("Application crashed!");
    app.critical("Exception: unknown.");
}
Source

pub fn logger( &mut self, level: LogLevel, message: &str, module_name: Option<&str>, )

Unified logger method that allows specifying a custom module name for the log message.

§Arguments
  • level - The log level (Info, Warn, Error, Debug, Critical)
  • message - The message content to be logged
  • module_name - The name of the module to associate with the log message (optional)
§Examples
use daemon_console_lite::{TerminalApp, logger::LogLevel};

fn example() {
    let mut app = TerminalApp::new();
    app.logger(LogLevel::Info, "Application started", Some("Main"));
    app.logger(LogLevel::Error, "Database connection failed", None);
}

Trait Implementations§

Source§

impl Default for TerminalApp

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.