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 cursor_position: usize,
    pub should_exit: bool,
    pub action_sender: Option<UnboundedSender<AppAction>>,
    /* private fields */
}
Expand description

Main terminal application structure managing state and command execution.

TerminalApp provides a complete terminal interface with:

  • Command history navigation
  • Cursor management
  • Custom command registration (sync and async)
  • Configurable unknown command handling
  • Non-blocking async command execution

Fields§

§stdout_handle: Stdout§command_history: Vec<String>§current_input: String§history_index: Option<usize>§last_ctrl_c: Option<Instant>§cursor_position: usize§should_exit: bool§action_sender: Option<UnboundedSender<AppAction>>

Implementations§

Source§

impl TerminalApp

Source

pub fn new() -> Self

Creates a new terminal application instance with default settings.

Examples found in repository?
demo/main.rs (line 7)
6async fn main() {
7    let mut app = TerminalApp::new();
8    register_commands(&mut app).await;
9    let _ = app
10        .run(&get_info!("App demo starting...", "Demo"), "")
11        .await;
12}
Source

pub fn register_command<S: Into<String>>( &mut self, name: S, handler: Box<dyn CommandHandler>, )

Registers a synchronous command handler with the application.

§Arguments
  • name - Command name that users will type
  • handler - Boxed command handler implementing CommandHandler
Source

pub fn register_async_command<S: Into<String>>( &mut self, name: S, handler: Box<dyn AsyncCommandHandler>, )

Registers an asynchronous command handler with the application.

§Arguments
  • name - Command name that users will type
  • handler - Boxed async command handler implementing AsyncCommandHandler
Examples found in repository?
demo/main.rs (line 15)
14async fn register_commands(app: &mut TerminalApp) {
15    app.register_async_command("register", Box::new(RegisterCommand {}));
16}
Source

pub fn set_unknown_command_handler<F>(&mut self, handler: F)
where F: Fn(&str) -> String + Send + Sync + 'static,

Sets a custom handler for unknown commands (synchronous).

§Arguments
  • handler - Closure that takes the full command string and returns a response
Source

pub fn set_async_unknown_command_handler<F>(&mut self, handler: F)
where F: Fn(&str) -> BoxFuture<'static, String> + Send + Sync + 'static,

Sets a custom handler for unknown commands (asynchronous).

§Arguments
  • handler - Closure that takes the full command string and returns a future
Source

pub fn clear_unknown_command_handler(&mut self)

Removes the custom unknown command handler.

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
  • stdout - Mutable reference to standard output
§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
  • stdout - Mutable reference to standard output
  • exit_message - Message to display on exit
§Errors

Returns an error if terminal shutdown fails.

Source

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

Main application loop that handles terminal input and command execution.

Initializes terminal event handling, processes keyboard input, and manages command execution until exit is requested. Handles special key combinations like Ctrl+C for graceful shutdown.

§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.

Examples found in repository?
demo/main.rs (line 10)
6async fn main() {
7    let mut app = TerminalApp::new();
8    register_commands(&mut app).await;
9    let _ = app
10        .run(&get_info!("App demo starting...", "Demo"), "")
11        .await;
12}
Source

pub fn clear_input_line(&mut self)

Clear the current input line and re-renders it.

Source

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

Prints a log entry while preserving the input line.

Clears the current line, prints the log message, and re-renders the input line.

§Arguments
  • stdout - Mutable reference to standard output
  • log_line - Log message to display
§Errors

Returns an error if writing to stdout fails.

Source

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

Handles Ctrl+D key press, signaling application exit.

§Returns

Ok(true) to signal the application should quit.

Source

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

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

The first press clears input, the second press within 5 seconds exits.

§Returns

Tuple of (should_quit, message_to_display)

Source

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

Handles Enter key press to execute the current command.

§Arguments
  • stdout - Mutable reference to standard output
  • input_prefix - Prefix to display before echoing the command
§Errors

Returns an error if writing to stdout fails.

Source

pub async fn execute_command(&mut self, command: &str) -> String

Executes a command by looking it up in the registered commands.

For sync commands, executes immediately and returns the result. For async commands, spawns them in the background and returns immediately.

§Arguments
  • command - Full command string including arguments
§Returns

String output from the command execution (empty for async commands)

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::TerminalApp;

fn 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::TerminalApp;

fn 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::TerminalApp;

fn 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::TerminalApp;

fn 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::TerminalApp;

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

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.