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: StdoutHandle to stdout for terminal operations
command_history: Vec<String>Command history for up/down navigation
current_input: StringCurrent 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: boolA flag used to exit the application.
app_name: StringApplication name, could be set to any valid text your like.
raw_mode_enabled: boolWhether raw mode is enabled
Implementations§
Source§impl TerminalApp
impl TerminalApp
Sourcepub fn new() -> Self
pub fn new() -> Self
Creates a new terminal application instance with default settings.
Some attributes are allowed to be modified later, like app_name.
Sourcepub fn enable_tab_completion(&mut self)
pub fn enable_tab_completion(&mut self)
Enables tab completion and initializes the completion tree.
Sourcepub fn is_tab_completion_enabled(&self) -> bool
pub fn is_tab_completion_enabled(&self) -> bool
Checks if tab completion is currently enabled.
Sourcepub fn register_tab_completions(&mut self, context: &str, completions: &[&str])
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"]);Sourcepub fn register_tab_completions_with_desc(
&mut self,
context: &str,
items: &[(&str, &str)],
)
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 completionsitems- List of (text, description) tuples
Sourcepub fn add_tab_completion(
&mut self,
context: &str,
text: &str,
description: Option<&str>,
)
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 totext- Completion textdescription- Optional description
Sourcepub async fn shutdown_terminal(
&mut self,
exit_message: &str,
) -> Result<(), Box<dyn Error>>
pub async fn shutdown_terminal( &mut self, exit_message: &str, ) -> Result<(), Box<dyn Error>>
Sourcepub async fn read_input(&mut self) -> Result<Option<String>, Box<dyn Error>>
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 stringOk(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(())
}Sourcepub async fn run(
&mut self,
startup_message: &str,
exit_message: &str,
) -> Result<(), Box<dyn Error>>
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 startupexit_message- Optional message to display on exit
§Errors
Returns an error if terminal initialization or event handling fails.
Sourcepub fn clear_input_line(&mut self)
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.
Sourcepub fn print_log_entry(&mut self, log_line: &str)
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.
Sourcepub async fn handle_ctrl_d(&mut self) -> Result<bool, Box<dyn Error>>
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.
Sourcepub async fn handle_ctrl_c(&mut self) -> Result<(bool, String), Box<dyn Error>>
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).
Sourcepub async fn handle_enter_key(
&mut self,
input_prefix: &str,
) -> Result<(bool, Option<String>), Box<dyn Error>>
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).
Sourcepub fn info(&mut self, message: &str)
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...");
}Sourcepub fn debug(&mut self, message: &str)
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...");
}Sourcepub fn warn(&mut self, message: &str)
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...");
}Sourcepub fn error(&mut self, message: &str)
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.");
}Sourcepub fn critical(&mut self, message: &str)
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.");
}Sourcepub fn logger(
&mut self,
level: LogLevel,
message: &str,
module_name: Option<&str>,
)
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 loggedmodule_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);
}