Context

R3BL TUI library & suite of apps focused on developer productivity

We are working on building command line apps in Rust which have rich text user interfaces (TUI). We want to lean into the terminal as a place of productivity, and build all kinds of awesome apps for it.

  1. 🔮 Instead of just building one app, we are building a library to enable any kind of rich TUI development w/ a twist: taking concepts that work really well for the frontend mobile and web development world and re-imagining them for TUI & Rust.

  2. 🌎 We are building apps to enhance developer productivity & workflows.

r3blrsutils_core

tui-core

This crate contains the core functionality for building rich text user interfaces (TUI) in Rust. The r3bl_tui crate depends on it. Here are the main features:

  1. ANSI text support
  2. Core dimensions and units that are used for positioning and sizing
  3. Grapheme cluster segment and unicode support (emoji support)
  4. Lolcat support
  5. CSS like styling support

Macros

Declarative

There are quite a few declarative macros that you will find in the library. They tend to be used internally in the implementation of the library itself. Here are some that are actually externally exposed via #[macro_export].

assert_eq2!

Similar to [assert_eq!] but automatically prints the left and right hand side variables if the assertion fails. Useful for debugging tests, since the cargo would just print out the left and right values w/out providing information on what variables were being compared.

throws!

Wrap the given block or stmt so that it returns a Result<()>. It is just syntactic sugar that helps having to write Ok(()) repeatedly at the end of each block. Here's an example.

rust fn test_simple_2_col_layout() -> CommonResult<()> { throws! { match input_event { InputEvent::DisplayableKeypress(character) => { println_raw!(character); } _ => todo!() } } }

Here's another example.

rust fn test_simple_2_col_layout() -> CommonResult<()> { throws!({ let mut canvas = Canvas::default(); canvas.stylesheet = create_stylesheet()?; canvas.canvas_start( CanvasPropsBuilder::new() .set_pos((0, 0).into()) .set_size((500, 500).into()) .build(), )?; layout_container(&mut canvas)?; canvas.canvas_end()?; }); }

throwswithreturn!

This is very similar to throws! but it also returns the result of the block.

rust fn test_simple_2_col_layout() -> CommonResult<RenderPipeline> { throws_with_return!({ println!("⛵ Draw -> draw: {}\r", state); render_pipeline!() }); }

log!

You can use this macro to dump log messages at 3 levels to a file. By default this file is named log.txt and is dumped in the current directory. Here's how you can use it.

Please note that the macro returns a Result. A type alias is provided to save some typing called CommonResult<T> which is just a short hand for std::result::Result<T, Box<dyn Error>>. The log file itself is overwritten for each "session" that you run your program.

```rust use r3blrsutils::{initfilelogger_once, log, CommonResult};

fn run() -> CommonResult<()> { let msg = "foo"; let msg_2 = "bar";

log!(INFO, "This is a info message"); log!(INFO, target: "foo", "This is a info message");

log!(WARN, "This is a warning message {}", msg); log!(WARN, target: "foo", "This is a warning message {}", msg);

log!(ERROR, "This is a error message {} {}", msg, msg2); log!(ERROR, target: "foo", "This is a error message {} {}", msg, msg2);

log!(DEBUG, "This is a debug message {} {}", msg, msg2); log!(DEBUG, target: "foo", "This is a debug message {} {}", msg, msg2);

log!(TRACE, "This is a debug message {} {}", msg, msg2); log!(TRACE, target: "foo", "This is a debug message {} {}", msg, msg2);

Ok(()) } ```

To change the default log file to whatever you choose, you can use the try_to_set_log_file_path() function. If the logger hasn't yet been initialized, this function will set the log file path. Otherwise it will return an error.

rust use r3bl_rs_utils::{try_set_log_file_path, CommonResult, CommonError}; fn run() { match try_set_log_file_path("new_log.txt") { Ok(path_set) => debug!(path_set), Err(error) => debug!(error), } }

To change the default log level or to disable the log itself, you can use the try_to_set_log_level() function.

If you want to override the default log level LOG_LEVEL, you can use this function. If the logger has already been initialized, then it will return a an error.

```rust use r3blrsutils::{trytosetloglevel, CommonResult, CommonError}; use log::LevelFilter;

fn run() { match trytosetloglevel(LevelFilter::Trace) { Ok(levelset) => debug!(levelset), Err(error) => debug!(error), } } ```

To disable logging simply set the log level to LevelFilter::Off.

```rust use r3blrsutils::{trytosetloglevel, CommonResult, CommonError}; use log::LevelFilter;

fn run() { match trytosetloglevel(LevelFilter::Off) { Ok(levelset) => debug!(levelset), Err(error) => debug!(error), } } ```

Please check out the source here.

lognoerr!

This macro is very similar to the log! macro, except that it won't return any error if the underlying logging system fails. It will simply print a message to stderr. Here's an example.

rust pub fn log_state(&self, msg: &str) { log_no_err!(INFO, "{:?} -> {}", msg, self.to_string()); log_no_err!(INFO, target: "foo", "{:?} -> {}", msg, self.to_string()); }

debuglogno_err!

This is a really simple macro to make it effortless to debug into a log file. It outputs DEBUG level logs. It takes a single identifier as an argument, or any number of them. It simply dumps an arrow symbol, followed by the identifier stringify'd along with the value that it contains (using the Debug formatter). All of the output is colorized for easy readability. You can use it like this.

rust let my_string = "Hello World!"; debug_log_no_err!(my_string);

tracelogno_err!

This is very similar to debuglogno_err! except that it outputs TRACE level logs.

rust let my_string = "Hello World!"; trace_log_no_err!(my_string);

makeapicall_for!

This macro makes it easy to create simple HTTP GET requests using the reqwest crate. It generates an async function called make_request() that returns a CommonResult<T> where T is the type of the response body. Here's an example.

```rust use std::{error::Error, fmt::Display}; use r3blrsutils::makeapicall_for; use serde::{Deserialize, Serialize};

const ENDPOINT: &str = "https://api.namefake.com/english-united-states/female/";

makeapicall_for! { FakeContactData at ENDPOINT }

[derive(Serialize, Deserialize, Debug, Default)]

pub struct FakeContactData { pub name: String, pub phoneh: String, pub emailu: String, pub email_d: String, pub address: String, }

let fakedata = fakecontactdataapi() .await .unwraporelse(|| FakeContactData { name: "Foo Bar".tostring(), phoneh: "123-456-7890".tostring(), emailu: "foo".tostring(), emaild: "bar.com".tostring(), ..FakeContactData::default() }); ```

You can find lots of examples here.

fireandforget!

This is a really simple wrapper around tokio::spawn() for the given block. Its just syntactic sugar. Here's an example of using it for a non-async block.

rust pub fn foo() { fire_and_forget!( { println!("Hello"); } ); }

And, here's an example of using it for an async block.

rust pub fn foo() { fire_and_forget!( let fake_data = fake_contact_data_api() .await .unwrap_or_else(|_| FakeContactData { name: "Foo Bar".to_string(), phone_h: "123-456-7890".to_string(), email_u: "foo".to_string(), email_d: "bar.com".to_string(), ..FakeContactData::default() }); ); }

calliftrue!

Syntactic sugar to run a conditional statement. Here's an example.

rust const DEBUG: bool = true; call_if_true!( DEBUG, eprintln!( "{} {} {}\r", r3bl_rs_utils::style_error("▶"), r3bl_rs_utils::style_prompt($msg), r3bl_rs_utils::style_dimmed(&format!("{:#?}", $err)) ) );

debug!

This is a really simple macro to make it effortless to use the color console logger. It takes a single identifier as an argument, or any number of them. It simply dumps an arrow symbol, followed by the identifier (stringified) along with the value that it contains (using the Debug formatter). All of the output is colorized for easy readability. You can use it like this.

rust let my_string = "Hello World!"; debug!(my_string); let my_number = 42; debug!(my_string, my_number);

You can also use it in these other forms for terminal raw mode output. This will dump the output to stderr.

rust if let Err(err) = $cmd { let msg = format!("❌ Failed to {}", stringify!($cmd)); debug!(ERROR_RAW &msg, err); }

This will dump the output to stdout.

rust let msg = format!("✅ Did the thing to {}", stringify!($name)); debug!(OK_RAW &msg);

with!

This is a macro that takes inspiration from the with scoping function in Kotlin. It just makes it easier to express a block of code that needs to run after an expression is evaluated and saved to a given variable. Here's an example.

rust with! { /* $eval */ LayoutProps { id: id.to_string(), dir, req_size: RequestedSize::new(width_pc, height_pc), }, as /* $id */ it, run /* $code */ { match self.is_layout_stack_empty() { true => self.add_root_layout(it), false => self.add_normal_layout(it), }?; } }

It does the following:

  1. Evaluates the $eval expression and assigns it to $id.
  2. Runs the $code block.

with_mut!

This macro is just like with! but it takes a mutable reference to the $id variable. Here's a code example.

rust with_mut! { StyleFlag::BOLD_SET | StyleFlag::DIM_SET, as mask2, run { assert!(mask2.contains(StyleFlag::BOLD_SET)); assert!(mask2.contains(StyleFlag::DIM_SET)); assert!(!mask2.contains(StyleFlag::UNDERLINE_SET)); assert!(!mask2.contains(StyleFlag::COLOR_FG_SET)); assert!(!mask2.contains(StyleFlag::COLOR_BG_SET)); assert!(!mask2.contains(StyleFlag::PADDING_SET)); } }

withmutreturns!

This macro is just like with_mut! except that it returns the value of the $code block. Here's a code example.

rust let tw_queue = with_mut_returns! { ColumnRenderComponent { lolcat }, as it, return { it.render_component(tw_surface.current_box()?, state, shared_store).await? } };

unwrapoptionorrunfnreturningerr!

This macro can be useful when you are working w/ an expression that returns an Option and if that Option is None then you want to abort and return an error immediately. The idea is that you are using this macro in a function that returns a Result<T> basically.

Here's an example to illustrate.

rust pub fn from( width_percent: u8, height_percent: u8, ) -> CommonResult<RequestedSize> { let size_tuple = (width_percent, height_percent); let (width_pc, height_pc) = unwrap_option_or_run_fn_returning_err!( convert_to_percent(size_tuple), || LayoutError::new_err(LayoutErrorType::InvalidLayoutSizePercentage) ); Ok(Self::new(width_pc, height_pc)) }

unwrapoptionorcomputeif_none!

This macro is basically a way to compute something lazily when it (the Option) is set to None. Unwrap the $option, and if None then run the $next closure which must return a value that is set to $option. Here's an example.

```rust use r3blrsutils::unwrapoptionorcomputeif_none;

[test]

fn testunwrapoptionorcomputeifnone() { struct MyStruct { field: Option, } let mut mystruct = MyStruct { field: None }; asserteq!(mystruct.field, None); unwrapoptionorcomputeifnone!(mystruct.field, { || 1 }); asserteq!(my_struct.field, Some(1)); } ```

Common

CommonResult and CommonError

These two structs make it easier to work w/ Results. They are just syntactic sugar and helper structs. You will find them used everywhere in the r3bl_rs_utils crate.

Here's an example of using them both.

```rust use r3blrsutils::{CommonError, CommonResult};

[derive(Default, Debug, Clone)]

pub struct Stylesheet { pub styles: Vec