### Install Ratisui with WinGet Source: https://github.com/honhimw/ratisui/blob/main/README.md Install Ratisui on Windows using the WinGet package manager. ```shell winget install HonhimW.Ratisui ``` -------------------------------- ### Install Ratisui with Cargo Source: https://github.com/honhimw/ratisui/blob/main/README.md Install Ratisui from source using Cargo, fetching the repository from GitHub. ```shell cargo install --git=https://github.com/honhimW/ratisui.git ``` -------------------------------- ### Example Theme File (theme/.ron) Source: https://github.com/honhimw/ratisui A minimal theme configuration example showing the `kind` and `toast` sections. Missing keys and sections fall back to defaults. See `assets/theme-template.ron` for the complete template. ```ron // ~/.config/ratisui/theme/your-theme.ron ( kind: Dark, toast: ( info: Tailwind(GREEN, C700), warn: Yellow, error: Rgb(255, 0, 0), ), ) ``` -------------------------------- ### Install Ratisui with Homebrew Source: https://github.com/honhimw/ratisui/blob/main/README.md Install Ratisui on macOS using Homebrew from the honhimW tap. ```shell brew install honhimW/tap/ratisui ``` -------------------------------- ### config.ron example Source: https://github.com/honhimw/ratisui Example configuration file for Ratisui. Values reflect defaults in source except `fps: 45` which is a user edit. All RON structures derive Serialize/Deserialize; unknown/missing fields fall back to serde defaults. ```ron // ~/.config/ratisui/config.ron ( fps: 45, scan_size: 500, try_format: false, theme: Some("your-theme"), history_size: 1000, cli_output_format: Redis, console_capacity: 2000, enable_mouse_capture: false, ) ``` -------------------------------- ### Install Ratisui with curl Source: https://github.com/honhimw/ratisui/blob/main/README.md Install Ratisui via the official shell script. Requires curl and sh. ```shell curl --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/honhimW/ratisui/main/scripts/install.sh | sh ``` -------------------------------- ### Tui::init Source: https://github.com/honhimw/ratisui Initializes the terminal backend by enabling raw mode, entering alternate screen, optionally enabling mouse capture, and installing a panic hook to restore the terminal. ```APIDOC ## Tui::init ### Description Initializes the terminal backend by enabling raw mode, entering alternate screen, optionally enabling mouse capture, and installing a panic hook to restore the terminal. ### Method init ### Parameters None ### Returns - **Result** - The initialized terminal backend. ### Request Example ```rust let mut terminal = tui.init()?; ``` ``` -------------------------------- ### Popup builder chain example Source: https://github.com/honhimw/ratisui Shows how to construct a Popup with a title, bottom title position, all borders, and double border set, then render it. ```rust let popup = Popup::new(paragraph) .title(String::from(" [Enter] Confirm | [Esc] Cancel ")) .title_position(Position::Bottom) .borders(Borders::ALL) .border_set(symbols::border::DOUBLE); frame.render_widget(popup, area); ``` -------------------------------- ### load_database_configuration Source: https://github.com/honhimw/ratisui Loads the database profile list from databases.ron. Starts from Databases::empty(). ```APIDOC ## load_database_configuration ### Description Loads the database profile list from databases.ron. Starts from Databases::empty(). ### Function Signature ```rust pub fn load_database_configuration() -> Result ``` ### Returns - `Result` - The loaded databases or an error. ``` -------------------------------- ### async_redis_opt usage example Source: https://github.com/honhimw/ratisui Shows awaiting a single GET operation and returning the value as String. ```rust use ratisui_core::redis_opt::async_redis_opt; let value: String = async_redis_opt(|operations| async move { Ok(operations.get("some_key").await?) }).await?; ``` -------------------------------- ### Tui usage example Source: https://github.com/honhimw/ratisui Shows typical usage: create a Tui with mouse capture enabled, initialize the terminal, draw a widget, and restore the terminal. The init call returns a Result that must be handled. ```rust let tui = Tui::new(true); let mut terminal = tui.init()?; terminal.draw(|f| f.render_widget(paragraph, f.area()))?; tui.restore()?; ``` -------------------------------- ### load_app_configuration Source: https://github.com/honhimw/ratisui Loads the application configuration from config.ron. Starts from Configuration::default() and overwrites with ron::from_str if the file is non-empty. ```APIDOC ## load_app_configuration ### Description Loads the application configuration from config.ron. Starts from Configuration::default() and overwrites with ron::from_str if the file is non-empty. ### Function Signature ```rust pub fn load_app_configuration() -> Result ``` ### Returns - `Result` - The loaded configuration or an error. ### Example ```rust use ratisui_core::configuration::{load_app_configuration}; let config = load_app_configuration()?; match config.theme { Some(name) => println!("theme: {name}"), None => println!("default dark theme"), } ``` ``` -------------------------------- ### Load app configuration and print theme Source: https://github.com/honhimw/ratisui Example usage of load_app_configuration and save_database_configuration. The theme field is Option; None indicates the default dark theme. ```rust use ratisui_core::configuration::{load_app_configuration, save_database_configuration}; let config = load_app_configuration()?; match config.theme { Some(name) => println!("theme: {name}"), None => println!("default dark theme"), } ``` -------------------------------- ### ratisui CLI usage examples Source: https://github.com/honhimw/ratisui Shell invocations showing --target with --theme, and --once with -t. Resolution order: --target beats databases.ron's default_database; --theme beats config.ron's theme. ```shell ratisui --target "remote standalone" --theme my-theme ratisui --once -t local ``` -------------------------------- ### Example usage of xadd and expire Source: https://github.com/honhimw/ratisui Example usage of the Redis operations: adds an event with xadd and sets an expiration with expire. The closure returns Ok(()) and is passed to spawn_redis_opt. ```rust spawn_redis_opt(|ops| async move { ops.xadd("events", "user", "42").await?; ops.expire("events", 3600).await?; Ok(()) })?; ``` -------------------------------- ### str_cmd! usage example Source: https://github.com/honhimw/ratisui Builds a command from a string and executes it via RedisOperations::cmd. Requires an instance inside a closure. ```rust let command = str_cmd!("FT.SEARCH idx:* @field:{foo bar}"); RedisOperations::cmd(command).await?; // when you have an instance ``` -------------------------------- ### databases.ron example configuration Source: https://github.com/honhimw/ratisui Example RON configuration file for defining Redis profiles. Passwords are stored base64-encoded; SSH tunnel password empty uses ~/.ssh/id_rsa key auth. Cluster mode is auto-detected via INFO SERVER. ```ron // ~/.config/ratisui/databases.ron ( default_database: Some("remote standalone"), databases: { "remote standalone": ( host: "standalone.host", port: 6379, username: Some("foo"), password: Some("d2FudG8tZGVjb2RlIQ=="), // base64 use_tls: false, use_ssh_tunnel: false, db: 0, protocol: RESP3, ), "remote cluster": ( host: "cluster.host", port: 6000, username: None, password: Some("cGFzc3dvcmQ="), use_tls: false, use_ssh_tunnel: false, db: 0, protocol: RESP3, ), }, ) ``` -------------------------------- ### str_cmd usage examples Source: https://github.com/honhimw/ratisui Shows calling str_cmd with a raw command string. FT.SEARCH returns a Value; DBSIZE returns a typed i64. ```rust // FT.SEARCH returns a Value let result: Value = ops.str_cmd("FT.SEARCH idx query") .await?; // typed let count: i64 = ops.str_cmd("DBSIZE").await?; ``` -------------------------------- ### Parsing AppArguments with clap Source: https://github.com/honhimw/ratisui Rust example importing AppArguments and Parser, calling parse() and printing the three fields. Shows how to access target, theme, and once values. ```rust use ratisui_core::cli::AppArguments; use clap::Parser; let args = AppArguments::parse(); println!("target={:?} theme={:?} once={}", args.target, args.theme, args.once); ``` -------------------------------- ### try_decode_arg usage example Source: https://github.com/honhimw/ratisui Example calls to try_decode_arg for base64 and file-path decoding. The base64 input decodes to the bytes for 'foo bar'; the fs input reads the file at /tmp/payload.bin. Both calls use the ? operator, so they require a function returning anyhow::Result. ```rust use ratisui_core::utils::try_decode_arg; let bytes = try_decode_arg(&"base64#Zm9vIGJhcg==#".to_string())?; let bytes = try_decode_arg(&"fs#/tmp/payload.bin#".to_string())?; ``` -------------------------------- ### Input::new Source: https://github.com/honhimw/ratisui Spawns the background input thread and starts in Polling state. Returns a new Input instance. ```APIDOC ## Input::new ### Description Spawns the background input thread; starts in `Polling` state. ### Method `pub fn new() -> Self` ### Parameters None ### Response Returns a new `Input` instance. ``` -------------------------------- ### redis_operations usage example Source: https://github.com/honhimw/ratisui Checks if operations are available and prints the server version. ```rust if let Some(ops) = redis_operations() { let version = ops.get_server_info("redis_version"); println!("redis version: {version:?}"); } ``` -------------------------------- ### Using KeyAsserter methods in key handling Source: https://github.com/honhimw/ratisui Example importing KeyAsserter and using generated methods is_c_c(), is_n_s(), and is_c_o() to trigger quit, open_server_switcher, and toggle_cmd_viewer. The macro call site declares a-z and 0-9 (36 chars × 7 combos = 252 methods). ```rust use ratisui_core::marcos::KeyAsserter; fn handle(key_event: KeyEvent) -> bool { if key_event.is_c_c() { quit(); return true; } if key_event.is_n_s() { open_server_switcher(); return true; } if key_event.is_c_o() { toggle_cmd_viewer(); return true; } false } ``` -------------------------------- ### Example: configuring a database with SSH tunnel Source: https://github.com/honhimw/ratisui Shows how to build a Databases configuration with a Database entry that uses an SSH tunnel and RESP3 protocol. The password is base64-encoded on serialization and round-trips to plaintext on load. ```rust use ratisui_core::configuration::{Database, Databases, Protocol, SshTunnel}; let mut databases = Databases::empty(); databases.databases.insert( "local".to_string(), Database { host: "127.0.0.1".to_string(), port: 6379, username: None, password: Some("secret".to_string()), use_tls: false, use_ssh_tunnel: true, db: 0, protocol: Protocol::RESP3, ssh_tunnel: Some(SshTunnel { host: "bastion.example.com".to_string(), port: 22, username: "ubuntu".to_string(), password: String::new(), }), }, ); save_database_configuration(&databases)?; ``` -------------------------------- ### Auto-detection example with JSON input Source: https://github.com/honhimw/ratisui Processes a JSON string with content_type None. Auto-detects JSON, pretty-prints, and sets content type to ContentType::Json. Asserts the detected type. ```rust use ratisui_core::highlight_value::HighlightProcessor; let mut processor = HighlightProcessor::new(r#"{"a": [1,2,3]}"#.to_string(), None); processor.process()?; // auto-detects JSON, pretty-prints assert_eq!(processor.get_content_type(), Some(ratisui_core::utils::ContentType::Json)); ``` -------------------------------- ### spawn_redis_opt usage example Source: https://github.com/honhimw/ratisui Shows fire-and-forget usage: sets a key in the background using the closure's RedisOperations. Requires an active client. ```rust use ratisui_core::redis_opt::spawn_redis_opt; // Fire and forget: set a key in the background. spawn_redis_opt(|operations| async move { operations.set_nx("my_key", "value").await?; Ok(()) })?; ``` -------------------------------- ### get Source: https://github.com/honhimw/ratisui Retrieves the value of a key. ```APIDOC ## get ### Description Retrieves the value of a key. ### Method GET ### Endpoint GET key ### Parameters - **key** (K) - Required - The key to retrieve. ### Response Returns the value as type V. ``` -------------------------------- ### Using deserialize_bytes Source: https://github.com/honhimw/ratisui Example of calling deserialize_bytes and matching on the optional ContentType to print the detected type or just the text. ```rust use ratisui_core::utils::deserialize_bytes; let (text, content_type) = deserialize_bytes(raw_bytes)?; match content_type { Some(ct) => println!("detected {ct}: {text}"), None => println!("{text}"), } ``` -------------------------------- ### split_args CLI-safe splitting example Source: https://github.com/honhimw/ratisui Shows split_args handling quoted arguments. The input uses double and single quotes; the output is a vector of the three tokens without quotes. ```rust // CLI-safe splitting let args = split_args(r#"SET "my key" 'hello world'"#); assert_eq!(args, vec!["SET", "my key", "hello world"]); ``` -------------------------------- ### characterize! usage examples Source: https://github.com/honhimw/ratisui Shows characterize!(b) expanding to 'b' and characterize!() expanding to 'a'. Used inside key_asserter! to convert a tt char token into a KeyCode::Char(characterize!($char)) literal. ```rust use ratisui_macros::characterize; let c: char = characterize!(b); // 'b' let d: char = characterize!(); // 'a' ``` -------------------------------- ### Tui type definition and methods Source: https://github.com/honhimw/ratisui Defines the Tui struct and its public API. The init method enables raw mode, enters the alternate screen, optionally enables mouse capture, builds the terminal backend, and installs a panic hook that restores the terminal. The restore method leaves the alternate screen, disables mouse capture if enabled, and disables raw mode. ```rust pub type TerminalBackEnd = Terminal>; #[derive(Clone)] pub struct Tui { enable_mouse_capture: bool, } impl Tui { pub fn new(enable_mouse_capture: bool) -> Self pub fn init(&self) -> Result pub fn restore(&self) -> Result<()> } ``` -------------------------------- ### Subscribe usage example Source: https://github.com/honhimw/ratisui Creates an unbounded crossbeam channel and spawns a Redis operation that subscribes to 'my_channel'. The monitor can be polled with try_recv() or disposed with dispose(). Errors from sending on the channel use ? inside the spawned task; auth/pool errors surface as Err from the awaited call. ```rust use crossbeam_channel::unbounded; use ratisui_core::redis_opt::spawn_redis_opt; let (tx, rx) = unbounded(); spawn_redis_opt(move |ops| async move { let monitor = ops.subscribe("my_channel", tx).await?; // poll with monitor.try_recv() or dispose with monitor.dispose() Ok(()) })?; ``` -------------------------------- ### SshTunnel::open usage example Source: https://github.com/honhimw/ratisui Creates a tunnel to a bastion host and opens it, returning the local address for a Redis client to connect to. Uses public-key auth because password is empty. ```rust let mut tunnel = SshTunnel::new( "bastion.example.com".to_string(), 22, "ubuntu".to_string(), "".to_string(), "redis.internal".to_string(), 6379, ); let addr = tunnel.open().await?; // redis client should connect to addr (127.0.0.1:) ``` -------------------------------- ### try_decode_arg Source: https://github.com/honhimw/ratisui Decodes a string argument that may be prefixed with `base64#`, `hex#`, or `fs#`. If no recognized prefix is present, returns the raw bytes. Uses the first `#` and last `#`; if start equals end (no suffix), falls back to identity. ```APIDOC ## try_decode_arg ### Description Decodes `prefix#content#` forms; anything else is returned as raw bytes. Uses the first `#` and last `#`; `start == end` (no suffix) falls back to identity. Errors propagate from the base64/hex/file readers. ### Signature ```rust pub fn try_decode_arg(arg: &String) -> anyhow::Result> ``` ### Parameters - **arg** (&String) - Required - The argument string to decode. ### Returns - **anyhow::Result>** - The decoded bytes or an error. ### Decoding Rules - `base64#...#` - `base64::STANDARD.decode` - `hex#...#` - `hex::decode` - `fs#...#` - `std::fs::read` of the path - other - Identity ### Example ```rust use ratisui_core::utils::try_decode_arg; let bytes = try_decode_arg(&"base64#Zm9vIGJhcg==#".to_string())?; let bytes = try_decode_arg(&"fs#/tmp/payload.bin#".to_string())?; ``` ``` -------------------------------- ### try_decode_arg signature Source: https://github.com/honhimw/ratisui Public signature for try_decode_arg. It decodes prefix#content# forms (base64, hex, fs) and returns raw bytes for anything else. Uses the first and last '#'; if start equals end (no suffix), it falls back to identity. Errors from base64, hex, or file reads propagate. ```rust pub fn try_decode_arg(arg: &String) -> anyhow::Result> ``` -------------------------------- ### Build and run Ratisui from source Source: https://github.com/honhimw/ratisui/blob/main/README.md Build and run Ratisui from source. Clones the repository, enters the directory, and runs the project with Cargo. ```shell # clone repo git clone https://github.com/honhimW/ratisui.git # enter cd ratisui # build and run cargo run ``` -------------------------------- ### HighlightProcessor::new constructor signature Source: https://github.com/honhimw/ratisui Creates a processor with the given source and content type. Expands tabs to 4 spaces, initializes empty fragments, do_formatting: true, tree: None. ```rust pub fn new(source: String, content_type: Option) -> Self ``` -------------------------------- ### xrange Source: https://github.com/honhimw/ratisui Retrieves a range of entries from a stream starting from a given ID. ```APIDOC ## xrange ### Description Retrieves a range of entries from a stream starting from a given ID. ### Method XRANGE ### Endpoint XRANGE key start + COUNT count ### Parameters - **key** (K) - Required - The key of the stream. - **start** (S) - Required - The starting ID. - **count** (usize) - Required - The number of entries to retrieve. ### Response Returns entries as type V. ``` -------------------------------- ### Options struct and OutputFormat enum in app_configuration_editor.rs Source: https://github.com/honhimw/ratisui Options form includes FPS, Scan Size, Try Format, Theme, History Size, Console Capacity, Cli Output Format, Enable Mouse Capture. Enter builds a new Configuration, calls save_configuration, then publishes GlobalEvent::Restart (changes apply after restart). Numeric fields: ↓/j −10, ↑/k +10, →/l +1, ←/h −1; Ctrl+a/z/y select all/undo/redo. ```rust pub struct Options { /* default_configuration: Configuration, editing, TextAreas fps/scan_size/theme/history_size/console_capacity, try_format, cli_output_format: OutputFormat, enable_mouse_capture, rects */ } #[derive(Default, Eq, PartialEq, EnumCount, EnumIter, Display)] pub enum OutputFormat { #[default] Redis, Ron } impl Options { pub fn next(&mut self) pub fn prev(&mut self) pub fn init_values(&mut self, config: Arc) // prefill from current config } ``` -------------------------------- ### load_theme_configuration Source: https://github.com/honhimw/ratisui Loads a theme from theme/.ron. Empty or unknown names log a warning and fall back to Theme::dark(); success logs "Theme '{name}' loaded successfully!". ```APIDOC ## load_theme_configuration ### Description Loads a theme from theme/.ron. Empty or unknown names log a warning and fall back to Theme::dark(); success logs "Theme '{name}' loaded successfully!". ### Function Signature ```rust pub fn load_theme_configuration(theme_name: Option) -> Result ``` ### Parameters - `theme_name` (Option) - Optional theme name. ### Returns - `Result` - The loaded theme or an error. ``` -------------------------------- ### monitor Source: https://github.com/honhimw/ratisui Starts a monitor stream that sends streamed Values to the provided sender. In cluster mode, attaches to every node. ```APIDOC ## monitor ### Description Creates a `DisposableMonitor` that streams `Value`s to the provided sender. In cluster mode, attaches to every node. If the stream is idle for 60s, a `SimpleString` "Pending Ns ..." sentinel is emitted. ### Method `pub async fn monitor(&self, sender: Sender) -> Result` ### Parameters - **sender** (`crossbeam_channel::Sender`) - Required - Receives streamed `Value`s; a final `VerbatimString` with `VerbatimFormat::Unknown("PROMPT")` is sent on shutdown. ### Response - **Result** - A disposable monitor handle. ### Request Example ```rust use crossbeam_channel::unbounded; use ratisui_core::redis_opt::spawn_redis_opt; let (tx, rx) = unbounded(); spawn_redis_opt(move |ops| async move { let monitor = ops.monitor(tx).await?; // poll with monitor.try_recv() or dispose with monitor.dispose() Ok(()) })?; ``` ``` -------------------------------- ### App methods signatures Source: https://github.com/honhimw/ratisui Shows the public methods of App: new, health, and close. new creates Context and Input with state Preparing; health returns true when state is Running or Preparing; close sets state to Closing and dispatches AppEvent::Destroy. ```rust impl App { pub fn new() -> Self // Context::new() + Input::new(), state Preparing pub fn health(&self) -> bool // state is Running | Preparing pub fn close(&mut self) -> Result<()> // state -> Closing, Context::on_app_event(AppEvent::Destroy) } ``` -------------------------------- ### Completion types: CompletionItem, Parameter, Label, Doc, CompletionItemKind Source: https://github.com/honhimw/ratisui Defines the data structures for completion items, parameters (flag, enum, arg, single, many), labels with optional detail and description, documentation with syntax/summary/attributes, and the completion item kind enum with custom string serialization. Builders are available for each type. ```rust #[derive(Debug, Clone)] pub struct CompletionItem { pub kind: CompletionItemKind, pub label: Label, pub parameters: Vec, pub range: (isize, isize), pub insert_text: String } #[derive(Clone, Debug)] pub enum Parameter { Flag(String, String), // [CH] Enum(Vec<(String, String)>), // [NX | XX] Arg { key: String, arg: String, detail: String }, Single(String), // cursor Many(String), // score member [score members...], tail } #[derive(Debug, Clone)] pub struct Label { pub label: String, pub detail: Option, pub description: Option } #[derive(Debug, Clone)] pub struct Doc { pub syntax: String, pub summary: String, pub attributes: Vec<(String, String)> } #[derive(Debug, Clone, Display)] pub enum CompletionItemKind { Generic, Option, String, List, Set, ZSet, Hash, Stream, PubSub, Server, Other, #[strum(to_string = "{0}")] Custom(String) } ``` -------------------------------- ### Tui::new Source: https://github.com/honhimw/ratisui Creates a new Tui instance with the specified mouse capture flag. ```APIDOC ## Tui::new ### Description Creates a new Tui instance with the specified mouse capture flag. ### Method new ### Parameters - **enable_mouse_capture** (bool) - Required - Whether to enable mouse capture. ### Returns - **Self** - A new Tui instance. ### Request Example ```rust let tui = Tui::new(true); ``` ``` -------------------------------- ### Load and save configuration function signatures Source: https://github.com/honhimw/ratisui Public functions for loading and saving configuration, database, theme, and CLI history files. All paths derive from dirs::home_dir() plus .config/ratisui, created if missing. Errors are returned as anyhow::Result. ```rust pub fn load_app_configuration() -> Result pub fn load_database_configuration() -> Result pub fn load_theme_configuration(theme_name: Option) -> Result pub fn load_history() -> Result> pub fn save_configuration(config: &Configuration) -> Result<()> // #[allow(unused)] pub fn save_database_configuration(databases: &Databases) -> Result<()> pub fn save_history(histories: VecDeque<(SystemTime, String)>) -> Result<()> ``` -------------------------------- ### CompletableTextArea struct and completion engine functions Source: https://github.com/honhimw/ratisui Provides a text area with completion support, including methods for focus, input, cursor, auto-suggestion, and updating completion items. Also includes split_args and sort_commands helpers. Ctrl+Space or Alt+/ opens the menu, Esc closes, Tab accepts and expands insert_text with $end anchors and range replacement. on_app_event(ClientChanged) refreshes redis_version to flag commands newer than the server. ```rust pub struct CompletableTextArea<'a> { /* TextArea<'a>, TableState, completion_items, segment, redis_version, menu/desc dimensions */ } impl CompletableTextArea<'_> { pub fn new() -> Self pub fn focus(&mut self) pub fn blur(&mut self) pub fn insert_str(&mut self, s: impl Into) pub fn get_input(&self) -> String pub fn get_cursor(&self) -> (usize, usize) pub fn set_auto_suggestion(&mut self, s: impl Into) pub fn update_frame(&mut self, frame_height: u16, frame_width: u16) pub fn update_completion_items(&mut self, items: Vec, segment: String) } pub fn split_args(cmd: impl Into) -> Vec<(String, Option, usize, usize)> pub fn sort_commands(commands: &mut Vec, segment: &String) ``` -------------------------------- ### Define a custom theme in your-theme.ron Source: https://github.com/honhimw/ratisui/blob/main/README.md Theme configuration file for ratisui. Stored at ~/.config/ratisui/theme/your-theme.ron. Defines the theme kind and toast colors. See the theme template for more details. ```ron // ~/.config/ratisui/theme/your-theme.ron ( kind: Dark, toast: ( info: Tailwind(GREEN, C700), warn: Yellow, error: Rgb(255, 0, 0), ), ) ``` -------------------------------- ### Input struct definition Source: https://github.com/honhimw/ratisui Holds the input thread's state and event receiver. Starts in Polling state; use set_polling to toggle. ```rust #[derive(Clone)] pub struct Input { desired_state: Arc>, current_state: Arc, receiver: Receiver, aborted: Arc, } ``` -------------------------------- ### save_database_configuration Source: https://github.com/honhimw/ratisui Saves the database profile list to databases.ron. Writes pretty RON via ron::ser::to_string_pretty. ```APIDOC ## save_database_configuration ### Description Saves the database profile list to databases.ron. Writes pretty RON via ron::ser::to_string_pretty. ### Function Signature ```rust pub fn save_database_configuration(databases: &Databases) -> Result<()> ``` ### Parameters - `databases` (&Databases) - The databases to save. ### Returns - `Result<()>` - Ok or an error. ### Example ```rust use ratisui_core::configuration::{save_database_configuration}; save_database_configuration(&databases)?; ``` ``` -------------------------------- ### Databases struct definition Source: https://github.com/honhimw/ratisui Configuration container mapping profile names to Database instances. Includes an optional default database and a required map of databases. ```rust #[derive(Serialize, Deserialize)] pub struct Databases { pub default_database: Option, pub databases: HashMap, } impl Databases { pub fn empty() -> Self // default_database: None, databases: empty map } ``` -------------------------------- ### Form struct and impl in database_editor.rs Source: https://github.com/honhimw/ratisui Private module imported by servers.rs. Defaults: enabled_authentication true, protocol RESP3, name prefilled with random Uuid::new_v4(), password fields masked with •, SSH password placeholder 'empty for ~/.ssh/id_rsa'. to_database uses placeholder values when blank (host 127.0.0.1, port 6379, db 0). ```rust pub struct Form { /* title, editing (usize index into Editing), TextAreas for name/host/port/username/password/db/ssh fields, booleans enabled_authentication/use_tls/use_ssh_tunnel, protocol: Protocol, ... */ } impl Form { pub fn from_data(data: &Data) -> Self // prefilled from servers::Data pub fn title(mut self, title: impl Into) -> Self pub fn get_name(&self) -> String pub fn to_database(&self) -> Database // placeholder values when blank (host 127.0.0.1, port 6379, db 0) pub fn next(&mut self) pub fn prev(&mut self) } ``` -------------------------------- ### has_module method signature and usage Source: https://github.com/honhimw/ratisui Scans cached INFO MODULES for lines matching 'module name='. The example shows checking for the 'search' module, returning true when RediSearch is loaded. ```rust pub fn has_module>(&self, s: T) -> Result ``` ```rust let has_search = ops.has_module("search")?; // true when RediSearch is loaded ``` -------------------------------- ### ServerList and Data structs in servers.rs Source: https://github.com/honhimw/ratisui Defines the Data struct and ServerList struct with methods for managing server profiles. ServerList::new builds rows with default selection '*', and switch() calls switch_client with the selected name and database. Validation errors include 'Profile name must not be blank' and 'Profile [{}] already exists'. ```rust #[derive(Clone)] pub struct Data { pub selected: String, pub name: String, pub location: String, pub db: String, pub username: String, pub use_tls: String, pub protocol: String, pub database: Database, } pub struct ServerList { /* TableState, items: Vec, create_form/edit_form: Form, save_on_exit, ... */ } impl ServerList { pub fn new(databases: &Databases) -> Self // builds rows, default selection "*" pub fn next(&mut self) pub fn previous(&mut self) pub fn switch(&mut self) -> Result<()> // switch_client(selected name, database) } ``` -------------------------------- ### Configure ratisui application settings in config.ron Source: https://github.com/honhimw/ratisui/blob/main/README.md Configuration file for ratisui application settings. Stored at ~/.config/ratisui/config.ron. Adjust fps, scan_size, try_format, theme, history_size, cli_output_format, and console_capacity. ```ron // ~/.config/ratisui/config.ron ( fps: 45, // tui render fps limitation scan_size: 500, // redis key scan size, try_format: false, // fotmat raw data theme: Some("your-theme"), // ~/.config/ratisui/theme/your-theme.ron history_size: 1000, // ~/.config/ratisui/cli.history cli_output_format: Redis, // Redis(default) | Ron console_capacity: 2000, // CLI output capacity, default as 3000 ) ``` -------------------------------- ### App struct definition Source: https://github.com/honhimw/ratisui Defines the main application struct with fields for state, context, and input. ```rust pub struct App { pub state: AppState, pub context: context::Context, pub input: Input, } ``` -------------------------------- ### Using none_match to close popup on Esc Source: https://github.com/honhimw/ratisui Shows how to use none_match to detect an Escape key press with no modifiers. The function returns true only when modifiers are NONE and the key code matches. In this example, the popup is closed when the condition is met. ```rust use ratisui_core::utils::none_match; use ratatui::crossterm::event::{KeyCode, KeyEvent}; if none_match(&key_event, KeyCode::Esc) { popup.close(); } ``` -------------------------------- ### Configuration struct definition Source: https://github.com/honhimw/ratisui Defines the Configuration struct with serde attributes and default functions. All fields have defaults; theme is optional. Default is implemented manually with the same defaults; no builder is provided. ```rust #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct Configuration { #[serde(default = "fps")] pub fps: u8, #[serde(default = "scan_size")] pub scan_size: u16, #[serde(default = "try_format")] pub try_format: bool, pub theme: Option, #[serde(default = "history_size")] pub history_size: u32, #[serde(default = "cli_output_kind")] pub cli_output_format: CliOutputFormatKind, #[serde(default = "console_capacity")] pub console_capacity: usize, #[serde(default = "enable_mouse_capture")] pub enable_mouse_capture: bool, } ``` -------------------------------- ### HighlightProcessor::new Source: https://github.com/honhimw/ratisui Creates a new HighlightProcessor with the given source string and optional content type. The source is stored with tabs expanded to 4 spaces. ```APIDOC ## HighlightProcessor::new ### Description Creates a new HighlightProcessor with the given source string and optional content type. The source is stored with tabs expanded to 4 spaces. ### Method Constructor ### Parameters - **source** (String) - Required - The raw value to be highlighted. - **content_type** (Option) - Optional - The content type of the source; if None, auto-detection is used. ### Returns - **Self** - A new HighlightProcessor instance. ### Example ```rust use ratisui_core::highlight_value::HighlightProcessor; use ratisui_core::utils::ContentType; let processor = HighlightProcessor::new(json_string, Some(ContentType::Json)); ``` ``` -------------------------------- ### Other HighlightProcessor method signatures Source: https://github.com/honhimw/ratisui Lists auxiliary methods: disable_formatting sets do_formatting false; get_content_type returns the detected type; get_cursor_path walks the tree at a Point and returns node path joined with ' > ' (empty when no tree); get_fragments returns the fragment vector. ```rust pub fn disable_formatting(&mut self) // set do_formatting = false pub fn get_content_type(&self) -> Option pub fn get_cursor_path(&self, row: usize, column: usize) -> Result // #[allow(unused)] pub fn get_fragments(&self) -> &Vec ``` -------------------------------- ### switch_client Source: https://github.com/honhimw/ratisui Builds a connection pool, initializes RedisOperations, swaps it into the global state, and publishes events. Returns Ok(()) immediately; the work runs in a spawned Tokio task. ```APIDOC ## switch_client ### Description Builds a connection pool, initializes RedisOperations, swaps it into the global state, and publishes events. Returns Ok(()) immediately; the work runs in a spawned Tokio task. ### Signature ```rust pub fn switch_client(name: impl Into, database: &Database) -> Result<()> ``` ### Parameters - **name** (impl Into) - Required - Profile name (used only for labeling) - **database** (&Database) - Required - Database descriptor; the function clones it ### Returns - `Result<()>` - Returns `Ok(())` immediately. ### Notes - `RedisOperations::new` is private; `switch_client` is one of the only ways to create a live `RedisOperations`. ``` -------------------------------- ### HighlightProcessor::process Source: https://github.com/honhimw/ratisui Processes the source according to the content type, tokenizing and highlighting the value. Returns Ok(()) on success or an error if processing fails. ```APIDOC ## HighlightProcessor::process ### Description Processes the source according to the content type, tokenizing and highlighting the value. Returns Ok(()) on success or an error if processing fails. ### Method process ### Parameters None ### Returns - **Result<()>** - Ok(()) on success, or an error if processing fails. ### Behavior - If content_type is Some(String), calls process_plain(). - If Some(Json), calls process_json(). - If Some(Xml), calls process_xml(). - If Some(JavaSerialized | Protobuf | Ron), calls process_ron(). - If None, auto-detects JSON → XML → RON → plain and sets self.content_type on success. ### Example ```rust use ratisui_core::highlight_value::HighlightProcessor; let mut processor = HighlightProcessor::new(json_string, Some(ContentType::Json)); processor.process()?; ``` ``` -------------------------------- ### load_history Source: https://github.com/honhimw/ratisui Loads CLI history from cli.history. Each line is `datetime;command` parsed with DATE_FORMAT_PATTERN (`%Y-%m-%dT%H:%M:%S%.3fZ`); lines that fail to parse are skipped. ```APIDOC ## load_history ### Description Loads CLI history from cli.history. Each line is `datetime;command` parsed with DATE_FORMAT_PATTERN (`%Y-%m-%dT%H:%M:%S%.3fZ`); lines that fail to parse are skipped. ### Function Signature ```rust pub fn load_history() -> Result> ``` ### Returns - `Result>` - The loaded history or an error. ``` -------------------------------- ### FtSearchPanel API and methods Source: https://github.com/honhimw/ratisui Defines the FtSearchPanel struct and its methods. list_indexes runs FT._LIST and FT.INFO per index in parallel tasks. ```rust impl<'a> FtSearchPanel<'a> { pub fn new() -> Self pub fn list_indexes(&mut self) -> Result<()> // FT._LIST + FT.INFO per index pub fn get_input(&self) -> Result<(String, String)> // (index, query) } ``` -------------------------------- ### Using set_theme and get_color Source: https://github.com/honhimw/ratisui Sets the dark theme and retrieves the background color from the current theme's context. Requires importing set_theme, get_color, and Theme from ratisui_core::theme. ```rust use ratisui_core::theme::{set_theme, get_color, Theme}; let theme = Theme::dark(); set_theme(theme); let bg = get_color(|t| &t.context.bg); // ratatui Color ``` -------------------------------- ### Color impl methods hex and to_color Source: https://github.com/honhimw/ratisui Provides the hex constructor and to_color conversion method. hex accepts any Into; to_color returns Option, with Fallback yielding None. ```rust impl Color { #[allow(unused)] pub fn hex>(s: T) -> Self pub fn to_color(&self) -> Option } ``` -------------------------------- ### AppArguments clap parser struct Source: https://github.com/honhimw/ratisui Clap derive parser for the ratisui binary entry point, parsed via AppArguments::parse() in src/main.rs. Defines flags -t/--target, -T/--theme, and --once with help text referencing config files. ```rust #[derive(Default, Clone, Debug, Parser)] #[command(name = "ratisui")] #[command(version, about = "Redis TUI build with Ratatui.", long_about = None)] pub struct AppArguments { #[arg( short = 't', long = "target", value_name = "TARGET", help = "Named redis target in ~/.config/ratisui/databases.ron" )] pub target: Option, #[arg( short = 'T', long = "theme", value_name = "THEME", help = "Theme configuration in ~/.config/ratisui/theme/.ron" )] pub theme: Option, #[arg(long = "once", help = "Will not load | save databases")] pub once: bool, } ``` -------------------------------- ### str_cmd! macro Source: https://github.com/honhimw/ratisui Parses a command string (with split_args, respecting quotes) into a deadpool_redis::redis::Cmd. Exported at the ratisui_core crate root. ```APIDOC ## str_cmd! macro ### Description Parses a command string (with split_args, respecting quotes) into a deadpool_redis::redis::Cmd. Exported at the ratisui_core crate root. ### Macro Definition ```rust #[macro_export] macro_rules! str_cmd { ($cmd:expr) => {{ let mut command = Cmd::new(); let parts: Vec = split_args($cmd); for arg in &parts { command.arg(arg); } command }}; } ``` ### Example ```rust let command = str_cmd!("FT.SEARCH idx:* @field:{foo bar}"); RedisOperations::cmd(command).await?; // when you have an instance ``` ### Notes - `RedisOperations` is only obtainable inside `spawn_redis_opt` / `async_redis_opt` closures, or via `redis_operations()`. ``` -------------------------------- ### Load and set theme from configuration file Source: https://github.com/honhimw/ratisui Loads a theme configuration from a file named 'my-theme' using `load_theme_configuration` and applies it with `set_theme`. The `?` operator propagates errors, so this code is typically used in a function that returns a `Result`. The RON schema is documented in configuration.md and the canonical template is `assets/theme-template.ron`. ```rust use ratisui_core::configuration::load_theme_configuration; use ratisui_core::theme::set_theme; let theme = load_theme_configuration(Some("my-theme".to_string()))?; set_theme(theme); ``` -------------------------------- ### Popup struct and builder methods Source: https://github.com/honhimw/ratisui Defines the Popup widget struct and its builder methods. Default is implemented for Popup> with rounded borders and title at top. ```rust pub struct Popup { pub title_position: Position, pub title: Option, pub inner_widget: Box, pub style: Style, pub borders: Borders, pub border_set: Set, pub border_style: Style, } impl Popup { pub fn new(widget: W) -> Self pub fn title_position(mut self, title_position: Position) -> Self pub fn title(mut self, title: String) -> Self pub fn inner_widget(mut self, inner_widget: Box) -> Self pub fn style(mut self, style: Style) -> Self pub fn borders(mut self, borders: Borders) -> Self pub fn border_set(mut self, border_set: Set) -> Self pub fn border_style(mut self, style: Style) -> Self } ``` -------------------------------- ### HighlightProcessor::process method signature Source: https://github.com/honhimw/ratisui Dispatches to process_plain, process_json, process_xml, or process_ron based on content_type. With None, auto-detects JSON → XML → RON → plain and sets self.content_type on success. ```rust pub fn process(&mut self) -> Result<()> ``` -------------------------------- ### Typical consumer pattern using DisposableMonitor Source: https://github.com/honhimw/ratisui Shows the typical consumer pattern as used by CliTab: create a monitor, try to receive a value, render it if available, then dispose to terminate the stream gracefully. ```rust // Typical consumer pattern (as used by CliTab): let mut monitor = ops.monitor(tx).await?; if let Ok(value) = monitor.try_recv() { render(value); } if monitor.dispose().is_ok() { // stream will terminate gracefully } ``` -------------------------------- ### Theme::light() Source: https://github.com/honhimw/ratisui Creates a new Theme with name "ratisui-light", Kind::Light, and the light palette. This is a built-in fallback theme. ```APIDOC ## Theme::light() ### Description Creates a new Theme with name "ratisui-light", Kind::Light, and the light palette. ### Function Signature ```rust pub fn light() -> Self ``` ### Returns - **Theme** - A new Theme instance with the light palette. ### Example ```rust use ratisui_core::theme::Theme; let theme = Theme::light(); ``` ``` -------------------------------- ### AppEvent enum definition Source: https://github.com/honhimw/ratisui Defines application events: InitConfig, Reset, Destroy, and Bus. InitConfig is dispatched once at startup with configuration and arguments; Reset is triggered by Ctrl+F5; Destroy on exit/restart; Bus passes GlobalEvent to all tabs and popups. ```rust #[derive(Clone, Debug)] pub enum AppEvent { InitConfig(Arc, Arc), Reset, Destroy, Bus(GlobalEvent), } ```