repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
Blockstream/greenlight | https://github.com/Blockstream/greenlight/blob/28e98f8e093100e576415734630cff4ea9f3421e/libs/gl-cli/src/node.rs | libs/gl-cli/src/node.rs | use crate::error::{Error, Result};
use crate::model;
use crate::util::{self, CREDENTIALS_FILE_NAME};
use clap::Subcommand;
use futures::stream::StreamExt;
use gl_client::pb::StreamLogRequest;
use gl_client::{bitcoin::Network, pb::cln};
use std::path::Path;
pub struct Config<P: AsRef<Path>> {
pub data_dir: P,
pub network: Network,
}
#[derive(Subcommand, Debug)]
pub enum Command {
/// Stream logs to stdout
Log,
/// Returns some basic node info
#[command(name = "getinfo")]
GetInfo,
/// Create a new invoice
Invoice {
#[arg(required = true)]
label: String,
#[arg(required = true)]
description: String,
#[arg(long, value_parser = clap::value_parser!(model::AmountOrAny))]
amount_msat: Option<model::AmountOrAny>,
#[arg(long)]
expiry: Option<u64>,
#[arg(long)]
fallbacks: Option<Vec<String>>,
#[arg(long)]
preimage: Option<Vec<u8>>,
#[arg(long)]
cltv: Option<u32>,
#[arg(long)]
deschashonly: Option<bool>,
},
/// Pay a bolt11 invoice
Pay {
#[arg(required = true)]
bolt11: String,
#[arg(long)]
amount_msat: Option<u64>,
#[arg(long)]
label: Option<String>,
#[arg(long)]
riskfactor: Option<f64>,
#[arg(long)]
maxfeepercent: Option<f64>,
#[arg(long)]
retry_for: Option<u32>,
#[arg(long)]
maxdelay: Option<u32>,
#[arg(long)]
exemptfee: Option<u64>,
#[arg(long)]
localinvreqid: Option<Vec<u8>>,
#[arg(long)]
exclude: Option<Vec<String>>,
#[arg(long)]
maxfee: Option<u64>,
#[arg(long)]
description: Option<String>,
},
/// Establish a new connection with another lightning node.
Connect {
#[arg(
required = true,
help = "The targets nodes public key, can be of form id@host:port, host and port must be omitted in this case."
)]
id: String,
#[arg(long, help = "The peer's hostname or IP address.")]
host: Option<String>,
#[arg(
long,
help = "The peer's port number defaults to the networks default ports if missing."
)]
port: Option<u32>,
},
/// List attempted payments
Listpays {
#[arg(long, help = "A Bolt11 string to get the payment details")]
bolt11: Option<String>,
#[arg(long, help = "A payment_hash to get the payment details")]
payment_hash: Option<String>,
#[arg(
long,
help = "Can be one of \"pending\", \"completed\", \"failed\", filters the payments that are returned"
)]
status: Option<String>,
},
/// Stop the node
Stop,
}
pub async fn command_handler<P: AsRef<Path>>(cmd: Command, config: Config<P>) -> Result<()> {
match cmd {
Command::Log => log(config).await,
Command::GetInfo => getinfo_handler(config).await,
Command::Invoice {
label,
description,
amount_msat,
expiry,
fallbacks,
preimage,
cltv,
deschashonly,
} => {
invoice_handler(
config,
label,
description,
amount_msat,
expiry,
fallbacks,
preimage,
cltv,
deschashonly,
)
.await
}
Command::Pay {
bolt11,
amount_msat,
label,
riskfactor,
maxfeepercent,
retry_for,
maxdelay,
exemptfee,
localinvreqid,
exclude,
maxfee,
description,
} => {
pay_handler(
config,
bolt11,
amount_msat,
label,
riskfactor,
maxfeepercent,
retry_for,
maxdelay,
exemptfee,
localinvreqid,
exclude,
maxfee,
description,
)
.await
}
Command::Connect { id, host, port } => connect_handler(config, id, host, port).await,
Command::Listpays {
bolt11,
payment_hash,
status,
} => {
let payment_hash = if let Some(v) = payment_hash {
match hex::decode(v) {
Ok(decoded) => Some(decoded),
Err(e) => {
println!("Payment hash is not a valid hex string: {}", e);
return Ok(()); // Exit the function early if hex decoding fails
}
}
} else {
None
};
let status = if let Some(status_str) = status {
match status_str.as_str() {
"pending" => Some(0),
"complete" => Some(1),
"failed" => Some(2),
_ => {
println!("Invalid status: {}, expected one of \"pending\", \"completed\", \"failed\"", status_str);
return Ok(()); // Exit the function early if the status is invalid
}
}
} else {
None
};
listpays_handler(config, bolt11, payment_hash, status).await
}
Command::Stop => stop(config).await,
}
}
async fn log<P: AsRef<Path>>(config: Config<P>) -> Result<()> {
let creds_path = config.data_dir.as_ref().join(CREDENTIALS_FILE_NAME);
let creds = match util::read_credentials(&creds_path) {
Some(c) => c,
None => {
return Err(Error::CredentialsNotFoundError(format!(
"could not read from {}",
creds_path.display()
)))
}
};
let scheduler = gl_client::scheduler::Scheduler::new(config.network, creds)
.await
.map_err(Error::custom)?;
let mut node: gl_client::node::Client = scheduler.node().await.map_err(Error::custom)?;
let mut stream = node
.stream_log(StreamLogRequest {})
.await
.map_err(Error::custom)?
.into_inner();
loop {
tokio::select! {
biased;
_ = tokio::signal::ctrl_c() => {
break;
}
maybe_line = stream.next() => {
match maybe_line {
Some(line) => {
println!("{}", line.map_err(Error::custom)?.line);
},
None => {
break;
},
}
}
}
}
Ok(())
}
async fn stop<P: AsRef<Path>>(config: Config<P>) -> Result<()> {
let creds_path = config.data_dir.as_ref().join(CREDENTIALS_FILE_NAME);
let creds = match util::read_credentials(&creds_path) {
Some(c) => c,
None => {
return Err(Error::CredentialsNotFoundError(format!(
"could not read from {}",
creds_path.display()
)))
}
};
let scheduler = gl_client::scheduler::Scheduler::new(config.network, creds)
.await
.map_err(Error::custom)?;
let mut node: gl_client::node::ClnClient = scheduler.node().await.map_err(Error::custom)?;
let res = node
.stop(cln::StopRequest {})
.await
.map_err(|e| Error::custom(e.message()))?
.into_inner();
println!("{:?}", res);
Ok(())
}
async fn getinfo_handler<P: AsRef<Path>>(config: Config<P>) -> Result<()> {
let creds_path = config.data_dir.as_ref().join(CREDENTIALS_FILE_NAME);
let creds = match util::read_credentials(&creds_path) {
Some(c) => c,
None => {
return Err(Error::CredentialsNotFoundError(format!(
"could not read from {}",
creds_path.display()
)))
}
};
let scheduler = gl_client::scheduler::Scheduler::new(config.network, creds)
.await
.map_err(Error::custom)?;
let mut node: gl_client::node::ClnClient = scheduler.node().await.map_err(Error::custom)?;
let res = node
.getinfo(cln::GetinfoRequest {})
.await
.map_err(|e| Error::custom(e.message()))?
.into_inner();
println!("{:?}", res);
Ok(())
}
async fn invoice_handler<P: AsRef<Path>>(
config: Config<P>,
label: String,
description: String,
amount_msat: Option<model::AmountOrAny>,
expiry: Option<u64>,
fallbacks: Option<Vec<String>>,
preimage: Option<Vec<u8>>,
cltv: Option<u32>,
deschashonly: Option<bool>,
) -> Result<()> {
let creds_path = config.data_dir.as_ref().join(CREDENTIALS_FILE_NAME);
let creds = match util::read_credentials(&creds_path) {
Some(c) => c,
None => {
return Err(Error::CredentialsNotFoundError(format!(
"could not read from {}",
creds_path.display()
)))
}
};
let scheduler = gl_client::scheduler::Scheduler::new(config.network, creds)
.await
.map_err(Error::custom)?;
let mut node: gl_client::node::ClnClient = scheduler.node().await.map_err(Error::custom)?;
let res = node
.invoice(cln::InvoiceRequest {
exposeprivatechannels: vec![],
amount_msat: amount_msat.map(|v| v.into()),
description,
label,
expiry,
fallbacks: fallbacks.unwrap_or_default(),
preimage,
cltv,
deschashonly,
})
.await
.map_err(|e| Error::custom(e.message()))?
.into_inner();
println!("{:?}", res);
Ok(())
}
async fn connect_handler<P: AsRef<Path>>(
config: Config<P>,
id: String,
host: Option<String>,
port: Option<u32>,
) -> Result<()> {
let creds_path = config.data_dir.as_ref().join(CREDENTIALS_FILE_NAME);
let creds = match util::read_credentials(&creds_path) {
Some(c) => c,
None => {
return Err(Error::CredentialsNotFoundError(format!(
"could not read from {}",
creds_path.display()
)))
}
};
let scheduler = gl_client::scheduler::Scheduler::new(config.network, creds)
.await
.map_err(Error::custom)?;
let mut node: gl_client::node::ClnClient = scheduler.node().await.map_err(Error::custom)?;
let res = node
.connect_peer(cln::ConnectRequest { id, host, port })
.await
.map_err(|e| Error::custom(e.message()))?
.into_inner();
println!("{:?}", res);
Ok(())
}
async fn listpays_handler<P: AsRef<Path>>(
config: Config<P>,
bolt11: Option<String>,
payment_hash: Option<Vec<u8>>,
status: Option<i32>,
) -> Result<()> {
let creds_path = config.data_dir.as_ref().join(CREDENTIALS_FILE_NAME);
let creds = match util::read_credentials(&creds_path) {
Some(c) => c,
None => {
return Err(Error::CredentialsNotFoundError(format!(
"could not read from {}",
creds_path.display()
)))
}
};
let scheduler = gl_client::scheduler::Scheduler::new(config.network, creds)
.await
.map_err(Error::custom)?;
let mut node: gl_client::node::ClnClient = scheduler.node().await.map_err(Error::custom)?;
let res = node
.list_pays(cln::ListpaysRequest {
index: None,
start: None,
limit: None,
bolt11,
payment_hash,
status,
})
.await
.map_err(|e| Error::custom(e.message()))?
.into_inner();
println!("{:?}", res);
Ok(())
}
async fn pay_handler<P: AsRef<Path>>(
config: Config<P>,
bolt11: String,
amount_msat: Option<u64>,
label: Option<String>,
riskfactor: Option<f64>,
maxfeepercent: Option<f64>,
retry_for: Option<u32>,
maxdelay: Option<u32>,
exemptfee: Option<u64>,
localinvreqid: Option<Vec<u8>>,
exclude: Option<Vec<String>>,
maxfee: Option<u64>,
description: Option<String>,
) -> Result<()> {
let creds_path = config.data_dir.as_ref().join(CREDENTIALS_FILE_NAME);
let creds = match util::read_credentials(&creds_path) {
Some(c) => c,
None => {
return Err(Error::CredentialsNotFoundError(format!(
"could not read from {}",
creds_path.display()
)))
}
};
let scheduler = gl_client::scheduler::Scheduler::new(config.network, creds)
.await
.map_err(Error::custom)?;
let mut node: gl_client::node::ClnClient = scheduler.node().await.map_err(Error::custom)?;
let res = node
.pay(cln::PayRequest {
bolt11,
amount_msat: amount_msat.map(|msat| cln::Amount { msat }),
label,
riskfactor,
maxfeepercent,
retry_for,
maxdelay,
exemptfee: exemptfee.map(|msat| cln::Amount { msat }),
localinvreqid,
exclude: exclude.unwrap_or_default(),
maxfee: maxfee.map(|msat| cln::Amount { msat }),
description,
partial_msat: None,
})
.await
.map_err(|e| Error::custom(e.message()))?
.into_inner();
println!("{:?}", res);
Ok(())
}
| rust | MIT | 28e98f8e093100e576415734630cff4ea9f3421e | 2026-01-04T20:21:42.079439Z | false |
Blockstream/greenlight | https://github.com/Blockstream/greenlight/blob/28e98f8e093100e576415734630cff4ea9f3421e/libs/gl-cli/src/lib.rs | libs/gl-cli/src/lib.rs | use crate::error::Result;
use clap::{Parser, Subcommand};
use gl_client::bitcoin::Network;
use std::{path::PathBuf, str::FromStr};
mod error;
pub mod model;
mod node;
mod scheduler;
mod signer;
mod util;
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
pub struct Cli {
/// The directory containing the seed and the credentials
#[arg(short, long, global = true, help_heading = "Global options")]
data_dir: Option<String>,
/// Bitcoin network to use. Supported networks are "signet" and "bitcoin"
#[arg(short, long, default_value = "bitcoin", value_parser = clap::value_parser!(Network), global = true, help_heading = "Global options")]
network: Network,
#[arg(long, short, global = true, help_heading = "Global options")]
verbose: bool,
#[command(subcommand)]
cmd: Commands,
}
#[derive(Subcommand, Debug)]
pub enum Commands {
/// Interact with the scheduler that is the brain of most operations
#[command(subcommand)]
Scheduler(scheduler::Command),
/// Interact with a local signer
#[command(subcommand)]
Signer(signer::Command),
/// Interact with the node
#[command(subcommand)]
Node(node::Command),
}
pub async fn run(cli: Cli) -> Result<()> {
if cli.verbose {
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "debug")
}
env_logger::init();
}
let data_dir = cli
.data_dir
.map(|d| util::DataDir(PathBuf::from_str(&d).expect("is not a valid path")))
.unwrap_or_default();
Ok(match cli.cmd {
Commands::Scheduler(cmd) => {
scheduler::command_handler(
cmd,
scheduler::Config {
data_dir,
network: cli.network,
},
)
.await?
}
Commands::Signer(cmd) => {
signer::command_handler(
cmd,
signer::Config {
data_dir,
network: cli.network,
},
)
.await?
}
Commands::Node(cmd) => {
node::command_handler(
cmd,
node::Config {
data_dir,
network: cli.network,
},
)
.await?
}
})
}
| rust | MIT | 28e98f8e093100e576415734630cff4ea9f3421e | 2026-01-04T20:21:42.079439Z | false |
Blockstream/greenlight | https://github.com/Blockstream/greenlight/blob/28e98f8e093100e576415734630cff4ea9f3421e/libs/gl-cli/src/error.rs | libs/gl-cli/src/error.rs | // -- Contains errors and formating for errors.
use crate::util;
pub type Result<T, E = Error> = core::result::Result<T, E>;
#[derive(thiserror::Error, core::fmt::Debug)]
pub enum Error {
#[error("{0}")]
Custom(String),
#[error("Seed not found: {0}")]
SeedNotFoundError(String),
#[error("Credentials not found: {0}")]
CredentialsNotFoundError(String),
#[error(transparent)]
UtilError(#[from] util::UtilsError),
}
impl Error {
/// Sets a custom error,
pub fn custom(e: impl std::fmt::Display) -> Error {
Error::Custom(e.to_string())
}
pub fn seed_not_found(e: impl std::fmt::Display) -> Error {
Error::SeedNotFoundError(e.to_string())
}
pub fn credentials_not_found(e: impl std::fmt::Display) -> Error {
Error::CredentialsNotFoundError(e.to_string())
}
}
// -- Disable hints for now as it would require to get rid of thiserror. Might
// be a nice future improvement.
//impl Error {
// fn hint(&self) -> Option<&'static str> {
// match self {
// Error::Custom(_) => None,
// Error::SeedNotFoundError(_) => {
// Some("check if data_dir is correct or register a node first")
// }
// Error::CredentialsNotFoundError(_) => {
// Some("check if data_dir is correct or try to recover")
// }
// Error::UtilError(_) => None,
// }
// }
//}
//
//impl Debug for Error {
// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// if let Some(hint) = self.hint() {
// write!(f, "error: {}\nhint: {}", self.to_string(), hint)
// } else {
// write!(f, "{}", self.to_string())
// }
// }
//}
| rust | MIT | 28e98f8e093100e576415734630cff4ea9f3421e | 2026-01-04T20:21:42.079439Z | false |
Blockstream/greenlight | https://github.com/Blockstream/greenlight/blob/28e98f8e093100e576415734630cff4ea9f3421e/libs/gl-cli/src/util.rs | libs/gl-cli/src/util.rs | use dirs;
use gl_client::bitcoin::secp256k1::rand::{self, RngCore};
use gl_client::credentials;
use std::path::PathBuf;
use std::{
fs::{self, File},
io::Write,
path::Path,
};
use thiserror;
pub const SEED_FILE_NAME: &str = "hsm_secret";
pub const CREDENTIALS_FILE_NAME: &str = "credentials.gfs";
pub const DEFAULT_GREENLIGHT_DIR: &str = "greenlight";
// -- Seed section
pub fn generate_seed() -> [u8; 32] {
let mut seed = [0u8; 32];
let mut rng = rand::thread_rng();
rng.fill_bytes(&mut seed);
seed
}
pub fn read_seed(file_path: impl AsRef<Path>) -> Option<Vec<u8>> {
fs::read(file_path).ok()
}
pub fn write_seed(file_path: impl AsRef<Path>, seed: impl AsRef<[u8]>) -> Result<()> {
let file_path = file_path.as_ref();
if let Some(parent) = file_path.parent() {
fs::create_dir_all(parent)?;
}
let mut file = File::create(file_path)?;
file.write_all(seed.as_ref())?;
file.sync_all()?;
Ok(())
}
// -- Credentials section
pub fn write_credentials(file_path: impl AsRef<Path>, creds: impl AsRef<[u8]>) -> Result<()> {
let mut file = File::create(&file_path)?;
file.write_all(creds.as_ref())?;
file.sync_all()?;
Ok(())
}
pub fn read_credentials(file_path: impl AsRef<Path>) -> Option<credentials::Device> {
let cred_data = fs::read(file_path).ok();
if let Some(data) = cred_data {
let creds = credentials::Device::from_bytes(data);
return Some(creds);
}
None
}
// -- Misc
pub struct DataDir(pub PathBuf);
impl core::default::Default for DataDir {
fn default() -> Self {
let data_dir = dirs::data_dir().unwrap().join(DEFAULT_GREENLIGHT_DIR);
Self(data_dir)
}
}
impl AsRef<Path> for DataDir {
fn as_ref(&self) -> &Path {
self.0.as_path()
}
}
// -- Error implementations
#[derive(thiserror::Error, core::fmt::Debug)]
pub enum UtilsError {
#[error(transparent)]
IoError(#[from] std::io::Error),
}
type Result<T, E = UtilsError> = core::result::Result<T, E>;
| rust | MIT | 28e98f8e093100e576415734630cff4ea9f3421e | 2026-01-04T20:21:42.079439Z | false |
Blockstream/greenlight | https://github.com/Blockstream/greenlight/blob/28e98f8e093100e576415734630cff4ea9f3421e/libs/gl-cli/src/model.rs | libs/gl-cli/src/model.rs | use gl_client::pb::cln::{self, amount_or_any};
#[derive(Debug, Clone)]
enum AmountOrAnyValue {
Any,
Amount(u64),
}
#[derive(Debug, Clone)]
pub struct AmountOrAny {
value: AmountOrAnyValue,
}
impl From<&str> for AmountOrAny {
fn from(value: &str) -> Self {
if value == "any" {
return Self {
value: AmountOrAnyValue::Any,
};
} else {
return match value.parse::<u64>() {
Ok(msat) => Self {
value: AmountOrAnyValue::Amount(msat),
},
Err(e) => panic!("{}", e),
};
}
}
}
impl Into<cln::AmountOrAny> for AmountOrAny {
fn into(self) -> cln::AmountOrAny {
match self.value {
AmountOrAnyValue::Any => cln::AmountOrAny {
value: Some(amount_or_any::Value::Any(true)),
},
AmountOrAnyValue::Amount(msat) => cln::AmountOrAny {
value: Some(amount_or_any::Value::Amount(cln::Amount { msat })),
},
}
}
}
| rust | MIT | 28e98f8e093100e576415734630cff4ea9f3421e | 2026-01-04T20:21:42.079439Z | false |
Blockstream/greenlight | https://github.com/Blockstream/greenlight/blob/28e98f8e093100e576415734630cff4ea9f3421e/libs/gl-cli/src/scheduler.rs | libs/gl-cli/src/scheduler.rs | use crate::error::{Error, Result};
use crate::util;
use clap::Subcommand;
use core::fmt::Debug;
use gl_client::{credentials, pairing, scheduler::Scheduler, signer::Signer};
use lightning_signer::bitcoin::Network;
use std::io::Write;
use std::path::Path;
use std::{fs, io};
use tokio::task;
use util::{CREDENTIALS_FILE_NAME, SEED_FILE_NAME};
pub struct Config<P: AsRef<Path>> {
pub data_dir: P,
pub network: Network,
}
#[derive(Subcommand, Debug)]
pub enum Command {
/// Register a new greenlight node
Register {
/// An invite code for greenlight, format is xxxx-xxxx
#[arg(short, long)]
invite_code: Option<String>,
},
/// Recover the credentials for a greenlight node, still needs to access the seed
Recover,
/// Schedule the node on greenlight services
Schedule,
/// Upgrades from using certificate and key to using credentials blob
UpgradeCredentials,
/// Start a new pairing session for a signer-less device
PairDevice {
#[arg(required = true, help = "The user visible name of the device to pair")]
name: String,
#[arg(
long,
help = "A description of the device purpose for the user to read upon approval"
)]
description: Option<String>,
#[arg(
long,
help = "A set of restrictions to restrict the node access for the device"
)]
restrictions: Option<String>,
},
/// Approves a pairing request made by a signer-less device
ApprovePairing {
#[arg(
required = true,
help = "The pairing data string received from the device to pair"
)]
pairing_data: String,
},
/// Export the node from Greenlight infrastructure
Export,
}
pub async fn command_handler<P: AsRef<Path>>(cmd: Command, config: Config<P>) -> Result<()> {
match cmd {
Command::Register { invite_code } => register_handler(config, invite_code).await,
Command::Recover => recover_handler(config).await,
Command::Schedule => schedule_handler(config).await,
Command::UpgradeCredentials => upgrade_credentials_handler(config).await,
Command::PairDevice {
name,
description,
restrictions,
} => {
pair_device_handler(
config,
&name,
&description.unwrap_or_default(),
&restrictions.unwrap_or_default(),
)
.await
}
Command::ApprovePairing { pairing_data } => {
approve_pairing_handler(config, &pairing_data).await
}
Command::Export => export_handler(config).await,
}
}
async fn register_handler<P: AsRef<Path>>(
config: Config<P>,
invite_code: Option<String>,
) -> Result<()> {
// Check if a node is already registered for the given seed.
let seed_path = config.data_dir.as_ref().join(SEED_FILE_NAME);
let seed = match util::read_seed(&seed_path) {
Some(seed) => {
println!("Seed already exists at {}, usign it", seed_path.display());
seed
}
None => {
// Generate a new seed and save it.
let seed = util::generate_seed();
util::write_seed(&seed_path, &seed)?;
println!("Seed saved to {}", seed_path.display());
seed.to_vec()
}
};
// Initialize a signer and scheduler with default credentials.
let creds = credentials::Nobody::new();
let signer = Signer::new(seed, config.network, creds.clone())
.map_err(|e| Error::custom(format!("Failed to create signer: {}", e)))?;
let scheduler = Scheduler::new(config.network, creds)
.await
.map_err(|e| Error::custom(format!("Failed to create scheduler: {}", e)))?;
// Attempt to register a new node.
let res = scheduler
.register(&signer, invite_code)
.await
.map_err(|e| Error::custom(format!("Failed to register node: {}", e)))?;
if res.creds.is_empty() {
println!("No credentials found. Please recover the node.");
}
// Save the device credentials to file.
let creds_path = config.data_dir.as_ref().join(CREDENTIALS_FILE_NAME);
let device_creds = credentials::Device::from_bytes(res.creds);
util::write_credentials(&creds_path, &device_creds.to_bytes())?;
println!("Credentials saved at {}", creds_path.display());
Ok(())
}
async fn recover_handler<P: AsRef<Path>>(config: Config<P>) -> Result<()> {
// Check if we can find a seed file, if we can not find one, we need to register first.
let seed_path = config.data_dir.as_ref().join(SEED_FILE_NAME);
let seed = util::read_seed(&seed_path);
if seed.is_none() {
println!("No seed found. Need to register first.");
return Err(Error::seed_not_found(format!(
"could not read from {}",
seed_path.display()
)));
}
let seed = seed.unwrap(); // we checked if it is none before.
// Initialize a signer and scheduler with default credentials.
let creds = credentials::Nobody::new();
let signer = Signer::new(seed, config.network, creds.clone())
.map_err(|e| Error::custom(format!("Failed to create signer: {}", e)))?;
let scheduler = Scheduler::new(config.network, creds)
.await
.map_err(|e| Error::custom(format!("Failed to create scheduler: {}", e)))?;
// Attempt to recover a new node.
let res = scheduler
.recover(&signer)
.await
.map_err(|e| Error::custom(format!("Failed to register node: {}", e)))?;
if res.creds.is_empty() {
println!("No credentials found. Please recover the node.");
}
// Save the device credentials to file.
let creds_path = config.data_dir.as_ref().join(CREDENTIALS_FILE_NAME);
let device_creds = credentials::Device::from_bytes(res.creds);
util::write_credentials(&creds_path, &device_creds.to_bytes())?;
println!("Credentials saved at {}", creds_path.display());
Ok(())
}
async fn schedule_handler<P: AsRef<Path>>(config: Config<P>) -> Result<()> {
let creds_path = config.data_dir.as_ref().join(CREDENTIALS_FILE_NAME);
let creds = util::read_credentials(&creds_path);
if creds.is_none() {
println!("Could not find credentials at {}", creds_path.display());
return Err(Error::credentials_not_found(format!(
"could not read from {}",
creds_path.display()
)));
}
let creds = creds.unwrap(); // we checked if it is none before.
let scheduler = Scheduler::new(config.network, creds)
.await
.map_err(|e| Error::custom(format!("Failed to create scheduler: {}", e)))?;
// Attempt to recover a new node.
let res = scheduler
.schedule()
.await
.map_err(|e| Error::custom(format!("Failed to register node: {}", e)))?;
println!("{:?}", res);
Ok(())
}
async fn upgrade_credentials_handler<P: AsRef<Path>>(config: Config<P>) -> Result<()> {
// Check if we can find a seed file, if we can not find one, we need to register first.
let seed_path = config.data_dir.as_ref().join(SEED_FILE_NAME);
let seed = util::read_seed(&seed_path);
if seed.is_none() {
println!("No seed found. Need to register first.");
return Err(Error::seed_not_found(format!(
"could not read from {}",
seed_path.display()
)));
}
let seed = seed.unwrap(); // we checked if it is none before.
// We are trying to upgrade credentials, load the ones we want to replace.
let cert_path = config.data_dir.as_ref().join("device.crt");
let cert = fs::read(cert_path).map_err(Error::custom)?;
let key_path = config.data_dir.as_ref().join("device-key.pem");
let key = fs::read(key_path).map_err(Error::custom)?;
let device = credentials::Device {
cert,
key,
..Default::default()
};
// Initialize a signer and scheduler with default credentials.
let nobody = credentials::Nobody::new();
let signer = Signer::new(seed, config.network, nobody.clone())
.map_err(|e| Error::custom(format!("Failed to create signer: {}", e)))?;
let scheduler = Scheduler::new(config.network, nobody)
.await
.map_err(|e| Error::custom(format!("Failed to create scheduler: {}", e)))?;
let creds = device
.upgrade(&scheduler, &signer)
.await
.map_err(Error::custom)?;
let creds_path = config.data_dir.as_ref().join(CREDENTIALS_FILE_NAME);
util::write_credentials(&creds_path, &creds.to_bytes())?;
println!("Credentials saved at {}", creds_path.display());
Ok(())
}
async fn pair_device_handler<P: AsRef<Path>>(
config: Config<P>,
name: &str,
description: &str,
restrictions: &str,
) -> Result<()> {
let creds = credentials::Nobody::new();
let dc = pairing::new_device::Client::new(creds)
.connect()
.await
.map_err(Error::custom)?;
let mut rec_stream = dc
.pair_device(name, description, restrictions)
.await
.map_err(Error::custom)?;
while let Some(data) = rec_stream.recv().await {
match data {
pairing::PairingSessionData::PairingResponse(pair_device_response) => {
let creds_path = config.data_dir.as_ref().join(CREDENTIALS_FILE_NAME);
util::write_credentials(&creds_path, &pair_device_response.creds)?;
println!("Credentials saved at {}", creds_path.display());
return Ok(());
}
pairing::PairingSessionData::PairingQr(qr) => {
println!("Share the following data with the device to pair with:\n{qr}");
}
pairing::PairingSessionData::PairingError(status) => {
return Err(Error::custom(format!("Pairing failed: {}", status)));
}
};
}
Err(Error::custom("Connection to scheduler has been closed"))
}
async fn export_handler<P: AsRef<Path>>(config: Config<P>) -> Result<()> {
let creds_path = config.data_dir.as_ref().join(CREDENTIALS_FILE_NAME);
let creds = util::read_credentials(&creds_path);
if creds.is_none() {
println!("Could not find credentials at {}", creds_path.display());
return Err(Error::credentials_not_found(format!(
"could not read from {}",
creds_path.display()
)));
}
let creds = creds.unwrap(); // we checked if it is none before.
let scheduler = Scheduler::new(config.network, creds)
.await
.map_err(|e| Error::custom(format!("Failed to create scheduler: {}", e)))?;
// Confirm export action with the user
print!(
"WARNING: Exporting your node will make it no longer schedulable on Greenlight.
After export, you will need to run the node on your own infrastructure.
This operation is idempotent and can be called multiple times.
Are you sure you want to export your node? (y/N) "
);
io::stdout().flush().expect("Failed to flush stdout");
let input = task::spawn_blocking(|| {
let mut input = String::new();
std::io::stdin()
.read_line(&mut input)
.expect("Failed to read line");
input
})
.await
.expect("Task failed");
if !input.trim().eq_ignore_ascii_case("y") {
println!("Export cancelled.");
return Ok(());
}
// Initiate the node export
let res = scheduler
.export_node()
.await
.map_err(|e| Error::custom(format!("Failed to export node: {}", e)))?;
println!("Node export initiated successfully!");
println!("Download the encrypted backup from: {}", res.url);
println!("\nNote: After exporting, the node will no longer be schedulable on Greenlight.");
println!("The backup is encrypted and can only be decrypted with your node secret.");
Ok(())
}
async fn approve_pairing_handler<P: AsRef<Path>>(
config: Config<P>,
pairing_data: &str,
) -> Result<()> {
let creds_path = config.data_dir.as_ref().join(CREDENTIALS_FILE_NAME);
let creds = util::read_credentials(&creds_path);
if creds.is_none() {
println!("Could not find credentials at {}", creds_path.display());
return Err(Error::credentials_not_found(format!(
"could not read from {}",
creds_path.display()
)));
}
let creds = creds.unwrap(); // we checked if it is none before.
let ac = pairing::attestation_device::Client::new(creds)
.map_err(Error::custom)?
.connect()
.await
.map_err(Error::custom)?;
let device_id = match pairing_data.split_once(":") {
Some((_, id)) => Ok(id),
None => Err(Error::custom(format!(
"could not extract device_id from given pairing data {}",
pairing_data
))),
}?;
let data = ac
.get_pairing_data(device_id)
.await
.map_err(Error::custom)?;
// Verify pairing data first.
pairing::attestation_device::Client::<
pairing::attestation_device::Connected,
credentials::Device,
>::verify_pairing_data(data.clone())
.map_err(|e| Error::custom(format!("could not verify pairing data: {}", e)))?;
print!(
"The following device requests attestation:
id: {}
name: {}
description: {}
restrictions: {}
Do you want to continue and attestate the pairing (y/N)? ",
data.device_id, data.device_name, data.description, data.restrictions
);
io::stdout().flush().expect("Failed to flush stdout");
let input = task::spawn_blocking(|| {
let mut input = String::new();
std::io::stdin()
.read_line(&mut input)
.expect("Failed to read line");
input
})
.await
.expect("Task failed");
if input.trim().eq_ignore_ascii_case("y") {
println!("Continue attestation.")
} else {
println!("Abort pairing.");
return Ok(());
}
ac.approve_pairing(&data.device_id, &data.device_name, &data.restrictions)
.await
.map_err(|e| Error::custom(format!("failed to attestate pairing data: {}", e)))?;
println!("Pairing done!");
Ok(())
}
| rust | MIT | 28e98f8e093100e576415734630cff4ea9f3421e | 2026-01-04T20:21:42.079439Z | false |
Blockstream/greenlight | https://github.com/Blockstream/greenlight/blob/28e98f8e093100e576415734630cff4ea9f3421e/libs/gl-cli/src/bin/glcli.rs | libs/gl-cli/src/bin/glcli.rs | use clap::Parser;
use gl_cli::{run, Cli};
#[tokio::main]
async fn main() {
let cli = Cli::parse();
match run(cli).await {
Ok(()) => (),
Err(e) => {
println!("{}", e);
}
}
}
| rust | MIT | 28e98f8e093100e576415734630cff4ea9f3421e | 2026-01-04T20:21:42.079439Z | false |
AndreasBackx/waycorner | https://github.com/AndreasBackx/waycorner/blob/6951316368e8db55d20203c3255176b897518aac/src/config.rs | src/config.rs | use std::{collections::HashMap, env, fs::File, io::Read, path::PathBuf};
use anyhow::{bail, Context, Result};
use regex::Regex;
use serde::{
de::{self, Unexpected},
Deserialize, Deserializer,
};
use tracing::{debug, info};
pub const COLOR_TRANSPARENT: u32 = 0x00_00_00_00;
pub const COLOR_RED: u32 = 0xFF_FF_00_00;
fn default_locations() -> Vec<Location> {
vec![Location::BottomRight, Location::BottomLeft]
}
fn default_size() -> u8 {
10
}
fn default_margin() -> i8 {
20
}
fn default_timeout_ms() -> u16 {
250
}
fn default_color() -> u32 {
COLOR_RED
}
fn default_command() -> Vec<String> {
Vec::new()
}
fn from_hex<'de, D>(deserializer: D) -> Result<u32, D::Error>
where
D: Deserializer<'de>,
{
let value: String = Deserialize::deserialize(deserializer)?;
let re: Regex = Regex::new(r"^#[0-9a-fA-F]{6,8}$").unwrap();
if !re.is_match(&value) {
return Err(de::Error::invalid_value(
Unexpected::Str(&value),
&"a valid hex code",
));
}
let without_prefix = value.trim_start_matches('#');
u32::from_str_radix(without_prefix, 16)
.map(|val| {
if val <= 0xFF_FF_FF {
val | 0xFF_00_00_00
} else {
val
}
})
.map_err(de::Error::custom)
}
#[derive(Clone, Debug, Deserialize)]
pub struct CornerConfig {
pub output: Option<OutputConfig>,
#[serde(default = "default_command", alias = "command")]
pub enter_command: Vec<String>,
#[serde(default = "default_command")]
pub exit_command: Vec<String>,
#[serde(default = "default_locations")]
pub locations: Vec<Location>,
#[serde(default = "default_size")]
pub size: u8,
#[serde(default = "default_margin")]
pub margin: i8,
#[serde(default = "default_timeout_ms")]
pub timeout_ms: u16,
#[serde(default = "default_color", deserialize_with = "from_hex")]
pub color: u32,
}
#[derive(Clone, Debug, Deserialize)]
pub struct OutputConfig {
pub description: Option<String>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Location {
TopLeft,
TopRight,
BottomRight,
BottomLeft,
Left,
Right,
Top,
Bottom,
}
type Config = HashMap<String, CornerConfig>;
pub fn get_configs(config_path: PathBuf) -> Result<Vec<CornerConfig>> {
let path = if config_path.starts_with("~/") {
debug!("Replacing ~/ with $HOME/");
let home_path = env::var_os("HOME")
.context("could not find the $HOME env var to use for the default config path")?;
let relative_path = config_path
.to_str()
.unwrap_or_else(|| panic!("invalid config path specified: {}", config_path.display()))
.to_string()
.split_off(2);
PathBuf::from(home_path).join(relative_path)
} else {
config_path
};
info!("Using config: {}", path.display());
let mut config_file = File::open(path.clone())
.with_context(|| format!("could not open the file {}", path.display()))?;
let mut config_content = String::new();
config_file.read_to_string(&mut config_content)?;
toml::from_str::<Config>(config_content.as_str()).map(|item| {
item.into_iter()
.map(|(key, value)| {
if value.enter_command.is_empty() && value.exit_command.is_empty() {
bail!(
"You must provide either an `exit_command` or an `enter_command` for `{}`",
key
)
}
Ok(value)
})
.collect::<Result<Vec<_>>>()
.with_context(|| format!("could not parse {}", path.display()))
})?
}
| rust | MIT | 6951316368e8db55d20203c3255176b897518aac | 2026-01-04T20:22:01.198602Z | false |
AndreasBackx/waycorner | https://github.com/AndreasBackx/waycorner/blob/6951316368e8db55d20203c3255176b897518aac/src/wayland.rs | src/wayland.rs | use crate::{
config::{self, CornerConfig, Location},
corner::Corner,
};
use anyhow::{Context, Result};
use crossbeam_utils::thread;
use smithay_client_toolkit::shm::Format;
use smithay_client_toolkit::{
data_device::DataDeviceHandler,
default_environment,
environment::{Environment, SimpleGlobal},
output::{with_output_info, OutputInfo, XdgOutputHandler},
primary_selection::PrimarySelectionHandler,
seat,
};
use std::{
convert::TryInto,
io::{BufWriter, Seek, SeekFrom, Write},
sync::{
mpsc::{self, Receiver, Sender},
Arc, Mutex,
},
};
use tracing::{debug, info};
use wayland_client::{
protocol::{wl_output::WlOutput, wl_pointer, wl_surface::WlSurface},
Attached, Display, Main, Proxy,
};
use wayland_protocols::{
unstable::xdg_output::v1::client::zxdg_output_manager_v1::ZxdgOutputManagerV1,
wlr::unstable::layer_shell::v1::client::{
zwlr_layer_shell_v1,
zwlr_layer_surface_v1::{self, Anchor, ZwlrLayerSurfaceV1},
},
};
default_environment!(Waycorner, fields = [
layer_shell: SimpleGlobal<zwlr_layer_shell_v1::ZwlrLayerShellV1>,
sctk_xdg_out: XdgOutputHandler,
],
singles = [
zwlr_layer_shell_v1::ZwlrLayerShellV1 => layer_shell,
ZxdgOutputManagerV1 => sctk_xdg_out,
],);
struct GlobalState {
close_requested: bool,
}
pub struct Wayland {
pub preview: bool,
corner_to_surfaces: Vec<(Corner, Vec<WlSurface>)>,
}
impl Wayland {
pub fn new(configs: Vec<CornerConfig>, preview: bool) -> Self {
Wayland {
preview,
corner_to_surfaces: configs
.into_iter()
.map(|corner| (Corner::new(corner), vec![]))
.collect(),
}
}
pub fn run(&mut self) -> Result<()> {
let display = Display::connect_to_env()?;
let mut event_queue = display.create_event_queue();
let wl_display = Proxy::clone(&display).attach(event_queue.token());
let (sctk_outputs, sctk_xdg_out) = XdgOutputHandler::new_output_handlers();
let mut seat_handler = smithay_client_toolkit::seat::SeatHandler::new();
let sctk_data_device_manager = DataDeviceHandler::init(&mut seat_handler);
let sctk_primary_selection_manager = PrimarySelectionHandler::init(&mut seat_handler);
let environment = smithay_client_toolkit::environment::Environment::new(
&wl_display,
&mut event_queue,
Waycorner {
sctk_compositor: SimpleGlobal::new(),
sctk_shm: smithay_client_toolkit::shm::ShmHandler::new(),
sctk_seats: seat_handler,
sctk_outputs,
sctk_xdg_out,
sctk_subcompositor: SimpleGlobal::new(),
sctk_data_device_manager,
sctk_primary_selection_manager,
layer_shell: SimpleGlobal::new(),
},
)?;
let layer_shell = environment.require_global::<zwlr_layer_shell_v1::ZwlrLayerShellV1>();
let env_handle = environment.clone();
for output in environment.get_all_outputs() {
if let Some(info) = with_output_info(&output, Clone::clone) {
self.output_handler(&env_handle, &layer_shell, output, &info)?;
}
}
let (tx, rx): (Sender<wl_pointer::Event>, Receiver<wl_pointer::Event>) = mpsc::channel();
for seat in environment.get_all_seats() {
let filter_tx = tx.clone();
if let Some(has_ptr) = seat::with_seat_data(&seat, |seat_data| {
seat_data.has_pointer && !seat_data.defunct
}) {
if !has_ptr {
continue;
}
seat.get_pointer().quick_assign(move |_, event, _| {
filter_tx
.send(event)
.expect("could not send event on channel");
});
}
}
let pointer_event_receiver = Arc::new(Mutex::new(rx));
thread::scope(|scope| -> Result<()> {
scope.spawn(|_| loop {
let event = pointer_event_receiver
.lock()
.expect("Could not lock event receiver")
.recv();
match event {
Ok(wl_pointer::Event::Enter { surface, .. }) => {
self.get_corner(&surface)
.and_then(|corner| corner.on_enter_mouse().ok());
}
Ok(wl_pointer::Event::Leave { surface, .. }) => {
self.get_corner(&surface)
.and_then(|corner| corner.on_leave_mouse().ok());
}
_ => (),
}
});
self.corner_to_surfaces.iter().for_each(|(corner, _)| {
scope.spawn(move |_| loop {
corner.wait().unwrap();
});
});
let mut global_state = GlobalState {
close_requested: false,
};
loop {
event_queue
.dispatch(&mut global_state, |_, _, _| {
panic!("An event was received not assigned to any callback!")
})
.context("Wayland connection lost!")?;
if global_state.close_requested {
break;
}
}
Ok(())
})
.unwrap()
}
fn get_corner(&self, surface: &WlSurface) -> Option<&Corner> {
self.corner_to_surfaces
.iter()
.filter(|(_, surfaces)| surfaces.iter().any(|value| value == surface))
.map(|(corner, _)| corner)
.next()
}
fn output_handler(
&mut self,
environment: &Environment<Waycorner>,
layer_shell: &Attached<zwlr_layer_shell_v1::ZwlrLayerShellV1>,
output: WlOutput,
info: &OutputInfo,
) -> Result<()> {
info!("{:?}", info);
let preview = self.preview;
self.corner_to_surfaces
.iter_mut()
.try_for_each(|(corner, surfaces)| -> Result<()> {
debug!("{:?}", corner);
if !corner.is_match(info.description.as_str()) {
debug!("Output description is NOT a match");
return Ok(());
}
debug!("Output description IS a match");
if info.obsolete {
debug!("Clearing surfaces");
surfaces.clear();
return Ok(());
}
debug!("Adding surfaces");
let mut corner_surfaces = Wayland::corner_setup(
environment,
layer_shell,
&output,
corner.config.clone(),
preview,
corner.config.color,
)?;
surfaces.append(&mut corner_surfaces);
Ok(())
})?;
if info.obsolete {
info!("Releasing output");
output.release();
}
Ok(())
}
fn corner_setup(
environment: &Environment<Waycorner>,
layer_shell: &Attached<zwlr_layer_shell_v1::ZwlrLayerShellV1>,
output: &WlOutput,
corner_config: CornerConfig,
preview: bool,
preview_color: u32,
) -> Result<Vec<WlSurface>> {
corner_config
.locations
.iter()
.map(|location| {
let anchor = match location {
Location::TopLeft => Anchor::Top | Anchor::Left,
Location::TopRight => Anchor::Top | Anchor::Right,
Location::BottomRight => Anchor::Bottom | Anchor::Right,
Location::BottomLeft => Anchor::Bottom | Anchor::Left,
Location::Left => Anchor::Left | Anchor::Top | Anchor::Bottom,
Location::Right => Anchor::Right | Anchor::Top | Anchor::Bottom,
Location::Top => Anchor::Top | Anchor::Left | Anchor::Right,
Location::Bottom => Anchor::Bottom | Anchor::Left | Anchor::Right,
};
info!("Adding anchorpoint {:?}", anchor);
let surface = environment.create_surface().detach();
let layer_surface = layer_shell.get_layer_surface(
&surface,
Some(output),
zwlr_layer_shell_v1::Layer::Overlay,
"waycorner".to_owned(),
);
let size = corner_config.size.into();
let margin = corner_config.margin.into();
layer_surface.set_size(
match location {
Location::Top | Location::Bottom => 0,
_ => size,
},
match location {
Location::Left | Location::Right => 0,
_ => size,
},
);
layer_surface.set_margin(
// top, right, bottom, left
match location {
Location::Left | Location::Right => margin,
_ => 0,
},
match location {
Location::Top | Location::Bottom => margin,
_ => 0,
},
match location {
Location::Left | Location::Right => margin,
_ => 0,
},
match location {
Location::Top | Location::Bottom => margin,
_ => 0,
},
);
layer_surface.set_anchor(anchor);
// Ignore exclusive zones.
layer_surface.set_exclusive_zone(-1);
Wayland::initial_draw(
environment,
surface.clone(),
layer_surface,
preview,
preview_color,
)?;
Ok(surface)
})
.collect()
}
fn initial_draw(
environment: &Environment<Waycorner>,
surface: WlSurface,
layer_surface: Main<ZwlrLayerSurfaceV1>,
preview: bool,
preview_color: u32,
) -> Result<()> {
let mut double_pool = environment
.create_double_pool(|_| {})
.context("Failed to create double pool!")?;
let surface_handle = surface.clone();
layer_surface.quick_assign(move |layer_surface, event, _| {
if let zwlr_layer_surface_v1::Event::Configure {
serial,
width,
height,
} = event
{
layer_surface.ack_configure(serial);
if let Some(pool) = double_pool.pool() {
let pxcount = width * height;
let bytecount = 4 * pxcount;
pool.resize(bytecount.try_into().unwrap()).unwrap();
pool.seek(SeekFrom::Start(0)).unwrap();
{
let mut writer = BufWriter::new(&mut *pool);
let color = if preview {
preview_color
} else {
config::COLOR_TRANSPARENT
};
for _ in 0..pxcount {
writer.write_all(&color.to_ne_bytes()).unwrap();
}
writer.flush().unwrap();
}
let buffer = pool.buffer(
0,
width.try_into().unwrap(),
height.try_into().unwrap(),
(4 * width).try_into().unwrap(),
Format::Argb8888,
);
surface_handle.attach(Some(&buffer), 0, 0);
surface_handle.damage_buffer(
0,
0,
width.try_into().unwrap(),
height.try_into().unwrap(),
);
surface_handle.commit();
}
}
});
surface.commit();
Ok(())
}
}
| rust | MIT | 6951316368e8db55d20203c3255176b897518aac | 2026-01-04T20:22:01.198602Z | false |
AndreasBackx/waycorner | https://github.com/AndreasBackx/waycorner/blob/6951316368e8db55d20203c3255176b897518aac/src/main.rs | src/main.rs | mod config;
mod corner;
mod wayland;
use anyhow::Result;
use clap::Parser;
use config::get_configs;
use std::path::PathBuf;
use wayland::Wayland;
/// Hot corners for Wayland.
/// Waycorner allows you to create anchors on specified locations of your monitors and execute a command of your choice.
#[derive(Parser)]
#[clap(version = env!("CARGO_PKG_VERSION"), author = "Andreas Backx")]
struct Opts {
/// Config file path.
#[clap(short, long, default_value = "~/.config/waycorner/config.toml")]
config: PathBuf,
/// Preview the corners on your screen(s).
#[clap(short, long)]
preview: bool,
}
fn main() -> Result<()> {
tracing_subscriber::fmt::init();
let opts = Opts::parse();
let mut frontend = Wayland::new(get_configs(opts.config)?, opts.preview);
frontend.run()
}
| rust | MIT | 6951316368e8db55d20203c3255176b897518aac | 2026-01-04T20:22:01.198602Z | false |
AndreasBackx/waycorner | https://github.com/AndreasBackx/waycorner/blob/6951316368e8db55d20203c3255176b897518aac/src/corner.rs | src/corner.rs | use std::{
borrow::Borrow,
cmp,
process::Command,
sync::{
mpsc::{channel, Receiver, Sender},
Arc, Mutex,
},
time::{Duration, Instant},
};
use anyhow::Result;
use regex::Regex;
use tracing::{debug, info};
use crate::config::CornerConfig;
#[derive(Debug, PartialEq)]
pub enum CornerEvent {
Enter,
Leave,
}
#[allow(clippy::type_complexity)]
#[derive(Debug)]
pub struct Corner {
pub config: CornerConfig,
pub channel: (
Arc<Mutex<Sender<CornerEvent>>>,
Arc<Mutex<Receiver<CornerEvent>>>,
),
}
impl Corner {
pub fn new(config: CornerConfig) -> Corner {
let (tx, rx) = channel();
Corner {
config,
channel: (Arc::new(Mutex::new(tx)), Arc::new(Mutex::new(rx))),
}
}
pub fn wait(&self) -> Result<()> {
let timeout = Duration::from_millis(cmp::max(self.config.timeout_ms.into(), 5));
let mut last_event = None;
let mut command_done_at = None;
loop {
let event_result = self
.channel
.1
.lock()
.expect("cannot get corner receiver")
.recv_timeout(timeout);
match event_result {
Ok(event) => {
debug!("Received event: {:?}", event);
if command_done_at.map_or(true, |value| {
Instant::now()
.duration_since(value)
.ge(&Duration::from_millis(250))
}) {
last_event = Some(event);
} else {
debug!("Ignored the event due to too fast after unlock.");
}
}
Err(_error) => {
if let Some(event) = last_event {
if event == CornerEvent::Enter {
self.execute_command(&self.config.enter_command)?;
} else if event == CornerEvent::Leave {
self.execute_command(&self.config.exit_command)?;
}
command_done_at = Some(Instant::now());
}
last_event = None;
}
}
}
}
pub fn on_enter_mouse(&self) -> Result<()> {
self.channel
.0
.lock()
.expect("Cannot get sender")
.send(CornerEvent::Enter)?;
Ok(())
}
pub fn on_leave_mouse(&self) -> Result<()> {
self.channel
.0
.lock()
.expect("Cannot get sender")
.send(CornerEvent::Leave)?;
Ok(())
}
pub fn is_match(&self, description: &str) -> bool {
self.config
.clone()
.output
.and_then(|value| value.description)
.and_then(|value| Regex::new(value.as_str()).ok())
.as_ref()
.map(|regex| regex.is_match(description))
.unwrap_or(true)
}
fn execute_command(&self, command: &[String]) -> Result<()> {
if let Some(binary) = command.first() {
let args = command
.iter()
.enumerate()
.filter(|(index, _)| index > 0.borrow())
.map(|(_, value)| value)
.collect::<Vec<_>>();
info!("executing command: {} {:?}", binary, args);
let output = Command::new(binary).args(args).output()?;
info!("output received: {:?}", output);
}
Ok(())
}
}
| rust | MIT | 6951316368e8db55d20203c3255176b897518aac | 2026-01-04T20:22:01.198602Z | false |
svenstaro/memefs | https://github.com/svenstaro/memefs/blob/975822eccca35d3c6559ff433a9b0fe1c396a396/src/main.rs | src/main.rs | use clap::{
crate_authors, crate_description, crate_name, crate_version, value_t_or_exit, App, AppSettings,
Arg,
};
use fuse::{
FileAttr, FileType, Filesystem, ReplyAttr, ReplyData, ReplyDirectory, ReplyEntry, Request,
};
use lazy_static::lazy_static;
use libc::ENOENT;
use serde_json::Value;
use std::cmp::min;
use std::ffi::OsStr;
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use time::Timespec;
lazy_static! {
static ref MEMES: Mutex<Vec<Post>> = Mutex::new(Vec::default());
static ref MEMEFSCONFIG: Mutex<MemeFSConfig> = Default::default();
static ref REQ_CLIENT: Mutex<reqwest::blocking::Client> = Mutex::new(reqwest::blocking::Client::new());
}
#[derive(Clone, Debug, Default)]
pub struct MemeFSConfig {
mountpoint: String,
verbose: bool,
subreddit: String,
limit: u16,
refresh_secs: u32,
}
fn dir_attr(ino: u64, size: u64) -> FileAttr {
let current_time = time::get_time();
FileAttr {
ino,
size,
blocks: 0,
atime: current_time,
mtime: current_time,
ctime: current_time,
crtime: current_time,
kind: FileType::Directory,
perm: 0o755,
nlink: 2,
uid: 0,
gid: 0,
rdev: 0,
flags: 0,
}
}
fn file_attr(ino: u64, size: u64) -> FileAttr {
let current_time = time::get_time();
FileAttr {
ino,
size,
blocks: 0,
atime: current_time,
mtime: current_time,
ctime: current_time,
crtime: current_time,
kind: FileType::RegularFile,
perm: 0o444,
nlink: 0,
uid: 0,
gid: 0,
rdev: 0,
flags: 0,
}
}
fn read_end(data_size: u64, offset: u64, read_size: u32) -> usize {
(offset + min(data_size - offset, read_size as u64)) as usize
}
#[derive(Debug, Clone)]
struct Post {
title: String,
score: i64,
url: String,
size: u64,
}
struct MemeFS;
impl Filesystem for MemeFS {
fn lookup(&mut self, _req: &Request, parent: u64, name: &OsStr, reply: ReplyEntry) {
let ttl = Timespec::new(1, 0);
let memes = MEMES.lock().expect("Couldn't acquire lock in lookup()");
if parent == 1 {
let entry = (*memes)
.iter()
.enumerate()
.find(|(_, post)| post.title == name.to_str().unwrap());
if let Some((ino, post)) = entry {
reply.entry(&ttl, &file_attr((ino + 2) as u64, post.size), 0);
}
} else {
reply.error(ENOENT);
}
}
fn getattr(&mut self, _req: &Request, ino: u64, reply: ReplyAttr) {
let ttl = Timespec::new(1, 0);
let memes = MEMES.lock().expect("Couldn't acquire lock in getattr()");
if ino == 1 {
reply.attr(&ttl, &dir_attr(1, memes.len() as u64))
} else {
let entry = (*memes)
.iter()
.enumerate()
.find(|(i, _)| (*i + 2) == ino as usize);
if let Some((_, post)) = entry {
let size = post.size;
reply.attr(&ttl, &file_attr(ino, size))
} else {
reply.error(ENOENT)
}
}
}
fn read(
&mut self,
_req: &Request,
ino: u64,
_fh: u64,
offset: i64,
size: u32,
reply: ReplyData,
) {
if ino == 1 {
reply.error(ENOENT);
} else {
let memes = MEMES
.lock()
.expect("Couldn't acquire lock to MEMES in read()");
let entry = (*memes)
.iter()
.enumerate()
.find(|(i, _)| (*i + 2) == ino as usize);
if let Some((_, post)) = entry {
let mut body_buf: Vec<u8> = vec![];
let req_client = REQ_CLIENT
.lock()
.expect("Couldn't acquire lock to REQ_CLIENT in read()");
let bytes_written = req_client
.get(&post.url)
.send()
.expect("Error while fetching posts")
.copy_to(&mut body_buf)
.expect("Can't copy response body to buffer");
let (data_buf, data_size) = (body_buf, bytes_written as u64);
let read_size = read_end(data_size, offset as u64, size);
reply.data(&data_buf[offset as usize..read_size]);
} else {
reply.error(ENOENT)
}
}
}
fn readdir(
&mut self,
_req: &Request,
ino: u64,
_fh: u64,
offset: i64,
mut reply: ReplyDirectory,
) {
if ino == 1 {
if offset == 0 {
reply.add(1, 0, FileType::Directory, ".");
reply.add(1, 1, FileType::Directory, "..");
let memes = MEMES.lock().unwrap();
for (i, meme) in (*memes).iter().enumerate() {
reply.add(
(i + 2) as u64,
(i + 2) as i64,
FileType::RegularFile,
&meme.title,
);
}
}
reply.ok();
} else {
reply.error(ENOENT);
}
}
}
fn get_memes(memefs_config: &MemeFSConfig) -> Vec<Post> {
let req_client = REQ_CLIENT
.lock()
.expect("Couldn't acquire lock to REQ_CLIENT in get_memes()");
let resp: Value = req_client
.get(&format!(
"{subreddit}/.json?limit={limit}",
subreddit = memefs_config.subreddit,
limit = memefs_config.limit
))
.send()
.expect("Error while fetching posts")
.json()
.expect("Can't parse posts as JSON");
let posts = resp["data"]["children"]
.as_array()
.expect("Reponse has no children");
let mut memes = vec![];
for post in posts {
let url_str = post["data"]["url"].as_str().expect("Post has no URL");
let url = reqwest::Url::parse(url_str).expect("Couldn't parse Post URL");
let url_file_ext = if let Some(url_segments) = url.path_segments() {
if let Some(last_url_segment) = url_segments.last() {
let file = Path::new(last_url_segment);
if let Some(ext) = file.extension() {
Some(ext.to_string_lossy().to_mut().to_lowercase())
} else {
None
}
} else {
None
}
} else {
None
};
if let Some(ext) = url_file_ext {
// Static list of known file extensions for now.
let known_extensions = vec!["png", "jpg", "jpeg", "mp4", "webm"];
if known_extensions.contains(&ext.as_str()) {
// If we've gotten this far, we're ready to add the meme as a file.
let title = post["data"]["title"].as_str().expect("Post has no Title");
let title_with_ext = format!("{title}.{ext}", title = title, ext = ext);
let meme = Post {
title: title_with_ext,
score: post["data"]["score"].as_i64().expect("Post has no Score"),
url: url_str.to_owned(),
size: req_client
.head(url)
.send()
.expect("HEAD request ")
.headers()
.get("content-length")
.map(|cl| cl.to_str().unwrap().parse::<u64>().unwrap())
.unwrap_or(0),
};
memes.push(meme);
}
}
}
memes
}
fn parse_args() {
let matches = App::new(crate_name!())
.version(crate_version!())
.about(crate_description!())
.author(crate_authors!())
.setting(AppSettings::ColoredHelp)
.arg(
Arg::with_name("MOUNTPOINT")
.help("Choose the mountpoint")
.required(true)
.index(1),
)
.arg(
Arg::with_name("verbose")
.help("Be verbose")
.short("v")
.long("verbose"),
)
.arg(
Arg::with_name("subreddit")
.help("Pick a subreddit or multi (requires subreddit URL)")
.short("s")
.default_value("https://www.reddit.com/user/Hydrauxine/m/memes")
.takes_value(true),
)
.arg(
Arg::with_name("limit")
.help("How many memes to fetch at once")
.short("l")
.default_value("20")
.takes_value(true),
)
.arg(
Arg::with_name("refresh_secs")
.help("How often to refresh your memes in secs")
.short("r")
.default_value("600")
.takes_value(true),
)
.get_matches();
let mountpoint = matches.value_of("MOUNTPOINT").unwrap().to_owned();
let verbose = matches.is_present("verbose");
let subreddit = matches.value_of("subreddit").unwrap().to_owned();
let limit = value_t_or_exit!(matches.value_of("limit"), u16);
let refresh_secs = value_t_or_exit!(matches.value_of("refresh_secs"), u32);
{
let mut config = MEMEFSCONFIG
.lock()
.expect("Couldn't acquire lock to MEMEFSCONFIG in main()");
config.mountpoint = mountpoint;
config.verbose = verbose;
config.subreddit = subreddit;
config.limit = limit;
config.refresh_secs = refresh_secs;
}
}
fn main() {
parse_args();
let options = ["-o", "ro", "-o", "fsname=memefs"]
.iter()
.map(|o| o.as_ref())
.collect::<Vec<&OsStr>>();
let running = Arc::new(AtomicBool::new(true));
let r = running.clone();
ctrlc::set_handler(move || {
r.store(false, Ordering::SeqCst);
})
.expect("Error setting Ctrl-C handler");
let _thread_handle = thread::spawn(move || loop {
let config = MEMEFSCONFIG
.lock()
.expect("Couldn't acquire lock to MEMEFSCONFIG in main()")
.clone();
{
let mut memes = MEMES
.lock()
.expect("Couldn't acquire lock to MEMES in main()");
if config.verbose {
println!("Refreshing memes");
}
let new_memes = get_memes(&config);
memes.clear();
memes.extend(new_memes);
}
thread::sleep(Duration::from_secs(config.refresh_secs.into()));
});
let config = MEMEFSCONFIG
.lock()
.expect("Couldn't acquire lock to MEMEFSCONFIG in main()")
.clone();
unsafe {
println!("Mounting to {}", config.mountpoint);
let _fuse_handle = fuse::spawn_mount(MemeFS, &config.mountpoint, &options).unwrap();
while running.load(Ordering::SeqCst) {
thread::sleep(Duration::from_millis(100));
}
println!("Unmounting and exiting");
}
}
| rust | MIT | 975822eccca35d3c6559ff433a9b0fe1c396a396 | 2026-01-04T20:21:54.711749Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-scrollview/src/lib.rs | tui-scrollview/src/lib.rs | //! A [Ratatui] widget to build smooth scrollable views. Part of the [tui-widgets] suite by [Joshka].
//!
//! 
//!
//! (Note: a github bug stops the example gif above being displayed, but you can view it at:
//! <https://vhs.charm.sh/vhs-6PuT3pdwSTp4aTvKrCBx9F.gif>)
//!
//! [![Crate badge]][Crate]
//! [![Docs Badge]][Docs]
//! [![Deps Badge]][Dependency Status]
//! [![License Badge]][License]
//! [![Coverage Badge]][Coverage]
//! [![Discord Badge]][Ratatui Discord]
//!
//! [GitHub Repository] · [API Docs] · [Examples] · [Changelog] · [Contributing]
//!
//! # Installation
//!
//! ```shell
//! cargo add tui-scrollview
//! ```
//!
//! # Usage
//!
//! ```rust
//! use std::iter;
//!
//! use ratatui::layout::Size;
//! use ratatui::prelude::*;
//! use ratatui::widgets::*;
//! use tui_scrollview::{ScrollView, ScrollViewState};
//!
//! struct MyScrollableWidget;
//!
//! impl StatefulWidget for MyScrollableWidget {
//! type State = ScrollViewState;
//!
//! fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
//! // 100 lines of text
//! let line_numbers = (1..=100).map(|i| format!("{:>3} ", i)).collect::<String>();
//! let content =
//! iter::repeat("Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n")
//! .take(100)
//! .collect::<String>();
//!
//! let content_size = Size::new(100, 30);
//! let mut scroll_view = ScrollView::new(content_size);
//!
//! // the layout doesn't have to be hardcoded like this, this is just an example
//! scroll_view.render_widget(Paragraph::new(line_numbers), Rect::new(0, 0, 5, 100));
//! scroll_view.render_widget(Paragraph::new(content), Rect::new(5, 0, 95, 100));
//!
//! scroll_view.render(buf.area, buf, state);
//! }
//! }
//! ```
//!
//! # Full Example
//!
//! A full example can be found in the [examples directory].
//! [scrollview.rs]
//!
//! This example shows a scrollable view with two paragraphs of text, one for the line numbers and
//! one for the text. On top of this a Gauge widget is rendered to show that this can be used in
//! combination with any other widget.
//!
//! # More widgets
//!
//! For the full suite of widgets, see [tui-widgets].
//!
//! [Crate]: https://crates.io/crates/tui-scrollview
//! [Docs]: https://docs.rs/tui-scrollview/
//! [Dependency Status]: https://deps.rs/repo/github/joshka/tui-widgets
//! [Coverage]: https://app.codecov.io/gh/joshka/tui-widgets
//! [Ratatui Discord]: https://discord.gg/pMCEU9hNEj
//! [Crate badge]: https://img.shields.io/crates/v/tui-scrollview?logo=rust&style=flat
//! [Docs Badge]: https://img.shields.io/docsrs/tui-scrollview?logo=rust&style=flat
//! [Deps Badge]: https://deps.rs/repo/github/joshka/tui-widgets/status.svg?style=flat
//! [License Badge]: https://img.shields.io/crates/l/tui-scrollview?style=flat
//! [License]: https://github.com/joshka/tui-widgets/blob/main/LICENSE-MIT
//! [Coverage Badge]:
//! https://img.shields.io/codecov/c/github/joshka/tui-widgets?logo=codecov&style=flat
//! [Discord Badge]: https://img.shields.io/discord/1070692720437383208?logo=discord&style=flat
//!
//! [GitHub Repository]: https://github.com/joshka/tui-widgets
//! [API Docs]: https://docs.rs/tui-scrollview/
//! [Examples]: https://github.com/joshka/tui-widgets/tree/main/tui-scrollview/examples
//! [examples directory]: https://github.com/joshka/tui-widgets/tree/main/tui-scrollview/examples
//! [scrollview.rs]:
//! https://github.com/joshka/tui-widgets/tree/main/tui-scrollview/examples/scrollview.rs
//! [Changelog]: https://github.com/joshka/tui-widgets/blob/main/tui-scrollview/CHANGELOG.md
//! [Contributing]: https://github.com/joshka/tui-widgets/blob/main/CONTRIBUTING.md
//!
//! [Ratatui]: https://crates.io/crates/ratatui
//!
//! [Joshka]: https://github.com/joshka
//! [tui-widgets]: https://crates.io/crates/tui-widgets
mod scroll_view;
mod state;
pub use scroll_view::{ScrollView, ScrollbarVisibility};
pub use state::ScrollViewState;
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-scrollview/src/state.rs | tui-scrollview/src/state.rs | use ratatui_core::layout::{Position, Size};
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash)]
pub struct ScrollViewState {
/// The offset is the number of rows and columns to shift the scroll view by.
pub(crate) offset: Position,
/// The size of the scroll view. Not set until the first render call.
pub(crate) size: Option<Size>,
/// The size of a page of the scroll view. Not set until the first render call.
pub(crate) page_size: Option<Size>,
}
impl ScrollViewState {
/// Create a new scroll view state with an offset of (0, 0)
pub fn new() -> Self {
Self::default()
}
/// Create a new scroll view state with the given offset
pub fn with_offset(offset: Position) -> Self {
Self {
offset,
..Default::default()
}
}
/// Set the offset of the scroll view state
pub const fn set_offset(&mut self, offset: Position) {
self.offset = offset;
}
/// Get the offset of the scroll view state
pub const fn offset(&self) -> Position {
self.offset
}
/// Move the scroll view state up by one row
pub const fn scroll_up(&mut self) {
self.offset.y = self.offset.y.saturating_sub(1);
}
/// Move the scroll view state down by one row
pub const fn scroll_down(&mut self) {
self.offset.y = self.offset.y.saturating_add(1);
}
/// Move the scroll view state down by one page
pub fn scroll_page_down(&mut self) {
let page_size = self.page_size.map_or(1, |size| size.height);
// we subtract 1 to ensure that there is a one row overlap between pages
self.offset.y = self.offset.y.saturating_add(page_size).saturating_sub(1);
}
/// Move the scroll view state up by one page
pub fn scroll_page_up(&mut self) {
let page_size = self.page_size.map_or(1, |size| size.height);
// we add 1 to ensure that there is a one row overlap between pages
self.offset.y = self.offset.y.saturating_add(1).saturating_sub(page_size);
}
/// Move the scroll view state left by one column
pub const fn scroll_left(&mut self) {
self.offset.x = self.offset.x.saturating_sub(1);
}
/// Move the scroll view state right by one column
pub const fn scroll_right(&mut self) {
self.offset.x = self.offset.x.saturating_add(1);
}
/// Move the scroll view state to the top of the buffer
pub const fn scroll_to_top(&mut self) {
self.offset = Position::ORIGIN;
}
/// Move the scroll view state to the bottom of the buffer
pub fn scroll_to_bottom(&mut self) {
// the render call will adjust the offset to ensure that we don't scroll past the end of
// the buffer, so we can set the offset to the maximum value here
let bottom = self
.size
.map_or(u16::MAX, |size| size.height.saturating_sub(1));
self.offset.y = bottom;
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-scrollview/src/scroll_view.rs | tui-scrollview/src/scroll_view.rs | use ratatui_core::buffer::Buffer;
use ratatui_core::layout::{Rect, Size};
use ratatui_core::widgets::{StatefulWidget, Widget};
use ratatui_widgets::scrollbar::{Scrollbar, ScrollbarOrientation, ScrollbarState};
use crate::ScrollViewState;
/// A widget that can scroll its contents
///
/// Allows you to render a widget into a buffer larger than the area it is rendered into, and then
/// scroll the contents of that buffer around.
///
/// Note that the origin of the buffer is always at (0, 0), and the buffer is always the size of the
/// size passed to `new`. The `ScrollView` widget itself is responsible for rendering the visible
/// area of the buffer into the main buffer.
///
/// # Examples
///
/// ```rust
/// use ratatui::{prelude::*, layout::Size, widgets::*};
/// use tui_scrollview::{ScrollView, ScrollViewState};
///
/// # fn render(buf: &mut Buffer) {
/// let mut scroll_view = ScrollView::new(Size::new(20, 20));
///
/// // render a few widgets into the buffer at various positions
/// scroll_view.render_widget(Paragraph::new("Hello, world!"), Rect::new(0, 0, 20, 1));
/// scroll_view.render_widget(Paragraph::new("Hello, world!"), Rect::new(10, 10, 20, 1));
/// scroll_view.render_widget(Paragraph::new("Hello, world!"), Rect::new(15, 15, 20, 1));
///
/// // You can also render widgets into the buffer programmatically
/// Line::raw("Hello, world!").render(Rect::new(0, 0, 20, 1), scroll_view.buf_mut());
///
/// // usually you would store the state of the scroll view in a struct that implements
/// // StatefulWidget (or in your app state if you're using an `App` struct)
/// let mut state = ScrollViewState::default();
///
/// // you can also scroll the view programmatically
/// state.scroll_down();
///
/// // render the scroll view into the main buffer at the given position within a widget
/// let scroll_view_area = Rect::new(0, 0, 10, 10);
/// scroll_view.render(scroll_view_area, buf, &mut state);
/// # }
/// // or if you're rendering in a terminal draw closure instead of from within another widget:
/// # fn terminal_draw(frame: &mut Frame, scroll_view: ScrollView, state: &mut ScrollViewState) {
/// frame.render_stateful_widget(scroll_view, frame.size(), state);
/// # }
/// ```
#[derive(Debug, Default, Clone, Eq, PartialEq, Hash)]
pub struct ScrollView {
buf: Buffer,
size: Size,
vertical_scrollbar_visibility: ScrollbarVisibility,
horizontal_scrollbar_visibility: ScrollbarVisibility,
}
/// The visbility of the vertical and horizontal scrollbars.
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash)]
pub enum ScrollbarVisibility {
/// Render the scrollbar only whenever needed.
#[default]
Automatic,
/// Always render the scrollbar.
Always,
/// Never render the scrollbar (hide it).
Never,
}
impl ScrollView {
/// Create a new scroll view with a buffer of the given size
///
/// The buffer will be empty, with coordinates ranging from (0, 0) to (size.width, size.height).
pub fn new(size: Size) -> Self {
// TODO: this is replaced with Rect::from(size) in the next version of ratatui
let area = Rect::new(0, 0, size.width, size.height);
Self {
buf: Buffer::empty(area),
size,
horizontal_scrollbar_visibility: ScrollbarVisibility::default(),
vertical_scrollbar_visibility: ScrollbarVisibility::default(),
}
}
/// The content size of the scroll view
pub const fn size(&self) -> Size {
self.size
}
/// The area of the buffer that is available to be scrolled
pub const fn area(&self) -> Rect {
self.buf.area
}
/// The buffer containing the contents of the scroll view
pub const fn buf(&self) -> &Buffer {
&self.buf
}
/// The mutable buffer containing the contents of the scroll view
///
/// This can be used to render widgets into the buffer programmatically
///
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, layout::Size, widgets::*};
/// # use tui_scrollview::ScrollView;
///
/// let mut scroll_view = ScrollView::new(Size::new(20, 20));
/// Line::raw("Hello, world!").render(Rect::new(0, 0, 20, 1), scroll_view.buf_mut());
/// ```
pub const fn buf_mut(&mut self) -> &mut Buffer {
&mut self.buf
}
/// Set the visibility of the vertical scrollbar
///
/// See [`ScrollbarVisibility`] for all the options.
///
/// This is a fluent setter method which must be chained or used as it consumes self
///
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, layout::Size, widgets::*};
/// # use tui_scrollview::{ScrollView, ScrollbarVisibility};
///
/// let mut scroll_view = ScrollView::new(Size::new(20, 20))
/// .vertical_scrollbar_visibility(ScrollbarVisibility::Always);
/// ```
pub const fn vertical_scrollbar_visibility(mut self, visibility: ScrollbarVisibility) -> Self {
self.vertical_scrollbar_visibility = visibility;
self
}
/// Set the visibility of the horizontal scrollbar
///
/// See [`ScrollbarVisibility`] for all the options.
///
/// This is a fluent setter method which must be chained or used as it consumes self
///
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, layout::Size, widgets::*};
/// # use tui_scrollview::{ScrollView, ScrollbarVisibility};
///
/// let mut scroll_view = ScrollView::new(Size::new(20, 20))
/// .horizontal_scrollbar_visibility(ScrollbarVisibility::Never);
/// ```
pub const fn horizontal_scrollbar_visibility(
mut self,
visibility: ScrollbarVisibility,
) -> Self {
self.horizontal_scrollbar_visibility = visibility;
self
}
/// Set the visibility of both vertical and horizontal scrollbars
///
/// See [`ScrollbarVisibility`] for all the options.
///
/// This is a fluent setter method which must be chained or used as it consumes self
///
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, layout::Size, widgets::*};
/// # use tui_scrollview::{ScrollView, ScrollbarVisibility};
///
/// let mut scroll_view =
/// ScrollView::new(Size::new(20, 20)).scrollbars_visibility(ScrollbarVisibility::Automatic);
/// ```
pub const fn scrollbars_visibility(mut self, visibility: ScrollbarVisibility) -> Self {
self.vertical_scrollbar_visibility = visibility;
self.horizontal_scrollbar_visibility = visibility;
self
}
/// Render a widget into the scroll buffer
///
/// This is the equivalent of `Frame::render_widget`, but renders the widget into the scroll
/// buffer rather than the main buffer. The widget will be rendered into the area of the buffer
/// specified by the `area` parameter.
///
/// This should not be confused with the `render` method, which renders the visible area of the
/// ScrollView into the main buffer.
pub fn render_widget<W: Widget>(&mut self, widget: W, area: Rect) {
widget.render(area, &mut self.buf);
}
/// Render a stateful widget into the scroll buffer
///
/// This is the equivalent of `Frame::render_stateful_widget`, but renders the stateful widget
/// into the scroll buffer rather than the main buffer. The stateful widget will be rendered
/// into the area of the buffer specified by the `area` parameter.
///
/// This should not be confused with the `render` method, which renders the visible area of the
/// ScrollView into the main buffer.
pub fn render_stateful_widget<W: StatefulWidget>(
&mut self,
widget: W,
area: Rect,
state: &mut W::State,
) {
widget.render(area, &mut self.buf, state);
}
}
impl StatefulWidget for ScrollView {
type State = ScrollViewState;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
let (mut x, mut y) = state.offset.into();
// ensure that we don't scroll past the end of the buffer in either direction
let max_x_offset = self
.buf
.area
.width
.saturating_sub(area.width.saturating_sub(1));
let max_y_offset = self
.buf
.area
.height
.saturating_sub(area.height.saturating_sub(1));
x = x.min(max_x_offset);
y = y.min(max_y_offset);
state.offset = (x, y).into();
state.size = Some(self.size);
state.page_size = Some(area.into());
let visible_area = self
.render_scrollbars(area, buf, state)
.intersection(self.buf.area);
self.render_visible_area(area, buf, visible_area);
}
}
impl ScrollView {
/// Render needed scrollbars and return remaining area relative to
/// scrollview's buffer area.
fn render_scrollbars(&self, area: Rect, buf: &mut Buffer, state: &mut ScrollViewState) -> Rect {
// fit value per direction
// > 0 => fits
// == 0 => exact fit
// < 0 => does not fit
let horizontal_space = area.width as i32 - self.size.width as i32;
let vertical_space = area.height as i32 - self.size.height as i32;
// if it fits in that direction, reset state to reflect it
if horizontal_space > 0 {
state.offset.x = 0;
}
if vertical_space > 0 {
state.offset.y = 0;
}
let (show_horizontal, show_vertical) =
self.visible_scrollbars(horizontal_space, vertical_space);
let new_height = if show_horizontal {
// if both bars are rendered, avoid the corner
let width = area.width.saturating_sub(show_vertical as u16);
let render_area = Rect { width, ..area };
// render scrollbar, update available space
self.render_horizontal_scrollbar(render_area, buf, state);
area.height.saturating_sub(1)
} else {
area.height
};
let new_width = if show_vertical {
// if both bars are rendered, avoid the corner
let height = area.height.saturating_sub(show_horizontal as u16);
let render_area = Rect { height, ..area };
// render scrollbar, update available space
self.render_vertical_scrollbar(render_area, buf, state);
area.width.saturating_sub(1)
} else {
area.width
};
Rect::new(state.offset.x, state.offset.y, new_width, new_height)
}
/// Resolve whether to render each scrollbar.
///
/// Considers the visibility options set by the user and whether the scrollview size fits into
/// the the available area on each direction.
///
/// The space arguments are the difference between the scrollview size and the available area.
///
/// Returns a bool tuple with (horizontal, vertical) resolutions.
const fn visible_scrollbars(&self, horizontal_space: i32, vertical_space: i32) -> (bool, bool) {
type V = crate::scroll_view::ScrollbarVisibility;
match (
self.horizontal_scrollbar_visibility,
self.vertical_scrollbar_visibility,
) {
// straightfoward, no need to check fit values
(V::Always, V::Always) => (true, true),
(V::Never, V::Never) => (false, false),
(V::Always, V::Never) => (true, false),
(V::Never, V::Always) => (false, true),
// Auto => render scrollbar only if it doesn't fit
(V::Automatic, V::Never) => (horizontal_space < 0, false),
(V::Never, V::Automatic) => (false, vertical_space < 0),
// Auto => render scrollbar if:
// it doesn't fit; or
// exact fit (other scrollbar steals a line and triggers it)
(V::Always, V::Automatic) => (true, vertical_space <= 0),
(V::Automatic, V::Always) => (horizontal_space <= 0, true),
// depends solely on fit values
(V::Automatic, V::Automatic) => {
if horizontal_space >= 0 && vertical_space >= 0 {
// there is enough space for both dimensions
(false, false)
} else if horizontal_space < 0 && vertical_space < 0 {
// there is not enough space for either dimension
(true, true)
} else if horizontal_space > 0 && vertical_space < 0 {
// horizontal fits, vertical does not
(false, true)
} else if horizontal_space < 0 && vertical_space > 0 {
// vertical fits, horizontal does not
(true, false)
} else {
// one is an exact fit and other does not fit which triggers both scrollbars to
// be visible because the other scrollbar will steal a line from the buffer
(true, true)
}
}
}
}
fn render_vertical_scrollbar(&self, area: Rect, buf: &mut Buffer, state: &ScrollViewState) {
let scrollbar_height = self.size.height.saturating_sub(area.height);
let mut scrollbar_state =
ScrollbarState::new(scrollbar_height as usize).position(state.offset.y as usize);
let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight);
scrollbar.render(area, buf, &mut scrollbar_state);
}
fn render_horizontal_scrollbar(&self, area: Rect, buf: &mut Buffer, state: &ScrollViewState) {
let scrollbar_width = self.size.width.saturating_sub(area.width);
let mut scrollbar_state =
ScrollbarState::new(scrollbar_width as usize).position(state.offset.x as usize);
let scrollbar = Scrollbar::new(ScrollbarOrientation::HorizontalBottom);
scrollbar.render(area, buf, &mut scrollbar_state);
}
fn render_visible_area(&self, area: Rect, buf: &mut Buffer, visible_area: Rect) {
// TODO: there's probably a more efficient way to do this
for (src_row, dst_row) in visible_area.rows().zip(area.rows()) {
for (src_col, dst_col) in src_row.columns().zip(dst_row.columns()) {
buf[dst_col] = self.buf[src_col].clone();
}
}
}
}
#[cfg(test)]
mod tests {
use ratatui_core::text::Span;
use rstest::{fixture, rstest};
use super::*;
/// Initialize a buffer and a scroll view with a buffer size of 10x10
///
/// The buffer will be filled with characters from A to Z in a 10x10 grid
///
/// ```plain
/// ABCDEFGHIJ
/// KLMNOPQRST
/// UVWXYZABCD
/// EFGHIJKLMN
/// OPQRSTUVWX
/// YZABCDEFGH
/// IJKLMNOPQR
/// STUVWXYZAB
/// CDEFGHIJKL
/// MNOPQRSTUV
/// ```
#[fixture]
fn scroll_view() -> ScrollView {
let mut scroll_view = ScrollView::new(Size::new(10, 10));
for y in 0..10 {
for x in 0..10 {
let c = char::from_u32((x + y * 10) % 26 + 65).unwrap();
let widget = Span::raw(format!("{c}"));
let area = Rect::new(x as u16, y as u16, 1, 1);
scroll_view.render_widget(widget, area);
}
}
scroll_view
}
#[rstest]
fn zero_offset(scroll_view: ScrollView) {
let mut buf = Buffer::empty(Rect::new(0, 0, 6, 6));
let mut state = ScrollViewState::default();
scroll_view.render(buf.area, &mut buf, &mut state);
assert_eq!(
buf,
Buffer::with_lines(vec![
"ABCDE▲",
"KLMNO█",
"UVWXY█",
"EFGHI║",
"OPQRS▼",
"◄██═► ",
])
)
}
#[rstest]
fn move_right(scroll_view: ScrollView) {
let mut buf = Buffer::empty(Rect::new(0, 0, 6, 6));
let mut state = ScrollViewState::with_offset((3, 0).into());
scroll_view.render(buf.area, &mut buf, &mut state);
assert_eq!(
buf,
Buffer::with_lines(vec![
"DEFGH▲",
"NOPQR█",
"XYZAB█",
"HIJKL║",
"RSTUV▼",
"◄═██► ",
])
)
}
#[rstest]
fn move_down(scroll_view: ScrollView) {
let mut buf = Buffer::empty(Rect::new(0, 0, 6, 6));
let mut state = ScrollViewState::with_offset((0, 3).into());
scroll_view.render(buf.area, &mut buf, &mut state);
assert_eq!(
buf,
Buffer::with_lines(vec![
"EFGHI▲",
"OPQRS║",
"YZABC█",
"IJKLM█",
"STUVW▼",
"◄██═► ",
])
)
}
#[rstest]
fn hides_both_scrollbars(scroll_view: ScrollView) {
let mut buf = Buffer::empty(Rect::new(0, 0, 10, 10));
let mut state = ScrollViewState::new();
scroll_view.render(buf.area, &mut buf, &mut state);
assert_eq!(
buf,
Buffer::with_lines(vec![
"ABCDEFGHIJ",
"KLMNOPQRST",
"UVWXYZABCD",
"EFGHIJKLMN",
"OPQRSTUVWX",
"YZABCDEFGH",
"IJKLMNOPQR",
"STUVWXYZAB",
"CDEFGHIJKL",
"MNOPQRSTUV",
])
)
}
#[rstest]
fn hides_horizontal_scrollbar(scroll_view: ScrollView) {
let mut buf = Buffer::empty(Rect::new(0, 0, 11, 9));
let mut state = ScrollViewState::new();
scroll_view.render(buf.area, &mut buf, &mut state);
assert_eq!(
buf,
Buffer::with_lines(vec![
"ABCDEFGHIJ▲",
"KLMNOPQRST█",
"UVWXYZABCD█",
"EFGHIJKLMN█",
"OPQRSTUVWX█",
"YZABCDEFGH█",
"IJKLMNOPQR█",
"STUVWXYZAB█",
"CDEFGHIJKL▼",
])
)
}
#[rstest]
fn hides_vertical_scrollbar(scroll_view: ScrollView) {
let mut buf = Buffer::empty(Rect::new(0, 0, 9, 11));
let mut state = ScrollViewState::new();
scroll_view.render(buf.area, &mut buf, &mut state);
assert_eq!(
buf,
Buffer::with_lines(vec![
"ABCDEFGHI",
"KLMNOPQRS",
"UVWXYZABC",
"EFGHIJKLM",
"OPQRSTUVW",
"YZABCDEFG",
"IJKLMNOPQ",
"STUVWXYZA",
"CDEFGHIJK",
"MNOPQRSTU",
"◄███████►",
])
)
}
/// Tests the scenario where the vertical scollbar steals a column from the right side of the
/// buffer which causes the horizontal scrollbar to be shown.
#[rstest]
fn does_not_hide_horizontal_scrollbar(scroll_view: ScrollView) {
let mut buf = Buffer::empty(Rect::new(0, 0, 10, 9));
let mut state = ScrollViewState::new();
scroll_view.render(buf.area, &mut buf, &mut state);
assert_eq!(
buf,
Buffer::with_lines(vec![
"ABCDEFGHI▲",
"KLMNOPQRS█",
"UVWXYZABC█",
"EFGHIJKLM█",
"OPQRSTUVW█",
"YZABCDEFG█",
"IJKLMNOPQ║",
"STUVWXYZA▼",
"◄███████► ",
])
)
}
/// Tests the scenario where the horizontal scollbar steals a row from the bottom side of the
/// buffer which causes the vertical scrollbar to be shown.
#[rstest]
fn does_not_hide_vertical_scrollbar(scroll_view: ScrollView) {
let mut buf = Buffer::empty(Rect::new(0, 0, 9, 10));
let mut state = ScrollViewState::new();
scroll_view.render(buf.area, &mut buf, &mut state);
assert_eq!(
buf,
Buffer::with_lines(vec![
"ABCDEFGH▲",
"KLMNOPQR█",
"UVWXYZAB█",
"EFGHIJKL█",
"OPQRSTUV█",
"YZABCDEF█",
"IJKLMNOP█",
"STUVWXYZ█",
"CDEFGHIJ▼",
"◄█████═► ",
])
)
}
/// The purpose of this test is to ensure that the buffer offset is correctly calculated when
/// rendering a scroll view into a buffer (i.e. the buffer offset is not always (0, 0)).
#[rstest]
fn ensure_buffer_offset_is_correct(scroll_view: ScrollView) {
let mut buf = Buffer::empty(Rect::new(0, 0, 20, 20));
let mut state = ScrollViewState::with_offset((2, 3).into());
scroll_view.render(Rect::new(5, 6, 7, 8), &mut buf, &mut state);
assert_eq!(
buf,
Buffer::with_lines(vec![
" ",
" ",
" ",
" ",
" ",
" ",
" GHIJKL▲ ",
" QRSTUV║ ",
" ABCDEF█ ",
" KLMNOP█ ",
" UVWXYZ█ ",
" EFGHIJ█ ",
" OPQRST▼ ",
" ◄═███► ",
" ",
" ",
" ",
" ",
" ",
" ",
])
)
}
/// The purpose of this test is to ensure that the last elements are rendered.
#[rstest]
fn ensure_buffer_last_elements(scroll_view: ScrollView) {
let mut buf = Buffer::empty(Rect::new(0, 0, 6, 6));
let mut state = ScrollViewState::with_offset((5, 5).into());
scroll_view.render(buf.area, &mut buf, &mut state);
assert_eq!(
buf,
Buffer::with_lines(vec![
"DEFGH▲",
"NOPQR║",
"XYZAB█",
"HIJKL█",
"RSTUV▼",
"◄═██► ",
])
)
}
#[rstest]
fn zero_width(scroll_view: ScrollView) {
let mut buf = Buffer::empty(Rect::new(0, 0, 0, 10));
let mut state = ScrollViewState::new();
scroll_view.render(buf.area, &mut buf, &mut state);
assert_eq!(buf, Buffer::empty(Rect::new(0, 0, 0, 10)));
}
#[rstest]
fn zero_height(scroll_view: ScrollView) {
let mut buf = Buffer::empty(Rect::new(0, 0, 10, 0));
let mut state = ScrollViewState::new();
scroll_view.render(buf.area, &mut buf, &mut state);
assert_eq!(buf, Buffer::empty(Rect::new(0, 0, 10, 0)));
}
#[rstest]
fn never_vertical_scrollbar(mut scroll_view: ScrollView) {
scroll_view = scroll_view.vertical_scrollbar_visibility(ScrollbarVisibility::Never);
let mut buf = Buffer::empty(Rect::new(0, 0, 11, 9));
let mut state = ScrollViewState::new();
scroll_view.render(buf.area, &mut buf, &mut state);
assert_eq!(
buf,
Buffer::with_lines(vec![
"ABCDEFGHIJ ",
"KLMNOPQRST ",
"UVWXYZABCD ",
"EFGHIJKLMN ",
"OPQRSTUVWX ",
"YZABCDEFGH ",
"IJKLMNOPQR ",
"STUVWXYZAB ",
"CDEFGHIJKL ",
])
)
}
#[rstest]
fn never_horizontal_scrollbar(mut scroll_view: ScrollView) {
scroll_view = scroll_view.horizontal_scrollbar_visibility(ScrollbarVisibility::Never);
let mut buf = Buffer::empty(Rect::new(0, 0, 9, 11));
let mut state = ScrollViewState::new();
scroll_view.render(buf.area, &mut buf, &mut state);
assert_eq!(
buf,
Buffer::with_lines(vec![
"ABCDEFGHI",
"KLMNOPQRS",
"UVWXYZABC",
"EFGHIJKLM",
"OPQRSTUVW",
"YZABCDEFG",
"IJKLMNOPQ",
"STUVWXYZA",
"CDEFGHIJK",
"MNOPQRSTU",
" ",
])
)
}
#[rstest]
fn does_not_trigger_horizontal_scrollbar(mut scroll_view: ScrollView) {
scroll_view = scroll_view.vertical_scrollbar_visibility(ScrollbarVisibility::Never);
let mut buf = Buffer::empty(Rect::new(0, 0, 10, 9));
let mut state = ScrollViewState::new();
scroll_view.render(buf.area, &mut buf, &mut state);
assert_eq!(
buf,
Buffer::with_lines(vec![
"ABCDEFGHIJ",
"KLMNOPQRST",
"UVWXYZABCD",
"EFGHIJKLMN",
"OPQRSTUVWX",
"YZABCDEFGH",
"IJKLMNOPQR",
"STUVWXYZAB",
"CDEFGHIJKL",
])
)
}
#[rstest]
fn does_not_trigger_vertical_scrollbar(mut scroll_view: ScrollView) {
scroll_view = scroll_view.horizontal_scrollbar_visibility(ScrollbarVisibility::Never);
let mut buf = Buffer::empty(Rect::new(0, 0, 9, 10));
let mut state = ScrollViewState::new();
scroll_view.render(buf.area, &mut buf, &mut state);
assert_eq!(
buf,
Buffer::with_lines(vec![
"ABCDEFGHI",
"KLMNOPQRS",
"UVWXYZABC",
"EFGHIJKLM",
"OPQRSTUVW",
"YZABCDEFG",
"IJKLMNOPQ",
"STUVWXYZA",
"CDEFGHIJK",
"MNOPQRSTU",
])
)
}
#[rstest]
fn does_not_render_vertical_scrollbar(mut scroll_view: ScrollView) {
scroll_view = scroll_view.vertical_scrollbar_visibility(ScrollbarVisibility::Never);
let mut buf = Buffer::empty(Rect::new(0, 0, 6, 6));
let mut state = ScrollViewState::default();
scroll_view.render(buf.area, &mut buf, &mut state);
assert_eq!(
buf,
Buffer::with_lines(vec![
"ABCDEF",
"KLMNOP",
"UVWXYZ",
"EFGHIJ",
"OPQRST",
"◄███═►",
])
)
}
#[rstest]
fn does_not_render_horizontal_scrollbar(mut scroll_view: ScrollView) {
scroll_view = scroll_view.horizontal_scrollbar_visibility(ScrollbarVisibility::Never);
let mut buf = Buffer::empty(Rect::new(0, 0, 7, 6));
let mut state = ScrollViewState::default();
scroll_view.render(buf.area, &mut buf, &mut state);
assert_eq!(
buf,
Buffer::with_lines(vec![
"ABCDEF▲",
"KLMNOP█",
"UVWXYZ█",
"EFGHIJ█",
"OPQRST║",
"YZABCD▼",
])
)
}
#[rstest]
#[rustfmt::skip]
fn does_not_render_both_scrollbars(mut scroll_view: ScrollView) {
scroll_view = scroll_view.scrollbars_visibility(ScrollbarVisibility::Never);
let mut buf = Buffer::empty(Rect::new(0, 0, 6, 6));
let mut state = ScrollViewState::default();
scroll_view.render(buf.area, &mut buf, &mut state);
assert_eq!(
buf,
Buffer::with_lines(vec![
"ABCDEF",
"KLMNOP",
"UVWXYZ",
"EFGHIJ",
"OPQRST",
"YZABCD",
])
)
}
#[rstest]
#[rustfmt::skip]
fn render_stateful_widget(mut scroll_view: ScrollView) {
use ratatui_widgets::list::{List, ListState};
scroll_view = scroll_view.horizontal_scrollbar_visibility(ScrollbarVisibility::Never);
let mut buf = Buffer::empty(Rect::new(0, 0, 7, 5));
let mut state = ScrollViewState::default();
let mut list_state = ListState::default();
let items: Vec<String> = (1..=10).map(|i| format!("Item {i}")).collect();
let list = List::new(items);
scroll_view.render_stateful_widget(list, scroll_view.area(), &mut list_state);
scroll_view.render(buf.area, &mut buf, &mut state);
assert_eq!(
buf,
Buffer::with_lines(vec![
"Item 1▲",
"Item 2█",
"Item 3█",
"Item 4║",
"Item 5▼",
])
)
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-scrollview/examples/tabs.rs | tui-scrollview/examples/tabs.rs | //! An example of using multiple tabs each with a scrollable view, as well as how state can be
//! managed across multiple tabs using Stateful Widgets.
//!
//! This example uses the `unstable-widget-ref` feature in Ratatui to allow the tab widgets to
//! created once and then reused across multiple frames. Each tab has some static lorem ipsum text,
//! and we store the scroll state for each tab separately.
use std::collections::HashMap;
use std::fmt::Debug;
use std::io;
use color_eyre::Result;
use lipsum::lipsum;
use ratatui::buffer::Buffer;
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEventKind};
use ratatui::layout::{Constraint, Layout, Rect, Size};
use ratatui::style::palette::tailwind;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::widgets::{Paragraph, StatefulWidget, StatefulWidgetRef, Tabs, Widget, Wrap};
use ratatui::DefaultTerminal;
use tui_scrollview::{ScrollView, ScrollViewState};
fn main() -> Result<()> {
color_eyre::install()?;
let terminal = ratatui::init();
let result = App::new().run(terminal);
ratatui::restore();
result
}
#[derive(Default)]
struct App {
state: AppState,
tabs: HashMap<
VisibleTab,
(
Box<dyn StatefulWidgetRef<State = ScrollViewState>>,
ScrollViewState,
),
>,
visible_tab: VisibleTab,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
enum VisibleTab {
#[default]
Red,
Green,
Blue,
}
#[derive(Debug, Default)]
struct RedTab {
text: String,
}
impl RedTab {
fn new() -> Self {
Self { text: lipsum(500) }
}
}
#[derive(Debug, Default, Clone)]
struct GreenTab {
text: String,
}
impl GreenTab {
fn new() -> Self {
Self {
text: lipsum(1_000),
}
}
}
#[derive(Debug, Default, Clone)]
struct BlueTab {
text: String,
}
impl BlueTab {
fn new() -> Self {
Self {
text: lipsum(10_000),
}
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
enum AppState {
#[default]
Running,
Quit,
}
impl App {
fn new() -> Self {
let mut tabs: HashMap<
VisibleTab,
(
Box<dyn StatefulWidgetRef<State = ScrollViewState>>,
ScrollViewState,
),
> = HashMap::new();
tabs.insert(
VisibleTab::Red,
(Box::new(RedTab::new()), ScrollViewState::default()),
);
tabs.insert(
VisibleTab::Green,
(Box::new(GreenTab::new()), ScrollViewState::default()),
);
tabs.insert(
VisibleTab::Blue,
(Box::new(BlueTab::new()), ScrollViewState::default()),
);
Self {
tabs,
..Default::default()
}
}
fn run(&mut self, mut terminal: DefaultTerminal) -> Result<()> {
while self.is_running() {
self.draw(&mut terminal)?;
self.handle_events()?;
}
Ok(())
}
fn is_running(&self) -> bool {
self.state == AppState::Running
}
fn draw(&mut self, terminal: &mut DefaultTerminal) -> io::Result<()> {
terminal.draw(|frame| frame.render_widget(self, frame.area()))?;
Ok(())
}
fn handle_events(&mut self) -> Result<()> {
use KeyCode::*;
let (_widget, scroll_view_state) = self
.tabs
.get_mut(&self.visible_tab)
.expect("visible tab should exist");
match event::read()? {
Event::Key(key) if key.kind == KeyEventKind::Press => match key.code {
Char('q') | Esc => self.quit(),
Tab => {
self.visible_tab = match self.visible_tab {
VisibleTab::Red => VisibleTab::Green,
VisibleTab::Green => VisibleTab::Blue,
VisibleTab::Blue => VisibleTab::Red,
}
}
BackTab => {
self.visible_tab = match self.visible_tab {
VisibleTab::Red => VisibleTab::Blue,
VisibleTab::Green => VisibleTab::Red,
VisibleTab::Blue => VisibleTab::Green,
}
}
Char('j') | Down => scroll_view_state.scroll_down(),
Char('k') | Up => scroll_view_state.scroll_up(),
Char('f') | PageDown => scroll_view_state.scroll_page_down(),
Char('b') | PageUp => scroll_view_state.scroll_page_up(),
Char('g') | Home => scroll_view_state.scroll_to_top(),
Char('G') | End => scroll_view_state.scroll_to_bottom(),
_ => (),
},
_ => {}
}
Ok(())
}
const fn quit(&mut self) {
self.state = AppState::Quit;
}
}
impl Widget for &mut App {
fn render(self, area: Rect, buf: &mut Buffer) {
let layout = Layout::vertical([
Constraint::Length(1),
Constraint::Length(1),
Constraint::Fill(1),
]);
let [title, tabs, body] = layout.areas(area);
self.title().render(title, buf);
self.tabs().render(tabs, buf);
let (tab, mut state) = self.tabs.get_mut(&self.visible_tab).unwrap();
tab.render_ref(body, buf, &mut state);
}
}
impl App {
fn title(&self) -> impl Widget {
let palette = tailwind::SLATE;
let fg = palette.c900;
let bg = palette.c300;
let keys_fg = palette.c50;
let keys_bg = palette.c600;
Line::from(vec![
"Tui-scrollview ".into(),
" ↓ | ↑ | PageDown | PageUp | Home | End | Tab "
.fg(keys_fg)
.bg(keys_bg),
" Quit: ".into(),
" Esc ".fg(keys_fg).bg(keys_bg),
])
.style((fg, bg))
}
fn tabs(&self) -> impl Widget {
let selected = self.visible_tab as usize;
Tabs::new([
" Red ".fg(tailwind::RED.c900),
" Green ".fg(tailwind::GREEN.c900),
" Blue ".fg(tailwind::BLUE.c900),
])
.padding("", "")
.divider("")
.select(selected)
.style(tailwind::SLATE.c900)
}
}
impl StatefulWidgetRef for RedTab {
type State = ScrollViewState;
fn render_ref(&self, area: Rect, buf: &mut Buffer, state: &mut ScrollViewState) {
const SCROLLVIEW_HEIGHT: u16 = 50;
let mut scroll_view = ScrollView::new(Size::new(area.width - 1, SCROLLVIEW_HEIGHT));
scroll_view.render_widget(
Paragraph::new(self.text.clone())
.white()
.on_red()
.wrap(Wrap::default()),
Rect::new(0, 0, area.width - 1, SCROLLVIEW_HEIGHT),
);
scroll_view.render(area, buf, state);
}
}
impl StatefulWidgetRef for GreenTab {
type State = ScrollViewState;
fn render_ref(&self, area: Rect, buf: &mut Buffer, state: &mut ScrollViewState) {
const SCROLLVIEW_HEIGHT: u16 = 100;
let mut scroll_view = ScrollView::new(Size::new(area.width - 1, SCROLLVIEW_HEIGHT));
scroll_view.render_widget(
Paragraph::new(self.text.clone())
.white()
.on_green()
.wrap(Wrap::default()),
Rect::new(0, 0, area.width - 1, SCROLLVIEW_HEIGHT),
);
scroll_view.render(area, buf, state);
}
}
impl StatefulWidgetRef for BlueTab {
type State = ScrollViewState;
fn render_ref(&self, area: Rect, buf: &mut Buffer, state: &mut ScrollViewState) {
const SCROLLVIEW_HEIGHT: u16 = 200;
let mut scroll_view = ScrollView::new(Size::new(area.width - 1, SCROLLVIEW_HEIGHT));
scroll_view.render_widget(
Paragraph::new(self.text.clone())
.white()
.on_blue()
.wrap(Wrap::default()),
Rect::new(0, 0, area.width - 1, SCROLLVIEW_HEIGHT),
);
scroll_view.render(area, buf, state);
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-scrollview/examples/horizontal.rs | tui-scrollview/examples/horizontal.rs | use std::io;
use color_eyre::Result;
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEventKind};
use ratatui::layout::Size;
use ratatui::widgets::{Paragraph, Wrap};
use ratatui::DefaultTerminal;
use tui_scrollview::{ScrollView, ScrollViewState};
fn main() -> Result<()> {
color_eyre::install()?;
let terminal = ratatui::init();
let result = App::new().run(terminal);
ratatui::restore();
result
}
#[derive(Debug, Default, Clone)]
struct App {
text: String,
scroll_view_state: ScrollViewState,
state: AppState,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
enum AppState {
#[default]
Running,
Quit,
}
impl App {
fn new() -> Self {
Self {
text: lipsum::lipsum(10_000),
..Default::default()
}
}
fn run(&mut self, mut terminal: DefaultTerminal) -> Result<()> {
while self.is_running() {
self.draw(&mut terminal)?;
self.handle_events()?;
}
Ok(())
}
fn is_running(&self) -> bool {
self.state == AppState::Running
}
const fn quit(&mut self) {
self.state = AppState::Quit;
}
fn draw(&mut self, terminal: &mut DefaultTerminal) -> io::Result<()> {
terminal.draw(|frame| {
let area = frame.area();
let size = Size::new(area.width * 2, area.width);
let mut scroll_view = ScrollView::new(size);
let paragraph = Paragraph::new(self.text.clone()).wrap(Wrap::default());
scroll_view.render_widget(paragraph, scroll_view.area());
frame.render_stateful_widget(scroll_view, area, &mut self.scroll_view_state);
})?;
Ok(())
}
fn handle_events(&mut self) -> Result<()> {
use KeyCode::*;
match event::read()? {
Event::Key(key) if key.kind == KeyEventKind::Press => match key.code {
Char('q') | Esc => self.quit(),
Char('h') | Left => self.scroll_view_state.scroll_left(),
Char('l') | Right => self.scroll_view_state.scroll_right(),
_ => (),
},
_ => {}
}
Ok(())
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-scrollview/examples/scrollview.rs | tui-scrollview/examples/scrollview.rs | use std::io::{self};
use color_eyre::Result;
use ratatui::buffer::Buffer;
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEventKind};
use ratatui::layout::{Constraint, Direction, Layout, Rect, Size};
use ratatui::style::palette::tailwind;
use ratatui::style::{Color, Stylize};
use ratatui::text::{Line, Text};
use ratatui::widgets::*;
use ratatui::DefaultTerminal;
use tui_scrollview::{ScrollView, ScrollViewState};
fn main() -> Result<()> {
color_eyre::install()?;
let terminal = ratatui::init();
let result = App::new().run(terminal);
ratatui::restore();
result
}
#[derive(Debug, Default, Clone)]
struct App {
text: [String; 3],
scroll_view_state: ScrollViewState,
state: AppState,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
enum AppState {
#[default]
Running,
Quit,
}
impl App {
fn new() -> Self {
Self {
text: [
lipsum::lipsum(10_000),
lipsum::lipsum(10_000),
lipsum::lipsum(10_000),
],
..Default::default()
}
}
fn run(&mut self, mut terminal: DefaultTerminal) -> Result<()> {
while self.is_running() {
self.draw(&mut terminal)?;
self.handle_events()?;
}
Ok(())
}
fn is_running(&self) -> bool {
self.state == AppState::Running
}
fn draw(&mut self, terminal: &mut DefaultTerminal) -> io::Result<()> {
terminal.draw(|frame| frame.render_widget(self, frame.area()))?;
Ok(())
}
fn handle_events(&mut self) -> Result<()> {
use KeyCode::*;
match event::read()? {
Event::Key(key) if key.kind == KeyEventKind::Press => match key.code {
Char('q') | Esc => self.quit(),
Char('j') | Down => self.scroll_view_state.scroll_down(),
Char('k') | Up => self.scroll_view_state.scroll_up(),
Char('f') | PageDown => self.scroll_view_state.scroll_page_down(),
Char('b') | PageUp => self.scroll_view_state.scroll_page_up(),
Char('g') | Home => self.scroll_view_state.scroll_to_top(),
Char('G') | End => self.scroll_view_state.scroll_to_bottom(),
_ => (),
},
_ => {}
}
Ok(())
}
const fn quit(&mut self) {
self.state = AppState::Quit;
}
}
const SCROLLVIEW_HEIGHT: u16 = 100;
impl Widget for &mut App {
fn render(self, area: Rect, buf: &mut Buffer) {
let layout = Layout::vertical([Constraint::Length(1), Constraint::Fill(1)]);
let [title, body] = layout.areas(area);
self.title().render(title, buf);
let width = if buf.area.height < SCROLLVIEW_HEIGHT {
buf.area.width - 1
} else {
buf.area.width
};
let mut scroll_view = ScrollView::new(Size::new(width, SCROLLVIEW_HEIGHT));
self.render_widgets_into_scrollview(scroll_view.buf_mut());
scroll_view.render(body, buf, &mut self.scroll_view_state)
}
}
impl App {
fn title(&self) -> impl Widget {
let palette = tailwind::SLATE;
let fg = palette.c900;
let bg = palette.c300;
let keys_fg = palette.c50;
let keys_bg = palette.c600;
Line::from(vec![
"Tui-scrollview ".into(),
" ↓ | ↑ | PageDown | PageUp | Home | End "
.fg(keys_fg)
.bg(keys_bg),
" Quit: ".into(),
" Esc ".fg(keys_fg).bg(keys_bg),
])
.style((fg, bg))
}
fn render_widgets_into_scrollview(&self, buf: &mut Buffer) {
use Constraint::*;
let area = buf.area;
let [numbers, widgets] = Layout::horizontal([Length(5), Fill(1)]).areas(area);
let [bar_charts, text_0, text_1, text_2] =
Layout::vertical([Length(7), Fill(1), Fill(2), Fill(4)]).areas(widgets);
let [left_bar, right_bar] = Layout::horizontal([Length(20), Fill(1)]).areas(bar_charts);
self.line_numbers(area.height).render(numbers, buf);
self.vertical_bar_chart().render(left_bar, buf);
self.horizontal_bar_chart().render(right_bar, buf);
self.text(0).render(text_0, buf);
self.text(1).render(text_1, buf);
self.text(2).render(text_2, buf);
}
fn line_numbers(&self, height: u16) -> impl Widget {
use std::fmt::Write;
let line_numbers = (1..=height).fold(String::new(), |mut output, n| {
let _ = writeln!(output, "{n:>4} ");
output
});
Text::from(line_numbers).dim()
}
fn vertical_bar_chart(&self) -> impl Widget {
let block = Block::bordered().title("Vertical Bar Chart");
BarChart::default()
.direction(Direction::Vertical)
.block(block)
.bar_width(5)
.bar_gap(1)
.data(bars())
}
fn horizontal_bar_chart(&self) -> impl Widget {
let block = Block::bordered().title("Horizontal Bar Chart");
BarChart::default()
.direction(Direction::Horizontal)
.block(block)
.bar_width(1)
.bar_gap(1)
.data(bars())
}
fn text(&self, index: usize) -> impl Widget {
let block = Block::bordered().title(format!("Text {index}"));
Paragraph::new(self.text[index].clone())
.wrap(Wrap { trim: false })
.block(block)
}
}
const CHART_DATA: [(&str, u64, Color); 3] = [
("Red", 2, Color::Red),
("Green", 7, Color::Green),
("Blue", 11, Color::Blue),
];
fn bars() -> BarGroup<'static> {
let data = CHART_DATA
.map(|(label, value, color)| Bar::default().label(label).value(value).style(color));
BarGroup::default().bars(&data)
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-qrcode/src/lib.rs | tui-qrcode/src/lib.rs | //! A [Ratatui] widget to render crisp, scan-happy QR codes in the terminal. Part of the
//! [tui-widgets] suite by [Joshka].
//!
//! 
//!
//! [![Crate badge]][Crate]
//! [![Docs Badge]][Docs]
//! [![Deps Badge]][Dependency Status]
//! [![License Badge]][License]
//! [![Coverage Badge]][Coverage]
//! [![Discord Badge]][Ratatui Discord]
//!
//! [GitHub Repository] · [API Docs] · [Examples] · [Changelog] · [Contributing]
//!
//! # Installation
//!
//! Add qrcode and tui-qrcode to your Cargo.toml. You can disable the default features of qrcode as
//! we don't need the code which renders the QR code to an image.
//!
//! ```shell
//! cargo add qrcode tui-qrcode --no-default-features
//! ```
//!
//! # Usage
//!
//! This example can be found in the `examples` directory of the repository.
//!
//! ```no_run
//! use qrcode::QrCode;
//! use ratatui::crossterm::event;
//! use ratatui::{DefaultTerminal, Frame};
//! use tui_qrcode::{Colors, QrCodeWidget};
//!
//! fn main() -> color_eyre::Result<()> {
//! color_eyre::install()?;
//! let terminal = ratatui::init();
//! let result = run(terminal);
//! ratatui::restore();
//! result
//! }
//!
//! fn run(mut terminal: DefaultTerminal) -> color_eyre::Result<()> {
//! loop {
//! terminal.draw(render)?;
//! if matches!(event::read()?, event::Event::Key(_)) {
//! break Ok(());
//! }
//! }
//! }
//!
//! fn render(frame: &mut Frame) {
//! let qr_code = QrCode::new("https://ratatui.rs").expect("failed to create QR code");
//! let widget = QrCodeWidget::new(qr_code).colors(Colors::Inverted);
//! frame.render_widget(widget, frame.area());
//! }
//! ```
//!
//! Renders the following QR code:
//!
//! ```text
//! █████████████████████████████████
//! █████████████████████████████████
//! ████ ▄▄▄▄▄ █▄ ▄▄▄ ████ ▄▄▄▄▄ ████
//! ████ █ █ █▄▄▄█▀▄██ █ █ █ ████
//! ████ █▄▄▄█ █▀ ▄▀ ███ █▄▄▄█ ████
//! ████▄▄▄▄▄▄▄█▄▀▄█ ▀▄▀ █▄▄▄▄▄▄▄████
//! ████ █▄▀▀▀▄▄▀▄▄ ▄█▀▄█▀ █▀▄▀ ████
//! ██████▀█ ▄▀▄▄▀▀ ▄ ▄█ ▄▄█ ▄█▄████
//! ████▄▀▀▀▄▄▄▄▀█▄▄█ ▀ ▀ ▀███▀ ████
//! ████▄▄ ▀█▄▄▀▄▄ ▄█▀█▄▀█▄▀▀ ▄█▄████
//! ████▄▄█▄██▄█ ▄▀▄ ▄█ ▄▄▄ ██▄▀████
//! ████ ▄▄▄▄▄ █▄▄▄▀ ▄ ▀ █▄█ ███ ████
//! ████ █ █ ██ ███ ▄▄ ▄▄ █▀ ▄████
//! ████ █▄▄▄█ █▄▀ ▄█▀█▀ ▄█ ▄█▄▄████
//! ████▄▄▄▄▄▄▄█▄▄█▄▄▄██▄█▄██▄██▄████
//! █████████████████████████████████
//! ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
//! ```
//!
//! # More widgets
//!
//! For the full suite of widgets, see [tui-widgets].
//!
//! [Ratatui]: https://crates.io/crates/ratatui
//! [Crate]: https://crates.io/crates/tui-qrcode
//! [Docs]: https://docs.rs/tui-qrcode/
//! [Dependency Status]: https://deps.rs/repo/github/joshka/tui-widgets
//! [Coverage]: https://app.codecov.io/gh/joshka/tui-widgets
//! [Ratatui Discord]: https://discord.gg/pMCEU9hNEj
//! [Crate badge]: https://img.shields.io/crates/v/tui-qrcode.svg?logo=rust&style=flat
//! [Docs Badge]: https://img.shields.io/docsrs/tui-qrcode?logo=rust&style=flat
//! [Deps Badge]: https://deps.rs/repo/github/joshka/tui-widgets/status.svg?style=flat
//! [License Badge]: https://img.shields.io/crates/l/tui-qrcode?style=flat
//! [License]: https://github.com/joshka/tui-widgets/blob/main/LICENSE-MIT
//! [Coverage Badge]:
//! https://img.shields.io/codecov/c/github/joshka/tui-widgets?logo=codecov&style=flat
//! [Discord Badge]: https://img.shields.io/discord/1070692720437383208?logo=discord&style=flat
//! [GitHub Repository]: https://github.com/joshka/tui-widgets
//! [API Docs]: https://docs.rs/tui-qrcode/
//! [Examples]: https://github.com/joshka/tui-widgets/tree/main/tui-qrcode/examples
//! [Changelog]: https://github.com/joshka/tui-widgets/blob/main/tui-qrcode/CHANGELOG.md
//! [Contributing]: https://github.com/joshka/tui-widgets/blob/main/CONTRIBUTING.md
//!
//! [Joshka]: https://github.com/joshka
//! [tui-widgets]: https://crates.io/crates/tui-widgets
use qrcode::render::unicode::Dense1x2;
use qrcode::QrCode;
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::{Rect, Size};
use ratatui_core::style::{Style, Styled};
use ratatui_core::text::Text;
use ratatui_core::widgets::Widget;
/// A [Ratatui] widget that renders a QR code.
///
/// This widget can be used to render a QR code in a terminal. It uses the [qrcode] crate to
/// generate the QR code.
///
/// # Examples
///
/// ```no_run
/// use qrcode::QrCode;
/// use tui_qrcode::QrCodeWidget;
///
/// let qr_code = QrCode::new("https://ratatui.rs").expect("failed to create QR code");
/// let widget = QrCodeWidget::new(qr_code);
/// ```
///
/// The widget can be customized using the `quiet_zone`, `scaling`, `colors`, and `style` methods.
/// Additionally, the widget implements the [`Styled`] trait, so all the methods from Ratatui's
/// [`ratatui_core::style::Stylize`] trait can be used.
///
/// ```no_run
/// use qrcode::QrCode;
/// use ratatui::style::{Style, Stylize};
/// use ratatui::Frame;
/// use tui_qrcode::{Colors, QrCodeWidget, QuietZone, Scaling};
///
/// fn render(frame: &mut Frame) {
/// let qr_code = QrCode::new("https://ratatui.rs").expect("failed to create QR code");
/// let widget = QrCodeWidget::new(qr_code)
/// .quiet_zone(QuietZone::Disabled)
/// .scaling(Scaling::Max)
/// .colors(Colors::Inverted)
/// .red()
/// .on_light_yellow();
/// frame.render_widget(widget, frame.area());
/// }
/// ```
///
/// [Ratatui]: https://crates.io/crates/ratatui
pub struct QrCodeWidget {
qr_code: QrCode,
quiet_zone: QuietZone,
scaling: Scaling,
colors: Colors,
style: Style,
}
/// The quiet zone (border) of a QR code.
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq)]
pub enum QuietZone {
/// The quiet zone is enabled.
#[default]
Enabled,
/// The quiet zone is disabled.
Disabled,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Scaling {
/// The QR code will be scaled to at least the size of the widget.
///
/// Note that this usually results in a QR code that is larger than the widget, which is not
/// ideal.
Min,
/// The QR code will be scaled to be at most the size of the widget.
///
/// Note that this may result in a QR code which is scaled more horizontally or vertically than
/// the other, which may not be ideal.
Max,
/// The QR code will be scaled so each pixel is the size of the given dimensions.
///
/// The minimum dimensions are 1x1 (width x height).
Exact(u16, u16),
}
impl Default for Scaling {
fn default() -> Self {
Self::Exact(1, 1)
}
}
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq)]
pub enum Colors {
/// The default colors. (Black on white)
#[default]
Normal,
/// The colors are inverted. (White on black)
Inverted,
}
impl QrCodeWidget {
/// Create a new QR code widget.
#[must_use]
pub fn new(qr_code: QrCode) -> Self {
Self {
qr_code,
quiet_zone: QuietZone::default(),
scaling: Scaling::default(),
colors: Colors::default(),
style: Style::default(),
}
}
/// Set whether the QR code should have a quiet zone.
///
/// This is the white border around the QR code. By default, the quiet zone is enabled.
///
/// # Example
///
/// ```
/// use qrcode::QrCode;
/// use tui_qrcode::{QrCodeWidget, QuietZone};
///
/// let qr_code = QrCode::new("https://ratatui.rs").expect("failed to create QR code");
/// let widget = QrCodeWidget::new(qr_code).quiet_zone(QuietZone::Disabled);
/// ```
#[must_use]
pub const fn quiet_zone(mut self, quiet_zone: QuietZone) -> Self {
self.quiet_zone = quiet_zone;
self
}
/// Set how the QR code should be scaled.
///
/// By default, the QR code will be scaled so each pixel is 1x1.
///
/// The `Min` variant will scale the QR code so it is at least the size of the widget. This may
/// result in a QR code that is larger than the widget, which is not ideal. The `Max` variant
/// will scale the QR code so it is at most the size of the widget. This may result in a QR code
/// which is scaled more horizontally or vertically than the other, which may not be ideal. The
/// `Exact` variant will scale the QR code so each pixel is the size of the given dimensions.
/// The minimum scaling is 1x1 (width x height).
///
/// # Example
///
/// ```
/// use qrcode::QrCode;
/// use tui_qrcode::{QrCodeWidget, Scaling};
///
/// let qr_code = QrCode::new("https://ratatui.rs").expect("failed to create QR code");
/// let widget = QrCodeWidget::new(qr_code).scaling(Scaling::Max);
/// ```
#[must_use]
pub const fn scaling(mut self, scaling: Scaling) -> Self {
self.scaling = scaling;
self
}
/// Set the colors of the QR code.
///
/// By default, the colors are normal (light on dark).
///
/// The `Normal` variant will use the default colors. The `Inverted` variant will invert the
/// colors (dark on light).
///
/// To set the foreground and background colors of the widget, use the `style` method.
///
/// # Example
///
/// ```
/// use qrcode::QrCode;
/// use tui_qrcode::{Colors, QrCodeWidget};
///
/// let qr_code = QrCode::new("https://ratatui.rs").expect("failed to create QR code");
/// let widget = QrCodeWidget::new(qr_code).colors(Colors::Inverted);
/// ```
#[must_use]
pub const fn colors(mut self, colors: Colors) -> Self {
self.colors = colors;
self
}
/// Set the style of the widget.
///
/// This will set the foreground and background colors of the widget.
///
/// # Example
///
/// ```
/// use qrcode::QrCode;
/// use ratatui::style::{Style, Stylize};
/// use tui_qrcode::QrCodeWidget;
///
/// let qr_code = QrCode::new("https://ratatui.rs").expect("failed to create QR code");
/// let style = Style::new().red().on_light_yellow();
/// let widget = QrCodeWidget::new(qr_code).style(style);
/// ```
#[must_use]
pub fn style(mut self, style: impl Into<Style>) -> Self {
self.style = style.into();
self
}
/// The theoretical size of the QR code if rendered into `area`.
///
/// Note that if the QR code does not fit into `area`, the resulting [`Size`] might be larger
/// than the size of `area`.
///
/// # Example
/// ```
/// use qrcode::QrCode;
/// use ratatui::layout::Rect;
/// use tui_qrcode::{QrCodeWidget, Scaling};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let qr_code = QrCode::new("https://ratatui.rs")?;
/// let widget = QrCodeWidget::new(qr_code).scaling(Scaling::Min);
/// let area = Rect::new(0, 0, 50, 50);
/// let widget_size = widget.size(area);
///
/// assert_eq!(widget_size.width, 66);
/// assert_eq!(widget_size.height, 66);
/// # Ok(())
/// # }
/// ```
#[must_use]
pub fn size(&self, area: Rect) -> Size {
let qr_width: u16 = match self.quiet_zone {
QuietZone::Enabled => 8,
QuietZone::Disabled => 0,
} + self.qr_code.width() as u16;
let (x, y) = match self.scaling {
Scaling::Exact(x, y) => (x, y),
Scaling::Min => {
let x = area.width.div_ceil(qr_width);
let y = (area.height * 2).div_ceil(qr_width);
(x, y)
}
Scaling::Max => {
let x = area.width / qr_width;
let y = (area.height * 2) / qr_width;
(x, y)
}
};
let (x, y) = (x.max(1), y.max(1));
let width = qr_width * x;
let height = (qr_width * y).div_ceil(2);
Size::new(width, height)
}
}
impl Styled for QrCodeWidget {
type Item = Self;
fn style(&self) -> Style {
self.style
}
fn set_style<S: Into<Style>>(self, style: S) -> Self::Item {
self.style(style)
}
}
impl Widget for QrCodeWidget {
fn render(self, area: Rect, buf: &mut Buffer) {
(&self).render(area, buf);
}
}
impl Widget for &QrCodeWidget {
fn render(self, area: Rect, buf: &mut Buffer) {
let mut renderer = self.qr_code.render::<Dense1x2>();
match self.quiet_zone {
QuietZone::Enabled => renderer.quiet_zone(true),
QuietZone::Disabled => renderer.quiet_zone(false),
};
match self.scaling {
Scaling::Min => renderer.min_dimensions(area.width as u32, area.height as u32 * 2),
Scaling::Max => renderer.max_dimensions(area.width as u32, area.height as u32 * 2),
Scaling::Exact(width, height) => {
renderer.module_dimensions(width as u32, height as u32)
}
};
match self.colors {
Colors::Normal => renderer
.dark_color(Dense1x2::Dark)
.light_color(Dense1x2::Light),
Colors::Inverted => renderer
.dark_color(Dense1x2::Light)
.light_color(Dense1x2::Dark),
};
Text::raw(renderer.build())
.style(self.style)
.render(area, buf);
}
}
#[cfg(test)]
mod tests {
use rstest::{fixture, rstest};
use super::*;
/// Creates an empty QR code widget. The basic dimensions of the QR code are 21x21 or 29x29 with
/// a quiet zone.
#[fixture]
fn empty_widget() -> QrCodeWidget {
let empty_qr = QrCode::new("").expect("failed to create QR code");
QrCodeWidget::new(empty_qr).quiet_zone(QuietZone::Disabled)
}
#[rstest]
/// Cases where the QR code is smaller (21x10.5) than the area (22, 12)
#[case::smaller_exact((22,12), Scaling::Exact(1, 1), (21, 11))]
#[case::smaller_max((22, 12), Scaling::Max, (21, 11))]
#[case::smaller_min((22,12),Scaling::Min, (42, 21))]
/// Cases where the QR code is the same size (21x10.5) as the area (21, 11)
#[case::same_exact((21, 11), Scaling::Exact(1, 1), (21, 11))]
#[case::same_max((21, 11), Scaling::Max, (21, 11))]
/// Exception: height would be 10.5, so height is doubled to 21
#[case::same_min((21, 11), Scaling::Min, (21, 21))]
/// Cases where the QR code is larger (21x10.5) than the area (20, 10)
#[rstest]
#[case::larger_exact((20, 10), Scaling::Exact(1, 1), (21, 11))]
#[case::larger_max((20, 10), Scaling::Max, (21, 11))]
#[case::larger_min((20, 10), Scaling::Min, (21, 11))]
/// Cases where the QR code is much smaller (21x10.5) than the area (71, 71).
#[rstest]
#[case::huge_exact((71, 71), Scaling::Exact(1, 1), (21, 11))]
#[case::huge_max((71, 71), Scaling::Max,(63, 63))]
#[case::huge_min((71, 71), Scaling::Min, (84, 74))]
fn size(
empty_widget: QrCodeWidget,
#[case] rect: (u16, u16),
#[case] scaling: Scaling,
#[case] expected: (u16, u16),
) {
let rect = Rect::new(0, 0, rect.0, rect.1);
let widget = empty_widget.scaling(scaling);
assert_eq!(widget.size(rect), Size::from(expected));
}
/// Testing that a QR code with a quiet zone (29x14.5) is scaled correctly into a large area
/// (71x71).
#[rstest]
#[case::huge_exact(Scaling::Exact(1, 1), (29, 15))]
#[case::huge_max(Scaling::Max, (58, 58))]
#[case::huge_min(Scaling::Min, (87, 73))]
fn size_with_quiet_zone(
empty_widget: QrCodeWidget,
#[case] scaling: Scaling,
#[case] expected: (u16, u16),
) {
let rect = Rect::new(0, 0, 71, 71);
let widget = empty_widget.quiet_zone(QuietZone::Enabled).scaling(scaling);
assert_eq!(widget.size(rect), Size::from(expected));
}
/// The QR code fits into the area without scaling
#[rstest]
fn render_exact_into_fitting_area(empty_widget: QrCodeWidget) {
let mut buf = Buffer::empty(Rect::new(0, 0, 21, 11));
empty_widget.render(buf.area, &mut buf);
assert_eq!(
buf,
Buffer::with_lines([
"█▀▀▀▀▀█ ▀▀▄█ █▀▀▀▀▀█",
"█ ███ █ █▀▀ ▀ █ ███ █",
"█ ▀▀▀ █ ██▄▄▀ █ ▀▀▀ █",
"▀▀▀▀▀▀▀ █▄▀ ▀ ▀▀▀▀▀▀▀",
"▀ ▀█▀█▀▄ ▀██▄▄█▀▀█▀▄ ",
"▄▄▄ ▀██▀▄▄█▄█▀ ▄ ▄ ",
"▀ ▀ ▀▀▀ █▄█ █ █ █ ",
"█▀▀▀▀▀█ ▄██▀ ▀ ▄█▀█▀█",
"█ ███ █ █▀██▄█▄ ▀█▀▀▀",
"█ ▀▀▀ █ ▀ ▄█▄█▀ ▄ ",
"▀▀▀▀▀▀▀ ▀ ▀ ▀ ▀ ",
])
);
}
/// The QR code fits into the area without scaling
#[rstest]
fn render_max_into_fitting_area(empty_widget: QrCodeWidget) {
let mut buf = Buffer::empty(Rect::new(0, 0, 21, 11));
empty_widget
.scaling(Scaling::Max)
.render(buf.area, &mut buf);
assert_eq!(
buf,
Buffer::with_lines([
"█▀▀▀▀▀█ ▀▀▄█ █▀▀▀▀▀█",
"█ ███ █ █▀▀ ▀ █ ███ █",
"█ ▀▀▀ █ ██▄▄▀ █ ▀▀▀ █",
"▀▀▀▀▀▀▀ █▄▀ ▀ ▀▀▀▀▀▀▀",
"▀ ▀█▀█▀▄ ▀██▄▄█▀▀█▀▄ ",
"▄▄▄ ▀██▀▄▄█▄█▀ ▄ ▄ ",
"▀ ▀ ▀▀▀ █▄█ █ █ █ ",
"█▀▀▀▀▀█ ▄██▀ ▀ ▄█▀█▀█",
"█ ███ █ █▀██▄█▄ ▀█▀▀▀",
"█ ▀▀▀ █ ▀ ▄█▄█▀ ▄ ",
"▀▀▀▀▀▀▀ ▀ ▀ ▀ ▀ ",
])
);
}
// The QR code is doubled vertically as the min scaling means this needs to render at least
// 21x10.5 but the buffer is 21x11
///
/// Note: this is an instance where the square aspect ratio of the QR code is not preserved
/// correctly. This doesn't align with the documentation of the qrcode crate.
#[rstest]
fn render_min_into_fitting_area(empty_widget: QrCodeWidget) {
let mut buf = Buffer::empty(Rect::new(0, 0, 21, 11));
empty_widget
.scaling(Scaling::Min)
.render(buf.area, &mut buf);
assert_eq!(
buf,
Buffer::with_lines([
"███████ ██ █ ███████",
"█ █ ██ █ █",
"█ ███ █ ███ █ █ ███ █",
"█ ███ █ █ █ ███ █",
"█ ███ █ ██ █ █ ███ █",
"█ █ ████ █ █",
"███████ █ █ █ ███████",
" ██ ",
"█ █████ ███ █████ ",
" █ █ █ █████ █ █ ",
" ████ █ ██ ",
])
);
}
/// The QR code fits into the area without scaling
#[rstest]
fn render_exact_into_larger_area(empty_widget: QrCodeWidget) {
let mut buf = Buffer::empty(Rect::new(0, 0, 22, 12));
empty_widget.render(buf.area, &mut buf);
assert_eq!(
buf,
Buffer::with_lines([
"█▀▀▀▀▀█ ▀▀▄█ █▀▀▀▀▀█ ",
"█ ███ █ █▀▀ ▀ █ ███ █ ",
"█ ▀▀▀ █ ██▄▄▀ █ ▀▀▀ █ ",
"▀▀▀▀▀▀▀ █▄▀ ▀ ▀▀▀▀▀▀▀ ",
"▀ ▀█▀█▀▄ ▀██▄▄█▀▀█▀▄ ",
"▄▄▄ ▀██▀▄▄█▄█▀ ▄ ▄ ",
"▀ ▀ ▀▀▀ █▄█ █ █ █ ",
"█▀▀▀▀▀█ ▄██▀ ▀ ▄█▀█▀█ ",
"█ ███ █ █▀██▄█▄ ▀█▀▀▀ ",
"█ ▀▀▀ █ ▀ ▄█▄█▀ ▄ ",
"▀▀▀▀▀▀▀ ▀ ▀ ▀ ▀ ",
" ",
])
);
}
/// The QR code fits into the area without scaling
#[rstest]
fn render_max_into_larger_area(empty_widget: QrCodeWidget) {
let mut buf = Buffer::empty(Rect::new(0, 0, 22, 12));
empty_widget
.scaling(Scaling::Max)
.render(buf.area, &mut buf);
assert_eq!(
buf,
Buffer::with_lines([
"█▀▀▀▀▀█ ▀▀▄█ █▀▀▀▀▀█ ",
"█ ███ █ █▀▀ ▀ █ ███ █ ",
"█ ▀▀▀ █ ██▄▄▀ █ ▀▀▀ █ ",
"▀▀▀▀▀▀▀ █▄▀ ▀ ▀▀▀▀▀▀▀ ",
"▀ ▀█▀█▀▄ ▀██▄▄█▀▀█▀▄ ",
"▄▄▄ ▀██▀▄▄█▄█▀ ▄ ▄ ",
"▀ ▀ ▀▀▀ █▄█ █ █ █ ",
"█▀▀▀▀▀█ ▄██▀ ▀ ▄█▀█▀█ ",
"█ ███ █ █▀██▄█▄ ▀█▀▀▀ ",
"█ ▀▀▀ █ ▀ ▄█▄█▀ ▄ ",
"▀▀▀▀▀▀▀ ▀ ▀ ▀ ▀ ",
" ",
])
);
}
/// The QR code is doubled vertically and horizontall as the min scaling means this needs to
/// render at least 21x10.5 but the buffer is 22x12
#[rstest]
fn render_min_into_larger_area(empty_widget: QrCodeWidget) {
let mut buf = Buffer::empty(Rect::new(0, 0, 22, 12));
empty_widget
.scaling(Scaling::Min)
.render(buf.area, &mut buf);
assert_eq!(
buf,
Buffer::with_lines([
"██████████████ ████",
"██ ██ ",
"██ ██████ ██ ██████",
"██ ██████ ██ ██ ",
"██ ██████ ██ ████ ",
"██ ██ ██████",
"██████████████ ██ ██",
" ████ ",
"██ ██████████ ████",
" ██ ██ ██ ██",
" ████████ ",
"██████ ████ ██",
])
);
}
/// The QR code is truncated as the area is smaller than the QR code
#[rstest]
fn render_exact_into_smaler_area(empty_widget: QrCodeWidget) {
let mut buf = Buffer::empty(Rect::new(0, 0, 20, 10));
empty_widget.render(buf.area, &mut buf);
assert_eq!(
buf,
Buffer::with_lines([
"█▀▀▀▀▀█ ▀▀▄█ █▀▀▀▀▀",
"█ ███ █ █▀▀ ▀ █ ███ ",
"█ ▀▀▀ █ ██▄▄▀ █ ▀▀▀ ",
"▀▀▀▀▀▀▀ █▄▀ ▀ ▀▀▀▀▀▀",
"▀ ▀█▀█▀▄ ▀██▄▄█▀▀█▀▄",
"▄▄▄ ▀██▀▄▄█▄█▀ ▄ ▄",
"▀ ▀ ▀▀▀ █▄█ █ █ █ ",
"█▀▀▀▀▀█ ▄██▀ ▀ ▄█▀█▀",
"█ ███ █ █▀██▄█▄ ▀█▀▀",
"█ ▀▀▀ █ ▀ ▄█▄█▀ ▄ ",
])
);
}
/// The QR code is truncated as the max scaling means this needs to render at most 21x10.5 but
/// the buffer is 20x10
#[rstest]
fn render_max_into_smaller_area(empty_widget: QrCodeWidget) {
let mut buf = Buffer::empty(Rect::new(0, 0, 20, 10));
empty_widget
.scaling(Scaling::Max)
.render(buf.area, &mut buf);
assert_eq!(
buf,
Buffer::with_lines([
"█▀▀▀▀▀█ ▀▀▄█ █▀▀▀▀▀",
"█ ███ █ █▀▀ ▀ █ ███ ",
"█ ▀▀▀ █ ██▄▄▀ █ ▀▀▀ ",
"▀▀▀▀▀▀▀ █▄▀ ▀ ▀▀▀▀▀▀",
"▀ ▀█▀█▀▄ ▀██▄▄█▀▀█▀▄",
"▄▄▄ ▀██▀▄▄█▄█▀ ▄ ▄",
"▀ ▀ ▀▀▀ █▄█ █ █ █ ",
"█▀▀▀▀▀█ ▄██▀ ▀ ▄█▀█▀",
"█ ███ █ █▀██▄█▄ ▀█▀▀",
"█ ▀▀▀ █ ▀ ▄█▄█▀ ▄ ",
])
);
}
/// The QR code is truncated as the min scaling means this needs to render at least 21x10.5 but
/// the buffer is already too small
#[rstest]
fn render_min_into_smaller_area(empty_widget: QrCodeWidget) {
let mut buf = Buffer::empty(Rect::new(0, 0, 20, 10));
empty_widget
.scaling(Scaling::Min)
.render(buf.area, &mut buf);
assert_eq!(
buf,
Buffer::with_lines([
"█▀▀▀▀▀█ ▀▀▄█ █▀▀▀▀▀",
"█ ███ █ █▀▀ ▀ █ ███ ",
"█ ▀▀▀ █ ██▄▄▀ █ ▀▀▀ ",
"▀▀▀▀▀▀▀ █▄▀ ▀ ▀▀▀▀▀▀",
"▀ ▀█▀█▀▄ ▀██▄▄█▀▀█▀▄",
"▄▄▄ ▀██▀▄▄█▄█▀ ▄ ▄",
"▀ ▀ ▀▀▀ █▄█ █ █ █ ",
"█▀▀▀▀▀█ ▄██▀ ▀ ▄█▀█▀",
"█ ███ █ █▀██▄█▄ ▀█▀▀",
"█ ▀▀▀ █ ▀ ▄█▄█▀ ▄ ",
])
);
}
/// Exact scaling doesn't scale the QR code
#[rstest]
fn render_exact_double_height(empty_widget: QrCodeWidget) {
let mut buf = Buffer::empty(Rect::new(0, 0, 21, 21));
empty_widget.render(buf.area, &mut buf);
assert_eq!(
buf,
Buffer::with_lines([
"█▀▀▀▀▀█ ▀▀▄█ █▀▀▀▀▀█",
"█ ███ █ █▀▀ ▀ █ ███ █",
"█ ▀▀▀ █ ██▄▄▀ █ ▀▀▀ █",
"▀▀▀▀▀▀▀ █▄▀ ▀ ▀▀▀▀▀▀▀",
"▀ ▀█▀█▀▄ ▀██▄▄█▀▀█▀▄ ",
"▄▄▄ ▀██▀▄▄█▄█▀ ▄ ▄ ",
"▀ ▀ ▀▀▀ █▄█ █ █ █ ",
"█▀▀▀▀▀█ ▄██▀ ▀ ▄█▀█▀█",
"█ ███ █ █▀██▄█▄ ▀█▀▀▀",
"█ ▀▀▀ █ ▀ ▄█▄█▀ ▄ ",
"▀▀▀▀▀▀▀ ▀ ▀ ▀ ▀ ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
])
);
}
/// The QR code is doubled vertically
///
/// Note: this is an instance where the square aspect ratio of the QR code is not preserved
/// correctly. This doesn't align with the documentation of the qrcode crate.
#[rstest]
fn render_max_double_height(empty_widget: QrCodeWidget) {
let mut buf = Buffer::empty(Rect::new(0, 0, 21, 21));
empty_widget
.scaling(Scaling::Max)
.render(buf.area, &mut buf);
assert_eq!(
buf,
Buffer::with_lines([
"███████ ██ █ ███████",
"█ █ ██ █ █",
"█ ███ █ ███ █ █ ███ █",
"█ ███ █ █ █ ███ █",
"█ ███ █ ██ █ █ ███ █",
"█ █ ████ █ █",
"███████ █ █ █ ███████",
" ██ ",
"█ █████ ███ █████ ",
" █ █ █ █████ █ █ ",
" ████ █ ██ ",
"███ ██ █████ █ █ ",
"█ █ ███ █ █ █ █ █ ",
" ███ █ █ █ ",
"███████ ███ █ █████",
"█ █ ███ ██ █ █",
"█ ███ █ ████ █ █████",
"█ ███ █ █ █████ █ ",
"█ ███ █ █ █ ██ ",
"█ █ ████ █ ",
"███████ █ █ █ █ ",
])
);
}
/// The QR code is doubled vertically
///
/// Note: this is an instance where the square aspect ratio of the QR code is not preserved
/// correctly. This doesn't align with the documentation of the qrcode crate.
#[rstest]
fn render_min_double_height(empty_widget: QrCodeWidget) {
let mut buf = Buffer::empty(Rect::new(0, 0, 21, 21));
empty_widget
.scaling(Scaling::Min)
.render(buf.area, &mut buf);
assert_eq!(
buf,
Buffer::with_lines([
"███████ ██ █ ███████",
"█ █ ██ █ █",
"█ ███ █ ███ █ █ ███ █",
"█ ███ █ █ █ ███ █",
"█ ███ █ ██ █ █ ███ █",
"█ █ ████ █ █",
"███████ █ █ █ ███████",
" ██ ",
"█ █████ ███ █████ ",
" █ █ █ █████ █ █ ",
" ████ █ ██ ",
"███ ██ █████ █ █ ",
"█ █ ███ █ █ █ █ █ ",
" ███ █ █ █ ",
"███████ ███ █ █████",
"█ █ ███ ██ █ █",
"█ ███ █ ████ █ █████",
"█ ███ █ █ █████ █ ",
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | true |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-qrcode/examples/qrcode.rs | tui-qrcode/examples/qrcode.rs | use qrcode::QrCode;
use ratatui::crossterm::event;
use ratatui::{DefaultTerminal, Frame};
use tui_qrcode::{Colors, QrCodeWidget};
fn main() -> color_eyre::Result<()> {
color_eyre::install()?;
let terminal = ratatui::init();
let result = run(terminal);
ratatui::restore();
result
}
fn run(mut terminal: DefaultTerminal) -> color_eyre::Result<()> {
loop {
terminal.draw(render)?;
if matches!(event::read()?, event::Event::Key(_)) {
break Ok(());
}
}
}
fn render(frame: &mut Frame) {
let qr_code = QrCode::new("https://ratatui.rs").expect("failed to create QR code");
let widget = QrCodeWidget::new(qr_code).colors(Colors::Inverted);
frame.render_widget(widget, frame.area());
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/src/lib.rs | src/lib.rs | //! A collection of useful widgets for building terminal user interfaces using [Ratatui].
//!
//! [Ratatui]: https://crates.io/crates/ratatui
//!
//! This is a crate that combines multiple previously standalone crates into one in order simplify
//! maintenance and to make it easier to use the widgets together.
//!
//! Workspace crates:
//!
//! - [tui-widgets] (this crate)
//! - [tui-bar-graph]
//! - [tui-big-text]
//! - [tui-box-text]
//! - [tui-cards]
//! - [tui-popup]
//! - [tui-prompts]
//! - [tui-qrcode]
//! - [tui-scrollbar]
//! - [tui-scrollview]
//!
//! The widget crates are also available as standalone crates.
//!
//! # Screenshots
//!
//! ## [tui-bar-graph]
//!
//! [][tui-bar-graph]
//!
//! ## [tui-big-text]
//!
//! [][tui-big-text]
//!
//! ## [tui-box-text]
//!
//! [][tui-box-text]
//!
//! ## [tui-cards]
//!
//! [][tui-cards]
//!
//! ## [tui-popup]
//!
//! [][tui-popup]
//!
//! ## [tui-prompts]
//!
//! [][tui-prompts]
//!
//! ## [tui-qrcode]
//!
//! [][tui-qrcode]
//!
//! ## [tui-scrollview]
//!
//! [][tui-scrollview]
//!
//! [tui-widgets]: https://crates.io/crates/tui-widgets
//! [tui-bar-graph]: https://crates.io/crates/tui-bar-graph
//! [tui-big-text]: https://crates.io/crates/tui-big-text
//! [tui-box-text]: https://crates.io/crates/tui-box-text
//! [tui-cards]: https://crates.io/crates/tui-cards
//! [tui-popup]: https://crates.io/crates/tui-popup
//! [tui-prompts]: https://crates.io/crates/tui-prompts
//! [tui-qrcode]: https://crates.io/crates/tui-qrcode
//! [tui-scrollbar]: https://crates.io/crates/tui-scrollbar
//! [tui-scrollview]: https://crates.io/crates/tui-scrollview
#![doc = document_features::document_features!()]
#[cfg(feature = "bar-graph")]
#[doc(inline)]
pub use tui_bar_graph as bar_graph;
#[cfg(feature = "big-text")]
#[doc(inline)]
pub use tui_big_text as big_text;
#[cfg(feature = "box-text")]
#[doc(inline)]
pub use tui_box_text as box_text;
#[cfg(feature = "cards")]
#[doc(inline)]
pub use tui_cards as cards;
#[cfg(feature = "popup")]
#[doc(inline)]
pub use tui_popup as popup;
#[cfg(feature = "prompts")]
#[doc(inline)]
pub use tui_prompts as prompts;
#[cfg(feature = "qrcode")]
#[doc(inline)]
pub use tui_qrcode as qrcode;
#[cfg(feature = "scrollbar")]
#[doc(inline)]
pub use tui_scrollbar as scrollbar;
#[cfg(feature = "scrollview")]
#[doc(inline)]
pub use tui_scrollview as scrollview;
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-cards/src/lib.rs | tui-cards/src/lib.rs | //! A [Ratatui] widget to render charming playing cards in the terminal. Part of the [tui-widgets]
//! suite by [Joshka].
//!
//! 
//!
//! [![Crate badge]][Crate]
//! [![Docs Badge]][Docs]
//! [![Deps Badge]][Dependency Status]
//! [![License Badge]][License]
//! [![Coverage Badge]][Coverage]
//! [![Discord Badge]][Ratatui Discord]
//!
//! [GitHub Repository] · [API Docs] · [Examples] · [Changelog] · [Contributing]
//!
//! # Usage
//!
//! Create a `Card` and render it directly in a frame.
//!
//! ```no_run
//! use tui_cards::{Card, Rank, Suit};
//!
//! # fn draw(frame: &mut ratatui::Frame) {
//! let card = Card::new(Rank::Ace, Suit::Spades);
//! frame.render_widget(&card, frame.area());
//! # }
//! ```
//!
//! # Demo
//!
//! ```shell
//! cargo run --example card
//! ```
//!
//! # More widgets
//!
//! For the full suite of widgets, see [tui-widgets].
//!
//! [Crate]: https://crates.io/crates/tui-cards
//! [Docs]: https://docs.rs/tui-cards/
//! [Dependency Status]: https://deps.rs/repo/github/joshka/tui-widgets
//! [Coverage]: https://app.codecov.io/gh/joshka/tui-widgets
//! [Ratatui Discord]: https://discord.gg/pMCEU9hNEj
//! [Crate badge]: https://img.shields.io/crates/v/tui-cards?logo=rust&style=flat
//! [Docs Badge]: https://img.shields.io/docsrs/tui-cards?logo=rust&style=flat
//! [Deps Badge]: https://deps.rs/repo/github/joshka/tui-widgets/status.svg?style=flat
//! [License Badge]: https://img.shields.io/crates/l/tui-cards?style=flat
//! [License]: https://github.com/joshka/tui-widgets/blob/main/LICENSE-MIT
//! [Coverage Badge]:
//! https://img.shields.io/codecov/c/github/joshka/tui-widgets?logo=codecov&style=flat
//! [Discord Badge]: https://img.shields.io/discord/1070692720437383208?logo=discord&style=flat
//!
//! [GitHub Repository]: https://github.com/joshka/tui-widgets
//! [API Docs]: https://docs.rs/tui-cards/
//! [Examples]: https://github.com/joshka/tui-widgets/tree/main/tui-cards/examples
//! [Changelog]: https://github.com/joshka/tui-widgets/blob/main/tui-cards/CHANGELOG.md
//! [Contributing]: https://github.com/joshka/tui-widgets/blob/main/CONTRIBUTING.md
//! [Joshka]: https://github.com/joshka
//! [tui-widgets]: https://crates.io/crates/tui-widgets
use std::iter::zip;
use indoc::indoc;
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::Rect;
use ratatui_core::style::{Color, Stylize};
use ratatui_core::widgets::Widget;
use strum::{Display, EnumIter};
/// A playing card.
///
/// # Example
///
/// ```rust
/// use tui_cards::{Card, Rank, Suit};
/// # fn draw(frame: &mut ratatui::Frame) {
/// let card = Card::new(Rank::Ace, Suit::Spades);
/// frame.render_widget(&card, frame.area());
/// # }
/// ```
#[derive(Debug, Clone, Copy)]
pub struct Card {
pub rank: Rank,
pub suit: Suit,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Display, EnumIter)]
pub enum Rank {
Ace,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Ten,
Jack,
Queen,
King,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Display, EnumIter)]
pub enum Suit {
Spades,
Hearts,
Diamonds,
Clubs,
}
impl Card {
pub const fn new(rank: Rank, suit: Suit) -> Self {
Self { rank, suit }
}
pub fn as_colored_symbol(&self) -> String {
format!(
"{}{}",
self.rank.as_symbol(),
self.suit.as_four_color_symbol()
)
}
}
impl Rank {
pub const fn as_symbol(self) -> char {
match self {
Self::Ace => 'A',
Self::Two => '2',
Self::Three => '3',
Self::Four => '4',
Self::Five => '5',
Self::Six => '6',
Self::Seven => '7',
Self::Eight => '8',
Self::Nine => '9',
Self::Ten => 'T',
Self::Jack => 'J',
Self::Queen => 'Q',
Self::King => 'K',
}
}
}
impl Suit {
pub const fn color(self) -> Color {
match self {
Self::Clubs => Color::Green,
Self::Diamonds => Color::Blue,
Self::Hearts => Color::Red,
Self::Spades => Color::Black,
}
}
pub const fn as_symbol(self) -> char {
match self {
Self::Clubs => '♣',
Self::Diamonds => '♦',
Self::Hearts => '♥',
Self::Spades => '♠',
}
}
pub const fn as_colored_symbol(self) -> &'static str {
match self {
Self::Clubs => "\u{2663}\u{FE0F}",
Self::Diamonds => "\u{2666}\u{FE0F}",
Self::Hearts => "\u{2665}\u{FE0F}",
Self::Spades => "\u{2660}\u{FE0F}",
}
}
pub const fn as_four_color_symbol(self) -> &'static str {
match self {
Self::Clubs => "\u{2618}\u{FE0F}", // shamrock
Self::Diamonds => "\u{1F537}\u{FE0F}", // blue diamond
Self::Hearts => "\u{2665}\u{FE0F}",
Self::Spades => "\u{2660}\u{FE0F}",
}
}
}
impl Rank {
pub const fn template(self) -> &'static str {
match self {
Self::Ace => indoc! {"
╭────────────╮
│ A │
│ │
│ │
│ xx │
│ │
│ │
│ A │
╰────────────╯"},
Self::Two => indoc! {"
╭────────────╮
│ 2 xx │
│ │
│ │
│ │
│ │
│ │
│ xx 2 │
╰────────────╯"},
Self::Three => indoc! {"
╭────────────╮
│ 3 xx │
│ │
│ │
│ xx │
│ │
│ │
│ xx 3 │
╰────────────╯"},
Self::Four => indoc! {"
╭────────────╮
│ 4xx xx │
│ │
│ │
│ │
│ │
│ │
│ xx xx4 │
╰────────────╯"},
Self::Five => indoc! {"
╭────────────╮
│ 5xx xx │
│ │
│ │
│ xx │
│ │
│ │
│ xx xx5 │
╰────────────╯"},
Self::Six => indoc! {"
╭────────────╮
│ 6xx xx │
│ │
│ │
│ xx xx │
│ │
│ │
│ xx xx6 │
╰────────────╯"},
Self::Seven => indoc! {"
╭────────────╮
│ 7xx xx │
│ │
│ xx │
│ xx xx │
│ │
│ │
│ xx xx7 │
╰────────────╯"},
Self::Eight => indoc! {"
╭────────────╮
│ 8xx xx │
│ │
│ xx │
│ xx xx │
│ xx │
│ │
│ xx xx8 │
╰────────────╯"},
Self::Nine => indoc! {"
╭────────────╮
│ 9xx xx │
│ │
│ xx xx │
│ xx │
│ xx xx │
│ │
│ xx xx9 │
╰────────────╯
"},
Self::Ten => indoc! {"
╭────────────╮
│10xx xx │
│ xx │
│ xx xx │
│ │
│ xx xx │
│ xx │
│ xx xx10│
╰────────────╯"},
Self::Jack => indoc! {"
╭────────────╮
│ Jxx │
│ JJ │
│ JJ │
│ JJ │
│ JJ JJ │
│ JJJJJ │
│ xxJ │
╰────────────╯"},
Self::Queen => indoc! {"
╭────────────╮
│ Qxx │
│ QQQQQ │
│ QQ QQ │
│ QQ QQ │
│ QQ QQ │
│ QQQQ Q │
│ xxQ │
╰────────────╯
"},
Self::King => indoc! {"
╭────────────╮
│ Kxx │
│ KK KK │
│ KK KK │
│ KK KK │
│ KK KK │
│ KK KK │
│ xxK │
╰────────────╯"},
}
}
}
impl Widget for &Card {
fn render(self, area: Rect, buf: &mut Buffer)
where
Self: Sized,
{
let template = self.rank.template();
let symbol = self.suit.as_four_color_symbol();
let card = template.replace("xx", symbol);
let color = self.suit.color();
for (line, row) in zip(card.lines(), area.rows()) {
let span = line.fg(color).bg(Color::White);
span.render(row, buf);
}
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-cards/examples/card.rs | tui-cards/examples/card.rs | use itertools::Itertools;
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent};
use ratatui::layout::Rect;
use ratatui::style::{Color, Stylize};
use ratatui::widgets::Block;
use ratatui::Frame;
use strum::IntoEnumIterator;
use tui_cards::{Card, Rank, Suit};
fn main() -> color_eyre::Result<()> {
color_eyre::install()?;
let mut terminal = ratatui::init();
// fix problem with skipping the wrong number of characters when drawing cards
// This is probably a bug in ratatui
terminal.draw(|frame| frame.render_widget(Block::new().bg(Color::White), frame.area()))?;
loop {
if terminal.draw(draw).is_err() {
break;
}
if matches!(
event::read()?,
Event::Key(KeyEvent {
code: KeyCode::Char('q'),
..
}),
) {
break;
}
}
ratatui::restore();
Ok(())
}
fn draw(frame: &mut Frame) {
let width = frame.area().width / 15 * 15;
let height = frame.area().height / 10 * 10;
let cards = Suit::iter()
.cartesian_product(Rank::iter())
.map(|(suit, rank)| Card::new(rank, suit));
let x_iter = (0..width).step_by(15);
let y_iter = (0..height).step_by(10);
for (card, (y, x)) in cards.zip(y_iter.cartesian_product(x_iter)) {
let area = Rect::new(x, y, 15, 10);
frame.render_widget(&card, area);
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-prompts/src/lib.rs | tui-prompts/src/lib.rs | //! A [Ratatui] widget set for friendly prompts and input flows. Part of the [tui-widgets] suite by
//! [Joshka].
//!
//! [![Crate badge]][Crate]
//! [![Docs Badge]][Docs]
//! [![Deps Badge]][Dependency Status]
//! [![License Badge]][License]
//! [![Coverage Badge]][Coverage]
//! [![Discord Badge]][Ratatui Discord]
//!
//! [GitHub Repository] · [API Docs] · [Examples] · [Changelog] · [Contributing]
//!
//! # Installation
//!
//! ```shell
//! cargo add ratatui tui-prompts crossterm
//! ```
//!
//! # Usage
//!
//! Pick a prompt type, keep its state, and render it inside your UI.
//!
//! ## Text Prompt
//!
//! <details>
//! <summary>Code</summary>
//!
//! ```rust
//! use ratatui::layout::{Constraint, Direction, Layout, Rect};
//! use ratatui::Frame;
//! use tui_prompts::{Prompt, TextPrompt, TextRenderStyle, TextState};
//!
//! struct App<'a> {
//! username_state: TextState<'a>,
//! password_state: TextState<'a>,
//! invisible_state: TextState<'a>,
//! }
//!
//! impl<'a> App<'a> {
//! fn draw_ui(&mut self, frame: &mut Frame) {
//! let (username_area, password_area, invisible_area) = split_layout(frame.area());
//!
//! TextPrompt::from("Username")
//! .draw(frame, username_area, &mut self.username_state);
//!
//! TextPrompt::from("Password")
//! .with_render_style(TextRenderStyle::Password)
//! .draw(frame, password_area, &mut self.password_state);
//!
//! TextPrompt::from("Invisible")
//! .with_render_style(TextRenderStyle::Invisible)
//! .draw(frame, invisible_area, &mut self.invisible_state);
//! }
//! }
//!
//! fn split_layout(area: Rect) -> (Rect, Rect, Rect) {
//! let rows = Layout::default()
//! .direction(Direction::Vertical)
//! .constraints([
//! Constraint::Length(1),
//! Constraint::Length(1),
//! Constraint::Length(1),
//! ])
//! .split(area);
//! (rows[0], rows[1], rows[2])
//! }
//! ```
//!
//! </details>
//!
//! 
//!
//! See the [text example] for more details.
//!
//! ## Soft Wrapping
//!
//! Text is automatically character wrapped to fit in the render area.
//!
//! 
//!
//! See the [multi line example] for more details.
//!
//! # Features
//!
//! - [x] Text prompt
//! - [x] Password prompt
//! - [x] Invisible prompt
//! - [x] Readline / emacs style Key Bindings
//! - [x] Crossterm backend
//! - [x] Soft wrapping single lines
//! - [ ] Multi-line input
//! - [ ] Scrolling
//! - [ ] More prompt types:
//! - [ ] Number
//! - [ ] Confirm
//! - [ ] List
//! - [ ] Toggle
//! - [ ] Select
//! - [ ] Multi-select
//! - [ ] Autocomplete
//! - [ ] Autocomplete multi-select
//! - [ ] Date
//! - [ ] Bracketed paste
//! - [ ] Validation
//! - [ ] Default initial value
//! - [ ] Custom style
//! - [ ] Themes
//! - [ ] Custom formatting
//! - [ ] Backend agnostic keyboard event handling
//! - [Termion]
//! - [Termwiz]
//! - [ ] Customizable key bindings
//! - [ ] Handle more advanced multi-key bindings e.g. `^[b` and `^[f`
//! - [ ] Prompt chaining
//!
//! # Key Bindings
//!
//! | Key | Action |
//! | --- | --- |
//! | Home, Ctrl+A | Move cursor to beginning of line |
//! | End, Ctrl+E | Move cursor to end of line |
//! | Left, Ctrl+B | Move cursor one character left |
//! | Right, Ctrl+F | Move cursor one character right |
//! | Backspace (Delete on Mac), Ctrl+H | Delete character before cursor |
//! | Delete (Fn+Delete on Mac), Ctrl+D | Delete character at cursor |
//! | Ctrl+K | Delete all characters from the cursor to the end of line |
//! | Ctrl+U | Delete the entire line |
//! | Enter | Complete the prompt |
//! | Escape, Ctrl+C | Abort the prompt |
//!
//! # More widgets
//!
//! For the full suite of widgets, see [tui-widgets].
//!
//! [Joshka]: https://github.com/joshka
//! [tui-widgets]: https://crates.io/crates/tui-widgets
//! [Crate]: https://crates.io/crates/tui-prompts
//! [Docs]: https://docs.rs/tui-prompts/
//! [Dependency Status]: https://deps.rs/repo/github/joshka/tui-widgets
//! [Coverage]: https://app.codecov.io/gh/joshka/tui-widgets
//! [Ratatui Discord]: https://discord.gg/pMCEU9hNEj
//! [GitHub Repository]: https://github.com/joshka/tui-widgets
//! [API Docs]: https://docs.rs/tui-prompts/
//! [Examples]: https://github.com/joshka/tui-widgets/tree/main/tui-prompts/examples
//! [text example]: https://github.com/joshka/tui-widgets/tree/main/tui-prompts/examples/text.rs
//! [multi line example]: https://github.com/joshka/tui-widgets/tree/main/tui-prompts/examples/multi_line.rs
//! [Changelog]: https://github.com/joshka/tui-widgets/blob/main/tui-prompts/CHANGELOG.md
//! [Contributing]: https://github.com/joshka/tui-widgets/blob/main/CONTRIBUTING.md
//! [Crate badge]: https://img.shields.io/crates/v/tui-prompts?logo=rust&style=flat
//! [Docs Badge]: https://img.shields.io/docsrs/tui-prompts?logo=rust&style=flat
//! [Deps Badge]: https://deps.rs/repo/github/joshka/tui-widgets/status.svg?style=flat
//! [License Badge]: https://img.shields.io/crates/l/tui-prompts?style=flat
//! [License]: https://github.com/joshka/tui-widgets/blob/main/LICENSE-MIT
//! [Coverage Badge]:
//! https://img.shields.io/codecov/c/github/joshka/tui-widgets?logo=codecov&style=flat
//! [Discord Badge]:
//! https://img.shields.io/discord/1070692720437383208?logo=discord&style=flat
//! [Ratatui]: https://crates.io/crates/ratatui
//! [Termion]: https://crates.io/crates/termion
//! [Termwiz]: https://crates.io/crates/termwiz
mod prompt;
mod status;
mod text_prompt;
mod text_state;
pub use prompt::*;
pub use status::*;
pub use text_prompt::*;
pub use text_state::*;
pub mod prelude {
pub use crate::{FocusState, Prompt, State, Status, TextPrompt, TextRenderStyle, TextState};
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-prompts/src/status.rs | tui-prompts/src/status.rs | use ratatui_core::style::Stylize;
use ratatui_core::text::Span;
/// The result of a prompt.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Status {
#[default]
Pending,
Aborted,
Done,
}
impl Status {
#[must_use]
pub const fn is_pending(&self) -> bool {
matches!(self, Self::Pending)
}
#[must_use]
pub const fn is_aborted(&self) -> bool {
matches!(self, Self::Aborted)
}
#[must_use]
pub const fn is_done(&self) -> bool {
matches!(self, Self::Done)
}
#[must_use]
pub const fn is_finished(&self) -> bool {
matches!(self, Self::Done | Self::Aborted)
}
#[must_use]
pub fn symbol(&self) -> Span<'static> {
match self {
Self::Pending => Symbols::default().pending,
Self::Aborted => Symbols::default().aborted,
Self::Done => Symbols::default().done,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Symbols {
pub pending: Span<'static>,
pub aborted: Span<'static>,
pub done: Span<'static>,
}
impl Default for Symbols {
fn default() -> Self {
Self {
pending: "?".cyan(),
aborted: "✘".red(),
done: "✔".green(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn status_symbols() {
assert_eq!(Status::Pending.symbol(), "?".cyan());
assert_eq!(Status::Aborted.symbol(), "✘".red());
assert_eq!(Status::Done.symbol(), "✔".green());
}
#[test]
fn status_is_pending() {
assert!(Status::Pending.is_pending());
assert!(!Status::Aborted.is_pending());
assert!(!Status::Done.is_pending());
}
#[test]
fn status_is_aborted() {
assert!(!Status::Pending.is_aborted());
assert!(Status::Aborted.is_aborted());
assert!(!Status::Done.is_aborted());
}
#[test]
fn status_is_done() {
assert!(!Status::Pending.is_done());
assert!(!Status::Aborted.is_done());
assert!(Status::Done.is_done());
}
#[test]
fn status_is_finished() {
assert!(!Status::Pending.is_finished());
assert!(Status::Aborted.is_finished());
assert!(Status::Done.is_finished());
}
#[test]
fn status_default() {
assert_eq!(Status::default(), Status::Pending);
}
#[test]
fn symbols_default() {
assert_eq!(
Symbols::default(),
Symbols {
pending: "?".cyan(),
aborted: "✘".red(),
done: "✔".green(),
}
);
}
#[test]
fn symbols_custom() {
let symbols = Symbols {
pending: "P".cyan(),
aborted: "A".red(),
done: "D".green(),
};
assert_eq!(symbols.pending, "P".cyan());
assert_eq!(symbols.aborted, "A".red());
assert_eq!(symbols.done, "D".green());
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-prompts/src/prompt.rs | tui-prompts/src/prompt.rs | use std::iter::once;
use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use itertools::chain;
use ratatui_core::layout::Rect;
use ratatui_core::terminal::Frame;
use ratatui_core::widgets::StatefulWidget;
use unicode_width::UnicodeWidthChar;
use crate::Status;
/// A prompt that can be drawn to a terminal.
pub trait Prompt: StatefulWidget {
/// Draws the prompt widget.
///
/// This is in addition to the [`StatefulWidget`] trait implementation as we need the [`Frame`]
/// to set the cursor position.
///
/// [`StatefulWidget`]: ratatui_core::widgets::StatefulWidget
/// [`Frame`]: ratatui_core::terminal::Frame
fn draw(self, frame: &mut Frame, area: Rect, state: &mut Self::State);
}
/// The focus state of a prompt.
#[derive(Debug, Clone, Default, Copy, PartialEq, Eq, Hash)]
pub enum FocusState {
#[default]
Unfocused,
Focused,
}
/// The state of a prompt.
///
/// Keybindings:
/// - Enter: Complete
/// - Esc | Ctrl+C: Abort
/// - Left | Ctrl+B: Move cursor left
/// - Right | Ctrl+F: Move cursor right
/// - Home | Ctrl+A: Move cursor to start of line
/// - End | Ctrl+E: Move cursor to end of line
/// - Backspace | Ctrl+H: Delete character before cursor
/// - Delete | Ctrl+D: Delete character after cursor
/// - Ctrl+K: Delete from cursor to end of line
/// - Ctrl+U: Delete from cursor to start of line
pub trait State {
/// The status of the prompt.
fn status(&self) -> Status;
/// A mutable reference to the status of the prompt.
fn status_mut(&mut self) -> &mut Status;
/// A mutable reference to the focus state of the prompt.
fn focus_state_mut(&mut self) -> &mut FocusState;
/// The focus state of the prompt.
fn focus_state(&self) -> FocusState;
/// Sets the focus state of the prompt to [`FocusState::Focused`].
fn focus(&mut self) {
*self.focus_state_mut() = FocusState::Focused;
}
/// Sets the focus state of the prompt to [`FocusState::Unfocused`].
fn blur(&mut self) {
*self.focus_state_mut() = FocusState::Unfocused;
}
/// Whether the prompt is focused.
fn is_focused(&self) -> bool {
self.focus_state() == FocusState::Focused
}
/// The position of the cursor in the prompt.
fn position(&self) -> usize;
/// A mutable reference to the position of the cursor in the prompt.
fn position_mut(&mut self) -> &mut usize;
/// The cursor position of the prompt.
fn cursor(&self) -> (u16, u16);
/// A mutable reference to the cursor position of the prompt.
fn cursor_mut(&mut self) -> &mut (u16, u16);
/// The value of the prompt.
fn value(&self) -> &str;
/// A mutable reference to the value of the prompt.
fn value_mut(&mut self) -> &mut String;
fn len(&self) -> usize {
self.value().chars().count()
}
fn is_empty(&self) -> bool {
self.value().len() == 0
}
fn handle_key_event(&mut self, key_event: KeyEvent) {
if key_event.kind == KeyEventKind::Release {
return;
}
match (key_event.code, key_event.modifiers) {
(KeyCode::Enter, _) => self.complete(),
(KeyCode::Esc, _) | (KeyCode::Char('c'), KeyModifiers::CONTROL) => self.abort(),
(KeyCode::Left, _) | (KeyCode::Char('b'), KeyModifiers::CONTROL) => self.move_left(),
(KeyCode::Right, _) | (KeyCode::Char('f'), KeyModifiers::CONTROL) => self.move_right(),
(KeyCode::Home, _) | (KeyCode::Char('a'), KeyModifiers::CONTROL) => self.move_start(),
(KeyCode::End, _) | (KeyCode::Char('e'), KeyModifiers::CONTROL) => self.move_end(),
(KeyCode::Backspace, _) | (KeyCode::Char('h'), KeyModifiers::CONTROL) => {
self.backspace();
}
(KeyCode::Delete, _) | (KeyCode::Char('d'), KeyModifiers::CONTROL) => self.delete(),
(KeyCode::Char('k'), KeyModifiers::CONTROL) => self.kill(),
(KeyCode::Char('u'), KeyModifiers::CONTROL) => self.truncate(),
(KeyCode::Char(c), KeyModifiers::NONE | KeyModifiers::SHIFT) => self.push(c),
_ => {}
}
}
fn complete(&mut self) {
*self.status_mut() = Status::Done;
}
fn abort(&mut self) {
*self.status_mut() = Status::Aborted;
}
fn delete(&mut self) {
let position = self.position();
if position == self.len() {
return;
}
*self.value_mut() = chain!(
self.value().chars().take(position),
self.value().chars().skip(position + 1)
)
.collect();
}
fn backspace(&mut self) {
let position = self.position();
if position == 0 {
return;
}
*self.value_mut() = chain!(
self.value().chars().take(position.saturating_sub(1)),
self.value().chars().skip(position)
)
.collect();
*self.position_mut() = position.saturating_sub(1);
}
fn move_right(&mut self) {
if self.position() == self.len() {
return;
}
*self.position_mut() = self.position().saturating_add(1);
}
fn move_left(&mut self) {
*self.position_mut() = self.position().saturating_sub(1);
}
fn move_end(&mut self) {
*self.position_mut() = self.len();
}
fn move_start(&mut self) {
*self.position_mut() = 0;
}
fn kill(&mut self) {
let position = self.position();
self.value_mut().truncate(position);
}
fn truncate(&mut self) {
self.value_mut().clear();
*self.position_mut() = 0;
}
fn push(&mut self, c: char) {
if self.position() == self.len() {
self.value_mut().push(c);
} else {
// We cannot use String::insert() as it operates on bytes, which can lead to incorrect
// modifications with multibyte characters. Instead, we handle text
// manipulation at the character level using Rust's char type for Unicode
// correctness. Check docs of String::insert() and String::chars() for futher info.
*self.value_mut() = chain![
self.value().chars().take(self.position()),
once(c),
self.value().chars().skip(self.position())
]
.collect();
}
*self.position_mut() = self.position().saturating_add(1);
}
/// The character width of the stored value up to the position pos.
fn width_to_pos(&self, pos: usize) -> usize {
self.value()
.chars()
.take(pos)
// assign a width of zero to control characters
.map(|x| x.width().unwrap_or(0))
.sum()
}
}
#[cfg(test)]
mod tests {
use ratatui_core::style::Stylize;
use super::*;
#[test]
fn status_symbols() {
assert_eq!(Status::Pending.symbol(), "?".cyan());
assert_eq!(Status::Aborted.symbol(), "✘".red());
assert_eq!(Status::Done.symbol(), "✔".green());
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-prompts/src/text_state.rs | tui-prompts/src/text_state.rs | use std::borrow::Cow;
use crate::prelude::*;
use crate::State;
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
pub struct TextState<'a> {
status: Status,
focus: FocusState,
position: usize,
cursor: (u16, u16),
value: Cow<'a, str>,
}
impl<'a> TextState<'a> {
#[must_use]
pub const fn new() -> Self {
Self {
status: Status::Pending,
focus: FocusState::Unfocused,
position: 0,
cursor: (0, 0),
value: Cow::Borrowed(""),
}
}
#[must_use]
pub const fn with_status(mut self, status: Status) -> Self {
self.status = status;
self
}
#[must_use]
pub const fn with_focus(mut self, focus: FocusState) -> Self {
self.focus = focus;
self
}
#[must_use]
pub fn with_value(mut self, value: impl Into<Cow<'a, str>>) -> Self {
self.value = value.into();
self
}
#[must_use]
pub const fn is_finished(&self) -> bool {
self.status.is_finished()
}
}
impl State for TextState<'_> {
fn status(&self) -> Status {
self.status
}
fn status_mut(&mut self) -> &mut Status {
&mut self.status
}
fn focus_state_mut(&mut self) -> &mut FocusState {
&mut self.focus
}
fn focus_state(&self) -> FocusState {
self.focus
}
fn position(&self) -> usize {
self.position
}
fn position_mut(&mut self) -> &mut usize {
&mut self.position
}
fn cursor(&self) -> (u16, u16) {
self.cursor
}
fn cursor_mut(&mut self) -> &mut (u16, u16) {
&mut self.cursor
}
fn value(&self) -> &str {
&self.value
}
fn value_mut(&mut self) -> &mut String {
self.value.to_mut()
}
}
#[cfg(test)]
mod tests {
use crate::{State, TextState};
#[test]
fn insert_multibyte_start() {
let mut test = TextState::new().with_value("äë");
test.move_start();
test.push('Ï');
assert_eq!(test.value(), "Ïäë");
assert_eq!(test.position(), 1);
}
#[test]
fn insert_multibyte_middle() {
let mut test = TextState::new().with_value("äë");
test.move_right();
test.push('Ï');
assert_eq!(test.value(), "äÏë");
assert_eq!(test.position(), 2);
}
#[test]
fn insert_multibyte_end() {
let mut test = TextState::new().with_value("äë");
test.move_end();
test.push('Ï');
assert_eq!(test.value(), "äëÏ");
assert_eq!(test.position(), 3);
}
#[test]
fn delete_multibyte_start() {
let mut test = TextState::new().with_value("äë");
test.move_start();
test.delete();
assert_eq!(test.value(), "ë");
assert_eq!(test.position(), 0);
}
#[test]
fn delete_multibyte_middle() {
let mut test = TextState::new().with_value("äë");
test.move_right();
test.delete();
assert_eq!(test.value(), "ä");
assert_eq!(test.position(), 1);
}
#[test]
fn delete_multibyte_end() {
let mut test = TextState::new().with_value("äë");
test.move_end();
test.delete();
assert_eq!(test.value(), "äë");
assert_eq!(test.position(), 2);
}
#[test]
fn backspace_multibyte_start() {
let mut test = TextState::new().with_value("äë");
test.move_start();
test.backspace();
assert_eq!(test.value(), "äë");
assert_eq!(test.position(), 0);
}
#[test]
fn backspace_multibyte_middle() {
let mut test = TextState::new().with_value("äë");
test.move_right();
test.backspace();
assert_eq!(test.value(), "ë");
assert_eq!(test.position(), 0);
}
#[test]
fn backspace_multibyte_end() {
let mut test = TextState::new().with_value("äë");
test.move_end();
test.backspace();
assert_eq!(test.value(), "ä");
assert_eq!(test.position(), 1);
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-prompts/src/text_prompt.rs | tui-prompts/src/text_prompt.rs | use std::borrow::Cow;
use std::vec;
use itertools::Itertools;
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::Rect;
use ratatui_core::style::Stylize;
use ratatui_core::terminal::Frame;
use ratatui_core::text::{Line, Span};
use ratatui_core::widgets::{StatefulWidget, Widget};
use ratatui_widgets::block::Block;
use ratatui_widgets::paragraph::Paragraph;
use unicode_width::UnicodeWidthStr;
use crate::prelude::*;
// TODO style the widget
// TODO style each element of the widget.
// TODO handle multi-line input.
// TODO handle scrolling.
// TODO handle vertical movement.
// TODO handle bracketed paste.
/// A prompt widget that displays a message and a text input.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct TextPrompt<'a> {
/// The message to display to the user before the input.
message: Cow<'a, str>,
/// The block to wrap the prompt in.
block: Option<Block<'a>>,
render_style: TextRenderStyle,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TextRenderStyle {
#[default]
Default,
Password,
Invisible,
}
impl TextRenderStyle {
#[must_use]
pub fn render(&self, state: &TextState) -> String {
match self {
Self::Default => state.value().to_string(),
Self::Password => "*".repeat(state.len()),
Self::Invisible => String::new(),
}
}
}
impl<'a> TextPrompt<'a> {
#[must_use]
pub const fn new(message: Cow<'a, str>) -> Self {
Self {
message,
block: None,
render_style: TextRenderStyle::Default,
}
}
#[must_use]
pub fn with_block(mut self, block: Block<'a>) -> Self {
self.block = Some(block);
self
}
#[must_use]
pub const fn with_render_style(mut self, render_style: TextRenderStyle) -> Self {
self.render_style = render_style;
self
}
}
impl Prompt for TextPrompt<'_> {
/// Draws the prompt widget.
///
/// This is in addition to the `Widget` trait implementation as we need the `Frame` to set the
/// cursor position.
fn draw(self, frame: &mut Frame, area: Rect, state: &mut Self::State) {
frame.render_stateful_widget(self, area, state);
if state.is_focused() {
frame.set_cursor_position(state.cursor());
}
}
}
impl<'a> StatefulWidget for TextPrompt<'a> {
type State = TextState<'a>;
fn render(mut self, mut area: Rect, buf: &mut Buffer, state: &mut Self::State) {
self.render_block(&mut area, buf);
let width = area.width as usize;
let height = area.height as usize;
let value = Span::raw(self.render_style.render(state));
let value_width = value.width();
let line = Line::from(vec![
state.status().symbol(),
" ".into(),
self.message.bold(),
" › ".cyan().dim(),
value,
]);
let prompt_width = line.width() - value_width;
let lines = wrap(line, width).take(height).collect_vec();
// constrain the position to the area
let position = state.width_to_pos(state.position()) + prompt_width;
let position = position.min(area.area() as usize - 1);
let row = position / width;
let column = position % width;
*state.cursor_mut() = (area.x + column as u16, area.y + row as u16);
Paragraph::new(lines).render(area, buf);
}
}
/// wraps a line into multiple lines of the given width.
///
/// This is a character based wrap, not a word based wrap.
///
/// TODO: move this into the `Line` type.
fn wrap(line: Line, width: usize) -> impl Iterator<Item = Line> {
let mut line = line;
std::iter::from_fn(move || {
if line.width() > width {
let (first, second) = line_split_at(line.clone(), width);
line = second;
Some(first)
} else if line.width() > 0 {
let first = line.clone();
line = Line::default();
Some(first)
} else {
None
}
})
}
/// splits a line into two lines at the given position.
///
/// TODO: move this into the `Line` type.
/// TODO: fix this so that it operates on multi-width characters.
fn line_split_at(line: Line, mid: usize) -> (Line, Line) {
let mut first = Line::default();
let mut second = Line::default();
first.alignment = line.alignment;
second.alignment = line.alignment;
for span in line.spans {
let first_width = first.width();
let span_width = span.width();
if first_width + span_width <= mid {
first.spans.push(span);
} else if first_width < mid && first_width + span_width > mid {
let span_mid = mid - first_width;
let (span_first, span_second) = span_split_at(span, span_mid);
first.spans.push(span_first);
second.spans.push(span_second);
} else {
second.spans.push(span);
}
}
(first, second)
}
/// Splits a span into two spans at the given character width
///
/// TODO: move this into the `Span` type.
fn span_split_at(span: Span, mid: usize) -> (Span, Span) {
let mut first = String::new();
let mut second = span.content.to_string();
while first.width() < mid {
first.push(second.remove(0));
}
(
Span::styled(first, span.style),
Span::styled(second, span.style),
)
}
impl TextPrompt<'_> {
fn render_block(&mut self, area: &mut Rect, buf: &mut Buffer) {
if let Some(block) = self.block.take() {
let inner = block.inner(*area);
block.render(*area, buf);
*area = inner;
};
}
}
impl<T> From<T> for TextPrompt<'static>
where
T: Into<Cow<'static, str>>,
{
fn from(message: T) -> Self {
Self::new(message.into())
}
}
#[cfg(test)]
mod tests {
use ratatui_core::backend::{Backend, TestBackend};
use ratatui_core::layout::Position;
use ratatui_core::style::{Color, Modifier};
use ratatui_core::terminal::Terminal;
use ratatui_macros::line;
use ratatui_widgets::borders::Borders;
use rstest::{fixture, rstest};
use super::*;
use crate::Status;
#[test]
fn new() {
const PROMPT: TextPrompt<'_> = TextPrompt::new(Cow::Borrowed("Enter your name"));
assert_eq!(PROMPT.message, "Enter your name");
assert_eq!(PROMPT.block, None);
assert_eq!(PROMPT.render_style, TextRenderStyle::Default);
}
#[test]
fn default() {
let prompt = TextPrompt::default();
assert_eq!(prompt.message, "");
assert_eq!(prompt.block, None);
assert_eq!(prompt.render_style, TextRenderStyle::Default);
}
#[test]
fn from() {
let prompt = TextPrompt::from("Enter your name");
assert_eq!(prompt.message, "Enter your name");
}
#[test]
fn render() {
let prompt = TextPrompt::from("prompt");
let mut state = TextState::new();
let mut buffer = Buffer::empty(Rect::new(0, 0, 15, 1));
prompt.render(buffer.area, &mut buffer, &mut state);
let line = line!["?".cyan(), " ", "prompt".bold(), " › ".cyan().dim(), " ",];
assert_eq!(buffer, Buffer::with_lines([line]));
assert_eq!(state.cursor(), (11, 0));
}
#[test]
fn render_emoji() {
let prompt = TextPrompt::from("🔍");
let mut state = TextState::new();
let mut buffer = Buffer::empty(Rect::new(0, 0, 11, 1));
prompt.render(buffer.area, &mut buffer, &mut state);
let line = line!["?".cyan(), " ", "🔍".bold(), " › ".cyan().dim(), " "];
assert_eq!(buffer, Buffer::with_lines([line]));
assert_eq!(state.cursor(), (7, 0));
}
#[test]
fn render_with_done() {
let prompt = TextPrompt::from("prompt");
let mut state = TextState::new().with_status(Status::Done);
let mut buffer = Buffer::empty(Rect::new(0, 0, 15, 1));
prompt.render(buffer.area, &mut buffer, &mut state);
let line = line![
"✔".green(),
" ",
"prompt".bold(),
" › ".cyan().dim(),
" "
];
assert_eq!(buffer, Buffer::with_lines([line]));
}
#[test]
fn render_with_aborted() {
let prompt = TextPrompt::from("prompt");
let mut state = TextState::new().with_status(Status::Aborted);
let mut buffer = Buffer::empty(Rect::new(0, 0, 15, 1));
prompt.render(buffer.area, &mut buffer, &mut state);
let line = line!["✘".red(), " ", "prompt".bold(), " › ".cyan().dim(), " "];
assert_eq!(buffer, Buffer::with_lines([line]));
}
#[test]
fn render_with_value() {
let prompt = TextPrompt::from("prompt");
let mut state = TextState::new().with_value("value");
let mut buffer = Buffer::empty(Rect::new(0, 0, 30, 1));
prompt.render(buffer.area, &mut buffer, &mut state);
let line = line![
"?".cyan(),
" ",
"prompt".bold(),
" › ".cyan().dim(),
"value ".to_string()
];
assert_eq!(buffer, Buffer::with_lines([line]));
}
#[test]
fn render_with_block() {
let prompt = TextPrompt::from("prompt")
.with_block(Block::default().borders(Borders::ALL).title("Title"));
let mut state = TextState::new();
let mut buffer = Buffer::empty(Rect::new(0, 0, 15, 3));
prompt.render(buffer.area, &mut buffer, &mut state);
let mut expected = Buffer::with_lines(vec![
"┌Title────────┐",
"│? prompt › │",
"└─────────────┘",
]);
expected.set_style(Rect::new(1, 1, 1, 1), Color::Cyan);
expected.set_style(Rect::new(3, 1, 6, 1), Modifier::BOLD);
expected.set_style(Rect::new(9, 1, 3, 1), (Color::Cyan, Modifier::DIM));
assert_eq!(buffer, expected);
}
#[test]
fn render_password() {
let prompt = TextPrompt::from("prompt").with_render_style(TextRenderStyle::Password);
let mut state = TextState::new().with_value("value");
let mut buffer = Buffer::empty(Rect::new(0, 0, 30, 1));
prompt.render(buffer.area, &mut buffer, &mut state);
let line = line![
"?".cyan(),
" ",
"prompt".bold(),
" › ".cyan().dim(),
"***** ".to_string()
];
assert_eq!(buffer, Buffer::with_lines([line]));
}
#[test]
fn render_invisible() {
let prompt = TextPrompt::from("prompt").with_render_style(TextRenderStyle::Invisible);
let mut state = TextState::new().with_value("value");
let mut buffer = Buffer::empty(Rect::new(0, 0, 30, 1));
prompt.render(buffer.area, &mut buffer, &mut state);
let line = line![
"?".cyan(),
" ",
"prompt".bold(),
" › ".cyan().dim(),
" ".to_string()
];
assert_eq!(buffer, Buffer::with_lines([line]));
}
#[fixture]
fn terminal() -> Terminal<TestBackend> {
Terminal::new(TestBackend::new(17, 2)).unwrap()
}
type Result<T> = std::result::Result<T, core::convert::Infallible>;
#[rstest]
fn draw_not_focused<'a>(mut terminal: Terminal<TestBackend>) -> Result<()> {
let prompt = TextPrompt::from("prompt");
let mut state = TextState::new().with_value("hello");
// The cursor is not changed when the prompt is not focused.
let _ = terminal.draw(|frame| prompt.draw(frame, frame.area(), &mut state))?;
assert_eq!(state.cursor(), (11, 0));
assert_eq!(
terminal.backend_mut().get_cursor_position().unwrap(),
Position::ORIGIN
);
Ok(())
}
#[rstest]
fn draw_focused<'a>(mut terminal: Terminal<TestBackend>) -> Result<()> {
let prompt = TextPrompt::from("prompt");
let mut state = TextState::new().with_value("hello");
// The cursor is changed when the prompt is focused.
state.focus();
let _ = terminal.draw(|frame| prompt.clone().draw(frame, frame.area(), &mut state))?;
assert_eq!(state.cursor(), (11, 0));
assert_eq!(
terminal.backend_mut().get_cursor_position().unwrap(),
Position::new(11, 0)
);
Ok(())
}
#[rstest]
#[case::position_0(0, (11, 0))] // start of value
#[case::position_3(2, (13, 0))] // middle of value
#[case::position_4(4, (15, 0))] // last character of value
#[case::position_5(5, (16, 0))] // one character beyond the value
fn draw_unwrapped_position<'a>(
#[case] position: usize,
#[case] expected_cursor: (u16, u16),
mut terminal: Terminal<TestBackend>,
) -> Result<()> {
let prompt = TextPrompt::from("prompt");
let mut state = TextState::new().with_value("hello");
// expected: "? prompt › hello "
// " "
// position: 012345
// cursor: 01234567890123456
// The cursor is changed when the prompt is focused and the position is changed.
state.focus();
*state.position_mut() = position;
let _ = terminal.draw(|frame| prompt.clone().draw(frame, frame.area(), &mut state))?;
assert_eq!(state.cursor(), expected_cursor);
assert_eq!(terminal.get_cursor_position()?, expected_cursor.into());
Ok(())
}
#[rstest]
#[case::position_0(0, (11, 0))]
#[case::position_1(1, (13, 0))]
#[case::position_2(2, (15, 0))]
#[case::position_3(3, (0, 1))]
fn draw_wrapped_position_fullwidth<'a>(
#[case] position: usize,
#[case] expected_cursor: (u16, u16),
mut terminal: Terminal<TestBackend>,
) -> Result<()> {
let prompt = TextPrompt::from("prompt");
let mut state = TextState::new().with_value("ほげほげほげ");
state.focus();
*state.position_mut() = position;
let _ = terminal.draw(|frame| prompt.clone().draw(frame, frame.area(), &mut state))?;
assert_eq!(state.cursor(), expected_cursor);
assert_eq!(terminal.get_cursor_position()?, expected_cursor.into());
Ok(())
}
#[rstest]
#[case::position_0(0, (12, 0))]
#[case::position_1(1, (14, 0))]
#[ignore]
#[case::position_2(2, (0, 1))]
#[ignore]
#[case::position_3(3, (2, 1))]
fn draw_wrapped_position_fullwidth_shift_by_one<'a>(
#[case] position: usize,
#[case] expected_cursor: (u16, u16),
mut terminal: Terminal<TestBackend>,
) -> Result<()> {
let prompt = TextPrompt::from("prompt2");
let mut state = TextState::new().with_value("ほげほげほげ");
state.focus();
*state.position_mut() = position;
let _ = terminal.draw(|frame| prompt.clone().draw(frame, frame.area(), &mut state))?;
assert_eq!(state.cursor(), expected_cursor);
assert_eq!(terminal.get_cursor_position()?, expected_cursor.into());
Ok(())
}
#[rstest]
#[case::position_0(0, (11, 0))] // start of value
#[case::position_1(3, (14, 0))] // middle of value
#[case::position_5(5, (16, 0))] // end of line
#[case::position_6(6, (0, 1))] // first character of the second line
#[case::position_7(7, (1, 1))] // second character of the second line
#[case::position_11(10, (4, 1))] // last character of the value
#[case::position_12(11, (5, 1))] // one character beyond the value
fn draw_wrapped_position<'a>(
#[case] position: usize,
#[case] expected_cursor: (u16, u16),
mut terminal: Terminal<TestBackend>,
) -> Result<()> {
let prompt = TextPrompt::from("prompt");
let mut state = TextState::new().with_value("hello world");
// line 1: "? prompt › hello "
// position: 012345
// cursor: 01234567890123456
// line 2: "world "
// position: 678901
// cursor: 01234567890123456
// The cursor is changed when the prompt is focused and the position is changed.
state.focus();
*state.position_mut() = position;
let _ = terminal.draw(|frame| prompt.clone().draw(frame, frame.area(), &mut state))?;
assert_eq!(state.cursor(), expected_cursor);
assert_eq!(terminal.get_cursor_position()?, expected_cursor.into());
Ok(())
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-prompts/examples/text.rs | tui-prompts/examples/text.rs | mod tui;
use std::thread::sleep;
use std::time::Duration;
use clap::Parser;
use color_eyre::Result;
use ratatui::crossterm::event::{self, Event, KeyEvent, KeyModifiers};
use ratatui::prelude::*;
use ratatui::widgets::*;
use tui::Tui;
use tui_prompts::prelude::*;
#[derive(Parser)]
struct Cli {
#[arg(short, long)]
debug: bool,
}
fn main() -> Result<()> {
let cli = Cli::parse();
let mut app = App::new(cli);
app.run()?;
Ok(())
}
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
struct App<'a> {
debug: bool,
current_field: Field,
username_state: TextState<'a>,
password_state: TextState<'a>,
invisible_state: TextState<'a>,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
enum Field {
#[default]
Username,
Password,
Invisible,
}
impl<'a> App<'a> {
pub fn new(cli: Cli) -> Self {
Self {
debug: cli.debug,
..Default::default()
}
}
pub fn run(&mut self) -> Result<()> {
let mut tui = Tui::new()?;
*self.current_state().focus_state_mut() = FocusState::Focused;
while !self.is_finished() {
self.handle_events()?;
tui.draw(|frame| self.draw_ui(frame))?;
}
tui.hide_cursor()?;
// wait two seconds before exiting so the user can see the final state of the UI.
sleep(Duration::from_secs(2));
Ok(())
}
fn handle_events(&mut self) -> Result<()> {
if event::poll(Duration::from_millis(16))? {
if let Event::Key(key_event) = event::read()? {
self.handle_key_event(key_event);
}
}
Ok(())
}
fn draw_ui(&mut self, frame: &mut Frame) {
let (username_area, password_area, invisible_area, value_area, debug_area) =
self.split_layout(frame.area());
self.draw_text_prompt(frame, username_area);
self.draw_password_prompt(frame, password_area);
self.draw_invisible_prompt(frame, invisible_area);
self.draw_state_value(frame, value_area);
self.draw_debug(frame, debug_area);
}
/// split the frame into 5 areas:
/// - username prompt
/// - password prompt
/// - invisible prompt
/// - state value
/// - debug area
///
/// The debug area is only visible if the `debug` flag is set.
fn split_layout(&self, area: Rect) -> (Rect, Rect, Rect, Rect, Rect) {
let (prompt_area, debug_area) = if self.debug {
let areas = Layout::default()
.direction(Direction::Horizontal)
.constraints(vec![Constraint::Ratio(1, 2); 2])
.split(area);
(areas[0], areas[1])
} else {
(area, area)
};
let areas = Layout::default()
.direction(Direction::Vertical)
.constraints(vec![Constraint::Length(1); 4])
.split(prompt_area);
(areas[0], areas[1], areas[2], areas[3], debug_area)
}
fn draw_text_prompt(&mut self, frame: &mut Frame, username_area: Rect) {
TextPrompt::from("Username").draw(frame, username_area, &mut self.username_state);
}
fn draw_password_prompt(&mut self, frame: &mut Frame, password_area: Rect) {
TextPrompt::from("Password")
.with_render_style(TextRenderStyle::Password)
.draw(frame, password_area, &mut self.password_state);
}
fn draw_invisible_prompt(&mut self, frame: &mut Frame, invisible_area: Rect) {
TextPrompt::from("Invisible")
.with_render_style(TextRenderStyle::Invisible)
.draw(frame, invisible_area, &mut self.invisible_state);
}
/// draw the value of the current state underneath the prompts.
fn draw_state_value(&mut self, frame: &mut Frame, value_area: Rect) {
let state = self.current_state();
let state = format!(" Value: {}", state.value());
frame.render_widget(
Paragraph::new(state).style(Style::new().dark_gray()),
value_area,
);
}
/// draw a debug string in the top right corner of the screen that shows the current state of
/// the app.
fn draw_debug(&self, frame: &mut Frame, area: Rect) {
if !self.debug {
return;
}
let debug = format!("{self:#?}");
frame.render_widget(
Paragraph::new(debug)
.wrap(Wrap { trim: false })
.block(Block::new().borders(Borders::LEFT)),
area,
);
}
const fn is_finished(&self) -> bool {
self.username_state.is_finished()
&& self.password_state.is_finished()
&& self.invisible_state.is_finished()
}
fn handle_key_event(&mut self, key_event: KeyEvent) {
match (key_event.code, key_event.modifiers) {
(event::KeyCode::Enter, _) => self.submit(),
(event::KeyCode::Tab, KeyModifiers::NONE) => self.focus_next(),
(event::KeyCode::BackTab, KeyModifiers::SHIFT) => self.focus_prev(),
_ => self.focus_handle_event(key_event),
}
}
fn focus_handle_event(&mut self, key_event: KeyEvent) {
let state = self.current_state();
state.handle_key_event(key_event);
}
fn focus_next(&mut self) {
self.current_state().blur();
self.current_field = self.next_field();
self.current_state().focus();
}
fn focus_prev(&mut self) {
self.current_state().blur();
self.current_field = self.prev_field();
self.current_state().focus();
}
fn submit(&mut self) {
self.current_state().complete();
if self.current_state().is_finished() && !self.is_finished() {
self.current_state().blur();
self.current_field = self.next_field();
self.current_state().focus();
}
}
const fn next_field(&self) -> Field {
match self.current_field {
Field::Username => Field::Password,
Field::Password => Field::Invisible,
Field::Invisible => Field::Username,
}
}
const fn prev_field(&self) -> Field {
match self.current_field {
Field::Username => Field::Invisible,
Field::Password => Field::Username,
Field::Invisible => Field::Password,
}
}
const fn current_state(&mut self) -> &mut TextState<'a> {
match self.current_field {
Field::Username => &mut self.username_state,
Field::Password => &mut self.password_state,
Field::Invisible => &mut self.invisible_state,
}
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-prompts/examples/multi_line.rs | tui-prompts/examples/multi_line.rs | mod tui;
use std::panic;
use std::thread::sleep;
use std::time::Duration;
use clap::Parser;
use color_eyre::Result;
use ratatui::crossterm::event::{self, Event, KeyEvent};
use ratatui::crossterm::{self};
use ratatui::prelude::*;
use ratatui::widgets::*;
use tui::Tui;
use tui_prompts::prelude::*;
#[derive(Parser)]
struct Cli {
#[arg(short, long)]
debug: bool,
}
fn main() -> Result<()> {
panic::set_hook(Box::new(|info| {
crossterm::execute!(std::io::stderr(), crossterm::terminal::LeaveAlternateScreen)
.expect("Failed to leave alternate screen");
eprintln!("Panic: {info:?}");
}));
let cli = Cli::parse();
let mut app = App::new(cli);
app.run()?;
Ok(())
}
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
struct App<'a> {
debug: bool,
state: TextState<'a>,
}
impl App<'_> {
pub const fn new(cli: Cli) -> Self {
Self {
debug: cli.debug,
state: TextState::new().with_focus(FocusState::Focused),
}
}
pub fn run(&mut self) -> Result<()> {
let mut tui = Tui::new()?;
while !self.is_finished() {
self.handle_events()?;
tui.draw(|frame| self.draw_ui(frame))?;
}
tui.hide_cursor()?;
// wait two seconds before exiting so the user can see the final state of the UI.
sleep(Duration::from_secs(2));
Ok(())
}
fn handle_events(&mut self) -> Result<()> {
if event::poll(Duration::from_millis(16))? {
if let Event::Key(key_event) = event::read()? {
self.handle_key_event(key_event);
}
}
Ok(())
}
fn draw_ui(&mut self, frame: &mut Frame) {
let (text_area, debug_area) = self.split_layout(frame.area());
self.draw_text_prompt(frame, text_area);
self.draw_debug(frame, debug_area);
}
/// split the frame into 2 areas:
/// - prompt area
/// - debug area
///
/// The debug area is only visible if the `debug` flag is set.
fn split_layout(&self, area: Rect) -> (Rect, Rect) {
if self.debug {
let areas = Layout::default()
.direction(Direction::Horizontal)
.constraints(vec![Constraint::Ratio(1, 2); 2])
.split(area);
let textbox_area = Rect {
height: 4, // 3 lines of text + 1 line of border
..areas[0]
};
(textbox_area, areas[1])
} else {
(area, Rect::default())
}
}
fn draw_text_prompt(&mut self, frame: &mut Frame, area: Rect) {
TextPrompt::from("Multi-line")
.with_block(Block::new().borders(Borders::RIGHT | Borders::BOTTOM))
.draw(frame, area, &mut self.state);
}
/// draw a debug string in the top right corner of the screen that shows the current state of
/// the app.
fn draw_debug(&self, frame: &mut Frame, area: Rect) {
if !self.debug {
return;
}
let debug = format!("{self:#?}");
frame.render_widget(Paragraph::new(debug).wrap(Wrap { trim: false }), area);
}
const fn is_finished(&self) -> bool {
self.state.is_finished()
}
fn handle_key_event(&mut self, key_event: KeyEvent) {
self.state.handle_key_event(key_event);
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-prompts/examples/tui/mod.rs | tui-prompts/examples/tui/mod.rs | use std::io::Stderr;
use std::ops::{Deref, DerefMut};
use color_eyre::Result;
use ratatui::crossterm;
use ratatui::prelude::*;
/// A wrapper around the terminal that enables raw mode on creation and disables it on drop.
pub struct Tui {
terminal: Terminal<CrosstermBackend<Stderr>>,
}
impl Tui {
pub fn new() -> Result<Self> {
let terminal = Self::init()?;
Ok(Self { terminal })
}
fn init() -> Result<Terminal<CrosstermBackend<Stderr>>> {
let buffer = std::io::stderr();
let mut backend = CrosstermBackend::new(buffer);
crossterm::execute!(backend, crossterm::terminal::EnterAlternateScreen)?;
crossterm::terminal::enable_raw_mode()?;
let mut terminal = Terminal::new(backend)?;
terminal.clear()?;
Ok(terminal)
}
fn cleanup(&mut self) -> Result<()> {
crossterm::execute!(
self.terminal.backend_mut(),
crossterm::terminal::LeaveAlternateScreen
)?;
crossterm::terminal::disable_raw_mode()?;
Ok(())
}
}
impl Deref for Tui {
type Target = Terminal<CrosstermBackend<Stderr>>;
fn deref(&self) -> &Self::Target {
&self.terminal
}
}
impl DerefMut for Tui {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.terminal
}
}
impl Drop for Tui {
fn drop(&mut self) {
self.cleanup().unwrap();
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-bar-graph/src/lib.rs | tui-bar-graph/src/lib.rs | //! A [Ratatui] widget to render bold, colorful bar graphs. Part of the [tui-widgets] suite by
//! [Joshka].
//!
//! 
//! 
//! 
//! 
//!
//! <details><summary>More examples</summary>
//!
//! 
//! 
//! 
//! 
//! 
//! 
//! 
//! 
//!
//! </details>
//!
//! Uses the [Colorgrad] crate for gradient coloring.
//!
//! [![Crate badge]][Crate]
//! [![Docs Badge]][Docs]
//! [![Deps Badge]][Dependency Status]
//! [![License Badge]][License]
//! [![Coverage Badge]][Coverage]
//! [![Discord Badge]][Ratatui Discord]
//!
//! [GitHub Repository] · [API Docs] · [Examples] · [Changelog] · [Contributing]
//!
//! # Installation
//!
//! ```shell
//! cargo add ratatui tui-bar-graph
//! ```
//!
//! # Usage
//!
//! Build a `BarGraph` with your data and render it in a widget area.
//!
//! ```rust
//! use tui_bar_graph::{BarGraph, BarStyle, ColorMode};
//!
//! # fn render(frame: &mut ratatui::Frame, area: ratatui::layout::Rect) {
//! let data = vec![0.0, 0.1, 0.2, 0.3, 0.4, 0.5];
//! let bar_graph = BarGraph::new(data)
//! .with_gradient(colorgrad::preset::turbo())
//! .with_bar_style(BarStyle::Braille)
//! .with_color_mode(ColorMode::VerticalGradient);
//! frame.render_widget(bar_graph, area);
//! # }
//! ```
//!
//! # More widgets
//!
//! For the full suite of widgets, see [tui-widgets].
//!
//! [Colorgrad]: https://crates.io/crates/colorgrad
//! [Ratatui]: https://crates.io/crates/ratatui
//! [Crate]: https://crates.io/crates/tui-bar-graph
//! [Docs]: https://docs.rs/tui-bar-graph/
//! [Dependency Status]: https://deps.rs/repo/github/joshka/tui-widgets
//! [Coverage]: https://app.codecov.io/gh/joshka/tui-widgets
//! [Ratatui Discord]: https://discord.gg/pMCEU9hNEj
//! [Crate badge]: https://img.shields.io/crates/v/tui-bar-graph.svg?logo=rust&style=flat
//! [Docs Badge]: https://img.shields.io/docsrs/tui-bar-graph?logo=rust&style=flat
//! [Deps Badge]: https://deps.rs/repo/github/joshka/tui-widgets/status.svg?style=flat
//! [License Badge]: https://img.shields.io/crates/l/tui-bar-graph.svg?style=flat
//! [License]: https://github.com/joshka/tui-widgets/blob/main/LICENSE-MIT
//! [Coverage Badge]:
//! https://img.shields.io/codecov/c/github/joshka/tui-widgets?logo=codecov&style=flat
//! [Discord Badge]: https://img.shields.io/discord/1070692720437383208?logo=discord&style=flat
//!
//! [GitHub Repository]: https://github.com/joshka/tui-widgets
//! [API Docs]: https://docs.rs/tui-bar-graph/
//! [Examples]: https://github.com/joshka/tui-widgets/tree/main/tui-bar-graph/examples
//! [Changelog]: https://github.com/joshka/tui-widgets/blob/main/tui-bar-graph/CHANGELOG.md
//! [Contributing]: https://github.com/joshka/tui-widgets/blob/main/CONTRIBUTING.md
//!
//! [Joshka]: https://github.com/joshka
//! [tui-widgets]: https://crates.io/crates/tui-widgets
use colorgrad::Gradient;
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::Rect;
use ratatui_core::style::Color;
use ratatui_core::widgets::Widget;
use strum::{Display, EnumString};
const BRAILLE_PATTERNS: [[&str; 5]; 5] = [
["⠀", "⢀", "⢠", "⢰", "⢸"],
["⡀", "⣀", "⣠", "⣰", "⣸"],
["⡄", "⣄", "⣤", "⣴", "⣼"],
["⡆", "⣆", "⣦", "⣶", "⣾"],
["⡇", "⣇", "⣧", "⣷", "⣿"],
];
const OCTANT_PATTERNS: [[&str; 5]; 5] = [
["⠀", "", "▗", "", "▐"],
["", "▂", "", "", ""],
["▖", "", "▄", "", "▟"],
["", "", "", "▆", ""],
["▌", "", "▙", "", "█"],
];
#[rustfmt::skip]
const QUADRANT_PATTERNS: [[&str; 3]; 3]= [
[" ", "▗", "▐"],
["▖", "▄", "▟"],
["▌", "▙", "█"],
];
/// A widget for displaying a bar graph.
///
/// The bars can be colored using a gradient, and can be rendered using either solid blocks or
/// braille characters for a more granular appearance.
///
/// # Example
///
/// ```rust
/// use tui_bar_graph::{BarGraph, BarStyle, ColorMode};
///
/// # fn render(frame: &mut ratatui::Frame, area: ratatui::layout::Rect) {
/// let data = vec![0.0, 0.1, 0.2, 0.3, 0.4, 0.5];
/// let bar_graph = BarGraph::new(data)
/// .with_gradient(colorgrad::preset::turbo())
/// .with_bar_style(BarStyle::Braille)
/// .with_color_mode(ColorMode::VerticalGradient);
/// frame.render_widget(bar_graph, area);
/// # }
/// ```
pub struct BarGraph<'g> {
/// The data to display as bars.
data: Vec<f64>,
/// The maximum value to display.
max: Option<f64>,
/// The minimum value to display.
min: Option<f64>,
/// A gradient to use for coloring the bars.
gradient: Option<Box<dyn Gradient + 'g>>,
/// The direction of the gradient coloring.
color_mode: ColorMode,
/// The style of bar to render.
bar_style: BarStyle,
}
/// The direction of the gradient coloring.
///
/// - `Solid`: Each bar has a single color based on its value.
/// - `Gradient`: Each bar is gradient-colored from bottom to top.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ColorMode {
/// Each bar has a single color based on its value.
Solid,
/// Each bar is gradient-colored from bottom to top.
#[default]
VerticalGradient,
}
/// The style of bar to render.
///
/// - `Solid`: Render bars using the full block character '`█`'.
/// - `Quadrant`: Render bars using quadrant block characters for a more granular representation.
/// - `Octant`: Render bars using octant block characters for a more granular representation.
/// - `Braille`: Render bars using braille characters for a more granular representation.
///
/// `Octant` and `Braille` offer the same level of granularity, but `Braille` is more widely
/// supported by fonts.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, EnumString, Display)]
#[strum(serialize_all = "snake_case")]
pub enum BarStyle {
/// Render bars using braille characters `⡀`, `⢀`, `⠄`, `⠠`, `⠂`, `⠐`, `⠁`, and `⠈` for a more
/// granular representation.
#[default]
Braille,
/// Render bars using the full block character '`█`'.
Solid,
/// Render bars using the quadrant block characters `▖`, `▗`, `▘`, and `▝` for a more granular
/// representation.
Quadrant,
/// Render bars using the octant block characters ``, ``, ``, ``, ``, ``, ``, and ``
/// for a more granular representation.
///
/// `Octant` uses characters from the [Symbols for Legacy Computing Supplement] block, which
/// is rendered correctly by a small but growing number of fonts.
///
/// [Symbols for Legacy Computing Supplement]:
/// https://en.wikipedia.org/wiki/Symbols_for_Legacy_Computing_Supplement
Octant,
}
impl<'g> BarGraph<'g> {
/// Creates a new bar graph with the given data.
pub fn new(data: Vec<f64>) -> Self {
Self {
data,
max: None,
min: None,
gradient: None,
color_mode: ColorMode::default(),
bar_style: BarStyle::default(),
}
}
/// Sets the gradient to use for coloring the bars.
///
/// See the [colorgrad] crate for information on creating gradients. Note that the default
/// domain (range) of the gradient is [0, 1], so you may need to scale your data to fit this
/// range, or modify the gradient's domain to fit your data.
pub fn with_gradient(mut self, gradient: impl Gradient + 'g) -> Self {
self.gradient = Some(gradient.boxed());
self
}
/// Sets the maximum value to display.
///
/// Values greater than this will be clamped to this value. If `None`, the maximum value is
/// calculated from the data.
pub fn with_max(mut self, max: impl Into<Option<f64>>) -> Self {
self.max = max.into();
self
}
/// Sets the minimum value to display.
///
/// Values less than this will be clamped to this value. If `None`, the minimum value is
/// calculated from the data.
pub fn with_min(mut self, min: impl Into<Option<f64>>) -> Self {
self.min = min.into();
self
}
/// Sets the color mode for the bars.
///
/// The default is `ColorMode::VerticalGradient`.
///
/// - `Solid`: Each bar has a single color based on its value.
/// - `Gradient`: Each bar is gradient-colored from bottom to top.
pub const fn with_color_mode(mut self, color: ColorMode) -> Self {
self.color_mode = color;
self
}
/// Sets the style of the bars.
///
/// The default is `BarStyle::Braille`.
///
/// - `Solid`: Render bars using the full block character '`█`'.
/// - `Quadrant`: Render bars using quadrant block characters for a more granular
/// representation.
/// - `Octant`: Render bars using octant block characters for a more granular representation.
/// - `Braille`: Render bars using braille characters for a more granular representation.
///
/// `Octant` and `Braille` offer the same level of granularity, but `Braille` is more widely
/// supported by fonts.
pub const fn with_bar_style(mut self, style: BarStyle) -> Self {
self.bar_style = style;
self
}
/// Renders the graph using solid blocks (█).
fn render_solid(&self, area: Rect, buf: &mut Buffer, min: f64, max: f64) {
let range = max - min;
for (&value, column) in self.data.iter().zip(area.columns()) {
let normalized = (value - min) / range;
let column_height = (normalized * area.height as f64).ceil() as usize;
for (i, row) in column.rows().rev().enumerate().take(column_height) {
let color = self.color_for(area, min, range, value, i);
buf[row].set_symbol("█").set_fg(color);
}
}
}
/// Renders the graph using braille characters.
fn render_braille(&self, area: Rect, buf: &mut Buffer, min: f64, max: f64) {
self.render_pattern(area, buf, min, max, 4, &BRAILLE_PATTERNS);
}
/// Renders the graph using octant blocks.
fn render_octant(&self, area: Rect, buf: &mut Buffer, min: f64, max: f64) {
self.render_pattern(area, buf, min, max, 4, &OCTANT_PATTERNS);
}
/// Renders the graph using quadrant blocks.
fn render_quadrant(&self, area: Rect, buf: &mut Buffer, min: f64, max: f64) {
self.render_pattern(area, buf, min, max, 2, &QUADRANT_PATTERNS);
}
/// Common rendering logic for pattern-based bar styles.
fn render_pattern<const N: usize, const M: usize>(
&self,
area: Rect,
buf: &mut Buffer,
min: f64,
max: f64,
dots_per_row: usize,
patterns: &[[&str; N]; M],
) {
let range = max - min;
let row_count = area.height;
let total_dots = row_count as usize * dots_per_row;
for (chunk, column) in self
.data
.chunks(2)
.zip(area.columns())
.take(area.width as usize)
{
let left_value = chunk[0];
let right_value = chunk.get(1).copied().unwrap_or(min);
let left_normalized = (left_value - min) / range;
let right_normalized = (right_value - min) / range;
let left_total_dots = (left_normalized * total_dots as f64).round() as usize;
let right_total_dots = (right_normalized * total_dots as f64).round() as usize;
let column_height = (left_total_dots.max(right_total_dots) as f64 / dots_per_row as f64)
.ceil() as usize;
for (row_index, row) in column.rows().rev().enumerate().take(column_height) {
let value = f64::midpoint(left_value, right_value);
let color = self.color_for(area, min, max, value, row_index);
let dots_below = row_index * dots_per_row;
let left_dots = left_total_dots.saturating_sub(dots_below).min(dots_per_row);
let right_dots = right_total_dots
.saturating_sub(dots_below)
.min(dots_per_row);
let symbol = patterns[left_dots][right_dots];
buf[row].set_symbol(symbol).set_fg(color);
}
}
}
fn color_for(&self, area: Rect, min: f64, max: f64, value: f64, row: usize) -> Color {
let color_value = match self.color_mode {
ColorMode::Solid => value,
ColorMode::VerticalGradient => {
(row as f64 / area.height as f64).mul_add(max - min, min)
}
};
self.gradient
.as_ref()
.map(|gradient| {
let color = gradient.at(color_value as f32);
let rgba = color.to_rgba8();
// TODO this can be changed to .into() in ratatui 0.30
Color::Rgb(rgba[0], rgba[1], rgba[2])
})
.unwrap_or(Color::Reset)
}
}
impl Widget for BarGraph<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
// f64 doesn't impl Ord because NaN != NaN, so we use fold instead of iter::max/min
let min = self
.min
.unwrap_or_else(|| self.data.iter().copied().fold(f64::INFINITY, f64::min));
let max = self
.max
.unwrap_or_else(|| self.data.iter().copied().fold(f64::NEG_INFINITY, f64::max));
let max = max.max(min + f64::EPSILON); // avoid division by zero if min == max
match self.bar_style {
BarStyle::Braille => self.render_braille(area, buf, min, max),
BarStyle::Solid => self.render_solid(area, buf, min, max),
BarStyle::Quadrant => self.render_quadrant(area, buf, min, max),
BarStyle::Octant => self.render_octant(area, buf, min, max),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn with_gradient() {
let data = vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0];
// check that we can use either a gradient or a boxed gradient
let _graph = BarGraph::new(data.clone()).with_gradient(colorgrad::preset::turbo());
let _graph = BarGraph::new(data).with_gradient(colorgrad::preset::turbo().boxed());
}
#[test]
fn braille() {
let data = (0..=40).map(|i| i as f64 * 0.125).collect();
let bar_graph = BarGraph::new(data);
let mut buf = Buffer::empty(Rect::new(0, 0, 21, 10));
bar_graph.render(buf.area, &mut buf);
assert_eq!(
buf,
Buffer::with_lines(vec![
" ⢀⣴⡇",
" ⢀⣴⣿⣿⡇",
" ⢀⣴⣿⣿⣿⣿⡇",
" ⢀⣴⣿⣿⣿⣿⣿⣿⡇",
" ⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⡇",
" ⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇",
" ⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇",
" ⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇",
" ⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇",
"⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇",
])
);
}
#[test]
fn solid() {
let data = vec![0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0];
let bar_graph = BarGraph::new(data).with_bar_style(BarStyle::Solid);
let mut buf = Buffer::empty(Rect::new(0, 0, 11, 10));
bar_graph.render(buf.area, &mut buf);
assert_eq!(
buf,
Buffer::with_lines(vec![
" █",
" ██",
" ███",
" ████",
" █████",
" ██████",
" ███████",
" ████████",
" █████████",
" ██████████",
])
);
}
#[test]
fn quadrant() {
let data = vec![
0.0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25, 3.5, 3.75,
4.0, 4.25, 4.5, 4.75, 5.0,
];
let bar_graph = BarGraph::new(data).with_bar_style(BarStyle::Quadrant);
let mut buf = Buffer::empty(Rect::new(0, 0, 11, 10));
bar_graph.render(buf.area, &mut buf);
assert_eq!(
buf,
Buffer::with_lines(vec![
" ▗▌",
" ▗█▌",
" ▗██▌",
" ▗███▌",
" ▗████▌",
" ▗█████▌",
" ▗██████▌",
" ▗███████▌",
" ▗████████▌",
"▗█████████▌",
])
);
}
#[test]
fn octant() {
let data = (0..=40).map(|i| i as f64 * 0.125).collect();
let bar_graph = BarGraph::new(data).with_bar_style(BarStyle::Octant);
let mut buf = Buffer::empty(Rect::new(0, 0, 21, 10));
bar_graph.render(buf.area, &mut buf);
assert_eq!(
buf,
Buffer::with_lines(vec![
" ▌",
" ██▌",
" ████▌",
" ██████▌",
" ████████▌",
" ██████████▌",
" ████████████▌",
" ██████████████▌",
" ████████████████▌",
"██████████████████▌",
])
);
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-bar-graph/examples/simple-bar-graph.rs | tui-bar-graph/examples/simple-bar-graph.rs | use crossterm::event::{self, Event, KeyEvent, KeyEventKind};
use rand::Rng;
use ratatui::{DefaultTerminal, Frame};
use tui_bar_graph::{BarGraph, BarStyle, ColorMode};
fn main() -> color_eyre::Result<()> {
color_eyre::install()?;
let terminal = ratatui::init();
let result = run(terminal);
ratatui::restore();
result
}
fn run(mut terminal: DefaultTerminal) -> color_eyre::Result<()> {
loop {
terminal.draw(render)?;
if matches!(
event::read()?,
Event::Key(KeyEvent {
kind: KeyEventKind::Press,
..
})
) {
break Ok(());
}
}
}
fn render(frame: &mut Frame) {
let data_count = frame.area().width as usize * 2;
let mut data = vec![0.0; data_count];
rand::rng().fill(&mut data[..]);
let gradient = colorgrad::preset::rainbow();
let bar_graph = BarGraph::new(data)
.with_gradient(gradient)
.with_color_mode(ColorMode::VerticalGradient)
.with_bar_style(BarStyle::Braille);
frame.render_widget(bar_graph, frame.area());
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-bar-graph/examples/tui-bar-graph.rs | tui-bar-graph/examples/tui-bar-graph.rs | use clap::{Parser, ValueEnum};
use colorgrad::Gradient;
use crossterm::event::{self, Event, KeyEvent, KeyEventKind};
use rand::Rng;
use ratatui::style::palette::tailwind::SLATE;
use ratatui::style::{Color, Stylize};
use ratatui::text::Line;
use ratatui::widgets::{Block, Borders};
use ratatui::{symbols, DefaultTerminal, Frame};
use strum::Display;
use tui_bar_graph::{BarGraph, BarStyle, ColorMode};
#[derive(Debug, Parser)]
struct Args {
/// The style of bar to render (solid, quadrant, octant, or braille)
#[arg(default_value_t = BarStyle::Braille)]
bar_style: BarStyle,
/// The color gradient preset to use
///
/// This is a small selection of the color gradients available in the `colorgrad` crate.
#[arg(default_value_t = Preset::Rainbow)]
preset: Preset,
}
#[derive(Debug, Clone, ValueEnum, Display)]
#[strum(serialize_all = "lowercase")]
enum Preset {
Rainbow,
Sinebow,
Viridis,
Inferno,
Magma,
Plasma,
}
impl Preset {
pub fn to_gradient(&self) -> Box<dyn Gradient> {
match self {
Self::Rainbow => Box::new(colorgrad::preset::rainbow()),
Self::Sinebow => Box::new(colorgrad::preset::sinebow()),
Self::Viridis => Box::new(colorgrad::preset::viridis()),
Self::Inferno => Box::new(colorgrad::preset::inferno()),
Self::Magma => Box::new(colorgrad::preset::magma()),
Self::Plasma => Box::new(colorgrad::preset::plasma()),
}
}
}
fn main() -> color_eyre::Result<()> {
let args = Args::parse();
color_eyre::install()?;
let terminal = ratatui::init();
let result = run(terminal, &args);
ratatui::restore();
result
}
fn run(mut terminal: DefaultTerminal, args: &Args) -> color_eyre::Result<()> {
loop {
terminal.draw(|frame| render(frame, args))?;
if matches!(
event::read()?,
Event::Key(KeyEvent {
kind: KeyEventKind::Press,
..
})
) {
break Ok(());
}
}
}
fn render(frame: &mut Frame, args: &Args) {
const TITLE_FG: Color = SLATE.c800;
const TITLE_BG: Color = SLATE.c100;
const BLOCK_FG: Color = SLATE.c100;
const BLOCK_BG: Color = SLATE.c900;
let title = format!(
"tui-bar-graph - BarStyle: {}, Preset: {}",
args.bar_style, args.preset
);
let block = Block::new()
.borders(Borders::TOP)
.border_set(symbols::border::FULL)
.border_style((TITLE_BG, TITLE_FG))
.style((BLOCK_FG, BLOCK_BG))
.title(
Line::from(title)
.centered()
.bg(TITLE_BG)
.fg(TITLE_FG)
.bold(),
);
frame.render_widget(&block, frame.area());
let area = block.inner(frame.area());
let width = match args.bar_style {
BarStyle::Solid => area.width as usize,
BarStyle::Octant | BarStyle::Braille => area.width as usize * 2,
BarStyle::Quadrant => area.width as usize * 4,
};
let mut data = vec![0.0; width];
rand::rng().fill(&mut data[..]);
let gradient = args.preset.to_gradient();
let bar_graph = BarGraph::new(data)
.with_gradient(gradient)
.with_color_mode(ColorMode::VerticalGradient)
.with_bar_style(args.bar_style);
frame.render_widget(bar_graph, area);
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-box-text/src/lib.rs | tui-box-text/src/lib.rs | //! A [Ratatui] widget to draw delightfully boxy text with line-drawing characters. Part of the
//! [tui-widgets] suite by [Joshka].
//!
//! 
//!
//! [![Crate badge]][Crate]
//! [![Docs Badge]][Docs]
//! [![Deps Badge]][Dependency Status]
//! [![License Badge]][License]
//! [![Coverage Badge]][Coverage]
//! [![Discord Badge]][Ratatui Discord]
//!
//! [GitHub Repository] · [API Docs] · [Examples] · [Changelog] · [Contributing]
//!
//! # Usage
//!
//! Create a `BoxChar` and render it into a region of your frame.
//!
//! ```rust
//! use tui_box_text::BoxChar;
//!
//! # fn draw(frame: &mut ratatui::Frame) {
//! let letter = BoxChar::new('A');
//! frame.render_widget(&letter, frame.area());
//! # }
//! ```
//!
//! # More widgets
//!
//! For the full suite of widgets, see [tui-widgets].
//!
//! [Crate]: https://crates.io/crates/tui-box-text
//! [Docs]: https://docs.rs/tui-box-text/
//! [Dependency Status]: https://deps.rs/repo/github/joshka/tui-widgets
//! [Coverage]: https://app.codecov.io/gh/joshka/tui-widgets
//! [Ratatui Discord]: https://discord.gg/pMCEU9hNEj
//! [Crate badge]: https://img.shields.io/crates/v/tui-box-text?logo=rust&style=flat
//! [Docs Badge]: https://img.shields.io/docsrs/tui-box-text?logo=rust&style=flat
//! [Deps Badge]: https://deps.rs/repo/github/joshka/tui-widgets/status.svg?style=flat
//! [License Badge]: https://img.shields.io/crates/l/tui-box-text?style=flat
//! [License]: https://github.com/joshka/tui-widgets/blob/main/LICENSE-MIT
//! [Coverage Badge]:
//! https://img.shields.io/codecov/c/github/joshka/tui-widgets?logo=codecov&style=flat
//! [Discord Badge]: https://img.shields.io/discord/1070692720437383208?logo=discord&style=flat
//!
//! [GitHub Repository]: https://github.com/joshka/tui-widgets
//! [API Docs]: https://docs.rs/tui-box-text/
//! [Examples]: https://github.com/joshka/tui-widgets/tree/main/tui-box-text/examples
//! [Changelog]: https://github.com/joshka/tui-widgets/blob/main/tui-box-text/CHANGELOG.md
//! [Contributing]: https://github.com/joshka/tui-widgets/blob/main/CONTRIBUTING.md
//! [Joshka]: https://github.com/joshka
//! [tui-widgets]: https://crates.io/crates/tui-widgets
use std::collections::HashMap;
use std::iter::zip;
use std::sync::LazyLock;
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::Rect;
use ratatui_core::widgets::Widget;
pub struct BoxChar(char);
impl BoxChar {
pub const fn new(c: char) -> Self {
Self(c)
}
}
impl Widget for &BoxChar {
fn render(self, area: Rect, buf: &mut Buffer) {
let c = self
.0
.to_uppercase() // TODO: add support for lower case characters
.next()
.and_then(|c| CHARS.get(&c))
.unwrap_or(&" ");
let lines = c.lines().collect::<Vec<_>>();
for (line, row) in zip(lines, area.rows()) {
for (char, cell) in zip(line.chars(), row.columns()) {
buf[cell.as_position()].set_symbol(&char.to_string());
}
}
}
}
/// A macro for creating a hash table that maps single characters to strings.
macro_rules! char_table {
( $($char:expr => $repr:expr),* $(,)? ) => {
{
let mut table = ::std::collections::HashMap::new();
$(
table.insert($char, ::indoc::indoc! {$repr});
)*
table
}
};
}
/// A hash table that maps single characters to strings that are 3 lines high and made up of box
/// drawing characters.
static CHARS: LazyLock<HashMap<char, &str>> = LazyLock::new(|| {
char_table!(
' ' => " ",
'!' => "│
╵
╵",
'"' => "╭╭",
'#' => "┼─┼
┼─┼",
'$' => "╭┼╴
└┼┐
╶┼╯",
'%' => "o╱
╱o",
'&' => "╭─╮
╭╲╯
╰─╲",
'\'' => "╭",
'(' => "╭
│
╰",
')' => "╮
│
╯",
'*' => "
*
",
'+' => "
╷
╶┼╴
╵",
',' => "
╯",
'-' => "
──
",
'.' => "
.
",
'/' => "
╱
╱
",
'0' => "╭─╮
│╱│
╰─╯",
'1' => "
╶┐
│
─┴─",
'2' => "╶─╮
┌─┘
└─╴",
'3' => "╶─╮
╶─┤
╶─╯",
'4' => "╷ ╷
╰─┤
╵",
'5' => "┌─╴
└─╮
╰─╯",
'6' => "╭─╴
├─╮
╰─╯",
'7' => "╶─┐
╱
╵ ",
'8' => "╭─╮
├─┤
╰─╯",
'9' => "╭─╮
╰─┤
╶─╯",
':' => "╷
╵
│
",
';' => "╷
╵
╯",
'<' => "
╱
╲
",
'=' => "
──
──",
'>' => "
╲
╱
",
'?' => "
╶─╮
╭╯
╷",
'@' => "╭─╮
╭╮│
╰┴╯",
'A' => "╭─╮
├─┤
╵ ╵",
'B' => "┌╮
├┴╮
╰─╯",
'C' => "╭─╮
│
╰─╯",
'D' => "┌─╮
│ │
└─╯",
'E' => "┌─╴
├─
└─╴",
'F' => "┌─╴
├─
╵ ",
'G' => "╭─╮
│─╮
╰─╯",
'H' => "╷ ╷
├─┤
╵ ╵",
'I' => "╶┬╴
│
╶┴╴",
'J' => " ╶┐
│
╰─╯",
'K' => "╷╭
├┴╮
╵ ╵",
'L' => "╷
│
└──",
'M' => "╭┬╮
│││
╵╵╵",
'N' => "╭─╮
│ │
╵ ╵",
'O' => "╭─╮
│ │
╰─╯",
'P' => "┌─╮
├─╯
╵ ",
'Q' => "╭─╮
│ │
╰─╳",
'R' => "┌─╮
├┬╯
╵╰ ",
'S' => "╭─╮
╰─╮
╰─╯",
'T' => "
╶┬╴
│
╵",
'U' => "╷ ╷
│ │
╰─╯",
'V' => "╷ ╷
│ │
└─╯",
'W' => "╷╷╷
│││
╰┴╯",
'X' => "╮ ╭
╰─╮
╯ ╰",
'Y' => "╮ ╭
╰┬╯
╵",
'Z' => "╶─╮
╱
╰─╴",
'[' => "┌─
│
└─",
'\\' => "
╲
╲
",
']' => "─┐
│
─┘",
'^' => "╱╲",
'_' => "
──",
'`' => "╮",
'{' => "
╭
┤
╰",
'|' => "│
│
│",
'}' => "╮
├
╯",
'~' => "
╭╮
╰╯",
)
});
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-box-text/examples/box_text.rs | tui-box-text/examples/box_text.rs | use std::iter::zip;
use color_eyre::eyre::Ok;
use ratatui::crossterm::event::{self, Event, KeyCode};
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::text::Line;
use ratatui::{DefaultTerminal, Frame};
use tui_box_text::BoxChar;
fn main() -> color_eyre::Result<()> {
color_eyre::install()?;
let terminal = ratatui::init();
let result = run(terminal);
ratatui::restore();
result
}
fn run(mut terminal: DefaultTerminal) -> color_eyre::Result<()> {
loop {
terminal.draw(draw)?;
if matches!(event::read()?, Event::Key(key) if key.code == KeyCode::Esc) {
break Ok(());
}
}
}
fn draw(frame: &mut Frame) {
let layout = Layout::vertical([Constraint::Length(1), Constraint::Fill(1)]);
let [header, body] = layout.areas(frame.area());
frame.render_widget(
Line::from("Tui-box-text. Press Esc to exit").centered(),
header,
);
let mut areas = Vec::new();
for y in (body.top() + 3..body.bottom()).step_by(3) {
for x in (body.left() + 4..body.right()).step_by(4) {
areas.push(Rect::new(x - 4, y - 3, 4, 3));
}
}
for (c, area) in zip(' '..='~', areas) {
let box_char = BoxChar::new(c);
frame.render_widget(&box_char, area);
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-popup/src/lib.rs | tui-popup/src/lib.rs | //! A [Ratatui] widget to show a snappy popup overlay. Part of the [tui-widgets] suite by [Joshka].
//!
//! 
//!
//! The popup widget is a simple widget that renders a popup in the center of the screen.
//!
//! [![Crate badge]][Crate]
//! [![Docs Badge]][Docs]
//! [![Deps Badge]][Dependency Status]
//! [![License Badge]][License]
//! [![Coverage Badge]][Coverage]
//! [![Discord Badge]][Ratatui Discord]
//!
//! [GitHub Repository] · [API Docs] · [Examples] · [Changelog] · [Contributing]
//!
//! # Installation
//!
//! ```shell
//! cargo add tui-popup
//! ```
//!
//! # Usage
//!
//! Build a `Popup` with content and render it over your frame.
//!
//! ```rust
//! use ratatui::style::{Style, Stylize};
//! use ratatui::Frame;
//! use tui_popup::Popup;
//!
//! fn render_popup(frame: &mut Frame) {
//! let popup = Popup::new("Press any key to exit")
//! .title("tui-popup demo")
//! .style(Style::new().white().on_blue());
//! frame.render_widget(popup, frame.area());
//! }
//! ```
//!
//! # State
//!
//! The widget supports storing the position of the popup in `PopupState`. This is experimental and
//! the exact API for this will likely change.
//!
//! ```rust
//! # #[cfg(feature = "crossterm")]
//! # {
//! use crossterm::event::{KeyCode, KeyEvent};
//! use ratatui::style::{Style, Stylize};
//! use ratatui::Frame;
//! use tui_popup::{Popup, PopupState};
//!
//! fn render_stateful_popup(frame: &mut Frame, popup_state: &mut PopupState) {
//! let popup = Popup::new("Press any key to exit")
//! .title("tui-popup demo")
//! .style(Style::new().white().on_blue());
//! frame.render_stateful_widget(popup, frame.area(), popup_state);
//! }
//!
//! fn handle_key(event: KeyEvent, state: &mut PopupState) {
//! match event.code {
//! KeyCode::Up => state.move_up(1),
//! KeyCode::Down => state.move_down(1),
//! KeyCode::Left => state.move_left(1),
//! KeyCode::Right => state.move_right(1),
//! _ => {}
//! }
//! }
//! # }
//! ```
//!
//! The popup can automatically handle being moved around by the mouse, by passing in the column and
//! row of mouse up, down, or drag events.
//!
//! ```rust
//! # #[cfg(feature = "crossterm")]
//! # {
//! use crossterm::event::{Event, MouseButton, MouseEventKind};
//! use tui_popup::PopupState;
//!
//! fn handle_mouse(event: Event, popup_state: &mut PopupState) {
//! if let Event::Mouse(event) = event {
//! match event.kind {
//! MouseEventKind::Down(MouseButton::Left) => {
//! popup_state.mouse_down(event.column, event.row)
//! }
//! MouseEventKind::Up(MouseButton::Left) => {
//! popup_state.mouse_up(event.column, event.row);
//! }
//! MouseEventKind::Drag(MouseButton::Left) => {
//! popup_state.mouse_drag(event.column, event.row);
//! }
//! _ => {}
//! }
//! }
//! }
//! # }
//! ```
//!
//! The popup also supports rendering arbitrary widgets by implementing [`KnownSize`] (or wrapping
//! them with [`KnownSizeWrapper`]). This makes it possible to support wrapping and scrolling in a
//! `Paragraph` widget, or scrolling any amount of widgets using [tui-scrollview].
//!
//! ```rust
//! use ratatui::prelude::*;
//! use ratatui::text::{Span, Text};
//! use ratatui::widgets::Paragraph;
//! use tui_popup::{KnownSizeWrapper, Popup};
//!
//! fn render_scrollable_popup(frame: &mut Frame, scroll: u16) {
//! let lines: Text = (0..10).map(|i| Span::raw(format!("Line {}", i))).collect();
//! let paragraph = Paragraph::new(lines).scroll((scroll, 0));
//! let sized_paragraph = KnownSizeWrapper {
//! inner: paragraph,
//! width: 21,
//! height: 5,
//! };
//! let popup = Popup::new(sized_paragraph)
//! .title("scroll: ↑/↓ quit: Esc")
//! .style(Style::new().white().on_blue());
//! frame.render_widget(popup, frame.area());
//! }
//! ```
//!
//! 
//!
//! # Features
//!
//! - [x] automatically centers
//! - [x] automatically sizes to content
//! - [x] style popup
//! - [x] move the popup (using state)
//! - [x] handle mouse events for dragging
//! - [x] move to position
//! - [ ] resize
//! - [ ] set border set / style
//! - [ ] add close button
//! - [ ] add nicer styling of header etc.
//! - [ ] configure text wrapping in body to conform to a specific size
//!
//! # More widgets
//!
//! For the full suite of widgets, see [tui-widgets].
//!
//!
//! [Crate]: https://crates.io/crates/tui-popup
//! [Docs]: https://docs.rs/tui-popup/
//! [Dependency Status]: https://deps.rs/repo/github/joshka/tui-widgets
//! [Coverage]: https://app.codecov.io/gh/joshka/tui-widgets
//! [Ratatui Discord]: https://discord.gg/pMCEU9hNEj
//! [Crate badge]: https://img.shields.io/crates/v/tui-popup?logo=rust&style=flat
//! [Docs Badge]: https://img.shields.io/docsrs/tui-popup?logo=rust&style=flat
//! [Deps Badge]: https://deps.rs/repo/github/joshka/tui-widgets/status.svg?style=flat
//! [License Badge]: https://img.shields.io/crates/l/tui-popup?style=flat
//! [License]: https://github.com/joshka/tui-widgets/blob/main/LICENSE-MIT
//! [Coverage Badge]:
//! https://img.shields.io/codecov/c/github/joshka/tui-widgets?logo=codecov&style=flat
//! [Discord Badge]: https://img.shields.io/discord/1070692720437383208?logo=discord&style=flat
//!
//! [GitHub Repository]: https://github.com/joshka/tui-widgets
//! [API Docs]: https://docs.rs/tui-popup/
//! [Examples]: https://github.com/joshka/tui-widgets/tree/main/tui-popup/examples
//! [Changelog]: https://github.com/joshka/tui-widgets/blob/main/tui-popup/CHANGELOG.md
//! [Contributing]: https://github.com/joshka/tui-widgets/blob/main/CONTRIBUTING.md
//! [KnownSize]: https://docs.rs/tui-popup/latest/tui_popup/trait.KnownSize.html
//! [KnownSizeWrapper]: https://docs.rs/tui-popup/latest/tui_popup/struct.KnownSizeWrapper.html
//! [tui-scrollview]: https://crates.io/crates/tui-scrollview
//!
//! [Joshka]: https://github.com/joshka
//! [tui-widgets]: https://crates.io/crates/tui-widgets
#![cfg_attr(docsrs, doc = "\n# Feature flags\n")]
#![cfg_attr(docsrs, doc = document_features::document_features!())]
mod known_size;
mod known_size_wrapper;
mod popup;
mod popup_state;
pub use crate::known_size::KnownSize;
pub use crate::known_size_wrapper::KnownSizeWrapper;
pub use crate::popup::Popup;
pub use crate::popup_state::{DragState, PopupState};
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-popup/src/known_size_wrapper.rs | tui-popup/src/known_size_wrapper.rs | use std::fmt::Debug;
use derive_setters::Setters;
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::Rect;
use ratatui_core::widgets::Widget;
use crate::KnownSize;
/// The `KnownSizeWrapper` struct wraps a widget and provides a fixed size for it.
///
/// This struct is used to wrap a widget and provide a fixed size for it. This is useful when you
/// want to use a widget that does not implement [`KnownSize`] as the body of a popup.
#[derive(Debug, Setters)]
pub struct KnownSizeWrapper<W> {
#[setters(skip)]
pub inner: W,
pub width: usize,
pub height: usize,
}
impl<W: Widget> Widget for KnownSizeWrapper<W> {
fn render(self, area: Rect, buf: &mut Buffer) {
self.inner.render(area, buf);
}
}
impl<W> Widget for &KnownSizeWrapper<W>
where
for<'a> &'a W: Widget,
{
fn render(self, area: Rect, buf: &mut Buffer) {
self.inner.render(area, buf);
}
}
impl<W> KnownSize for KnownSizeWrapper<W> {
fn width(&self) -> usize {
self.width
}
fn height(&self) -> usize {
self.height
}
}
impl<W> KnownSize for &KnownSizeWrapper<W> {
fn width(&self) -> usize {
self.width
}
fn height(&self) -> usize {
self.height
}
}
impl<W> KnownSizeWrapper<W> {
/// Create a new `KnownSizeWrapper` with the given widget and size.
pub const fn new(inner: W, width: usize, height: usize) -> Self {
Self {
inner,
width,
height,
}
}
}
#[cfg(test)]
mod tests {
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::Rect;
use ratatui_core::widgets::Widget;
use super::*;
struct TestWidget;
impl Widget for TestWidget {
fn render(self, area: Rect, buf: &mut Buffer) {
"Hello".render(area, buf);
}
}
#[test]
fn test_sized_wrapper_new() {
let widget = TestWidget;
let wrapper = KnownSizeWrapper::new(widget, 10, 20);
assert_eq!(wrapper.width, 10);
assert_eq!(wrapper.height, 20);
}
#[test]
fn test_sized_wrapper_render() {
let widget = TestWidget;
let wrapper = KnownSizeWrapper::new(widget, 20, 5);
let mut buffer = Buffer::empty(Rect::new(0, 0, 20, 5));
wrapper.render(buffer.area, &mut buffer);
let expected = Buffer::with_lines([
"Hello ",
" ",
" ",
" ",
" ",
]);
assert_eq!(buffer, expected);
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-popup/src/known_size.rs | tui-popup/src/known_size.rs | use ratatui_core::text::Text;
/// A trait for widgets that have a fixed size.
///
/// This trait allows the popup to automatically size itself based on the size of the body widget.
/// Implementing this trait for a widget allows it to be used as the body of a popup. You can also
/// wrap existing widgets in a newtype and implement this trait for the newtype to use them as the
/// body of a popup.
///
/// This trait was previously called `SizedWidgetRef`, but was renamed to [`KnownSize`] to avoid
/// confusion with the `WidgetRef` trait from `ratatui`.
pub trait KnownSize {
fn width(&self) -> usize;
fn height(&self) -> usize;
}
impl KnownSize for Text<'_> {
fn width(&self) -> usize {
self.width()
}
fn height(&self) -> usize {
self.height()
}
}
impl KnownSize for &Text<'_> {
fn width(&self) -> usize {
Text::width(self)
}
fn height(&self) -> usize {
Text::height(self)
}
}
impl KnownSize for &str {
fn width(&self) -> usize {
Text::from(*self).width()
}
fn height(&self) -> usize {
Text::from(*self).height()
}
}
impl KnownSize for String {
fn width(&self) -> usize {
Text::from(self.as_str()).width()
}
fn height(&self) -> usize {
Text::from(self.as_str()).height()
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-popup/src/popup.rs | tui-popup/src/popup.rs | use std::fmt;
use derive_setters::Setters;
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::{Constraint, Rect};
use ratatui_core::style::Style;
use ratatui_core::symbols::border::Set;
use ratatui_core::text::Line;
use ratatui_core::widgets::{StatefulWidget, Widget};
use ratatui_widgets::block::Block;
use ratatui_widgets::borders::Borders;
use ratatui_widgets::clear::Clear;
use crate::{KnownSize, PopupState};
/// Configuration for a popup.
///
/// This struct is used to configure a [`Popup`]. It can be created using
/// [`Popup::new`](Popup::new).
///
/// # Example
///
/// ```rust
/// use ratatui::prelude::*;
/// use ratatui::symbols::border;
/// use tui_popup::Popup;
///
/// fn render_popup(frame: &mut Frame) {
/// let popup = Popup::new("Press any key to exit")
/// .title("tui-popup demo")
/// .style(Style::new().white().on_blue())
/// .border_set(border::ROUNDED)
/// .border_style(Style::new().bold());
/// frame.render_widget(popup, frame.area());
/// }
/// ```
#[derive(Setters)]
#[setters(into)]
#[non_exhaustive]
pub struct Popup<'content, W> {
/// The body of the popup.
#[setters(skip)]
pub body: W,
/// The title of the popup.
pub title: Line<'content>,
/// The style to apply to the entire popup.
pub style: Style,
/// The borders of the popup.
pub borders: Borders,
/// The symbols used to render the border.
pub border_set: Set<'content>,
/// Border style
pub border_style: Style,
}
impl<W> fmt::Debug for Popup<'_, W> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// body does not implement Debug, so we can't use #[derive(Debug)]
f.debug_struct("Popup")
.field("body", &"...")
.field("title", &self.title)
.field("style", &self.style)
.field("borders", &self.borders)
.field("border_set", &self.border_set)
.field("border_style", &self.border_style)
.finish()
}
}
impl<W: PartialEq> PartialEq for Popup<'_, W> {
fn eq(&self, other: &Self) -> bool {
self.body == other.body
&& self.title == other.title
&& self.style == other.style
&& self.borders == other.borders
&& self.border_set == other.border_set
&& self.border_style == other.border_style
}
}
impl<W> Popup<'_, W> {
/// Create a new popup with the given title and body with all the borders.
///
/// # Parameters
///
/// - `body` - The body of the popup. This can be any type that can be converted into a
/// [`Text`](ratatui_core::text::Text).
///
/// # Example
///
/// ```rust
/// use tui_popup::Popup;
///
/// let popup = Popup::new("Press any key to exit").title("tui-popup demo");
/// ```
pub fn new(body: W) -> Self {
Self {
body,
borders: Borders::ALL,
border_set: Set::default(),
border_style: Style::default(),
title: Line::default(),
style: Style::default(),
}
}
}
/// Owned render path for a popup.
///
/// Use this when you have an owned `Popup` value and want to render it by value. This is the
/// simplest option for new users, and it works well with common bodies like `&str` or `String`.
///
/// # Example
///
/// ```rust
/// # use ratatui::buffer::Buffer;
/// # use ratatui::layout::Rect;
/// # use ratatui::widgets::Widget;
/// # use tui_popup::Popup;
/// # let mut buffer = Buffer::empty(Rect::new(0, 0, 1, 1));
/// let popup = Popup::new("Body");
/// popup.render(buffer.area, &mut buffer);
/// ```
impl<W: KnownSize + Widget> Widget for Popup<'_, W> {
fn render(self, area: Rect, buf: &mut Buffer) {
let mut state = PopupState::default();
StatefulWidget::render(self, area, buf, &mut state);
}
}
/// Reference render path for a popup body that supports rendering by reference.
///
/// Use this when you want to keep a `Popup` around and render it by reference. This is helpful
/// when the body implements `Widget` for references (such as `Text`), or when you need to avoid
/// rebuilding the widget each frame.
///
/// # Example
///
/// ```rust
/// # use ratatui::buffer::Buffer;
/// # use ratatui::layout::Rect;
/// # use ratatui::text::Text;
/// # use ratatui::widgets::Widget;
/// # use tui_popup::Popup;
/// # let mut buffer = Buffer::empty(Rect::new(0, 0, 1, 1));
/// let popup = Popup::new(Text::from("Body"));
/// let popup_ref = &popup;
/// popup_ref.render(buffer.area, &mut buffer);
/// ```
impl<W> Widget for &Popup<'_, W>
where
W: KnownSize,
for<'a> &'a W: Widget,
{
fn render(self, area: Rect, buf: &mut Buffer) {
let mut state = PopupState::default();
StatefulWidget::render(self, area, buf, &mut state);
}
}
/// Owned stateful render path for a popup.
///
/// Use this when you have a `PopupState` that you want to update across frames and you can pass
/// the popup by value in the render call.
///
/// # Example
///
/// ```rust
/// # use ratatui::buffer::Buffer;
/// # use ratatui::layout::Rect;
/// # use ratatui::widgets::StatefulWidget;
/// # use tui_popup::{Popup, PopupState};
/// # let mut buffer = Buffer::empty(Rect::new(0, 0, 1, 1));
/// let popup = Popup::new("Body");
/// let mut state = PopupState::default();
/// popup.render(buffer.area, &mut buffer, &mut state);
/// ```
impl<W: KnownSize + Widget> StatefulWidget for Popup<'_, W> {
type State = PopupState;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
let area = area.clamp(buf.area);
let popup_area = self.popup_area(state, area);
state.area.replace(popup_area);
Clear.render(popup_area, buf);
let block = Block::default()
.borders(self.borders)
.border_set(self.border_set)
.border_style(self.border_style)
.title(self.title)
.style(self.style);
let inner_area = block.inner(popup_area);
block.render(popup_area, buf);
self.body.render(inner_area, buf);
}
}
/// Reference stateful render path for a popup body that renders by reference.
///
/// Use this when you have long-lived popup data and want to update `PopupState` without moving the
/// popup each frame. This requires the body to support rendering by reference.
///
/// # Example
///
/// ```rust
/// # use ratatui::buffer::Buffer;
/// # use ratatui::layout::Rect;
/// # use ratatui::text::Text;
/// # use ratatui::widgets::StatefulWidget;
/// # use tui_popup::{Popup, PopupState};
/// # let mut buffer = Buffer::empty(Rect::new(0, 0, 1, 1));
/// let popup = Popup::new(Text::from("Body"));
/// let popup_ref = &popup;
/// let mut state = PopupState::default();
/// popup_ref.render(buffer.area, &mut buffer, &mut state);
/// ```
impl<W> StatefulWidget for &Popup<'_, W>
where
W: KnownSize,
for<'a> &'a W: Widget,
{
type State = PopupState;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
let area = area.clamp(buf.area);
let popup_area = self.popup_area(state, area);
state.area.replace(popup_area);
Clear.render(popup_area, buf);
let block = Block::default()
.borders(self.borders)
.border_set(self.border_set)
.border_style(self.border_style)
.title(self.title.clone())
.style(self.style);
let inner_area = block.inner(popup_area);
block.render(popup_area, buf);
self.body.render(inner_area, buf);
}
}
impl<W: KnownSize> Popup<'_, W> {
fn popup_area(&self, state: &mut PopupState, area: Rect) -> Rect {
if let Some(current) = state.area.take() {
return current.clamp(area);
}
let has_top = self.borders.intersects(Borders::TOP);
let has_bottom = self.borders.intersects(Borders::BOTTOM);
let has_left = self.borders.intersects(Borders::LEFT);
let has_right = self.borders.intersects(Borders::RIGHT);
let border_height = usize::from(has_top) + usize::from(has_bottom);
let border_width = usize::from(has_left) + usize::from(has_right);
let height = self.body.height().saturating_add(border_height);
let width = self.body.width().saturating_add(border_width);
let height = u16::try_from(height).unwrap_or(area.height);
let width = u16::try_from(width).unwrap_or(area.width);
area.centered(Constraint::Length(width), Constraint::Length(height))
}
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use ratatui_core::text::Text;
use super::*;
struct RefBody;
impl KnownSize for RefBody {
fn width(&self) -> usize {
11
}
fn height(&self) -> usize {
1
}
}
impl Widget for &RefBody {
fn render(self, area: Rect, buf: &mut Buffer) {
"Hello World".render(area, buf);
}
}
#[test]
fn new() {
let popup = Popup::new("Test Body");
assert_eq!(
popup,
Popup {
body: "Test Body", // &str is a widget
borders: Borders::ALL,
border_set: Set::default(),
border_style: Style::default(),
title: Line::default(),
style: Style::default(),
}
);
}
#[test]
fn render() {
let mut buffer = Buffer::empty(Rect::new(0, 0, 20, 5));
let mut state = PopupState::default();
let expected = Buffer::with_lines([
" ",
" ┌Title──────┐ ",
" │Hello World│ ",
" └───────────┘ ",
" ",
]);
// Check that a popup ref can render a body widget that supports rendering by reference.
let popup = Popup::new(RefBody).title("Title");
StatefulWidget::render(&popup, buffer.area, &mut buffer, &mut state);
assert_eq!(buffer, expected);
// Check that an owned popup can render a widget defined by a ref value (e.g. `&str`).
let popup = Popup::new("Hello World").title("Title");
StatefulWidget::render(popup, buffer.area, &mut buffer, &mut state);
assert_eq!(buffer, expected);
// Check that an owned popup can render a widget defined by a owned value (e.g. `String`).
let popup = Popup::new("Hello World".to_string()).title("Title");
StatefulWidget::render(popup, buffer.area, &mut buffer, &mut state);
assert_eq!(buffer, expected);
// Check that a popup ref can render a reference-supported body with default state.
let popup = Popup::new(Text::from("Hello World")).title("Title");
Widget::render(&popup, buffer.area, &mut buffer);
assert_eq!(buffer, expected);
// Check that an owned popup can render a ref value (e.g. `&str`), with default state.
let popup = Popup::new("Hello World").title("Title");
Widget::render(popup, buffer.area, &mut buffer);
assert_eq!(buffer, expected);
// Check that an owned popup can render an owned value (e.g. `String`), with default state.
let popup = Popup::new("Hello World".to_string()).title("Title");
Widget::render(popup, buffer.area, &mut buffer);
assert_eq!(buffer, expected);
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-popup/src/popup_state.rs | tui-popup/src/popup_state.rs | #[cfg(feature = "crossterm")]
use crossterm::event::{MouseButton, MouseEvent, MouseEventKind};
use derive_getters::Getters;
use ratatui_core::layout::Rect;
#[derive(Clone, Debug, Default, Getters)]
pub struct PopupState {
/// The last rendered area of the popup
pub(crate) area: Option<Rect>,
/// A state indicating whether the popup is being dragged or not
pub(crate) drag_state: DragState,
}
#[derive(Clone, Debug, Default)]
pub enum DragState {
#[default]
NotDragging,
Dragging {
col_offset: u16,
row_offset: u16,
},
}
impl PopupState {
pub fn move_up(&mut self, amount: u16) {
self.move_by(0, -i32::from(amount));
}
pub fn move_down(&mut self, amount: u16) {
self.move_by(0, i32::from(amount));
}
pub fn move_left(&mut self, amount: u16) {
self.move_by(-i32::from(amount), 0);
}
pub fn move_right(&mut self, amount: u16) {
self.move_by(i32::from(amount), 0);
}
/// Move the popup by the given amount.
pub fn move_by(&mut self, x: i32, y: i32) {
if let Some(area) = self.area {
self.area.replace(Rect {
x: i32::from(area.x)
.saturating_add(x)
.try_into()
.unwrap_or(area.x),
y: i32::from(area.y)
.saturating_add(y)
.try_into()
.unwrap_or(area.y),
..area
});
}
}
/// Move the popup to the given position.
pub const fn move_to(&mut self, x: u16, y: u16) {
if let Some(area) = self.area {
self.area.replace(Rect { x, y, ..area });
}
}
/// Set the state to dragging if the mouse click is in the popup title
pub fn mouse_down(&mut self, col: u16, row: u16) {
if let Some(area) = self.area {
if area.contains((col, row).into()) {
self.drag_state = DragState::Dragging {
col_offset: col.saturating_sub(area.x),
row_offset: row.saturating_sub(area.y),
};
}
}
}
/// Set the state to not dragging
pub const fn mouse_up(&mut self, _col: u16, _row: u16) {
self.drag_state = DragState::NotDragging;
}
/// Move the popup if the state is dragging
pub const fn mouse_drag(&mut self, col: u16, row: u16) {
if let DragState::Dragging {
col_offset,
row_offset,
} = self.drag_state
{
if let Some(area) = self.area {
let x = col.saturating_sub(col_offset);
let y = row.saturating_sub(row_offset);
self.area.replace(Rect { x, y, ..area });
}
}
}
#[cfg(feature = "crossterm")]
pub fn handle_mouse_event(&mut self, event: MouseEvent) {
match event.kind {
MouseEventKind::Down(MouseButton::Left) => self.mouse_down(event.column, event.row),
MouseEventKind::Up(MouseButton::Left) => self.mouse_up(event.column, event.row),
MouseEventKind::Drag(MouseButton::Left) => self.mouse_drag(event.column, event.row),
_ => {}
}
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-popup/examples/state.rs | tui-popup/examples/state.rs | use color_eyre::Result;
use lipsum::lipsum;
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind};
use ratatui::prelude::{Constraint, Frame, Layout, Rect, Style, Stylize, Text};
use ratatui::widgets::{Paragraph, Wrap};
use ratatui::DefaultTerminal;
use tui_popup::{Popup, PopupState};
fn main() -> Result<()> {
color_eyre::install()?;
let terminal = ratatui::init();
let result = run(terminal);
ratatui::restore();
result
}
fn run(mut terminal: DefaultTerminal) -> Result<()> {
let mut state = PopupState::default();
let mut exit = false;
while !exit {
terminal.draw(|frame| draw(frame, &mut state))?;
handle_events(&mut state, &mut exit)?;
}
Ok(())
}
fn draw(frame: &mut Frame, state: &mut PopupState) {
let vertical = Layout::vertical([Constraint::Min(0), Constraint::Length(1)]);
let [background_area, status_area] = vertical.areas(frame.area());
render_background(frame, background_area);
render_popup(frame, background_area, state);
render_status_bar(frame, status_area, state);
}
fn render_background(frame: &mut Frame, area: Rect) {
let lorem_ipsum = lipsum(area.area() as usize / 5);
let background = Paragraph::new(lorem_ipsum)
.wrap(Wrap { trim: false })
.dark_gray();
frame.render_widget(background, area);
}
fn render_popup(frame: &mut Frame, area: Rect, state: &mut PopupState) {
let body = Text::from_iter([
"q: exit",
"r: reset",
"j: move down",
"k: move up",
"h: move left",
"l: move right",
]);
let popup = Popup::new(body)
.title("Popup")
.style(Style::new().white().on_blue());
frame.render_stateful_widget(popup, area, state);
}
/// Status bar at the bottom of the screen
///
/// Must be called after rendering the popup widget as it relies on the popup area being set
fn render_status_bar(frame: &mut Frame, area: Rect, state: &PopupState) {
let popup_area = state.area().unwrap_or_default();
let text = format!("Popup area: {popup_area:?}");
let paragraph = Paragraph::new(text).style(Style::new().white().on_black());
frame.render_widget(paragraph, area);
}
fn handle_events(popup: &mut PopupState, exit: &mut bool) -> Result<()> {
match event::read()? {
Event::Key(event) if event.kind == KeyEventKind::Press => {
handle_key_event(event, popup, exit);
}
Event::Mouse(event) => popup.handle_mouse_event(event),
_ => (),
}
Ok(())
}
fn handle_key_event(event: KeyEvent, popup: &mut PopupState, exit: &mut bool) {
match event.code {
KeyCode::Char('q') | KeyCode::Esc => *exit = true,
KeyCode::Char('r') => *popup = PopupState::default(),
KeyCode::Char('j') | KeyCode::Down => popup.move_down(1),
KeyCode::Char('k') | KeyCode::Up => popup.move_up(1),
KeyCode::Char('h') | KeyCode::Left => popup.move_left(1),
KeyCode::Char('l') | KeyCode::Right => popup.move_right(1),
_ => {}
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-popup/examples/popup.rs | tui-popup/examples/popup.rs | use color_eyre::Result;
use lipsum::lipsum;
use ratatui::crossterm::event::{self, Event};
use ratatui::prelude::{Rect, Style, Stylize};
use ratatui::widgets::{Paragraph, Wrap};
use ratatui::Frame;
use tui_popup::Popup;
fn main() -> Result<()> {
color_eyre::install()?;
let mut terminal = ratatui::init();
let result = run(&mut terminal);
ratatui::restore();
result
}
fn run(terminal: &mut ratatui::DefaultTerminal) -> Result<()> {
loop {
terminal.draw(|frame| {
render(frame);
})?;
if matches!(event::read()?, Event::Key(_)) {
break Ok(());
}
}
}
fn render(frame: &mut Frame) {
let area = frame.area();
let background = background(area);
let popup = Popup::new("Press any key to exit")
.title("tui-popup demo")
.style(Style::new().white().on_blue());
frame.render_widget(background, area);
frame.render_widget(popup, area);
}
fn background(area: Rect) -> Paragraph<'static> {
let lorem_ipsum = lipsum(area.area() as usize / 5);
Paragraph::new(lorem_ipsum)
.wrap(Wrap { trim: false })
.dark_gray()
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-popup/examples/paragraph.rs | tui-popup/examples/paragraph.rs | use color_eyre::Result;
use lipsum::lipsum;
use ratatui::crossterm::event::{self, Event, KeyCode};
use ratatui::prelude::{Rect, Span, Style, Stylize, Text};
use ratatui::widgets::{Paragraph, Wrap};
use ratatui::Frame;
use tui_popup::{KnownSizeWrapper, Popup};
fn main() -> Result<()> {
color_eyre::install()?;
let terminal = ratatui::init();
let result = App::default().run(terminal);
ratatui::restore();
result
}
#[derive(Default)]
struct App {
should_exit: bool,
lorem_ipsum: String,
scroll: u16,
}
impl App {
fn run(&mut self, mut terminal: ratatui::DefaultTerminal) -> Result<()> {
self.lorem_ipsum = lipsum(2000);
while !self.should_exit {
terminal.draw(|frame| self.render(frame))?;
self.handle_events()?;
}
Ok(())
}
fn render(&self, frame: &mut Frame) {
let area = frame.area();
self.render_background(frame, area);
self.render_popup(frame);
}
fn render_background(&self, frame: &mut Frame, area: Rect) {
let text = Text::raw(&self.lorem_ipsum);
let paragraph = Paragraph::new(text).wrap(Wrap { trim: false }).dark_gray();
frame.render_widget(paragraph, area);
}
fn render_popup(&self, frame: &mut Frame) {
let lines: Text = (0..10).map(|i| Span::raw(format!("Line {i}"))).collect();
let paragraph = Paragraph::new(lines).scroll((self.scroll, 0));
let wrapper = KnownSizeWrapper {
inner: paragraph,
width: 21,
height: 5,
};
let popup = Popup::new(wrapper)
.title("scroll: ↑/↓ quit: Esc")
.style(Style::new().white().on_blue());
frame.render_widget(popup, frame.area());
}
fn handle_events(&mut self) -> Result<()> {
if let Event::Key(key) = event::read()? {
match key.code {
KeyCode::Char('q') | KeyCode::Esc => self.should_exit = true,
KeyCode::Char('j') | KeyCode::Down => self.scroll_down(),
KeyCode::Char('k') | KeyCode::Up => self.scroll_up(),
_ => {}
}
}
Ok(())
}
const fn scroll_up(&mut self) {
self.scroll = self.scroll.saturating_sub(1);
}
const fn scroll_down(&mut self) {
self.scroll = self.scroll.saturating_add(1);
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-big-text/src/big_text.rs | tui-big-text/src/big_text.rs | use std::cmp::min;
use derive_builder::Builder;
use font8x8::UnicodeFonts;
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::{Alignment, Rect};
use ratatui_core::style::Style;
use ratatui_core::text::{Line, StyledGrapheme};
use ratatui_core::widgets::Widget;
use crate::PixelSize;
/// Displays one or more lines of text using 8x8 pixel characters.
///
/// The text is rendered using the [font8x8](https://crates.io/crates/font8x8) crate.
///
/// Using the `pixel_size` method, you can also chose, how 'big' a pixel should be. Currently a
/// pixel of the 8x8 font can be represented by one full or half (horizontal/vertical/both)
/// character cell of the terminal.
///
/// # Examples
///
/// ```rust
/// use ratatui::prelude::*;
/// use tui_big_text::{BigText, PixelSize};
///
/// BigText::builder()
/// .pixel_size(PixelSize::Full)
/// .style(Style::new().white())
/// .lines(vec![
/// "Hello".red().into(),
/// "World".blue().into(),
/// "=====".into(),
/// ])
/// .build();
/// ```
///
/// Renders:
///
/// ```plain
/// ██ ██ ███ ███
/// ██ ██ ██ ██
/// ██ ██ ████ ██ ██ ████
/// ██████ ██ ██ ██ ██ ██ ██
/// ██ ██ ██████ ██ ██ ██ ██
/// ██ ██ ██ ██ ██ ██ ██
/// ██ ██ ████ ████ ████ ████
///
/// ██ ██ ███ ███
/// ██ ██ ██ ██
/// ██ ██ ████ ██ ███ ██ ██
/// ██ █ ██ ██ ██ ███ ██ ██ █████
/// ███████ ██ ██ ██ ██ ██ ██ ██
/// ███ ███ ██ ██ ██ ██ ██ ██
/// ██ ██ ████ ████ ████ ███ ██
///
/// ███ ██ ███ ██ ███ ██ ███ ██ ███ ██
/// ██ ███ ██ ███ ██ ███ ██ ███ ██ ███
/// ```
#[derive(Debug, Builder, Clone, PartialEq, Eq, Hash)]
#[builder(build_fn(skip))]
#[non_exhaustive]
pub struct BigText<'a> {
/// The text to display
#[builder(default, setter(into))]
pub lines: Vec<Line<'a>>,
/// The style of the widget
///
/// Defaults to `Style::default()`
#[builder(default, setter(into))]
pub style: Style,
/// The size of single glyphs
///
/// Defaults to `PixelSize::default()` (=> PixelSize::Full)
#[builder(default)]
pub pixel_size: PixelSize,
/// The horizontal alignment of the text
///
/// Defaults to `Alignment::default()` (=> Alignment::Left)
#[builder(default)]
pub alignment: Alignment,
}
impl BigText<'static> {
/// Create a new [`BigTextBuilder`] to configure a [`BigText`] widget.
pub fn builder() -> BigTextBuilder<'static> {
BigTextBuilder::default()
}
}
impl BigTextBuilder<'_> {
/// Set the alignment of the text.
pub fn left_aligned(&mut self) -> &mut Self {
self.alignment(Alignment::Left)
}
/// Set the alignment of the text.
pub fn right_aligned(&mut self) -> &mut Self {
self.alignment(Alignment::Right)
}
/// Set the alignment of the text.
pub fn centered(&mut self) -> &mut Self {
self.alignment(Alignment::Center)
}
}
impl<'a> BigTextBuilder<'a> {
/// Build the [`BigText`] widget.
pub fn build(&self) -> BigText<'a> {
BigText {
lines: self.lines.as_ref().cloned().unwrap_or_default(),
style: self.style.unwrap_or_default(),
pixel_size: self.pixel_size.unwrap_or_default(),
alignment: self.alignment.unwrap_or_default(),
}
}
}
impl Widget for BigText<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
let layout = layout(area, &self.pixel_size, self.alignment, &self.lines);
for (line, line_layout) in self.lines.iter().zip(layout) {
for (g, cell) in line.styled_graphemes(self.style).zip(line_layout) {
render_symbol(g, cell, buf, &self.pixel_size);
}
}
}
}
/// Chunk the area into as many x*y cells as possible returned as a 2D iterator of `Rect`s
/// representing the rows of cells. The size of each cell depends on given font size
fn layout<'a>(
area: Rect,
pixel_size: &PixelSize,
alignment: Alignment,
lines: &'a [Line<'a>],
) -> impl IntoIterator<Item = impl IntoIterator<Item = Rect>> + 'a {
let (step_x, step_y) = pixel_size.pixels_per_cell();
let width = 8_u16.div_ceil(step_x);
let height = 8_u16.div_ceil(step_y);
(area.top()..area.bottom())
.step_by(height as usize)
.zip(lines.iter())
.map(move |(y, line)| {
let offset = get_alignment_offset(area.width, width, alignment, line);
(area.left() + offset..area.right())
.step_by(width as usize)
.map(move |x| {
let width = min(area.right() - x, width);
let height = min(area.bottom() - y, height);
Rect::new(x, y, width, height)
})
})
}
fn get_alignment_offset<'a>(
area_width: u16,
letter_width: u16,
alignment: Alignment,
line: &'a Line<'a>,
) -> u16 {
let big_line_width = line.width() as u16 * letter_width;
match alignment {
Alignment::Center => (area_width / 2).saturating_sub(big_line_width / 2),
Alignment::Right => area_width.saturating_sub(big_line_width),
Alignment::Left => 0,
}
}
/// Render a single grapheme into a cell by looking up the corresponding 8x8 bitmap in the
/// `BITMAPS` array and setting the corresponding cells in the buffer.
fn render_symbol(grapheme: StyledGrapheme, area: Rect, buf: &mut Buffer, pixel_size: &PixelSize) {
buf.set_style(area, grapheme.style);
let c = grapheme.symbol.chars().next().unwrap(); // TODO: handle multi-char graphemes
if let Some(glyph) = font8x8::BASIC_FONTS.get(c) {
render_glyph(glyph, area, buf, pixel_size);
}
}
/// Render a single 8x8 glyph into a cell by setting the corresponding cells in the buffer.
fn render_glyph(glyph: [u8; 8], area: Rect, buf: &mut Buffer, pixel_size: &PixelSize) {
let (step_x, step_y) = pixel_size.pixels_per_cell();
let glyph_vertical_index = (0..glyph.len()).step_by(step_y as usize);
let glyph_horizontal_bit_selector = (0..8).step_by(step_x as usize);
for (y, row) in glyph_vertical_index.zip(area.rows()) {
for (x, col) in glyph_horizontal_bit_selector.clone().zip(row.columns()) {
buf[col].set_char(pixel_size.symbol_for_position(&glyph, y, x));
}
}
}
#[cfg(test)]
mod tests {
use ratatui_core::style::Stylize;
use super::*;
#[test]
fn build() {
let lines = vec![Line::from(vec!["Hello".red(), "World".blue()])];
let style = Style::new().green();
let pixel_size = PixelSize::default();
let alignment = Alignment::Center;
assert_eq!(
BigText::builder()
.lines(lines.clone())
.style(style)
.alignment(Alignment::Center)
.build(),
BigText {
lines,
style,
pixel_size,
alignment,
}
);
}
#[test]
fn render_single_line() {
let big_text = BigText::builder()
.lines(vec![Line::from("SingleLine")])
.build();
let mut buf = Buffer::empty(Rect::new(0, 0, 80, 8));
big_text.render(buf.area, &mut buf);
let expected = Buffer::with_lines(vec![
" ████ ██ ███ ████ ██ ",
"██ ██ ██ ██ ",
"███ ███ █████ ███ ██ ██ ████ ██ ███ █████ ████ ",
" ███ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ",
" ███ ██ ██ ██ ██ ██ ██ ██████ ██ █ ██ ██ ██ ██████ ",
"██ ██ ██ ██ ██ █████ ██ ██ ██ ██ ██ ██ ██ ██ ",
" ████ ████ ██ ██ ██ ████ ████ ███████ ████ ██ ██ ████ ",
" █████ ",
]);
assert_eq!(buf, expected);
}
#[test]
fn render_truncated() {
let big_text = BigText::builder()
.lines(vec![Line::from("Truncated")])
.build();
let mut buf = Buffer::empty(Rect::new(0, 0, 70, 6));
big_text.render(buf.area, &mut buf);
let expected = Buffer::with_lines(vec![
"██████ █ ███",
"█ ██ █ ██ ██",
" ██ ██ ███ ██ ██ █████ ████ ████ █████ ████ ██",
" ██ ███ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ █████",
" ██ ██ ██ ██ ██ ██ ██ ██ █████ ██ ██████ ██ ██",
" ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ █ ██ ██ ██",
]);
assert_eq!(buf, expected);
}
#[test]
fn render_multiple_lines() {
let big_text = BigText::builder()
.lines(vec![Line::from("Multi"), Line::from("Lines")])
.build();
let mut buf = Buffer::empty(Rect::new(0, 0, 40, 16));
big_text.render(buf.area, &mut buf);
let expected = Buffer::with_lines(vec![
"██ ██ ███ █ ██ ",
"███ ███ ██ ██ ",
"███████ ██ ██ ██ █████ ███ ",
"███████ ██ ██ ██ ██ ██ ",
"██ █ ██ ██ ██ ██ ██ ██ ",
"██ ██ ██ ██ ██ ██ █ ██ ",
"██ ██ ███ ██ ████ ██ ████ ",
" ",
"████ ██ ",
" ██ ",
" ██ ███ █████ ████ █████ ",
" ██ ██ ██ ██ ██ ██ ██ ",
" ██ █ ██ ██ ██ ██████ ████ ",
" ██ ██ ██ ██ ██ ██ ██ ",
"███████ ████ ██ ██ ████ █████ ",
" ",
]);
assert_eq!(buf, expected);
}
#[test]
fn render_widget_style() {
let big_text = BigText::builder()
.lines(vec![Line::from("Styled")])
.style(Style::new().bold())
.build();
let mut buf = Buffer::empty(Rect::new(0, 0, 48, 8));
big_text.render(buf.area, &mut buf);
let mut expected = Buffer::with_lines(vec![
" ████ █ ███ ███ ",
"██ ██ ██ ██ ██ ",
"███ █████ ██ ██ ██ ████ ██ ",
" ███ ██ ██ ██ ██ ██ ██ █████ ",
" ███ ██ ██ ██ ██ ██████ ██ ██ ",
"██ ██ ██ █ █████ ██ ██ ██ ██ ",
" ████ ██ ██ ████ ████ ███ ██ ",
" █████ ",
]);
expected.set_style(Rect::new(0, 0, 48, 8), Style::new().bold());
assert_eq!(buf, expected);
}
#[test]
fn render_line_style() {
let big_text = BigText::builder()
.lines(vec![
Line::from("Red".red()),
Line::from("Green".green()),
Line::from("Blue".blue()),
])
.build();
let mut buf = Buffer::empty(Rect::new(0, 0, 40, 24));
big_text.render(buf.area, &mut buf);
let mut expected = Buffer::with_lines(vec![
"██████ ███ ",
" ██ ██ ██ ",
" ██ ██ ████ ██ ",
" █████ ██ ██ █████ ",
" ██ ██ ██████ ██ ██ ",
" ██ ██ ██ ██ ██ ",
"███ ██ ████ ███ ██ ",
" ",
" ████ ",
" ██ ██ ",
"██ ██ ███ ████ ████ █████ ",
"██ ███ ██ ██ ██ ██ ██ ██ ██ ",
"██ ███ ██ ██ ██████ ██████ ██ ██ ",
" ██ ██ ██ ██ ██ ██ ██ ",
" █████ ████ ████ ████ ██ ██ ",
" ",
"██████ ███ ",
" ██ ██ ██ ",
" ██ ██ ██ ██ ██ ████ ",
" █████ ██ ██ ██ ██ ██ ",
" ██ ██ ██ ██ ██ ██████ ",
" ██ ██ ██ ██ ██ ██ ",
"██████ ████ ███ ██ ████ ",
" ",
]);
expected.set_style(Rect::new(0, 0, 24, 8), Style::new().red());
expected.set_style(Rect::new(0, 8, 40, 8), Style::new().green());
expected.set_style(Rect::new(0, 16, 32, 8), Style::new().blue());
assert_eq!(buf, expected);
}
#[test]
fn render_half_height_single_line() {
let big_text = BigText::builder()
.pixel_size(PixelSize::HalfHeight)
.lines(vec![Line::from("SingleLine")])
.build();
let mut buf = Buffer::empty(Rect::new(0, 0, 80, 4));
big_text.render(buf.area, &mut buf);
let expected = Buffer::with_lines(vec![
"▄█▀▀█▄ ▀▀ ▀██ ▀██▀ ▀▀ ",
"▀██▄ ▀██ ██▀▀█▄ ▄█▀▀▄█▀ ██ ▄█▀▀█▄ ██ ▀██ ██▀▀█▄ ▄█▀▀█▄ ",
"▄▄ ▀██ ██ ██ ██ ▀█▄▄██ ██ ██▀▀▀▀ ██ ▄█ ██ ██ ██ ██▀▀▀▀ ",
" ▀▀▀▀ ▀▀▀▀ ▀▀ ▀▀ ▄▄▄▄█▀ ▀▀▀▀ ▀▀▀▀ ▀▀▀▀▀▀▀ ▀▀▀▀ ▀▀ ▀▀ ▀▀▀▀ ",
]);
assert_eq!(buf, expected);
}
#[test]
fn render_half_height_truncated() {
let big_text = BigText::builder()
.pixel_size(PixelSize::HalfHeight)
.lines(vec![Line::from("Truncated")])
.build();
let mut buf = Buffer::empty(Rect::new(0, 0, 70, 3));
big_text.render(buf.area, &mut buf);
let expected = Buffer::with_lines(vec![
"█▀██▀█ ▄█ ▀██",
" ██ ▀█▄█▀█▄ ██ ██ ██▀▀█▄ ▄█▀▀█▄ ▀▀▀█▄ ▀██▀▀ ▄█▀▀█▄ ▄▄▄██",
" ██ ██ ▀▀ ██ ██ ██ ██ ██ ▄▄ ▄█▀▀██ ██ ▄ ██▀▀▀▀ ██ ██",
]);
assert_eq!(buf, expected);
}
#[test]
fn render_half_height_multiple_lines() {
let big_text = BigText::builder()
.pixel_size(PixelSize::HalfHeight)
.lines(vec![Line::from("Multi"), Line::from("Lines")])
.build();
let mut buf = Buffer::empty(Rect::new(0, 0, 40, 8));
big_text.render(buf.area, &mut buf);
let expected = Buffer::with_lines(vec![
"██▄ ▄██ ▀██ ▄█ ▀▀ ",
"███████ ██ ██ ██ ▀██▀▀ ▀██ ",
"██ ▀ ██ ██ ██ ██ ██ ▄ ██ ",
"▀▀ ▀▀ ▀▀▀ ▀▀ ▀▀▀▀ ▀▀ ▀▀▀▀ ",
"▀██▀ ▀▀ ",
" ██ ▀██ ██▀▀█▄ ▄█▀▀█▄ ▄█▀▀▀▀ ",
" ██ ▄█ ██ ██ ██ ██▀▀▀▀ ▀▀▀█▄ ",
"▀▀▀▀▀▀▀ ▀▀▀▀ ▀▀ ▀▀ ▀▀▀▀ ▀▀▀▀▀ ",
]);
assert_eq!(buf, expected);
}
#[test]
fn render_half_height_widget_style() {
let big_text = BigText::builder()
.pixel_size(PixelSize::HalfHeight)
.lines(vec![Line::from("Styled")])
.style(Style::new().bold())
.build();
let mut buf = Buffer::empty(Rect::new(0, 0, 48, 4));
big_text.render(buf.area, &mut buf);
let mut expected = Buffer::with_lines(vec![
"▄█▀▀█▄ ▄█ ▀██ ▀██ ",
"▀██▄ ▀██▀▀ ██ ██ ██ ▄█▀▀█▄ ▄▄▄██ ",
"▄▄ ▀██ ██ ▄ ▀█▄▄██ ██ ██▀▀▀▀ ██ ██ ",
" ▀▀▀▀ ▀▀ ▄▄▄▄█▀ ▀▀▀▀ ▀▀▀▀ ▀▀▀ ▀▀ ",
]);
expected.set_style(Rect::new(0, 0, 48, 4), Style::new().bold());
assert_eq!(buf, expected);
}
#[test]
fn render_half_height_line_style() {
let big_text = BigText::builder()
.pixel_size(PixelSize::HalfHeight)
.lines(vec![
Line::from("Red".red()),
Line::from("Green".green()),
Line::from("Blue".blue()),
])
.build();
let mut buf = Buffer::empty(Rect::new(0, 0, 40, 12));
big_text.render(buf.area, &mut buf);
let mut expected = Buffer::with_lines(vec![
"▀██▀▀█▄ ▀██ ",
" ██▄▄█▀ ▄█▀▀█▄ ▄▄▄██ ",
" ██ ▀█▄ ██▀▀▀▀ ██ ██ ",
"▀▀▀ ▀▀ ▀▀▀▀ ▀▀▀ ▀▀ ",
" ▄█▀▀█▄ ",
"██ ▀█▄█▀█▄ ▄█▀▀█▄ ▄█▀▀█▄ ██▀▀█▄ ",
"▀█▄ ▀██ ██ ▀▀ ██▀▀▀▀ ██▀▀▀▀ ██ ██ ",
" ▀▀▀▀▀ ▀▀▀▀ ▀▀▀▀ ▀▀▀▀ ▀▀ ▀▀ ",
"▀██▀▀█▄ ▀██ ",
" ██▄▄█▀ ██ ██ ██ ▄█▀▀█▄ ",
" ██ ██ ██ ██ ██ ██▀▀▀▀ ",
"▀▀▀▀▀▀ ▀▀▀▀ ▀▀▀ ▀▀ ▀▀▀▀ ",
]);
expected.set_style(Rect::new(0, 0, 24, 4), Style::new().red());
expected.set_style(Rect::new(0, 4, 40, 4), Style::new().green());
expected.set_style(Rect::new(0, 8, 32, 4), Style::new().blue());
assert_eq!(buf, expected);
}
#[test]
fn render_half_width_single_line() {
let big_text = BigText::builder()
.pixel_size(PixelSize::HalfWidth)
.lines(vec![Line::from("SingleLine")])
.build();
let mut buf = Buffer::empty(Rect::new(0, 0, 40, 8));
big_text.render(buf.area, &mut buf);
let expected = Buffer::with_lines(vec![
"▐█▌ █ ▐█ ██ █ ",
"█ █ █ ▐▌ ",
"█▌ ▐█ ██▌ ▐█▐▌ █ ▐█▌ ▐▌ ▐█ ██▌ ▐█▌ ",
"▐█ █ █ █ █ █ █ █ █ ▐▌ █ █ █ █ █ ",
" ▐█ █ █ █ █ █ █ ███ ▐▌ ▌ █ █ █ ███ ",
"█ █ █ █ █ ▐██ █ █ ▐▌▐▌ █ █ █ █ ",
"▐█▌ ▐█▌ █ █ █ ▐█▌ ▐█▌ ███▌▐█▌ █ █ ▐█▌ ",
" ██▌ ",
]);
assert_eq!(buf, expected);
}
#[test]
fn render_half_width_truncated() {
let big_text = BigText::builder()
.pixel_size(PixelSize::HalfWidth)
.lines(vec![Line::from("Truncated")])
.build();
let mut buf = Buffer::empty(Rect::new(0, 0, 35, 6));
big_text.render(buf.area, &mut buf);
let expected = Buffer::with_lines(vec![
"███ ▐ ▐█",
"▌█▐ █ █",
" █ █▐█ █ █ ██▌ ▐█▌ ▐█▌ ▐██ ▐█▌ █",
" █ ▐█▐▌█ █ █ █ █ █ █ █ █ █ ▐██",
" █ ▐▌▐▌█ █ █ █ █ ▐██ █ ███ █ █",
" █ ▐▌ █ █ █ █ █ █ █ █ █▐ █ █ █",
]);
assert_eq!(buf, expected);
}
#[test]
fn render_half_width_multiple_lines() {
let big_text = BigText::builder()
.pixel_size(PixelSize::HalfWidth)
.lines(vec![Line::from("Multi"), Line::from("Lines")])
.build();
let mut buf = Buffer::empty(Rect::new(0, 0, 20, 16));
big_text.render(buf.area, &mut buf);
let expected = Buffer::with_lines(vec![
"█ ▐▌ ▐█ ▐ █ ",
"█▌█▌ █ █ ",
"███▌█ █ █ ▐██ ▐█ ",
"███▌█ █ █ █ █ ",
"█▐▐▌█ █ █ █ █ ",
"█ ▐▌█ █ █ █▐ █ ",
"█ ▐▌▐█▐▌▐█▌ ▐▌ ▐█▌ ",
" ",
"██ █ ",
"▐▌ ",
"▐▌ ▐█ ██▌ ▐█▌ ▐██ ",
"▐▌ █ █ █ █ █ █ ",
"▐▌ ▌ █ █ █ ███ ▐█▌ ",
"▐▌▐▌ █ █ █ █ █ ",
"███▌▐█▌ █ █ ▐█▌ ██▌ ",
" ",
]);
assert_eq!(buf, expected);
}
#[test]
fn render_half_width_widget_style() {
let big_text = BigText::builder()
.pixel_size(PixelSize::HalfWidth)
.lines(vec![Line::from("Styled")])
.style(Style::new().bold())
.build();
let mut buf = Buffer::empty(Rect::new(0, 0, 24, 8));
big_text.render(buf.area, &mut buf);
let mut expected = Buffer::with_lines(vec![
"▐█▌ ▐ ▐█ ▐█ ",
"█ █ █ █ █ ",
"█▌ ▐██ █ █ █ ▐█▌ █ ",
"▐█ █ █ █ █ █ █ ▐██ ",
" ▐█ █ █ █ █ ███ █ █ ",
"█ █ █▐ ▐██ █ █ █ █ ",
"▐█▌ ▐▌ █ ▐█▌ ▐█▌ ▐█▐▌",
" ██▌ ",
]);
expected.set_style(Rect::new(0, 0, 24, 8), Style::new().bold());
assert_eq!(buf, expected);
}
#[test]
fn render_half_width_line_style() {
let big_text = BigText::builder()
.pixel_size(PixelSize::HalfWidth)
.lines(vec![
Line::from("Red".red()),
Line::from("Green".green()),
Line::from("Blue".blue()),
])
.build();
let mut buf = Buffer::empty(Rect::new(0, 0, 20, 24));
big_text.render(buf.area, &mut buf);
let mut expected = Buffer::with_lines(vec![
"███ ▐█ ",
"▐▌▐▌ █ ",
"▐▌▐▌▐█▌ █ ",
"▐██ █ █ ▐██ ",
"▐▌█ ███ █ █ ",
"▐▌▐▌█ █ █ ",
"█▌▐▌▐█▌ ▐█▐▌ ",
" ",
" ██ ",
"▐▌▐▌ ",
"█ █▐█ ▐█▌ ▐█▌ ██▌ ",
"█ ▐█▐▌█ █ █ █ █ █ ",
"█ █▌▐▌▐▌███ ███ █ █ ",
"▐▌▐▌▐▌ █ █ █ █ ",
" ██▌██ ▐█▌ ▐█▌ █ █ ",
" ",
"███ ▐█ ",
"▐▌▐▌ █ ",
"▐▌▐▌ █ █ █ ▐█▌ ",
"▐██ █ █ █ █ █ ",
"▐▌▐▌ █ █ █ ███ ",
"▐▌▐▌ █ █ █ █ ",
"███ ▐█▌ ▐█▐▌▐█▌ ",
" ",
]);
expected.set_style(Rect::new(0, 0, 12, 8), Style::new().red());
expected.set_style(Rect::new(0, 8, 20, 8), Style::new().green());
expected.set_style(Rect::new(0, 16, 16, 8), Style::new().blue());
assert_eq!(buf, expected);
}
#[test]
fn render_quadrant_size_single_line() {
let big_text = BigText::builder()
.pixel_size(PixelSize::Quadrant)
.lines(vec![Line::from("SingleLine")])
.build();
let mut buf = Buffer::empty(Rect::new(0, 0, 40, 4));
big_text.render(buf.area, &mut buf);
let expected = Buffer::with_lines(vec![
"▟▀▙ ▀ ▝█ ▜▛ ▀ ",
"▜▙ ▝█ █▀▙ ▟▀▟▘ █ ▟▀▙ ▐▌ ▝█ █▀▙ ▟▀▙ ",
"▄▝█ █ █ █ ▜▄█ █ █▀▀ ▐▌▗▌ █ █ █ █▀▀ ",
"▝▀▘ ▝▀▘ ▀ ▀ ▄▄▛ ▝▀▘ ▝▀▘ ▀▀▀▘▝▀▘ ▀ ▀ ▝▀▘ ",
]);
assert_eq!(buf, expected);
}
#[test]
fn render_quadrant_size_truncated() {
let big_text = BigText::builder()
.pixel_size(PixelSize::Quadrant)
.lines(vec![Line::from("Truncated")])
.build();
let mut buf = Buffer::empty(Rect::new(0, 0, 35, 3));
big_text.render(buf.area, &mut buf);
let expected = Buffer::with_lines(vec![
"▛█▜ ▟ ▝█",
" █ ▜▟▜▖█ █ █▀▙ ▟▀▙ ▝▀▙ ▝█▀ ▟▀▙ ▗▄█",
" █ ▐▌▝▘█ █ █ █ █ ▄ ▟▀█ █▗ █▀▀ █ █",
]);
assert_eq!(buf, expected);
}
#[test]
fn render_quadrant_size_multiple_lines() {
let big_text = BigText::builder()
.pixel_size(PixelSize::Quadrant)
.lines(vec![Line::from("Multi"), Line::from("Lines")])
.build();
let mut buf = Buffer::empty(Rect::new(0, 0, 20, 8));
big_text.render(buf.area, &mut buf);
let expected = Buffer::with_lines(vec![
"█▖▟▌ ▝█ ▟ ▀ ",
"███▌█ █ █ ▝█▀ ▝█ ",
"█▝▐▌█ █ █ █▗ █ ",
"▀ ▝▘▝▀▝▘▝▀▘ ▝▘ ▝▀▘ ",
"▜▛ ▀ ",
"▐▌ ▝█ █▀▙ ▟▀▙ ▟▀▀ ",
"▐▌▗▌ █ █ █ █▀▀ ▝▀▙ ",
"▀▀▀▘▝▀▘ ▀ ▀ ▝▀▘ ▀▀▘ ",
]);
assert_eq!(buf, expected);
}
#[test]
fn render_quadrant_size_widget_style() {
let big_text = BigText::builder()
.pixel_size(PixelSize::Quadrant)
.lines(vec![Line::from("Styled")])
.style(Style::new().bold())
.build();
let mut buf = Buffer::empty(Rect::new(0, 0, 24, 4));
big_text.render(buf.area, &mut buf);
let mut expected = Buffer::with_lines(vec![
"▟▀▙ ▟ ▝█ ▝█ ",
"▜▙ ▝█▀ █ █ █ ▟▀▙ ▗▄█ ",
"▄▝█ █▗ ▜▄█ █ █▀▀ █ █ ",
"▝▀▘ ▝▘ ▄▄▛ ▝▀▘ ▝▀▘ ▝▀▝▘",
]);
expected.set_style(Rect::new(0, 0, 24, 4), Style::new().bold());
assert_eq!(buf, expected);
}
#[test]
fn render_quadrant_size_line_style() {
let big_text = BigText::builder()
.pixel_size(PixelSize::Quadrant)
.lines(vec![
Line::from("Red".red()),
Line::from("Green".green()),
Line::from("Blue".blue()),
])
.build();
let mut buf = Buffer::empty(Rect::new(0, 0, 20, 12));
big_text.render(buf.area, &mut buf);
let mut expected = Buffer::with_lines(vec![
"▜▛▜▖ ▝█ ",
"▐▙▟▘▟▀▙ ▗▄█ ",
"▐▌▜▖█▀▀ █ █ ",
"▀▘▝▘▝▀▘ ▝▀▝▘ ",
"▗▛▜▖ ",
"█ ▜▟▜▖▟▀▙ ▟▀▙ █▀▙ ",
"▜▖▜▌▐▌▝▘█▀▀ █▀▀ █ █ ",
" ▀▀▘▀▀ ▝▀▘ ▝▀▘ ▀ ▀ ",
"▜▛▜▖▝█ ",
"▐▙▟▘ █ █ █ ▟▀▙ ",
"▐▌▐▌ █ █ █ █▀▀ ",
"▀▀▀ ▝▀▘ ▝▀▝▘▝▀▘ ",
]);
expected.set_style(Rect::new(0, 0, 12, 4), Style::new().red());
expected.set_style(Rect::new(0, 4, 20, 4), Style::new().green());
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | true |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-big-text/src/lib.rs | tui-big-text/src/lib.rs | //! A [Ratatui] widget to render gloriously oversized pixel text using glyphs from the [font8x8]
//! crate. Part of the [tui-widgets] suite by [Joshka].
//!
//! 
//!
//! [![Crate badge]][Crate]
//! [![Docs Badge]][Docs]
//! [![Deps Badge]][Dependency Status]
//! [![License Badge]][License]
//! [![Coverage Badge]][Coverage]
//! [![Discord Badge]][Ratatui Discord]
//!
//! [GitHub Repository] · [API Docs] · [Examples] · [Changelog] · [Contributing]
//!
//! # Installation
//!
//! ```shell
//! cargo add ratatui tui-big-text
//! ```
//!
//! # Usage
//!
//! Create a [`BigText`] widget using [`BigText::builder`] and pass it to [`render_widget`]. The
//! builder allows you to customize the [`Style`] of the widget and the [`PixelSize`] of the
//! glyphs.
//!
//! # Examples
//!
//! ```rust
//! use ratatui::prelude::{Frame, Style, Stylize};
//! use tui_big_text::{BigText, PixelSize};
//!
//! fn render(frame: &mut Frame) {
//! let big_text = BigText::builder()
//! .pixel_size(PixelSize::Full)
//! .style(Style::new().blue())
//! .lines(vec![
//! "Hello".red().into(),
//! "World".white().into(),
//! "~~~~~".into(),
//! ])
//! .build();
//! frame.render_widget(big_text, frame.size());
//! }
//! ```
//!
//! The [`PixelSize`] can be used to control how many character cells are used to represent a single
//! pixel of the 8x8 font. It has six variants:
//!
//! - `Full` (default) - Each pixel is represented by a single character cell.
//! - `HalfHeight` - Each pixel is represented by half the height of a character cell.
//! - `HalfWidth` - Each pixel is represented by half the width of a character cell.
//! - `Quadrant` - Each pixel is represented by a quarter of a character cell.
//! - `ThirdHeight` - Each pixel is represented by a third of the height of a character cell.
//! - `Sextant` - Each pixel is represented by a sixth of a character cell.
//! - `QuarterHeight` - Each pixel is represented by a quarter of the height of a character cell.
//! - `Octant` - Each pixel is represented by an eighth of a character cell.
//!
//! ```rust
//! # use tui_big_text::*;
//! BigText::builder().pixel_size(PixelSize::Full);
//! BigText::builder().pixel_size(PixelSize::HalfHeight);
//! BigText::builder().pixel_size(PixelSize::Quadrant);
//! ```
//!
//! 
//!
//! Text can be aligned to the Left / Right / Center using the `alignment` methods.
//!
//! ```rust
//! # use tui_big_text::*;
//! BigText::builder().left_aligned();
//! BigText::builder().centered();
//! BigText::builder().right_aligned();
//! ```
//!
//! 
//!
//! # More widgets
//!
//! For the full suite of widgets, see [tui-widgets].
//!
//! [tui-big-text]: https://crates.io/crates/tui-big-text
//! [Ratatui]: https://crates.io/crates/ratatui
//! [font8x8]: https://crates.io/crates/font8x8
//!
//! <!-- Note that these links are sensitive to breaking with cargo-rdme -->
//! [`BigText`]: https://docs.rs/tui-big-text/tui_big_text/big_text/struct.BigText.html
//! [`BigText::builder`]:
//! https://docs.rs/tui-big-text/tui_big_text/big_text/struct.BigText.html#method.builder
//! [`PixelSize`]: https://docs.rs/tui-big-text/tui_big_text/pixel_size/enum.PixelSize.html
//! [`render_widget`]: https://docs.rs/ratatui/ratatui/struct.Frame.html#method.render_widget
//! [`Style`]: https://docs.rs/ratatui/ratatui/style/struct.Style.html
//!
//! [Crate]: https://crates.io/crates/tui-big-text
//! [Docs]: https://docs.rs/tui-big-text/
//! [Dependency Status]: https://deps.rs/repo/github/joshka/tui-widgets
//! [Coverage]: https://app.codecov.io/gh/joshka/tui-widgets
//! [Ratatui Discord]: https://discord.gg/pMCEU9hNEj
//! [Crate badge]: https://img.shields.io/crates/v/tui-big-text?logo=rust&style=flat
//! [Docs Badge]: https://img.shields.io/docsrs/tui-big-text?logo=rust&style=flat
//! [Deps Badge]: https://deps.rs/repo/github/joshka/tui-widgets/status.svg?style=flat
//! [License Badge]: https://img.shields.io/crates/l/tui-big-text?style=flat
//! [License]: https://github.com/joshka/tui-widgets/blob/main/LICENSE-MIT
//! [Coverage Badge]:
//! https://img.shields.io/codecov/c/github/joshka/tui-widgets?logo=codecov&style=flat
//! [Discord Badge]: https://img.shields.io/discord/1070692720437383208?logo=discord&style=flat
//!
//! [GitHub Repository]: https://github.com/joshka/tui-widgets
//! [API Docs]: https://docs.rs/tui-big-text/
//! [Examples]: https://github.com/joshka/tui-widgets/tree/main/tui-big-text/examples
//! [Changelog]: https://github.com/joshka/tui-widgets/blob/main/tui-big-text/CHANGELOG.md
//! [Contributing]: https://github.com/joshka/tui-widgets/blob/main/CONTRIBUTING.md
//!
//! [Joshka]: https://github.com/joshka
//! [tui-widgets]: https://crates.io/crates/tui-widgets
mod big_text;
mod pixel_size;
pub use big_text::{BigText, BigTextBuilder};
pub use pixel_size::PixelSize;
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-big-text/src/pixel_size.rs | tui-big-text/src/pixel_size.rs | #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Default)]
pub enum PixelSize {
#[default]
/// A pixel from the 8x8 font is represented by a full character cell in the terminal.
Full,
/// A pixel from the 8x8 font is represented by a half (upper/lower) character cell in the
/// terminal.
HalfHeight,
/// A pixel from the 8x8 font is represented by a half (left/right) character cell in the
/// terminal.
HalfWidth,
/// A pixel from the 8x8 font is represented by a quadrant of a character cell in the
/// terminal.
Quadrant,
/// A pixel from the 8x8 font is represented by a third (top/middle/bottom) of a character
/// cell in the terminal.
/// *Note: depending on how the used terminal renders characters, the generated text with
/// this PixelSize might look very strange.*
ThirdHeight,
/// A pixel from the 8x8 font is represented by a sextant of a character cell in the
/// terminal.
/// *Note: depending on how the used terminal renders characters, the generated text with
/// this PixelSize might look very strange.*
Sextant,
/// A pixel from the 8x8 font is represented by a quarter
/// (top/upper-middle/lower-middle/bottom) of a character cell in the terminal.
/// *Note: depending on how the used terminal renders characters, the generated text with
/// this PixelSize might look very strange.*
QuarterHeight,
/// A pixel from the 8x8 font is represented by an octant of a character cell in the
/// terminal.
/// *Note: depending on how the used terminal renders characters, the generated text with
/// this PixelSize might look very strange.*
Octant,
}
impl PixelSize {
/// The number of pixels that can be displayed in a single character cell for the given
/// pixel size.
///
/// The first value is the number of pixels in the horizontal direction, the second value is
/// the number of pixels in the vertical direction.
pub(crate) const fn pixels_per_cell(self) -> (u16, u16) {
match self {
Self::Full => (1, 1),
Self::HalfHeight => (1, 2),
Self::HalfWidth => (2, 1),
Self::Quadrant => (2, 2),
Self::ThirdHeight => (1, 3),
Self::Sextant => (2, 3),
Self::QuarterHeight => (1, 4),
Self::Octant => (2, 4),
}
}
/// Get a symbol/char that represents the pixels at the given position with the given pixel size
pub(crate) const fn symbol_for_position(self, glyph: &[u8; 8], row: usize, col: i32) -> char {
match self {
Self::Full => match glyph[row] & (1 << col) {
0 => ' ',
_ => '█',
},
Self::HalfHeight => {
let top = glyph[row] & (1 << col);
let bottom = glyph[row + 1] & (1 << col);
get_symbol_half_height(top, bottom)
}
Self::HalfWidth => {
let left = glyph[row] & (1 << col);
let right = glyph[row] & (1 << (col + 1));
get_symbol_half_width(left, right)
}
Self::Quadrant => {
let top_left = glyph[row] & (1 << col);
let top_right = glyph[row] & (1 << (col + 1));
let bottom_left = glyph[row + 1] & (1 << col);
let bottom_right = glyph[row + 1] & (1 << (col + 1));
get_symbol_quadrant_size(top_left, top_right, bottom_left, bottom_right)
}
Self::ThirdHeight => {
let top = glyph[row] & (1 << col);
let is_middle_available = (row + 1) < glyph.len();
let middle = if is_middle_available {
glyph[row + 1] & (1 << col)
} else {
0
};
let is_bottom_available = (row + 2) < glyph.len();
let bottom = if is_bottom_available {
glyph[row + 2] & (1 << col)
} else {
0
};
get_symbol_third_height(top, middle, bottom)
}
Self::Sextant => {
let top_left = glyph[row] & (1 << col);
let top_right = glyph[row] & (1 << (col + 1));
let is_middle_available = (row + 1) < glyph.len();
let (middle_left, middle_right) = if is_middle_available {
(
glyph[row + 1] & (1 << col),
glyph[row + 1] & (1 << (col + 1)),
)
} else {
(0, 0)
};
let is_bottom_available = (row + 2) < glyph.len();
let (bottom_left, bottom_right) = if is_bottom_available {
(
glyph[row + 2] & (1 << col),
glyph[row + 2] & (1 << (col + 1)),
)
} else {
(0, 0)
};
get_symbol_sextant_size(
top_left,
top_right,
middle_left,
middle_right,
bottom_left,
bottom_right,
)
}
Self::QuarterHeight => {
let top = glyph[row] & (1 << col);
let is_upper_middle_available = (row + 1) < glyph.len();
let upper_middle = if is_upper_middle_available {
glyph[row + 1] & (1 << col)
} else {
0
};
let is_lower_middle_available = (row + 2) < glyph.len();
let lower_middle = if is_lower_middle_available {
glyph[row + 2] & (1 << col)
} else {
0
};
let is_bottom_available = (row + 3) < glyph.len();
let bottom = if is_bottom_available {
glyph[row + 3] & (1 << col)
} else {
0
};
get_symbol_quarter_height(top, upper_middle, lower_middle, bottom)
}
Self::Octant => {
let top_left = glyph[row] & (1 << col);
let top_right = glyph[row] & (1 << (col + 1));
let is_upper_middle_available = (row + 1) < glyph.len();
let (upper_middle_left, upper_middle_right) = if is_upper_middle_available {
(
glyph[row + 1] & (1 << col),
glyph[row + 1] & (1 << (col + 1)),
)
} else {
(0, 0)
};
let is_lower_middle_available = (row + 2) < glyph.len();
let (lower_middle_left, lower_middle_right) = if is_lower_middle_available {
(
glyph[row + 2] & (1 << col),
glyph[row + 2] & (1 << (col + 1)),
)
} else {
(0, 0)
};
let is_bottom_available = (row + 3) < glyph.len();
let (bottom_left, bottom_right) = if is_bottom_available {
(
glyph[row + 3] & (1 << col),
glyph[row + 3] & (1 << (col + 1)),
)
} else {
(0, 0)
};
get_symbol_octant_size(
top_left,
top_right,
upper_middle_left,
upper_middle_right,
lower_middle_left,
lower_middle_right,
bottom_left,
bottom_right,
)
}
}
}
}
/// Get the correct unicode symbol for two vertical "pixels"
const fn get_symbol_half_height(top: u8, bottom: u8) -> char {
match top {
0 => match bottom {
0 => ' ',
_ => '▄',
},
_ => match bottom {
0 => '▀',
_ => '█',
},
}
}
/// Get the correct unicode symbol for two horizontal "pixels"
const fn get_symbol_half_width(left: u8, right: u8) -> char {
match left {
0 => match right {
0 => ' ',
_ => '▐',
},
_ => match right {
0 => '▌',
_ => '█',
},
}
}
/// Get the correct unicode symbol for 2x2 "pixels"
const fn get_symbol_quadrant_size(
top_left: u8,
top_right: u8,
bottom_left: u8,
bottom_right: u8,
) -> char {
let top_left = if top_left > 0 { 1 } else { 0 };
let top_right = if top_right > 0 { 1 } else { 0 };
let bottom_left = if bottom_left > 0 { 1 } else { 0 };
let bottom_right = if bottom_right > 0 { 1 } else { 0 };
// We use an array here instead of directly indexing into the unicode symbols, because although
// most symbols are in order in unicode, some of them are already part of another character set
// and missing in this character set.
const QUADRANT_SYMBOLS: [char; 16] = [
' ', '▘', '▝', '▀', '▖', '▌', '▞', '▛', '▗', '▚', '▐', '▜', '▄', '▙', '▟', '█',
];
let character_index = top_left + (top_right << 1) + (bottom_left << 2) + (bottom_right << 3);
QUADRANT_SYMBOLS[character_index]
}
/// Get the correct unicode symbol for 1x3 "pixels"
const fn get_symbol_third_height(top: u8, middle: u8, bottom: u8) -> char {
get_symbol_sextant_size(top, top, middle, middle, bottom, bottom)
}
/// Get the correct unicode symbol for 2x3 "pixels"
const fn get_symbol_sextant_size(
top_left: u8,
top_right: u8,
middle_left: u8,
middle_right: u8,
bottom_left: u8,
bottom_right: u8,
) -> char {
let top_left = if top_left > 0 { 1 } else { 0 };
let top_right = if top_right > 0 { 1 } else { 0 };
let middle_left = if middle_left > 0 { 1 } else { 0 };
let middle_right = if middle_right > 0 { 1 } else { 0 };
let bottom_left = if bottom_left > 0 { 1 } else { 0 };
let bottom_right = if bottom_right > 0 { 1 } else { 0 };
// We use an array here instead of directly indexing into the unicode symbols, because although
// most symbols are in order in unicode, some of them are already part of another character set
// and missing in this character set.
const SEXANT_SYMBOLS: [char; 64] = [
' ', '🬀', '🬁', '🬂', '🬃', '🬄', '🬅', '🬆', '🬇', '🬈', '🬉', '🬊', '🬋', '🬌', '🬍', '🬎', '🬏', '🬐',
'🬑', '🬒', '🬓', '▌', '🬔', '🬕', '🬖', '🬗', '🬘', '🬙', '🬚', '🬛', '🬜', '🬝', '🬞', '🬟', '🬠', '🬡',
'🬢', '🬣', '🬤', '🬥', '🬦', '🬧', '▐', '🬨', '🬩', '🬪', '🬫', '🬬', '🬭', '🬮', '🬯', '🬰', '🬱', '🬲',
'🬳', '🬴', '🬵', '🬶', '🬷', '🬸', '🬹', '🬺', '🬻', '█',
];
let character_index = top_left
+ (top_right << 1)
+ (middle_left << 2)
+ (middle_right << 3)
+ (bottom_left << 4)
+ (bottom_right << 5);
SEXANT_SYMBOLS[character_index]
}
/// Get the correct unicode symbol for 1x4 "pixels"
const fn get_symbol_quarter_height(
top: u8,
upper_middle: u8,
lower_middle: u8,
bottom: u8,
) -> char {
get_symbol_octant_size(
top,
top,
upper_middle,
upper_middle,
lower_middle,
lower_middle,
bottom,
bottom,
)
}
/// Get the correct unicode symbol for 2x4 "pixels"
#[allow(clippy::too_many_arguments)]
const fn get_symbol_octant_size(
top_left: u8,
top_right: u8,
upper_middle_left: u8,
upper_middle_right: u8,
lower_middle_left: u8,
lower_middle_right: u8,
bottom_left: u8,
bottom_right: u8,
) -> char {
let top_left = if top_left > 0 { 1 } else { 0 };
let top_right = if top_right > 0 { 1 } else { 0 };
let upper_middle_left = if upper_middle_left > 0 { 1 } else { 0 };
let upper_middle_right = if upper_middle_right > 0 { 1 } else { 0 };
let lower_middle_left = if lower_middle_left > 0 { 1 } else { 0 };
let lower_middle_right = if lower_middle_right > 0 { 1 } else { 0 };
let bottom_left = if bottom_left > 0 { 1 } else { 0 };
let bottom_right = if bottom_right > 0 { 1 } else { 0 };
// We use an array here instead of directly indexing into the unicode symbols, because although
// most symbols are in order in unicode, some of them are already part of another character set
// and missing in this character set.
const OCTANT_SYMBOLS: [char; 256] = [
' ', '', '', '🮂', '', '▘', '', '', '', '', '▝', '', '', '', '', '▀', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '🮅', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '▖', '', '', '', '', '▌', '', '', '', '',
'▞', '', '', '', '', '▛', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '▗', '',
'', '', '', '▚', '', '', '', '', '▐', '', '', '', '', '▜', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '▂', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '▄', '', '', '', '', '▙', '', '', '', '', '▟', '',
'▆', '', '', '█',
];
let character_index = top_left
+ (top_right << 1)
+ (upper_middle_left << 2)
+ (upper_middle_right << 3)
+ (lower_middle_left << 4)
+ (lower_middle_right << 5)
+ (bottom_left << 6)
+ (bottom_right << 7);
OCTANT_SYMBOLS[character_index]
}
#[cfg(test)]
mod tests {
use super::*;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
#[test]
fn check_quadrant_size_symbols() -> Result<()> {
assert_eq!(get_symbol_quadrant_size(0, 0, 0, 0), ' ');
assert_eq!(get_symbol_quadrant_size(1, 0, 0, 0), '▘');
assert_eq!(get_symbol_quadrant_size(0, 1, 0, 0), '▝');
assert_eq!(get_symbol_quadrant_size(1, 1, 0, 0), '▀');
assert_eq!(get_symbol_quadrant_size(0, 0, 1, 0), '▖');
assert_eq!(get_symbol_quadrant_size(1, 0, 1, 0), '▌');
assert_eq!(get_symbol_quadrant_size(0, 1, 1, 0), '▞');
assert_eq!(get_symbol_quadrant_size(1, 1, 1, 0), '▛');
assert_eq!(get_symbol_quadrant_size(0, 0, 0, 1), '▗');
assert_eq!(get_symbol_quadrant_size(1, 0, 0, 1), '▚');
assert_eq!(get_symbol_quadrant_size(0, 1, 0, 1), '▐');
assert_eq!(get_symbol_quadrant_size(1, 1, 0, 1), '▜');
assert_eq!(get_symbol_quadrant_size(0, 0, 1, 1), '▄');
assert_eq!(get_symbol_quadrant_size(1, 0, 1, 1), '▙');
assert_eq!(get_symbol_quadrant_size(0, 1, 1, 1), '▟');
assert_eq!(get_symbol_quadrant_size(1, 1, 1, 1), '█');
Ok(())
}
#[test]
#[allow(clippy::cognitive_complexity)]
fn check_sextant_size_symbols() -> Result<()> {
assert_eq!(get_symbol_sextant_size(0, 0, 0, 0, 0, 0), ' ');
assert_eq!(get_symbol_sextant_size(1, 0, 0, 0, 0, 0), '🬀');
assert_eq!(get_symbol_sextant_size(0, 1, 0, 0, 0, 0), '🬁');
assert_eq!(get_symbol_sextant_size(1, 1, 0, 0, 0, 0), '🬂');
assert_eq!(get_symbol_sextant_size(0, 0, 1, 0, 0, 0), '🬃');
assert_eq!(get_symbol_sextant_size(1, 0, 1, 0, 0, 0), '🬄');
assert_eq!(get_symbol_sextant_size(0, 1, 1, 0, 0, 0), '🬅');
assert_eq!(get_symbol_sextant_size(1, 1, 1, 0, 0, 0), '🬆');
assert_eq!(get_symbol_sextant_size(0, 0, 0, 1, 0, 0), '🬇');
assert_eq!(get_symbol_sextant_size(1, 0, 0, 1, 0, 0), '🬈');
assert_eq!(get_symbol_sextant_size(0, 1, 0, 1, 0, 0), '🬉');
assert_eq!(get_symbol_sextant_size(1, 1, 0, 1, 0, 0), '🬊');
assert_eq!(get_symbol_sextant_size(0, 0, 1, 1, 0, 0), '🬋');
assert_eq!(get_symbol_sextant_size(1, 0, 1, 1, 0, 0), '🬌');
assert_eq!(get_symbol_sextant_size(0, 1, 1, 1, 0, 0), '🬍');
assert_eq!(get_symbol_sextant_size(1, 1, 1, 1, 0, 0), '🬎');
assert_eq!(get_symbol_sextant_size(0, 0, 0, 0, 1, 0), '🬏');
assert_eq!(get_symbol_sextant_size(1, 0, 0, 0, 1, 0), '🬐');
assert_eq!(get_symbol_sextant_size(0, 1, 0, 0, 1, 0), '🬑');
assert_eq!(get_symbol_sextant_size(1, 1, 0, 0, 1, 0), '🬒');
assert_eq!(get_symbol_sextant_size(0, 0, 1, 0, 1, 0), '🬓');
assert_eq!(get_symbol_sextant_size(1, 0, 1, 0, 1, 0), '▌');
assert_eq!(get_symbol_sextant_size(0, 1, 1, 0, 1, 0), '🬔');
assert_eq!(get_symbol_sextant_size(1, 1, 1, 0, 1, 0), '🬕');
assert_eq!(get_symbol_sextant_size(0, 0, 0, 1, 1, 0), '🬖');
assert_eq!(get_symbol_sextant_size(1, 0, 0, 1, 1, 0), '🬗');
assert_eq!(get_symbol_sextant_size(0, 1, 0, 1, 1, 0), '🬘');
assert_eq!(get_symbol_sextant_size(1, 1, 0, 1, 1, 0), '🬙');
assert_eq!(get_symbol_sextant_size(0, 0, 1, 1, 1, 0), '🬚');
assert_eq!(get_symbol_sextant_size(1, 0, 1, 1, 1, 0), '🬛');
assert_eq!(get_symbol_sextant_size(0, 1, 1, 1, 1, 0), '🬜');
assert_eq!(get_symbol_sextant_size(1, 1, 1, 1, 1, 0), '🬝');
assert_eq!(get_symbol_sextant_size(0, 0, 0, 0, 0, 1), '🬞');
assert_eq!(get_symbol_sextant_size(1, 0, 0, 0, 0, 1), '🬟');
assert_eq!(get_symbol_sextant_size(0, 1, 0, 0, 0, 1), '🬠');
assert_eq!(get_symbol_sextant_size(1, 1, 0, 0, 0, 1), '🬡');
assert_eq!(get_symbol_sextant_size(0, 0, 1, 0, 0, 1), '🬢');
assert_eq!(get_symbol_sextant_size(1, 0, 1, 0, 0, 1), '🬣');
assert_eq!(get_symbol_sextant_size(0, 1, 1, 0, 0, 1), '🬤');
assert_eq!(get_symbol_sextant_size(1, 1, 1, 0, 0, 1), '🬥');
assert_eq!(get_symbol_sextant_size(0, 0, 0, 1, 0, 1), '🬦');
assert_eq!(get_symbol_sextant_size(1, 0, 0, 1, 0, 1), '🬧');
assert_eq!(get_symbol_sextant_size(0, 1, 0, 1, 0, 1), '▐');
assert_eq!(get_symbol_sextant_size(1, 1, 0, 1, 0, 1), '🬨');
assert_eq!(get_symbol_sextant_size(0, 0, 1, 1, 0, 1), '🬩');
assert_eq!(get_symbol_sextant_size(1, 0, 1, 1, 0, 1), '🬪');
assert_eq!(get_symbol_sextant_size(0, 1, 1, 1, 0, 1), '🬫');
assert_eq!(get_symbol_sextant_size(1, 1, 1, 1, 0, 1), '🬬');
assert_eq!(get_symbol_sextant_size(0, 0, 0, 0, 1, 1), '🬭');
assert_eq!(get_symbol_sextant_size(1, 0, 0, 0, 1, 1), '🬮');
assert_eq!(get_symbol_sextant_size(0, 1, 0, 0, 1, 1), '🬯');
assert_eq!(get_symbol_sextant_size(1, 1, 0, 0, 1, 1), '🬰');
assert_eq!(get_symbol_sextant_size(0, 0, 1, 0, 1, 1), '🬱');
assert_eq!(get_symbol_sextant_size(1, 0, 1, 0, 1, 1), '🬲');
assert_eq!(get_symbol_sextant_size(0, 1, 1, 0, 1, 1), '🬳');
assert_eq!(get_symbol_sextant_size(1, 1, 1, 0, 1, 1), '🬴');
assert_eq!(get_symbol_sextant_size(0, 0, 0, 1, 1, 1), '🬵');
assert_eq!(get_symbol_sextant_size(1, 0, 0, 1, 1, 1), '🬶');
assert_eq!(get_symbol_sextant_size(0, 1, 0, 1, 1, 1), '🬷');
assert_eq!(get_symbol_sextant_size(1, 1, 0, 1, 1, 1), '🬸');
assert_eq!(get_symbol_sextant_size(0, 0, 1, 1, 1, 1), '🬹');
assert_eq!(get_symbol_sextant_size(1, 0, 1, 1, 1, 1), '🬺');
assert_eq!(get_symbol_sextant_size(0, 1, 1, 1, 1, 1), '🬻');
assert_eq!(get_symbol_sextant_size(1, 1, 1, 1, 1, 1), '█');
Ok(())
}
#[test]
#[allow(clippy::cognitive_complexity)]
fn check_octant_size_symbols() -> Result<()> {
assert_eq!(get_symbol_octant_size(0, 0, 0, 0, 0, 0, 0, 0), ' ');
assert_eq!(get_symbol_octant_size(1, 0, 0, 0, 0, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 0, 0, 0, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 0, 0, 0, 0, 0, 0), '🮂');
assert_eq!(get_symbol_octant_size(0, 0, 1, 0, 0, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 1, 0, 0, 0, 0, 0), '▘');
assert_eq!(get_symbol_octant_size(0, 1, 1, 0, 0, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 1, 0, 0, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 0, 1, 0, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 0, 1, 0, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 0, 1, 0, 0, 0, 0), '▝');
assert_eq!(get_symbol_octant_size(1, 1, 0, 1, 0, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 1, 1, 0, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 1, 1, 0, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 1, 1, 0, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 1, 1, 0, 0, 0, 0), '▀');
assert_eq!(get_symbol_octant_size(0, 0, 0, 0, 1, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 0, 0, 1, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 0, 0, 1, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 0, 0, 1, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 1, 0, 1, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 1, 0, 1, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 1, 0, 1, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 1, 0, 1, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 0, 1, 1, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 0, 1, 1, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 0, 1, 1, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 0, 1, 1, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 1, 1, 1, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 1, 1, 1, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 1, 1, 1, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 1, 1, 1, 0, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 0, 0, 0, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 0, 0, 0, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 0, 0, 0, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 0, 0, 0, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 1, 0, 0, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 1, 0, 0, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 1, 0, 0, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 1, 0, 0, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 0, 1, 0, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 0, 1, 0, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 0, 1, 0, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 0, 1, 0, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 1, 1, 0, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 1, 1, 0, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 1, 1, 0, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 1, 1, 0, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 0, 0, 1, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 0, 0, 1, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 0, 0, 1, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 0, 0, 1, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 1, 0, 1, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 1, 0, 1, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 1, 0, 1, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 1, 0, 1, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 0, 1, 1, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 0, 1, 1, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 0, 1, 1, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 0, 1, 1, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 1, 1, 1, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 1, 1, 1, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 1, 1, 1, 1, 0, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 1, 1, 1, 1, 0, 0), '🮅');
assert_eq!(get_symbol_octant_size(0, 0, 0, 0, 0, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 0, 0, 0, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 0, 0, 0, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 0, 0, 0, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 1, 0, 0, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 1, 0, 0, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 1, 0, 0, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 1, 0, 0, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 0, 1, 0, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 0, 1, 0, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 0, 1, 0, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 0, 1, 0, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 1, 1, 0, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 1, 1, 0, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 1, 1, 0, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 1, 1, 0, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 0, 0, 1, 0, 1, 0), '▖');
assert_eq!(get_symbol_octant_size(1, 0, 0, 0, 1, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 0, 0, 1, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 0, 0, 1, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 1, 0, 1, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 1, 0, 1, 0, 1, 0), '▌');
assert_eq!(get_symbol_octant_size(0, 1, 1, 0, 1, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 1, 0, 1, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 0, 1, 1, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 0, 1, 1, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 0, 1, 1, 0, 1, 0), '▞');
assert_eq!(get_symbol_octant_size(1, 1, 0, 1, 1, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 1, 1, 1, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 1, 1, 1, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 1, 1, 1, 0, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 1, 1, 1, 0, 1, 0), '▛');
assert_eq!(get_symbol_octant_size(0, 0, 0, 0, 0, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 0, 0, 0, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 0, 0, 0, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 0, 0, 0, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 1, 0, 0, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 1, 0, 0, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 1, 0, 0, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 1, 0, 0, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 0, 1, 0, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 0, 1, 0, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 0, 1, 0, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 0, 1, 0, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 1, 1, 0, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 1, 1, 0, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 1, 1, 0, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 1, 1, 0, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 0, 0, 1, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 0, 0, 1, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 0, 0, 1, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 0, 0, 1, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 1, 0, 1, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 1, 0, 1, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 1, 0, 1, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 1, 0, 1, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 0, 1, 1, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 0, 1, 1, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 0, 1, 1, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 0, 1, 1, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 1, 1, 1, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 0, 1, 1, 1, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 1, 1, 1, 1, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(1, 1, 1, 1, 1, 1, 1, 0), '');
assert_eq!(get_symbol_octant_size(0, 0, 0, 0, 0, 0, 0, 1), '');
assert_eq!(get_symbol_octant_size(1, 0, 0, 0, 0, 0, 0, 1), '');
assert_eq!(get_symbol_octant_size(0, 1, 0, 0, 0, 0, 0, 1), '');
assert_eq!(get_symbol_octant_size(1, 1, 0, 0, 0, 0, 0, 1), '');
assert_eq!(get_symbol_octant_size(0, 0, 1, 0, 0, 0, 0, 1), '');
assert_eq!(get_symbol_octant_size(1, 0, 1, 0, 0, 0, 0, 1), '');
assert_eq!(get_symbol_octant_size(0, 1, 1, 0, 0, 0, 0, 1), '');
assert_eq!(get_symbol_octant_size(1, 1, 1, 0, 0, 0, 0, 1), '');
assert_eq!(get_symbol_octant_size(0, 0, 0, 1, 0, 0, 0, 1), '');
assert_eq!(get_symbol_octant_size(1, 0, 0, 1, 0, 0, 0, 1), '');
assert_eq!(get_symbol_octant_size(0, 1, 0, 1, 0, 0, 0, 1), '');
assert_eq!(get_symbol_octant_size(1, 1, 0, 1, 0, 0, 0, 1), '');
assert_eq!(get_symbol_octant_size(0, 0, 1, 1, 0, 0, 0, 1), '');
assert_eq!(get_symbol_octant_size(1, 0, 1, 1, 0, 0, 0, 1), '');
assert_eq!(get_symbol_octant_size(0, 1, 1, 1, 0, 0, 0, 1), '');
assert_eq!(get_symbol_octant_size(1, 1, 1, 1, 0, 0, 0, 1), '');
assert_eq!(get_symbol_octant_size(0, 0, 0, 0, 1, 0, 0, 1), '');
assert_eq!(get_symbol_octant_size(1, 0, 0, 0, 1, 0, 0, 1), '');
assert_eq!(get_symbol_octant_size(0, 1, 0, 0, 1, 0, 0, 1), '');
assert_eq!(get_symbol_octant_size(1, 1, 0, 0, 1, 0, 0, 1), '');
assert_eq!(get_symbol_octant_size(0, 0, 1, 0, 1, 0, 0, 1), '');
assert_eq!(get_symbol_octant_size(1, 0, 1, 0, 1, 0, 0, 1), '');
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | true |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-big-text/examples/big_text.rs | tui-big-text/examples/big_text.rs | use color_eyre::Result;
use ratatui::layout::Offset;
use ratatui::prelude::{Frame, Style, Stylize};
use ratatui::text::Line;
use tui_big_text::BigText;
mod common;
fn main() -> Result<()> {
color_eyre::install()?;
common::run(render)?;
Ok(())
}
fn render(frame: &mut Frame) {
let title = Line::from("tui-big-text demo. <q> quit").cyan();
let big_text = BigText::builder()
.style(Style::new().blue())
.lines(vec![
"Tui-".red().into(),
"big-".white().into(),
"text".into(),
])
.build();
let area = frame.area();
frame.render_widget(title, area);
let area = area.offset(Offset { x: 0, y: 2 }).intersection(area);
frame.render_widget(big_text, area);
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-big-text/examples/alignment.rs | tui-big-text/examples/alignment.rs | use color_eyre::Result;
use ratatui::layout::{Constraint, Layout, Offset};
use ratatui::prelude::{Frame, Stylize};
use ratatui::text::Line;
use tui_big_text::{BigText, PixelSize};
mod common;
fn main() -> Result<()> {
color_eyre::install()?;
common::run(render)?;
Ok(())
}
fn render(frame: &mut Frame) {
let title = Line::from("tui-big-text alignment demo. <q> quit")
.cyan()
.centered();
let left = BigText::builder()
.pixel_size(PixelSize::Quadrant)
.left_aligned()
.lines(vec!["Left".white().into()])
.build();
let right = BigText::builder()
.pixel_size(PixelSize::Quadrant)
.right_aligned()
.lines(vec!["Right".green().into()])
.build();
let centered = BigText::builder()
.pixel_size(PixelSize::Quadrant)
.centered()
.lines(vec!["Centered".red().into()])
.build();
let area = frame.area();
frame.render_widget(title, area);
let area = area.offset(Offset { x: 0, y: 2 }).intersection(area);
let [top, middle, bottom] = Layout::vertical([Constraint::Length(4); 3]).areas(area);
frame.render_widget(left, top);
frame.render_widget(centered, middle);
frame.render_widget(right, bottom);
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-big-text/examples/pixel_size.rs | tui-big-text/examples/pixel_size.rs | use color_eyre::Result;
use ratatui::prelude::*;
use tui_big_text::{BigText, PixelSize};
mod common;
fn main() -> Result<()> {
color_eyre::install()?;
common::run(render)?;
Ok(())
}
fn render(frame: &mut Frame) {
let title = Line::from("tui-big-text pixel size demo. <q> quit")
.centered()
.cyan();
let full_size_text = BigText::builder()
.pixel_size(PixelSize::Full)
.lines(vec!["FullSize".white().into()])
.build();
let half_height_text = BigText::builder()
.pixel_size(PixelSize::HalfHeight)
.lines(vec!["1/2 high".green().into()])
.build();
let half_wide_text = BigText::builder()
.pixel_size(PixelSize::HalfWidth)
.lines(vec!["1/2 wide".red().into()])
.build();
let quadrant_text = BigText::builder()
.pixel_size(PixelSize::Quadrant)
.lines(vec!["Quadrant".blue().into(), " 1/2*1/2".blue().into()])
.build();
let third_text = BigText::builder()
.pixel_size(PixelSize::ThirdHeight)
.lines(vec!["1/3".yellow().into(), "high".yellow().into()])
.build();
let sextant_text = BigText::builder()
.pixel_size(PixelSize::Sextant)
.lines(vec!["Sextant".cyan().into(), " 1/2*1/3".cyan().into()])
.build();
let quarter_text = BigText::builder()
.pixel_size(PixelSize::QuarterHeight)
.lines(vec!["1/4".dark_gray().into(), "high".dark_gray().into()])
.build();
let octant_text = BigText::builder()
.pixel_size(PixelSize::Octant)
.lines(vec!["Octant".magenta().into(), " 1/2*1/4".magenta().into()])
.build();
// Setup layout for the title and 8 blocks
use Constraint::*;
let [top, full, half_height, upper_middle, lower_middle, bottom] = Layout::vertical([
Length(2),
Length(8),
Length(4),
Length(8),
Length(6),
Length(4),
])
.areas(frame.area());
let [half_wide, quadrant] = Layout::horizontal([Length(32), Length(32)]).areas(upper_middle);
let [third_height, sextant] = Layout::horizontal([Length(32), Length(32)]).areas(lower_middle);
let [quarter_height, octant] = Layout::horizontal([Length(32), Length(32)]).areas(bottom);
frame.render_widget(title, top);
frame.render_widget(full_size_text, full);
frame.render_widget(half_height_text, half_height);
frame.render_widget(half_wide_text, half_wide);
frame.render_widget(quadrant_text, quadrant);
frame.render_widget(third_text, third_height);
frame.render_widget(sextant_text, sextant);
frame.render_widget(quarter_text, quarter_height);
frame.render_widget(octant_text, octant);
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-big-text/examples/stopwatch.rs | tui-big-text/examples/stopwatch.rs | use std::io::{self, Stdout};
use std::time::{Duration, Instant};
use color_eyre::eyre::{bail, Context};
use color_eyre::Result;
use crossterm::event::{self, KeyCode};
use crossterm::execute;
use crossterm::terminal::{
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
};
use futures::{FutureExt, StreamExt};
// use futures::{select, FutureExt, StreamExt};
use itertools::Itertools;
use ratatui::prelude::*;
use ratatui::widgets::Paragraph;
use strum::EnumIs;
use tokio::select;
use tui_big_text::BigText;
#[tokio::main]
async fn main() -> Result<()> {
let mut app = StopwatchApp::default();
app.run().await
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, EnumIs)]
enum AppState {
#[default]
Stopped,
Running,
Quitting,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Message {
StartOrSplit,
Stop,
Tick,
Quit,
}
#[derive(Debug, Default, Clone, PartialEq)]
struct StopwatchApp {
state: AppState,
splits: Vec<Instant>,
fps_counter: FpsCounter,
}
impl StopwatchApp {
async fn run(&mut self) -> Result<()> {
let mut tui = Tui::init()?;
let mut events = EventHandler::new(60.0);
while !self.state.is_quitting() {
self.draw(&mut tui)?;
let message = events.next().await?;
self.handle_message(message)?;
}
Ok(())
}
fn handle_message(&mut self, message: Message) -> Result<()> {
match message {
Message::StartOrSplit => self.start_or_split(),
Message::Stop => self.stop(),
Message::Tick => self.tick(),
Message::Quit => self.quit(),
}
Ok(())
}
fn start_or_split(&mut self) {
if self.state.is_stopped() {
self.start();
} else {
self.record_split();
}
}
fn stop(&mut self) {
self.record_split();
self.state = AppState::Stopped;
}
fn tick(&mut self) {
self.fps_counter.tick()
}
const fn quit(&mut self) {
self.state = AppState::Quitting
}
fn start(&mut self) {
self.splits.clear();
self.state = AppState::Running;
self.record_split();
}
fn record_split(&mut self) {
if !self.state.is_running() {
return;
}
self.splits.push(Instant::now());
}
fn elapsed(&self) -> Duration {
if self.state.is_running() {
self.splits.first().map_or(Duration::ZERO, Instant::elapsed)
} else {
// last - first or 0 if there are no splits
let now = Instant::now();
let first = *self.splits.first().unwrap_or(&now);
let last = *self.splits.last().unwrap_or(&now);
last - first
}
}
fn draw(&self, tui: &mut Tui) -> Result<()> {
tui.draw(|frame| {
let layout = layout(frame.area());
frame.render_widget(Paragraph::new("Stopwatch Example"), layout[0]);
frame.render_widget(self.fps_paragraph(), layout[1]);
frame.render_widget(self.timer_paragraph(), layout[2]);
frame.render_widget(Paragraph::new("Splits:"), layout[3]);
frame.render_widget(self.splits_paragraph(), layout[4]);
frame.render_widget(self.help_paragraph(), layout[5]);
})
}
fn fps_paragraph(&self) -> Paragraph<'_> {
let fps = format!("{:.2} fps", self.fps_counter.fps);
Paragraph::new(fps).dim().right_aligned()
}
fn timer_paragraph(&self) -> BigText<'_> {
let style = if self.state.is_running() {
Style::new().green()
} else {
Style::new().red()
};
let duration = format_duration(self.elapsed());
let lines = vec![duration.into()];
BigText::builder().lines(lines).style(style).build()
}
/// Renders the splits as a list of lines.
///
/// ```text
/// #01 -- 00:00.693 -- 00:00.693
/// #02 -- 00:00.719 -- 00:01.413
/// ```
fn splits_paragraph(&self) -> Paragraph<'_> {
let start = self.splits.first().copied().unwrap_or_else(Instant::now);
let mut splits = self
.splits
.iter()
.copied()
.tuple_windows()
.enumerate()
.map(|(index, (prev, current))| format_split(index, start, prev, current))
.collect::<Vec<_>>();
splits.reverse();
Paragraph::new(splits)
}
fn help_paragraph(&self) -> Paragraph<'_> {
let space_action = if self.state.is_stopped() {
"start"
} else {
"split"
};
let help_text = Line::from(vec![
"space ".into(),
space_action.dim(),
" enter ".into(),
"stop".dim(),
" q ".into(),
"quit".dim(),
]);
Paragraph::new(help_text).gray()
}
}
fn layout(area: Rect) -> Vec<Rect> {
let layout = Layout::vertical(vec![
Constraint::Length(2), // top bar
Constraint::Length(8), // timer
Constraint::Length(1), // splits header
Constraint::Min(0), // splits
Constraint::Length(1), // help
])
.split(area);
let top_layout = Layout::horizontal(vec![
Constraint::Length(20), // title
Constraint::Min(0), // fps counter
])
.split(layout[0]);
// return a new vec with the top_layout rects and then rest of layout
top_layout[..]
.iter()
.chain(layout[1..].iter())
.copied()
.collect()
}
fn format_split<'a>(index: usize, start: Instant, previous: Instant, current: Instant) -> Line<'a> {
let split = format_duration(current - previous);
let elapsed = format_duration(current - start);
Line::from(vec![
format!("#{:02} -- ", index + 1).into(),
Span::styled(split, Style::new().yellow()),
" -- ".into(),
Span::styled(elapsed, Style::new()),
])
}
fn format_duration(duration: Duration) -> String {
format!(
"{:02}:{:02}.{:03}",
duration.as_secs() / 60,
duration.as_secs() % 60,
duration.subsec_millis()
)
}
#[derive(Debug, Clone, PartialEq)]
struct FpsCounter {
start_time: Instant,
frames: u32,
pub fps: f64,
}
impl Default for FpsCounter {
fn default() -> Self {
Self::new()
}
}
impl FpsCounter {
fn new() -> Self {
Self {
start_time: Instant::now(),
frames: 0,
fps: 0.0,
}
}
fn tick(&mut self) {
self.frames += 1;
let now = Instant::now();
let elapsed = (now - self.start_time).as_secs_f64();
if elapsed >= 1.0 {
self.fps = self.frames as f64 / elapsed;
self.start_time = now;
self.frames = 0;
}
}
}
/// Handles events from crossterm and emits `Message`s.
struct EventHandler {
crossterm_events: event::EventStream,
interval: tokio::time::Interval,
}
impl EventHandler {
/// Creates a new event handler that emits a `Message::Tick` every `1.0 / max_fps` seconds.
fn new(max_fps: f32) -> Self {
let period = Duration::from_secs_f32(1.0 / max_fps);
Self {
crossterm_events: event::EventStream::new(),
interval: tokio::time::interval(period),
}
}
async fn next(&mut self) -> Result<Message> {
select! {
event = self.crossterm_events.next().fuse() => Self::handle_crossterm_event(event),
_ = self.interval.tick().fuse() => Ok(Message::Tick),
}
}
fn handle_crossterm_event(
event: Option<core::result::Result<event::Event, std::io::Error>>,
) -> Result<Message> {
match event {
Some(Ok(event::Event::Key(key))) => Ok(match key.code {
KeyCode::Char('q') => Message::Quit,
KeyCode::Char(' ') => Message::StartOrSplit,
KeyCode::Char('s') | KeyCode::Enter => Message::Stop,
_ => Message::Tick,
}),
Some(Err(err)) => bail!(err),
None => bail!("event stream ended unexpectedly"),
_ => Ok(Message::Tick),
}
}
}
struct Tui {
terminal: Terminal<CrosstermBackend<Stdout>>,
}
impl Tui {
fn init() -> Result<Self> {
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen).wrap_err("failed to enter alternate screen")?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend).wrap_err("failed to create terminal")?;
enable_raw_mode().wrap_err("failed to enable raw mode")?;
terminal.hide_cursor().wrap_err("failed to hide cursor")?;
terminal.clear().wrap_err("failed to clear console")?;
Ok(Self { terminal })
}
fn draw(&mut self, frame: impl FnOnce(&mut Frame)) -> Result<()> {
self.terminal.draw(frame).wrap_err("failed to draw frame")?;
Ok(())
}
}
impl Drop for Tui {
fn drop(&mut self) {
disable_raw_mode().expect("failed to disable raw mode");
execute!(self.terminal.backend_mut(), LeaveAlternateScreen)
.expect("failed to switch to main screen");
self.terminal.show_cursor().expect("failed to show cursor");
self.terminal.clear().expect("failed to clear console");
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-big-text/examples/common/mod.rs | tui-big-text/examples/common/mod.rs | //! common module for examples
use std::io;
use color_eyre::Result;
use crossterm::terminal::{
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
};
use crossterm::ExecutableCommand;
use ratatui::prelude::CrosstermBackend;
/// A type alias for the terminal
type Terminal = ratatui::Terminal<CrosstermBackend<io::Stdout>>;
/// A generic main loop for a TUI example that just renders the given function and exits when the
/// user presses 'q' or 'Esc'
pub fn run<F>(render: F) -> Result<()>
where
F: Fn(&mut ratatui::Frame),
{
install_panic_handler();
with_terminal(|mut terminal| loop {
terminal.draw(|frame| render(frame))?;
if let crossterm::event::Event::Key(event) = crossterm::event::read()? {
if matches!(
event.code,
crossterm::event::KeyCode::Char('q') | crossterm::event::KeyCode::Esc
) {
break Ok(());
}
}
})
}
/// Install a panic handler that restores the terminal before panicking
fn install_panic_handler() {
let hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |panic_info| {
if let Err(err) = restore() {
eprintln!("failed to restore terminal: {err}");
}
hook(panic_info);
}));
}
/// Run a function with a terminal ensuring that the terminal is restored afterwards
fn with_terminal<F>(f: F) -> color_eyre::Result<()>
where
F: FnOnce(Terminal) -> color_eyre::Result<()>,
{
let terminal = init()?;
let result = f(terminal);
restore()?;
result?;
Ok(())
}
/// Initialize a terminal
fn init() -> io::Result<Terminal> {
io::stdout().execute(EnterAlternateScreen)?;
enable_raw_mode()?;
let backend = CrosstermBackend::new(io::stdout());
let mut terminal = Terminal::new(backend)?;
terminal.clear()?;
Ok(terminal)
}
/// Restore the terminal to its original state
fn restore() -> io::Result<()> {
io::stdout().execute(LeaveAlternateScreen)?;
disable_raw_mode()?;
Ok(())
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-scrollbar/src/lengths.rs | tui-scrollbar/src/lengths.rs | /// Bundle content and viewport lengths to avoid ambiguous arguments.
///
/// This struct is a convenience for readability. Use a struct literal so each field is named at
/// the call site:
///
/// ```rust
/// use tui_scrollbar::ScrollLengths;
///
/// let lengths = ScrollLengths {
/// content_len: 200,
/// viewport_len: 20,
/// };
/// ```
///
/// Zero values are accepted, and consumers like [`ScrollBar`] and [`ScrollMetrics`] will treat
/// them as 1.
///
/// [`ScrollBar`]: crate::ScrollBar
/// [`ScrollMetrics`]: crate::ScrollMetrics
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ScrollLengths {
/// Total scrollable content length in logical units.
pub content_len: usize,
/// Visible viewport length in logical units.
pub viewport_len: usize,
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-scrollbar/src/lib.rs | tui-scrollbar/src/lib.rs | //! Smooth, fractional scrollbars for Ratatui. Part of the [tui-widgets] suite by [Joshka].
//!
//! 
//!
//! [![Crate badge]][Crate]
//! [![Docs Badge]][Docs]
//! [![Deps Badge]][Dependency Status]
//! [![License Badge]][License]
//! [![Coverage Badge]][Coverage]
//! [![Discord Badge]][Ratatui Discord]
//!
//! [GitHub Repository] · [API Docs] · [Examples] · [Changelog] · [Contributing] · [Crate source]
//!
//! Use this crate when you want scrollbars that communicate position and size more precisely than
//! full-cell glyphs. The widget renders into a [`Buffer`] for a given [`Rect`] and stays reusable
//! by implementing [`Widget`] for `&ScrollBar`.
//!
//! # Feature highlights
//!
//! - Fractional thumbs: render 1/8th-cell steps for clearer position/size feedback.
//! - Arrow endcaps: optional start/end arrows with click-to-step support.
//! - Backend-agnostic input: handle pointer + wheel events without tying to a backend.
//! - Stateless rendering: render via [`Widget`] for `&ScrollBar` with external state.
//! - Metrics-first: [`ScrollMetrics`] exposes pure geometry for testing and hit testing.
//!
//! # Why not Ratatui's scrollbar?
//!
//! Ratatui's built-in scrollbar favors simple full-cell glyphs and a stateful widget workflow.
//! This crate chooses fractional glyphs for more precise thumbs, keeps rendering stateless, and
//! exposes a small interaction API plus pure metrics so apps can control behavior explicitly.
//!
//! # Installation
//!
//! ```shell
//! cargo add tui-scrollbar
//! ```
//!
//! # Quick start
//!
//! This example renders a vertical [`ScrollBar`] into a [`Buffer`] using a fixed track size and
//! offset. Use it as a minimal template when you just need a thumb and track on screen.
//! If you prefer named arguments, use [`ScrollLengths`].
//!
//! ```rust
//! use ratatui_core::buffer::Buffer;
//! use ratatui_core::layout::Rect;
//! use ratatui_core::widgets::Widget;
//! use tui_scrollbar::{ScrollBar, ScrollBarArrows, ScrollLengths};
//!
//! let area = Rect::new(0, 0, 1, 6);
//! let lengths = ScrollLengths {
//! content_len: 120,
//! viewport_len: 30,
//! };
//! let scrollbar = ScrollBar::vertical(lengths)
//! .arrows(ScrollBarArrows::Both)
//! .offset(45);
//!
//! let mut buffer = Buffer::empty(area);
//! scrollbar.render(area, &mut buffer);
//! ```
//!
//! # Conceptual overview
//!
//! The scrollbar works in three pieces:
//!
//! 1. Your app owns `content_len`, `viewport_len`, and `offset` (lengths along the scroll axis).
//! 2. [`ScrollMetrics`] converts those values into a thumb position and size.
//! 3. [`ScrollBar`] renders the track + thumb using fractional glyphs.
//!
//! Most apps update `offset` in response to input events and re-render each frame.
//!
//! ## Units and subcell conversions
//!
//! `content_len`, `viewport_len`, and `offset` are measured in logical units along the scroll
//! axis. For many apps, those units are items or lines. The ratio between `viewport_len` and
//! `content_len` is what matters, so any consistent unit works.
//!
//! Zero lengths are treated as 1.
//!
//! # Layout integration
//!
//! This example shows how to reserve a column for a vertical [`ScrollBar`] alongside your content.
//! Use the same pattern for a horizontal [`ScrollBar`] by splitting rows instead of columns.
//!
//! ```rust,no_run
//! use ratatui_core::buffer::Buffer;
//! use ratatui_core::layout::{Constraint, Layout, Rect};
//! use ratatui_core::widgets::Widget;
//! use tui_scrollbar::{ScrollBar, ScrollLengths};
//!
//! let area = Rect::new(0, 0, 12, 6);
//! let [content_area, bar_area] = area.layout(&Layout::horizontal([
//! Constraint::Fill(1),
//! Constraint::Length(1),
//! ]));
//!
//! let lengths = ScrollLengths {
//! content_len: 400,
//! viewport_len: 80,
//! };
//! let scrollbar = ScrollBar::vertical(lengths).offset(0);
//!
//! let mut buffer = Buffer::empty(area);
//! scrollbar.render(bar_area, &mut buffer);
//! ```
//!
//! # Interaction loop
//!
//! This pattern assumes you have enabled mouse capture in your terminal backend and have the
//! scrollbar [`Rect`] (`bar_area`) from your layout each frame. Keep a [`ScrollBarInteraction`] in
//! your app state so drag operations persist across draws. Mouse events are handled via
//! [`ScrollBar::handle_mouse_event`], which returns a [`ScrollCommand`] to apply.
//!
//! ```rust,no_run
//! use ratatui_core::layout::Rect;
//! use tui_scrollbar::{ScrollBar, ScrollBarInteraction, ScrollCommand, ScrollLengths};
//!
//! let bar_area = Rect::new(0, 0, 1, 10);
//! let lengths = ScrollLengths {
//! content_len: 400,
//! viewport_len: 80,
//! };
//! let scrollbar = ScrollBar::vertical(lengths).offset(0);
//! let mut interaction = ScrollBarInteraction::new();
//! let mut offset = 0;
//!
//! # #[cfg(feature = "crossterm")]
//! # {
//! # use crossterm::event::{self, Event};
//! if let Event::Mouse(event) = event::read()? {
//! if let Some(ScrollCommand::SetOffset(next)) =
//! scrollbar.handle_mouse_event(bar_area, event, &mut interaction)
//! {
//! offset = next;
//! }
//! }
//! # }
//! # let _ = offset;
//! # Ok::<(), std::io::Error>(())
//! ```
//!
//! # Metrics-first workflow
//!
//! This example shows how to compute thumb geometry without rendering via [`ScrollMetrics`]. It's
//! useful for testing, hit testing, or when you want to inspect thumb sizing directly.
//!
//! ```rust
//! use tui_scrollbar::{ScrollLengths, ScrollMetrics, SUBCELL};
//!
//! let track_cells = 12;
//! let viewport_len = track_cells * SUBCELL;
//! let content_len = viewport_len * 6;
//! let lengths = ScrollLengths {
//! content_len,
//! viewport_len,
//! };
//! let metrics = ScrollMetrics::new(lengths, 0, track_cells as u16);
//! assert!(metrics.thumb_len() >= SUBCELL);
//! ```
//!
//! # Glyph selection
//!
//! The default glyphs include [Symbols for Legacy Computing] so the thumb can render upper/right
//! partial fills that are missing from the standard block set. Use [`GlyphSet`] when you want to
//! switch to a glyph set that avoids legacy symbols.
//!
//! ```rust
//! use tui_scrollbar::{GlyphSet, ScrollBar, ScrollLengths};
//!
//! let lengths = ScrollLengths {
//! content_len: 10,
//! viewport_len: 5,
//! };
//! let scrollbar = ScrollBar::vertical(lengths).glyph_set(GlyphSet::unicode());
//! ```
//!
//! # API map
//!
//! ## Widgets
//!
//! - [`ScrollBar`]: renders vertical or horizontal scrollbars with fractional thumbs.
//!
//! ## Supporting types
//!
//! - [`ScrollBarInteraction`]: drag capture state for pointer interaction.
//! - [`ScrollMetrics`]: pure math for thumb sizing and hit testing.
//! - [`GlyphSet`]: glyph selection for track and thumb rendering.
//! - [`ScrollBarArrows`]: arrow endcap configuration.
//!
//! ## Enums and events
//!
//! - [`ScrollBarOrientation`], [`ScrollBarArrows`], [`TrackClickBehavior`]
//! - [`ScrollEvent`], [`ScrollCommand`]
//! - [`PointerEvent`], [`PointerEventKind`], [`PointerButton`]
//! - [`ScrollWheel`], [`ScrollAxis`]
//!
//! # Features
//!
//! - `crossterm`: enables the `handle_mouse_event` adapter for crossterm mouse events.
//!
//! # Important
//!
//! - Zero lengths are treated as 1.
//! - Arrow endcaps are enabled by default; configure them with [`ScrollBarArrows`].
//! - The default glyphs use [Symbols for Legacy Computing] for missing upper/right eighth blocks.
//! Use [`GlyphSet::unicode`] if you need only standard Unicode block elements.
//!
//! # See also
//!
//! - [tui-scrollbar examples]
//! - [`scrollbar_mouse` example]
//! - [`scrollbar` example]
//! - [`Widget`]
//! - [Ratatui]
//!
//! # More widgets
//!
//! For the full suite of widgets, see [tui-widgets].
//!
//! [Ratatui]: https://crates.io/crates/ratatui
//! [Crate]: https://crates.io/crates/tui-scrollbar
//! [Docs]: https://docs.rs/tui-scrollbar/
//! [Dependency Status]: https://deps.rs/repo/github/joshka/tui-widgets
//! [Coverage]: https://app.codecov.io/gh/joshka/tui-widgets
//! [Ratatui Discord]: https://discord.gg/pMCEU9hNEj
//! [Crate badge]: https://img.shields.io/crates/v/tui-scrollbar?logo=rust&style=flat
//! [Docs Badge]: https://img.shields.io/docsrs/tui-scrollbar?logo=rust&style=flat
//! [Deps Badge]: https://deps.rs/repo/github/joshka/tui-widgets/status.svg?style=flat
//! [License Badge]: https://img.shields.io/crates/l/tui-scrollbar?style=flat
//! [License]: https://github.com/joshka/tui-widgets/blob/main/LICENSE-MIT
//! [Coverage Badge]:
//! https://img.shields.io/codecov/c/github/joshka/tui-widgets?logo=codecov&style=flat
//! [Discord Badge]: https://img.shields.io/discord/1070692720437383208?logo=discord&style=flat
//! [GitHub Repository]: https://github.com/joshka/tui-widgets
//! [API Docs]: https://docs.rs/tui-scrollbar/
//! [Examples]: https://github.com/joshka/tui-widgets/tree/main/tui-scrollbar/examples
//! [Changelog]: https://github.com/joshka/tui-widgets/blob/main/tui-scrollbar/CHANGELOG.md
//! [Contributing]: https://github.com/joshka/tui-widgets/blob/main/CONTRIBUTING.md
//! [Crate source]: https://github.com/joshka/tui-widgets/blob/main/tui-scrollbar/src/lib.rs
//! [`scrollbar_mouse` example]: https://github.com/joshka/tui-widgets/tree/main/tui-scrollbar/examples/scrollbar_mouse.rs
//! [`scrollbar` example]: https://github.com/joshka/tui-widgets/tree/main/tui-scrollbar/examples/scrollbar.rs
//! [tui-scrollbar examples]: https://github.com/joshka/tui-widgets/tree/main/tui-scrollbar/examples
//! [`Buffer`]: ratatui_core::buffer::Buffer
//! [`Rect`]: ratatui_core::layout::Rect
//! [`Widget`]: ratatui_core::widgets::Widget
//! [Symbols for Legacy Computing]: https://en.wikipedia.org/wiki/Symbols_for_Legacy_Computing
//!
//! [Joshka]: https://github.com/joshka
//! [tui-widgets]: https://crates.io/crates/tui-widgets
#![cfg_attr(docsrs, doc = "\n# Feature flags\n")]
#![cfg_attr(docsrs, doc = document_features::document_features!())]
#![deny(missing_docs)]
mod glyphs;
mod input;
mod lengths;
mod metrics;
mod scrollbar;
pub use crate::glyphs::GlyphSet;
pub use crate::input::{
PointerButton, PointerEvent, PointerEventKind, ScrollAxis, ScrollBarInteraction, ScrollCommand,
ScrollEvent, ScrollWheel,
};
pub use crate::lengths::ScrollLengths;
pub use crate::metrics::{CellFill, HitTest, ScrollMetrics, SUBCELL};
pub use crate::scrollbar::{ScrollBar, ScrollBarArrows, ScrollBarOrientation, TrackClickBehavior};
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-scrollbar/src/glyphs.rs | tui-scrollbar/src/glyphs.rs | //! Glyph configuration for scrollbar rendering.
/// Glyphs used to render the track, arrows, and thumb.
///
/// Arrays use indices 0..=7 to represent 1/8th through full coverage.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GlyphSet {
/// Track glyph for vertical scrollbars.
pub track_vertical: char,
/// Track glyph for horizontal scrollbars.
pub track_horizontal: char,
/// Arrow glyph for the start of a vertical scrollbar (top).
pub arrow_vertical_start: char,
/// Arrow glyph for the end of a vertical scrollbar (bottom).
pub arrow_vertical_end: char,
/// Arrow glyph for the start of a horizontal scrollbar (left).
pub arrow_horizontal_start: char,
/// Arrow glyph for the end of a horizontal scrollbar (right).
pub arrow_horizontal_end: char,
/// Thumb glyphs for vertical lower fills (1/8th through full).
pub thumb_vertical_lower: [char; 8],
/// Thumb glyphs for vertical upper fills (1/8th through full).
pub thumb_vertical_upper: [char; 8],
/// Thumb glyphs for horizontal left fills (1/8th through full).
pub thumb_horizontal_left: [char; 8],
/// Thumb glyphs for horizontal right fills (1/8th through full).
pub thumb_horizontal_right: [char; 8],
}
impl GlyphSet {
/// Glyphs that mix standard block elements with legacy supplement glyphs.
///
/// Use this to get full 1/8th coverage for upper and right edges that the standard block set
/// lacks; these glyphs come from [Symbols for Legacy Computing].
///
/// [Symbols for Legacy Computing]: https://en.wikipedia.org/wiki/Symbols_for_Legacy_Computing
pub const fn symbols_for_legacy_computing() -> Self {
let vertical_lower = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
let vertical_upper = ['▔', '🮂', '🮃', '▀', '🮄', '🮅', '🮆', '█'];
let horizontal_left = ['▏', '▎', '▍', '▌', '▋', '▊', '▉', '█'];
let horizontal_right = ['▕', '🮇', '🮈', '▐', '🮉', '🮊', '🮋', '█'];
Self {
track_vertical: '│',
track_horizontal: '─',
arrow_vertical_start: '▲',
arrow_vertical_end: '▼',
arrow_horizontal_start: '◀',
arrow_horizontal_end: '▶',
thumb_vertical_lower: vertical_lower,
thumb_vertical_upper: vertical_upper,
thumb_horizontal_left: horizontal_left,
thumb_horizontal_right: horizontal_right,
}
}
/// Glyphs using only standard Unicode block elements.
///
/// Use this if your font lacks the legacy glyphs; upper/right partials will use the same
/// glyphs as lower/left partials.
pub const fn unicode() -> Self {
let vertical = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
let horizontal = ['▏', '▎', '▍', '▌', '▋', '▊', '▉', '█'];
Self {
track_vertical: '│',
track_horizontal: '─',
arrow_vertical_start: '▲',
arrow_vertical_end: '▼',
arrow_horizontal_start: '◀',
arrow_horizontal_end: '▶',
thumb_vertical_lower: vertical,
thumb_vertical_upper: vertical,
thumb_horizontal_left: horizontal,
thumb_horizontal_right: horizontal,
}
}
}
impl Default for GlyphSet {
fn default() -> Self {
Self::symbols_for_legacy_computing()
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-scrollbar/src/metrics.rs | tui-scrollbar/src/metrics.rs | //! Pure scrollbar geometry and hit testing.
//!
//! This module contains the math behind thumb sizing and positioning. It is backend-agnostic and
//! does not touch terminal rendering, making it suitable for unit tests and hit testing.
//!
//! Use [`ScrollMetrics`] when you need the thumb geometry without rendering a widget. This is
//! especially useful for input handling, layout tests, or validating edge cases such as
//! `content_len <= viewport_len`.
//!
//! ## Subcells
//!
//! A subcell is one eighth of a terminal cell. This module measures content, viewport, and offsets
//! in logical units so fractional thumb sizes can be represented precisely. These lengths are
//! logical values (not pixels); you decide how they map to your data. The track length is still
//! expressed in full cells, then multiplied by [`SUBCELL`] to compute subcell positions.
//!
//! The example below shows a common pattern: convert a track measured in cells into subcell units,
//! then compute a proportional thumb size and position.
//!
//! ```rust
//! use tui_scrollbar::{ScrollLengths, ScrollMetrics, SUBCELL};
//!
//! let track_cells = 8;
//! let viewport_len = track_cells * SUBCELL;
//! let content_len = viewport_len * 4;
//! let lengths = ScrollLengths {
//! content_len,
//! viewport_len,
//! };
//! let metrics = ScrollMetrics::new(lengths, 0, track_cells as u16);
//!
//! assert!(metrics.thumb_len() >= SUBCELL);
//! ```
use std::ops::Range;
/// Number of subcells in a single terminal cell.
pub const SUBCELL: usize = 8;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Describes how much of a single cell is covered by the thumb.
///
/// Use this to select track vs thumb glyphs. Partial fills are measured from the start of the
/// cell (top for vertical, left for horizontal).
pub enum CellFill {
/// No coverage; the track should render.
Empty,
/// Entire cell is covered by the thumb.
Full,
/// A fractional range inside the cell is covered by the thumb.
Partial {
/// Subcell offset within the cell where coverage starts.
start: u8,
/// Number of subcells covered within the cell.
len: u8,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Whether a position lands on the thumb or track.
///
/// Positions are measured in subcells along the track.
pub enum HitTest {
/// The position is inside the thumb.
Thumb,
/// The position is outside the thumb.
Track,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Precomputed values for proportional scrollbars.
///
/// All positions are tracked in subcell units (1/8 of a terminal cell). Use this type to compute
/// thumb length, travel, and hit testing without rendering anything. The inputs are:
///
/// - `content_len` and `viewport_len` in logical units (zero treated as 1)
/// - `track_cells` in terminal cells
pub struct ScrollMetrics {
content_len: usize,
viewport_len: usize,
offset: usize,
track_cells: usize,
track_len: usize,
thumb_len: usize,
thumb_start: usize,
}
impl ScrollMetrics {
/// Build metrics using a [`crate::ScrollLengths`] helper.
pub fn from_lengths(lengths: crate::ScrollLengths, offset: usize, track_cells: u16) -> Self {
Self::new(lengths, offset, track_cells)
}
/// Build metrics for the given content and viewport lengths.
///
/// The `track_cells` parameter is the number of terminal cells available for the track
/// (height for vertical scrollbars, width for horizontal). The lengths are logical units.
/// When `content_len` is smaller than `viewport_len`, the thumb fills the track to indicate no
/// scrolling. Zero lengths are treated as 1.
pub fn new(lengths: crate::ScrollLengths, offset: usize, track_cells: u16) -> Self {
let track_cells = track_cells as usize;
let track_len = track_cells.saturating_mul(SUBCELL);
if track_len == 0 {
return Self {
content_len: lengths.content_len,
viewport_len: lengths.viewport_len,
offset,
track_cells,
track_len,
thumb_len: 0,
thumb_start: 0,
};
}
let content_len = lengths.content_len.max(1);
let viewport_len = lengths.viewport_len.min(content_len).max(1);
let max_offset = content_len.saturating_sub(viewport_len);
let offset = offset.min(max_offset);
let (thumb_len, thumb_start) = if max_offset == 0 {
(track_len, 0)
} else {
let thumb_len = (track_len.saturating_mul(viewport_len) / content_len)
.max(SUBCELL)
.min(track_len);
let thumb_travel = track_len.saturating_sub(thumb_len);
let thumb_start = thumb_travel.saturating_mul(offset) / max_offset;
(thumb_len, thumb_start)
};
Self {
content_len,
viewport_len,
offset,
track_cells,
track_len,
thumb_len,
thumb_start,
}
}
/// Returns the current content length in logical units.
pub const fn content_len(&self) -> usize {
self.content_len
}
/// Returns the current viewport length in logical units.
pub const fn viewport_len(&self) -> usize {
self.viewport_len
}
/// Returns the current content offset in logical units.
pub const fn offset(&self) -> usize {
self.offset
}
/// Returns the track length in terminal cells.
pub const fn track_cells(&self) -> usize {
self.track_cells
}
/// Returns the track length in subcells.
pub const fn track_len(&self) -> usize {
self.track_len
}
/// Returns the thumb length in subcells.
pub const fn thumb_len(&self) -> usize {
self.thumb_len
}
/// Returns the thumb start position in subcells.
pub const fn thumb_start(&self) -> usize {
self.thumb_start
}
/// Returns the maximum scrollable offset in subcells.
pub const fn max_offset(&self) -> usize {
self.content_len.saturating_sub(self.viewport_len)
}
/// Returns the maximum thumb travel in subcells.
pub const fn thumb_travel(&self) -> usize {
self.track_len.saturating_sub(self.thumb_len)
}
/// Returns the thumb range in subcell coordinates.
pub const fn thumb_range(&self) -> Range<usize> {
self.thumb_start..self.thumb_start.saturating_add(self.thumb_len)
}
/// Returns whether a subcell position hits the thumb or the track.
pub const fn hit_test(&self, position: usize) -> HitTest {
if position >= self.thumb_start
&& position < self.thumb_start.saturating_add(self.thumb_len)
{
HitTest::Thumb
} else {
HitTest::Track
}
}
/// Converts an offset (in subcells) to a thumb start position (in subcells).
///
/// Larger offsets move the thumb toward the end of the track, clamped to the maximum travel.
pub fn thumb_start_for_offset(&self, offset: usize) -> usize {
let max_offset = self.max_offset();
if max_offset == 0 {
return 0;
}
let offset = offset.min(max_offset);
self.thumb_travel().saturating_mul(offset) / max_offset
}
/// Converts a thumb start position (in subcells) to an offset (in subcells).
///
/// Thumb positions beyond the end of travel are clamped to the maximum offset.
pub fn offset_for_thumb_start(&self, thumb_start: usize) -> usize {
let max_offset = self.max_offset();
if max_offset == 0 {
return 0;
}
let thumb_start = thumb_start.min(self.thumb_travel());
max_offset.saturating_mul(thumb_start) / self.thumb_travel()
}
/// Returns how much of a cell is filled by the thumb.
///
/// The `cell_index` is in terminal cells, not subcells. Use this to select the correct glyph
/// for the track or thumb.
pub fn cell_fill(&self, cell_index: usize) -> CellFill {
if self.thumb_len == 0 {
return CellFill::Empty;
}
let cell_start = cell_index.saturating_mul(SUBCELL);
let cell_end = cell_start.saturating_add(SUBCELL);
let thumb_end = self.thumb_start.saturating_add(self.thumb_len);
let start = self.thumb_start.max(cell_start);
let end = thumb_end.min(cell_end);
if end <= start {
return CellFill::Empty;
}
let len = end.saturating_sub(start).min(SUBCELL) as u8;
let start = start.saturating_sub(cell_start).min(SUBCELL) as u8;
if len as usize >= SUBCELL {
CellFill::Full
} else {
CellFill::Partial { start, len }
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fills_track_when_no_scroll() {
let metrics = ScrollMetrics::new(
crate::ScrollLengths {
content_len: 10,
viewport_len: 10,
},
0,
4,
);
assert_eq!(metrics.thumb_len(), 32);
assert_eq!(metrics.thumb_start(), 0);
}
#[test]
fn clamps_offset_to_max() {
let metrics = ScrollMetrics::new(
crate::ScrollLengths {
content_len: 100,
viewport_len: 10,
},
200,
4,
);
assert_eq!(metrics.offset(), 90);
assert_eq!(metrics.thumb_start(), metrics.thumb_travel());
}
#[test]
fn reports_partial_cell_fills() {
let metrics = ScrollMetrics::new(
crate::ScrollLengths {
content_len: 10,
viewport_len: 3,
},
1,
4,
);
assert_eq!(metrics.cell_fill(0), CellFill::Partial { start: 3, len: 5 });
assert_eq!(metrics.cell_fill(1), CellFill::Partial { start: 0, len: 4 });
assert_eq!(metrics.cell_fill(2), CellFill::Empty);
}
#[test]
fn distinguishes_thumb_vs_track_hits() {
let metrics = ScrollMetrics::new(
crate::ScrollLengths {
content_len: 10,
viewport_len: 3,
},
1,
4,
);
assert_eq!(metrics.hit_test(0), HitTest::Track);
assert_eq!(metrics.hit_test(4), HitTest::Thumb);
assert_eq!(metrics.hit_test(12), HitTest::Track);
}
#[test]
fn stays_scale_invariant_for_logical_units() {
let track_cells = 10;
let base = ScrollMetrics::new(
crate::ScrollLengths {
content_len: 200,
viewport_len: 20,
},
10,
track_cells,
);
let scaled = ScrollMetrics::new(
crate::ScrollLengths {
content_len: 200 * SUBCELL,
viewport_len: 20 * SUBCELL,
},
10 * SUBCELL,
track_cells,
);
assert_eq!(base.thumb_len(), scaled.thumb_len());
assert_eq!(base.thumb_start(), scaled.thumb_start());
}
#[test]
fn yields_empty_thumb_when_track_len_zero() {
let lengths = crate::ScrollLengths {
content_len: 10,
viewport_len: 4,
};
let metrics = ScrollMetrics::new(lengths, 0, 0);
assert_eq!(metrics.track_len(), 0);
assert_eq!(metrics.thumb_len(), 0);
assert_eq!(metrics.cell_fill(0), CellFill::Empty);
}
#[test]
fn reports_full_cell_when_thumb_covers_track() {
let lengths = crate::ScrollLengths {
content_len: 8,
viewport_len: 8,
};
let metrics = ScrollMetrics::new(lengths, 0, 1);
assert_eq!(metrics.thumb_len(), SUBCELL);
assert_eq!(metrics.cell_fill(0), CellFill::Full);
}
#[test]
fn treats_zero_lengths_as_one() {
let lengths = crate::ScrollLengths {
content_len: 0,
viewport_len: 0,
};
let metrics = ScrollMetrics::new(lengths, 0, 1);
assert_eq!(metrics.content_len(), 1);
assert_eq!(metrics.viewport_len(), 1);
assert_eq!(metrics.thumb_len(), SUBCELL);
}
#[test]
fn thumb_start_for_offset_returns_zero_when_no_scroll() {
let lengths = crate::ScrollLengths {
content_len: 10,
viewport_len: 10,
};
let metrics = ScrollMetrics::new(lengths, 0, 4);
assert_eq!(metrics.thumb_start_for_offset(5), 0);
}
#[test]
fn offset_for_thumb_start_returns_zero_when_no_scroll() {
let lengths = crate::ScrollLengths {
content_len: 10,
viewport_len: 10,
};
let metrics = ScrollMetrics::new(lengths, 0, 4);
assert_eq!(metrics.offset_for_thumb_start(5), 0);
}
#[test]
fn hit_test_returns_track_before_thumb_start() {
let lengths = crate::ScrollLengths {
content_len: 10,
viewport_len: 3,
};
let metrics = ScrollMetrics::new(lengths, 1, 4);
assert_eq!(
metrics.hit_test(metrics.thumb_start().saturating_sub(1)),
HitTest::Track
);
}
#[test]
fn hit_test_returns_track_at_thumb_end() {
let lengths = crate::ScrollLengths {
content_len: 10,
viewport_len: 3,
};
let metrics = ScrollMetrics::new(lengths, 1, 4);
let thumb_end = metrics.thumb_start().saturating_add(metrics.thumb_len());
assert_eq!(metrics.hit_test(thumb_end), HitTest::Track);
}
#[test]
fn reports_empty_cell_fill_when_thumb_len_zero() {
let lengths = crate::ScrollLengths {
content_len: 10,
viewport_len: 4,
};
let metrics = ScrollMetrics::new(lengths, 0, 0);
assert_eq!(metrics.cell_fill(0), CellFill::Empty);
}
#[test]
fn thumb_range_matches_start_and_len() {
let lengths = crate::ScrollLengths {
content_len: 10,
viewport_len: 3,
};
let metrics = ScrollMetrics::new(lengths, 1, 4);
assert_eq!(
metrics.thumb_range(),
metrics.thumb_start()..metrics.thumb_start().saturating_add(metrics.thumb_len())
);
}
#[test]
fn clamps_thumb_start_for_offset() {
let lengths = crate::ScrollLengths {
content_len: 100,
viewport_len: 10,
};
let metrics = ScrollMetrics::new(lengths, 0, 4);
let max_offset = metrics.max_offset();
assert_eq!(
metrics.thumb_start_for_offset(max_offset.saturating_add(10)),
metrics.thumb_travel()
);
}
#[test]
fn clamps_offset_for_thumb_start() {
let lengths = crate::ScrollLengths {
content_len: 100,
viewport_len: 10,
};
let metrics = ScrollMetrics::new(lengths, 0, 4);
let max_offset = metrics.max_offset();
assert_eq!(
metrics.offset_for_thumb_start(metrics.thumb_travel().saturating_add(10)),
max_offset
);
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-scrollbar/src/input.rs | tui-scrollbar/src/input.rs | //! Input types and interaction state for scrollbars.
//!
//! ## Design notes
//!
//! These types are intentionally backend-agnostic and small. The widget does not own scroll state;
//! it returns a [`ScrollCommand`] so the application can decide how to apply offsets. This keeps
//! the API compatible with any event loop and makes it easy to test.
/// Action requested by a pointer or wheel event.
///
/// Apply these to your stored offsets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScrollCommand {
/// Update the content offset in the same logical units you supplied.
SetOffset(usize),
}
/// Axis for scroll wheel events.
///
/// The scrollbar ignores wheel events that do not match its orientation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScrollAxis {
/// Wheel scroll in the vertical direction.
Vertical,
/// Wheel scroll in the horizontal direction.
Horizontal,
}
/// Pointer button used for interaction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PointerButton {
/// Primary pointer button (usually left mouse button).
Primary,
}
/// Kind of pointer interaction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PointerEventKind {
/// Pointer pressed down.
Down,
/// Pointer moved while pressed down.
Drag,
/// Pointer released.
Up,
}
/// Pointer input in terminal cell coordinates.
///
/// Use this to describe a pointer action relative to the scrollbar area.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PointerEvent {
/// Column of the event, in terminal cells.
pub column: u16,
/// Row of the event, in terminal cells.
pub row: u16,
/// Event kind.
pub kind: PointerEventKind,
/// Pointer button.
pub button: PointerButton,
}
/// Scroll wheel input with an axis and a signed delta.
///
/// Positive deltas scroll down/right, negative deltas scroll up/left. The `column` and `row` are
/// used to ignore wheel events outside the scrollbar area.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ScrollWheel {
/// Axis the wheel is scrolling.
pub axis: ScrollAxis,
/// Signed delta. Positive values scroll down/right.
pub delta: isize,
/// Column where the wheel event occurred.
pub column: u16,
/// Row where the wheel event occurred.
pub row: u16,
}
/// Backend-agnostic input event for a scrollbar.
///
/// Use this in input handling when you want to stay backend-agnostic.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScrollEvent {
/// Pointer down/drag/up events.
Pointer(PointerEvent),
/// Scroll wheel input.
ScrollWheel(ScrollWheel),
}
/// Drag state that should persist between frames.
///
/// Store this in your app state so drags remain active across draw calls.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct ScrollBarInteraction {
pub(crate) drag_state: DragState,
}
/// Internal drag capture state stored by [`ScrollBarInteraction`].
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DragState {
/// No active drag.
#[default]
Idle,
/// A drag is active; `grab_offset` is in subcells.
Dragging { grab_offset: usize },
}
impl ScrollBarInteraction {
/// Creates a fresh interaction state with no active drag.
pub fn new() -> Self {
Self::default()
}
/// Starts a drag by recording the grab offset in subcells.
///
/// This keeps the pointer anchored to the same point within the thumb while dragging.
pub(crate) fn start_drag(&mut self, grab_offset: usize) {
self.drag_state = DragState::Dragging { grab_offset };
}
/// Stops any active drag and returns to the idle state.
pub(crate) fn stop_drag(&mut self) {
self.drag_state = DragState::Idle;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn starts_idle() {
let interaction = ScrollBarInteraction::new();
assert_eq!(interaction.drag_state, DragState::Idle);
}
#[test]
fn records_grab_offset_on_start_drag() {
let mut interaction = ScrollBarInteraction::new();
interaction.start_drag(6);
assert_eq!(
interaction.drag_state,
DragState::Dragging { grab_offset: 6 }
);
}
#[test]
fn resets_state_on_stop_drag() {
let mut interaction = ScrollBarInteraction::new();
interaction.start_drag(3);
interaction.stop_drag();
assert_eq!(interaction.drag_state, DragState::Idle);
}
// ScrollViewState is in tui-scrollview; only exercise scrollbar input here.
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-scrollbar/src/scrollbar/interaction.rs | tui-scrollbar/src/scrollbar/interaction.rs | //! Input handling and hit-testing helpers for the scrollbar widget.
//!
//! This module groups pointer/wheel handling so the main widget definition stays focused on
//! configuration and rendering. The functions here are pure in/out helpers that return
//! [`ScrollCommand`] values for the application to apply.
//!
//! When a pointer presses inside the thumb, the handler stores a subcell grab offset so subsequent
//! drag events keep the pointer anchored to the same position within the thumb.
#[cfg(feature = "crossterm")]
use crossterm::event::{MouseButton, MouseEvent, MouseEventKind};
use ratatui_core::layout::Rect;
use super::{ArrowHit, ArrowLayout, ScrollBar, ScrollBarOrientation, TrackClickBehavior};
use crate::input::{
DragState, PointerButton, PointerEvent, PointerEventKind, ScrollAxis, ScrollBarInteraction,
ScrollCommand, ScrollEvent, ScrollWheel,
};
use crate::metrics::{HitTest, ScrollMetrics, SUBCELL};
use crate::ScrollLengths;
impl ScrollBar {
/// Handles a backend-agnostic scrollbar event.
///
/// Returns a [`ScrollCommand`] when the event should update the offset.
///
/// Pointer events outside the track are ignored. Scroll wheel events are ignored unless the
/// axis matches the scrollbar orientation.
///
/// ```rust
/// use ratatui_core::layout::Rect;
/// use tui_scrollbar::{
/// PointerButton, PointerEvent, PointerEventKind, ScrollBar, ScrollBarInteraction,
/// ScrollEvent, ScrollLengths,
/// };
///
/// let area = Rect::new(0, 0, 1, 6);
/// let lengths = ScrollLengths {
/// content_len: 120,
/// viewport_len: 24,
/// };
/// let scrollbar = ScrollBar::vertical(lengths).offset(0);
/// let mut interaction = ScrollBarInteraction::new();
/// let event = ScrollEvent::Pointer(PointerEvent {
/// column: 0,
/// row: 2,
/// kind: PointerEventKind::Down,
/// button: PointerButton::Primary,
/// });
///
/// let _ = scrollbar.handle_event(area, event, &mut interaction);
/// ```
pub fn handle_event(
&self,
area: Rect,
event: ScrollEvent,
interaction: &mut ScrollBarInteraction,
) -> Option<ScrollCommand> {
if area.width == 0 || area.height == 0 {
return None;
}
let layout = self.arrow_layout(area);
let lengths = ScrollLengths {
content_len: self.content_len,
viewport_len: self.viewport_len,
};
let track_cells = match self.orientation {
ScrollBarOrientation::Vertical => layout.track_area.height,
ScrollBarOrientation::Horizontal => layout.track_area.width,
};
let metrics = ScrollMetrics::new(lengths, self.offset, track_cells);
match event {
ScrollEvent::Pointer(event) => {
if let Some(command) =
self.handle_arrow_pointer(&layout, metrics, event, interaction)
{
return Some(command);
}
self.handle_pointer_event(layout.track_area, metrics, event, interaction)
}
ScrollEvent::ScrollWheel(event) => self.handle_scroll_wheel(area, metrics, event),
}
}
#[cfg(feature = "crossterm")]
/// Handles crossterm mouse events for this scrollbar.
///
/// This helper converts crossterm events into [`ScrollEvent`] values before delegating to
/// [`Self::handle_event`].
pub fn handle_mouse_event(
&self,
area: Rect,
event: MouseEvent,
interaction: &mut ScrollBarInteraction,
) -> Option<ScrollCommand> {
let event = match event.kind {
MouseEventKind::Down(MouseButton::Left) => Some(ScrollEvent::Pointer(PointerEvent {
column: event.column,
row: event.row,
kind: PointerEventKind::Down,
button: PointerButton::Primary,
})),
MouseEventKind::Up(MouseButton::Left) => Some(ScrollEvent::Pointer(PointerEvent {
column: event.column,
row: event.row,
kind: PointerEventKind::Up,
button: PointerButton::Primary,
})),
MouseEventKind::Drag(MouseButton::Left) => Some(ScrollEvent::Pointer(PointerEvent {
column: event.column,
row: event.row,
kind: PointerEventKind::Drag,
button: PointerButton::Primary,
})),
MouseEventKind::ScrollUp => Some(ScrollEvent::ScrollWheel(ScrollWheel {
axis: ScrollAxis::Vertical,
delta: -1,
column: event.column,
row: event.row,
})),
MouseEventKind::ScrollDown => Some(ScrollEvent::ScrollWheel(ScrollWheel {
axis: ScrollAxis::Vertical,
delta: 1,
column: event.column,
row: event.row,
})),
MouseEventKind::ScrollLeft => Some(ScrollEvent::ScrollWheel(ScrollWheel {
axis: ScrollAxis::Horizontal,
delta: -1,
column: event.column,
row: event.row,
})),
MouseEventKind::ScrollRight => Some(ScrollEvent::ScrollWheel(ScrollWheel {
axis: ScrollAxis::Horizontal,
delta: 1,
column: event.column,
row: event.row,
})),
_ => None,
};
event.and_then(|event| self.handle_event(area, event, interaction))
}
/// Handles pointer down/drag/up events and converts them to scroll commands.
fn handle_pointer_event(
&self,
area: Rect,
metrics: ScrollMetrics,
event: PointerEvent,
interaction: &mut ScrollBarInteraction,
) -> Option<ScrollCommand> {
if event.button != PointerButton::Primary {
return None;
}
match event.kind {
PointerEventKind::Down => {
let cell_index = axis_cell_index(area, event.column, event.row, self.orientation)?;
let position = cell_index
.saturating_mul(SUBCELL)
.saturating_add(SUBCELL / 2);
if metrics.thumb_len() == 0 {
return None;
}
match metrics.hit_test(position) {
HitTest::Thumb => {
let grab_offset = position.saturating_sub(metrics.thumb_start());
interaction.start_drag(grab_offset);
None
}
HitTest::Track => {
interaction.stop_drag();
self.handle_track_click(metrics, position)
}
}
}
PointerEventKind::Drag => match interaction.drag_state {
DragState::Idle => None,
DragState::Dragging { grab_offset } => {
let cell_index =
axis_cell_index_clamped(area, event.column, event.row, self.orientation)?;
let position = cell_index
.saturating_mul(SUBCELL)
.saturating_add(SUBCELL / 2);
let thumb_start = position.saturating_sub(grab_offset);
Some(ScrollCommand::SetOffset(
metrics.offset_for_thumb_start(thumb_start),
))
}
},
PointerEventKind::Up => {
interaction.stop_drag();
None
}
}
}
/// Converts a click on the track into a page or jump action.
fn handle_track_click(&self, metrics: ScrollMetrics, position: usize) -> Option<ScrollCommand> {
if metrics.max_offset() == 0 {
return None;
}
match self.track_click_behavior {
TrackClickBehavior::Page => {
let thumb_end = metrics.thumb_start().saturating_add(metrics.thumb_len());
if position < metrics.thumb_start() {
Some(ScrollCommand::SetOffset(
metrics.offset().saturating_sub(metrics.viewport_len()),
))
} else if position >= thumb_end {
Some(ScrollCommand::SetOffset(
(metrics.offset() + metrics.viewport_len()).min(metrics.max_offset()),
))
} else {
None
}
}
TrackClickBehavior::JumpToClick => {
let half_thumb = metrics.thumb_len() / 2;
let thumb_start = position.saturating_sub(half_thumb);
Some(ScrollCommand::SetOffset(
metrics.offset_for_thumb_start(thumb_start),
))
}
}
}
/// Handles scroll wheel input, respecting axis and clamping to bounds.
fn handle_scroll_wheel(
&self,
_area: Rect,
metrics: ScrollMetrics,
event: ScrollWheel,
) -> Option<ScrollCommand> {
let matches_axis = matches!(
(self.orientation, event.axis),
(ScrollBarOrientation::Vertical, ScrollAxis::Vertical)
| (ScrollBarOrientation::Horizontal, ScrollAxis::Horizontal)
);
if !matches_axis {
return None;
}
let step = self.scroll_step.max(1) as isize;
let delta = event.delta.saturating_mul(step);
let max_offset = metrics.max_offset() as isize;
let next = (metrics.offset() as isize).saturating_add(delta);
let next = next.clamp(0, max_offset);
Some(ScrollCommand::SetOffset(next as usize))
}
/// Handles arrow clicks by stepping the offset in the requested direction.
fn handle_arrow_pointer(
&self,
layout: &ArrowLayout,
metrics: ScrollMetrics,
event: PointerEvent,
interaction: &mut ScrollBarInteraction,
) -> Option<ScrollCommand> {
if event.button != PointerButton::Primary || event.kind != PointerEventKind::Down {
return None;
}
let hit = self.arrow_hit(layout, event)?;
if metrics.max_offset() == 0 {
return None;
}
interaction.stop_drag();
let step = self.scroll_step.max(1) as isize;
let delta = match hit {
ArrowHit::Start => -step,
ArrowHit::End => step,
};
let max_offset = metrics.max_offset() as isize;
let next = (metrics.offset() as isize).saturating_add(delta);
let next = next.clamp(0, max_offset);
Some(ScrollCommand::SetOffset(next as usize))
}
/// Returns which arrow (if any) a pointer event hit.
fn arrow_hit(&self, layout: &ArrowLayout, event: PointerEvent) -> Option<ArrowHit> {
if let Some((x, y)) = layout.start {
if event.column == x && event.row == y {
return Some(ArrowHit::Start);
}
}
if let Some((x, y)) = layout.end {
if event.column == x && event.row == y {
return Some(ArrowHit::End);
}
}
None
}
}
/// Returns the cell index along the scroll axis for a pointer location.
fn axis_cell_index(
area: Rect,
column: u16,
row: u16,
orientation: ScrollBarOrientation,
) -> Option<usize> {
match orientation {
ScrollBarOrientation::Vertical => {
if row < area.y || row >= area.y.saturating_add(area.height) {
None
} else {
Some(row.saturating_sub(area.y) as usize)
}
}
ScrollBarOrientation::Horizontal => {
if column < area.x || column >= area.x.saturating_add(area.width) {
None
} else {
Some(column.saturating_sub(area.x) as usize)
}
}
}
}
/// Returns a clamped cell index along the scroll axis for drag updates.
fn axis_cell_index_clamped(
area: Rect,
column: u16,
row: u16,
orientation: ScrollBarOrientation,
) -> Option<usize> {
match orientation {
ScrollBarOrientation::Vertical => {
if area.height == 0 {
return None;
}
let end = area.y.saturating_add(area.height).saturating_sub(1);
let row = row.clamp(area.y, end);
Some(row.saturating_sub(area.y) as usize)
}
ScrollBarOrientation::Horizontal => {
if area.width == 0 {
return None;
}
let end = area.x.saturating_add(area.width).saturating_sub(1);
let column = column.clamp(area.x, end);
Some(column.saturating_sub(area.x) as usize)
}
}
}
#[cfg(test)]
mod tests {
use ratatui_core::layout::Rect;
use super::*;
use crate::{ScrollBarArrows, ScrollLengths};
#[test]
fn pages_when_clicking_track() {
let lengths = ScrollLengths {
content_len: 100,
viewport_len: 20,
};
let scrollbar = ScrollBar::vertical(lengths)
.arrows(ScrollBarArrows::None)
.offset(40);
let area = Rect::new(0, 0, 1, 10);
let event = ScrollEvent::Pointer(PointerEvent {
column: 0,
row: 0,
kind: PointerEventKind::Down,
button: PointerButton::Primary,
});
let expected = 20;
let mut interaction = ScrollBarInteraction::default();
assert_eq!(
scrollbar.handle_event(area, event, &mut interaction),
Some(ScrollCommand::SetOffset(expected))
);
}
#[test]
fn updates_offset_while_dragging() {
let lengths = ScrollLengths {
content_len: 16,
viewport_len: 8,
};
let scrollbar = ScrollBar::vertical(lengths)
.arrows(ScrollBarArrows::None)
.offset(0);
let area = Rect::new(0, 0, 1, 4);
let mut interaction = ScrollBarInteraction::default();
let down = ScrollEvent::Pointer(PointerEvent {
column: 0,
row: 0,
kind: PointerEventKind::Down,
button: PointerButton::Primary,
});
assert_eq!(scrollbar.handle_event(area, down, &mut interaction), None);
let drag = ScrollEvent::Pointer(PointerEvent {
column: 0,
row: 1,
kind: PointerEventKind::Drag,
button: PointerButton::Primary,
});
assert_eq!(
scrollbar.handle_event(area, drag, &mut interaction),
Some(ScrollCommand::SetOffset(4))
);
}
#[test]
fn applies_scroll_step_to_wheel() {
let lengths = ScrollLengths {
content_len: 100,
viewport_len: 20,
};
let scrollbar = ScrollBar::vertical(lengths)
.arrows(ScrollBarArrows::None)
.offset(40)
.scroll_step(3);
let area = Rect::new(0, 0, 1, 10);
let mut interaction = ScrollBarInteraction::default();
let event = ScrollEvent::ScrollWheel(ScrollWheel {
axis: ScrollAxis::Vertical,
delta: 1,
column: 0,
row: 0,
});
assert_eq!(
scrollbar.handle_event(area, event, &mut interaction),
Some(ScrollCommand::SetOffset(43))
);
}
#[test]
fn steps_offset_when_clicking_arrows() {
let lengths = ScrollLengths {
content_len: 100,
viewport_len: 20,
};
let scrollbar = ScrollBar::vertical(lengths).offset(10).scroll_step(5);
let area = Rect::new(0, 0, 1, 5);
let mut interaction = ScrollBarInteraction::default();
let up = ScrollEvent::Pointer(PointerEvent {
column: 0,
row: 0,
kind: PointerEventKind::Down,
button: PointerButton::Primary,
});
assert_eq!(
scrollbar.handle_event(area, up, &mut interaction),
Some(ScrollCommand::SetOffset(5))
);
let down = ScrollEvent::Pointer(PointerEvent {
column: 0,
row: 4,
kind: PointerEventKind::Down,
button: PointerButton::Primary,
});
assert_eq!(
scrollbar.handle_event(area, down, &mut interaction),
Some(ScrollCommand::SetOffset(15))
);
}
#[test]
fn ignores_scroll_wheel_on_other_axis() {
let lengths = ScrollLengths {
content_len: 100,
viewport_len: 20,
};
let scrollbar = ScrollBar::vertical(lengths);
let area = Rect::new(0, 0, 1, 5);
let mut interaction = ScrollBarInteraction::default();
let event = ScrollEvent::ScrollWheel(ScrollWheel {
axis: ScrollAxis::Horizontal,
delta: 1,
column: 0,
row: 2,
});
assert_eq!(scrollbar.handle_event(area, event, &mut interaction), None);
}
#[test]
fn applies_negative_scroll_wheel_delta() {
let lengths = ScrollLengths {
content_len: 100,
viewport_len: 20,
};
let scrollbar = ScrollBar::vertical(lengths).offset(10).scroll_step(2);
let area = Rect::new(0, 0, 1, 5);
let event = ScrollEvent::ScrollWheel(ScrollWheel {
axis: ScrollAxis::Vertical,
delta: -1,
column: 0,
row: 2,
});
let mut interaction = ScrollBarInteraction::default();
assert_eq!(
scrollbar.handle_event(area, event, &mut interaction),
Some(ScrollCommand::SetOffset(8))
);
}
#[test]
fn jumps_toward_track_click() {
let lengths = ScrollLengths {
content_len: 8,
viewport_len: 4,
};
let scrollbar = ScrollBar::vertical(lengths)
.arrows(ScrollBarArrows::None)
.track_click_behavior(TrackClickBehavior::JumpToClick);
let area = Rect::new(0, 0, 1, 4);
let event = ScrollEvent::Pointer(PointerEvent {
column: 0,
row: 2,
kind: PointerEventKind::Down,
button: PointerButton::Primary,
});
let expected = 3;
let mut interaction = ScrollBarInteraction::default();
assert_eq!(
scrollbar.handle_event(area, event, &mut interaction),
Some(ScrollCommand::SetOffset(expected))
);
}
#[test]
fn clears_drag_on_pointer_up() {
let lengths = ScrollLengths {
content_len: 100,
viewport_len: 20,
};
let scrollbar = ScrollBar::vertical(lengths);
let area = Rect::new(0, 0, 1, 5);
let mut interaction = ScrollBarInteraction::default();
interaction.start_drag(3);
let event = ScrollEvent::Pointer(PointerEvent {
column: 0,
row: 1,
kind: PointerEventKind::Up,
button: PointerButton::Primary,
});
assert_eq!(scrollbar.handle_event(area, event, &mut interaction), None);
assert_eq!(interaction.drag_state, DragState::Idle);
}
#[test]
fn ignores_pointer_events_outside_track() {
let lengths = ScrollLengths {
content_len: 100,
viewport_len: 20,
};
let scrollbar = ScrollBar::vertical(lengths);
let area = Rect::new(0, 0, 1, 5);
let event = ScrollEvent::Pointer(PointerEvent {
column: 0,
row: 6,
kind: PointerEventKind::Down,
button: PointerButton::Primary,
});
let mut interaction = ScrollBarInteraction::default();
assert_eq!(scrollbar.handle_event(area, event, &mut interaction), None);
}
#[test]
fn ignores_arrow_clicks_when_max_offset_zero() {
let lengths = ScrollLengths {
content_len: 10,
viewport_len: 10,
};
let scrollbar = ScrollBar::vertical(lengths).arrows(ScrollBarArrows::Both);
let area = Rect::new(0, 0, 1, 5);
let event = ScrollEvent::Pointer(PointerEvent {
column: 0,
row: 0,
kind: PointerEventKind::Down,
button: PointerButton::Primary,
});
let mut interaction = ScrollBarInteraction::default();
assert_eq!(scrollbar.handle_event(area, event, &mut interaction), None);
}
#[test]
fn stops_drag_on_track_click() {
let lengths = ScrollLengths {
content_len: 10,
viewport_len: 5,
};
let scrollbar = ScrollBar::vertical(lengths).arrows(ScrollBarArrows::None);
let area = Rect::new(0, 0, 1, 4);
let mut interaction = ScrollBarInteraction::default();
interaction.start_drag(2);
let event = ScrollEvent::Pointer(PointerEvent {
column: 0,
row: 3,
kind: PointerEventKind::Down,
button: PointerButton::Primary,
});
assert_eq!(
scrollbar.handle_event(area, event, &mut interaction),
Some(ScrollCommand::SetOffset(5))
);
assert_eq!(interaction.drag_state, DragState::Idle);
}
#[test]
fn returns_none_when_clicking_inside_thumb_in_page_mode() {
let lengths = ScrollLengths {
content_len: 100,
viewport_len: 20,
};
let scrollbar = ScrollBar::vertical(lengths).arrows(ScrollBarArrows::None);
let area = Rect::new(0, 0, 1, 10);
let mut interaction = ScrollBarInteraction::default();
let event = ScrollEvent::Pointer(PointerEvent {
column: 0,
row: 0,
kind: PointerEventKind::Down,
button: PointerButton::Primary,
});
assert_eq!(scrollbar.handle_event(area, event, &mut interaction), None);
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-scrollbar/src/scrollbar/render.rs | tui-scrollbar/src/scrollbar/render.rs | //! Rendering helpers and `Widget` implementation for [`ScrollBar`].
//!
//! The core widget delegates rendering to these helpers so the draw logic is grouped separately
//! from configuration and input handling. Keep rendering changes localized here.
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::Rect;
use ratatui_core::style::Style;
use ratatui_core::widgets::Widget;
use super::{ArrowLayout, ScrollBar, ScrollBarOrientation};
use crate::metrics::{CellFill, ScrollMetrics};
use crate::ScrollLengths;
impl Widget for &ScrollBar {
fn render(self, area: Rect, buf: &mut Buffer) {
self.render_inner(area, buf);
}
}
impl ScrollBar {
/// Renders the scrollbar into the provided buffer.
fn render_inner(&self, area: Rect, buf: &mut Buffer) {
if area.width == 0 || area.height == 0 {
return;
}
let layout = self.arrow_layout(area);
self.render_arrows(&layout, buf);
if layout.track_area.width == 0 || layout.track_area.height == 0 {
return;
}
match self.orientation {
ScrollBarOrientation::Vertical => {
self.render_vertical_track(layout.track_area, buf);
}
ScrollBarOrientation::Horizontal => {
self.render_horizontal_track(layout.track_area, buf);
}
}
}
/// Renders arrow endcaps into the buffer before the thumb/track.
fn render_arrows(&self, layout: &ArrowLayout, buf: &mut Buffer) {
let arrow_style = self.arrow_style.unwrap_or(self.track_style);
if let Some((x, y)) = layout.start {
let glyph = match self.orientation {
ScrollBarOrientation::Vertical => self.glyph_set.arrow_vertical_start,
ScrollBarOrientation::Horizontal => self.glyph_set.arrow_horizontal_start,
};
let cell = &mut buf[(x, y)];
cell.set_char(glyph);
cell.set_style(arrow_style);
}
if let Some((x, y)) = layout.end {
let glyph = match self.orientation {
ScrollBarOrientation::Vertical => self.glyph_set.arrow_vertical_end,
ScrollBarOrientation::Horizontal => self.glyph_set.arrow_horizontal_end,
};
let cell = &mut buf[(x, y)];
cell.set_char(glyph);
cell.set_style(arrow_style);
}
}
/// Renders the vertical track and thumb into the provided area.
fn render_vertical_track(&self, area: Rect, buf: &mut Buffer) {
let metrics = ScrollMetrics::new(
ScrollLengths {
content_len: self.content_len,
viewport_len: self.viewport_len,
},
self.offset,
area.height,
);
let x = area.x;
for (idx, y) in (area.y..area.y.saturating_add(area.height)).enumerate() {
let (glyph, style) = self.glyph_for_vertical(metrics.cell_fill(idx));
let cell = &mut buf[(x, y)];
cell.set_char(glyph);
cell.set_style(style);
}
}
/// Renders the horizontal track and thumb into the provided area.
fn render_horizontal_track(&self, area: Rect, buf: &mut Buffer) {
let metrics = ScrollMetrics::new(
ScrollLengths {
content_len: self.content_len,
viewport_len: self.viewport_len,
},
self.offset,
area.width,
);
let y = area.y;
for (idx, x) in (area.x..area.x.saturating_add(area.width)).enumerate() {
let (glyph, style) = self.glyph_for_horizontal(metrics.cell_fill(idx));
let cell = &mut buf[(x, y)];
cell.set_char(glyph);
cell.set_style(style);
}
}
/// Chooses the vertical glyph + style for a track cell fill.
fn glyph_for_vertical(&self, fill: CellFill) -> (char, Style) {
match fill {
CellFill::Empty => (self.glyph_set.track_vertical, self.track_style),
CellFill::Full => (self.glyph_set.thumb_vertical_lower[7], self.thumb_style),
CellFill::Partial { start, len } => {
let index = len.saturating_sub(1) as usize;
let glyph = if start == 0 {
self.glyph_set.thumb_vertical_upper[index]
} else {
self.glyph_set.thumb_vertical_lower[index]
};
(glyph, self.thumb_style)
}
}
}
/// Chooses the horizontal glyph + style for a track cell fill.
fn glyph_for_horizontal(&self, fill: CellFill) -> (char, Style) {
match fill {
CellFill::Empty => (self.glyph_set.track_horizontal, self.track_style),
CellFill::Full => (self.glyph_set.thumb_horizontal_left[7], self.thumb_style),
CellFill::Partial { start, len } => {
let index = len.saturating_sub(1) as usize;
let glyph = if start == 0 {
self.glyph_set.thumb_horizontal_left[index]
} else {
self.glyph_set.thumb_horizontal_right[index]
};
(glyph, self.thumb_style)
}
}
}
}
#[cfg(test)]
mod tests {
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::Rect;
use super::*;
use crate::{ScrollBarArrows, ScrollLengths};
#[test]
fn render_vertical_fractional_thumb() {
let scrollbar = ScrollBar::vertical(ScrollLengths {
content_len: 10,
viewport_len: 3,
})
.arrows(ScrollBarArrows::None)
.offset(1);
let mut buf = Buffer::empty(Rect::new(0, 0, 1, 4));
(&scrollbar).render(buf.area, &mut buf);
let mut expected = Buffer::with_lines(vec!["▅", "▀", "│", "│"]);
expected.set_style(expected.area, scrollbar.track_style);
expected[(0, 0)].set_style(scrollbar.thumb_style);
expected[(0, 1)].set_style(scrollbar.thumb_style);
assert_eq!(buf, expected);
}
#[test]
fn render_horizontal_fractional_thumb() {
let scrollbar = ScrollBar::horizontal(ScrollLengths {
content_len: 10,
viewport_len: 3,
})
.arrows(ScrollBarArrows::None)
.offset(1);
let mut buf = Buffer::empty(Rect::new(0, 0, 4, 1));
(&scrollbar).render(buf.area, &mut buf);
let mut expected = Buffer::with_lines(vec!["🮉▌──"]);
expected.set_style(expected.area, scrollbar.track_style);
expected[(0, 0)].set_style(scrollbar.thumb_style);
expected[(1, 0)].set_style(scrollbar.thumb_style);
assert_eq!(buf, expected);
}
#[test]
fn render_full_thumb_when_no_scroll() {
let scrollbar = ScrollBar::vertical(ScrollLengths {
content_len: 5,
viewport_len: 10,
})
.arrows(ScrollBarArrows::None);
let mut buf = Buffer::empty(Rect::new(0, 0, 1, 3));
(&scrollbar).render(buf.area, &mut buf);
let mut expected = Buffer::with_lines(vec!["█", "█", "█"]);
expected.set_style(expected.area, scrollbar.thumb_style);
assert_eq!(buf, expected);
}
#[test]
fn render_vertical_arrows() {
let scrollbar = ScrollBar::vertical(ScrollLengths {
content_len: 5,
viewport_len: 2,
});
let mut buf = Buffer::empty(Rect::new(0, 0, 1, 3));
(&scrollbar).render(buf.area, &mut buf);
let mut expected = Buffer::with_lines(vec!["▲", "█", "▼"]);
expected[(0, 0)].set_style(scrollbar.arrow_style.unwrap_or(scrollbar.track_style));
expected[(0, 1)].set_style(scrollbar.thumb_style);
expected[(0, 2)].set_style(scrollbar.arrow_style.unwrap_or(scrollbar.track_style));
assert_eq!(buf, expected);
}
#[test]
fn render_horizontal_arrows() {
let scrollbar = ScrollBar::horizontal(ScrollLengths {
content_len: 5,
viewport_len: 2,
});
let mut buf = Buffer::empty(Rect::new(0, 0, 3, 1));
(&scrollbar).render(buf.area, &mut buf);
let mut expected = Buffer::with_lines(vec!["◀█▶"]);
expected[(0, 0)].set_style(scrollbar.arrow_style.unwrap_or(scrollbar.track_style));
expected[(1, 0)].set_style(scrollbar.thumb_style);
expected[(2, 0)].set_style(scrollbar.arrow_style.unwrap_or(scrollbar.track_style));
assert_eq!(buf, expected);
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-scrollbar/src/scrollbar/mod.rs | tui-scrollbar/src/scrollbar/mod.rs | //! Rendering and interaction for proportional scrollbars.
//!
//! This module provides the widget, glyph selection, and interaction helpers. The pure math lives
//! in [`crate::metrics`].
//!
//! # How the parts interact
//!
//! 1. Your app owns `content_len`, `viewport_len`, and `offset`.
//! 2. [`ScrollMetrics`] converts them into thumb geometry.
//! 3. [`ScrollBar`] renders using the selected [`GlyphSet`].
//! 4. Input events update `offset` via [`ScrollCommand`].
//!
//! The scrollbar renders only a single row or column. If you provide a larger [`Rect`], it will
//! still render into the first row/column of that area.
//!
//! ## Layout choices
//!
//! The widget treats the provided area as the track container. When arrows are enabled, one cell
//! at each end is reserved for the endcaps and the remaining inner area is used for the thumb.
//!
//! Arrow endcaps are optional. When enabled, they consume one cell at the start/end of the track,
//! and the thumb renders inside the remaining inner area.
//!
//! ## Interaction choices
//!
//! - The widget is stateless: it renders from inputs and returns commands instead of mutating
//! scroll offsets. This keeps control with the application.
//! - Dragging stores a grab offset in subcells so the thumb does not jump under the pointer.
//! - Arrow endcaps consume track space; the inner track is used for metrics and hit testing so
//! thumb math stays consistent regardless of arrows.
//!
//! Partial glyph selection uses [`CellFill::Partial`]: `start == 0` means the partial fill begins
//! at the leading edge (top/left), so the upper/left glyphs are chosen. Non-zero `start` uses the
//! lower/right glyphs to indicate a trailing-edge fill.
//!
//! Drag operations store a "grab offset" in subcells (1/8 of a cell; see [`crate::SUBCELL`]) so the
//! thumb does not jump when the pointer starts dragging; subsequent drag events subtract that
//! offset to keep the grab point stable.
//!
//! Wheel events are ignored unless their axis matches the scrollbar orientation. Positive deltas
//! scroll down/right.
//!
//! The example below renders a vertical scrollbar into a buffer. It demonstrates how the widget
//! uses `content_len`, `viewport_len`, and `offset` to decide the thumb size and position.
//!
//! ```rust
//! use ratatui_core::buffer::Buffer;
//! use ratatui_core::layout::Rect;
//! use ratatui_core::widgets::Widget;
//! use tui_scrollbar::{ScrollBar, ScrollLengths};
//!
//! let area = Rect::new(0, 0, 1, 4);
//! let lengths = ScrollLengths {
//! content_len: 120,
//! viewport_len: 40,
//! };
//! let scrollbar = ScrollBar::vertical(lengths).offset(20);
//!
//! let mut buffer = Buffer::empty(area);
//! scrollbar.render(area, &mut buffer);
//! ```
//!
//! [`Rect`]: ratatui_core::layout::Rect
use ratatui_core::layout::Rect;
use ratatui_core::style::{Color, Style};
use crate::glyphs::GlyphSet;
mod interaction;
mod render;
/// Axis the scrollbar is laid out on.
///
/// Orientation determines whether the track length is derived from height or width.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScrollBarOrientation {
/// A vertical scrollbar that fills a single column.
Vertical,
/// A horizontal scrollbar that fills a single row.
Horizontal,
}
/// Behavior when the user clicks on the track outside the thumb.
///
/// Page clicks move by `viewport_len`. Jump-to-click centers the thumb near the click.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TrackClickBehavior {
/// Move by one viewport length toward the click position.
Page,
/// Jump the thumb toward the click position.
JumpToClick,
}
/// Which arrow endcaps to render on the track.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum ScrollBarArrows {
/// Do not render arrow endcaps.
None,
/// Render the arrow at the start of the track (top/left).
Start,
/// Render the arrow at the end of the track (bottom/right).
End,
/// Render arrows at both ends of the track.
#[default]
Both,
}
impl ScrollBarArrows {
const fn has_start(self) -> bool {
matches!(self, Self::Start | Self::Both)
}
const fn has_end(self) -> bool {
matches!(self, Self::End | Self::Both)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ArrowHit {
Start,
End,
}
#[derive(Debug, Clone, Copy)]
struct ArrowLayout {
track_area: Rect,
start: Option<(u16, u16)>,
end: Option<(u16, u16)>,
}
/// A proportional scrollbar widget with fractional thumb rendering.
///
/// # Key methods
///
/// - [`Self::new`]
/// - [`Self::orientation`]
/// - [`Self::arrows`]
/// - [`Self::content_len`]
/// - [`Self::viewport_len`]
/// - [`Self::offset`]
///
/// # Important
///
/// - `content_len` and `viewport_len` are in logical units.
/// - Zero values are treated as 1.
/// - The scrollbar renders into a single row or column.
///
/// # Behavior
///
/// The thumb length is proportional to `viewport_len / content_len` and clamped to at least one
/// full cell for usability. When `content_len <= viewport_len`, the thumb fills the track. Areas
/// with zero width or height render nothing.
///
/// Arrow endcaps, when enabled, consume one cell at the start/end of the track. The thumb and
/// track render in the remaining inner area. Clicking an arrow steps the offset by `scroll_step`.
///
/// # Styling
///
/// Track glyphs use `track_style`. Thumb glyphs use `thumb_style`. Arrow endcaps use
/// `arrow_style`, which defaults to white on dark gray.
///
/// # State
///
/// This widget is stateless. Pointer drag state lives in [`ScrollBarInteraction`].
///
/// # Examples
///
/// ```rust
/// use ratatui_core::buffer::Buffer;
/// use ratatui_core::layout::Rect;
/// use ratatui_core::widgets::Widget;
/// use tui_scrollbar::{ScrollBar, ScrollLengths};
///
/// let area = Rect::new(0, 0, 1, 5);
/// let lengths = ScrollLengths {
/// content_len: 200,
/// viewport_len: 40,
/// };
/// let scrollbar = ScrollBar::vertical(lengths).offset(60);
///
/// let mut buffer = Buffer::empty(area);
/// scrollbar.render(area, &mut buffer);
/// ```
///
/// ## Updating offsets on input
///
/// This is the typical pattern for pointer handling: feed events to the scrollbar and apply the
/// returned command to your stored offset.
///
/// ```rust,no_run
/// use ratatui_core::layout::Rect;
/// use tui_scrollbar::{
/// PointerButton, PointerEvent, PointerEventKind, ScrollBar, ScrollBarInteraction,
/// ScrollCommand, ScrollEvent, ScrollLengths,
/// };
///
/// let area = Rect::new(0, 0, 1, 10);
/// let lengths = ScrollLengths {
/// content_len: 400,
/// viewport_len: 80,
/// };
/// let scrollbar = ScrollBar::vertical(lengths).offset(0);
/// let mut interaction = ScrollBarInteraction::new();
/// let mut offset = 0;
///
/// let event = ScrollEvent::Pointer(PointerEvent {
/// column: 0,
/// row: 3,
/// kind: PointerEventKind::Down,
/// button: PointerButton::Primary,
/// });
///
/// if let Some(ScrollCommand::SetOffset(next)) =
/// scrollbar.handle_event(area, event, &mut interaction)
/// {
/// offset = next;
/// }
/// # let _ = offset;
/// ```
///
/// ## Track click behavior
///
/// Choose between classic page jumps or jump-to-click behavior.
///
/// ```rust
/// use tui_scrollbar::{ScrollBar, ScrollLengths, TrackClickBehavior};
///
/// let lengths = ScrollLengths {
/// content_len: 10,
/// viewport_len: 5,
/// };
/// let scrollbar =
/// ScrollBar::vertical(lengths).track_click_behavior(TrackClickBehavior::JumpToClick);
/// ```
///
/// ## Arrow endcaps
///
/// Arrow endcaps are optional. When enabled, they reserve one cell at each end of the track.
///
/// ```rust
/// use tui_scrollbar::{ScrollBar, ScrollBarArrows, ScrollLengths};
///
/// let lengths = ScrollLengths {
/// content_len: 120,
/// viewport_len: 24,
/// };
/// let scrollbar = ScrollBar::vertical(lengths).arrows(ScrollBarArrows::Both);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScrollBar {
orientation: ScrollBarOrientation,
content_len: usize,
viewport_len: usize,
offset: usize,
track_style: Style,
thumb_style: Style,
arrow_style: Option<Style>,
glyph_set: GlyphSet,
arrows: ScrollBarArrows,
track_click_behavior: TrackClickBehavior,
scroll_step: usize,
}
impl ScrollBar {
/// Creates a scrollbar with the given orientation and lengths.
///
/// Zero lengths are treated as 1.
///
/// ```rust
/// use tui_scrollbar::{ScrollBar, ScrollBarOrientation, ScrollLengths};
///
/// let lengths = ScrollLengths {
/// content_len: 120,
/// viewport_len: 40,
/// };
/// let scrollbar = ScrollBar::new(ScrollBarOrientation::Vertical, lengths);
/// ```
pub fn new(orientation: ScrollBarOrientation, lengths: crate::ScrollLengths) -> Self {
Self {
orientation,
content_len: lengths.content_len,
viewport_len: lengths.viewport_len,
offset: 0,
track_style: Style::new().bg(Color::DarkGray),
thumb_style: Style::new().fg(Color::White).bg(Color::DarkGray),
arrow_style: Some(Style::new().fg(Color::White).bg(Color::DarkGray)),
glyph_set: GlyphSet::default(),
arrows: ScrollBarArrows::default(),
track_click_behavior: TrackClickBehavior::Page,
scroll_step: 1,
}
}
/// Creates a vertical scrollbar with the given content and viewport lengths.
pub fn vertical(lengths: crate::ScrollLengths) -> Self {
Self::new(ScrollBarOrientation::Vertical, lengths)
}
/// Creates a horizontal scrollbar with the given content and viewport lengths.
pub fn horizontal(lengths: crate::ScrollLengths) -> Self {
Self::new(ScrollBarOrientation::Horizontal, lengths)
}
/// Sets the scrollbar orientation.
pub const fn orientation(mut self, orientation: ScrollBarOrientation) -> Self {
self.orientation = orientation;
self
}
/// Sets the total scrollable content length in logical units.
///
/// Larger values shrink the thumb, while smaller values enlarge it.
///
/// Zero values are treated as 1.
pub const fn content_len(mut self, content_len: usize) -> Self {
self.content_len = content_len;
self
}
/// Sets the visible viewport length in logical units.
///
/// When `viewport_len >= content_len`, the thumb fills the track.
///
/// Zero values are treated as 1.
pub const fn viewport_len(mut self, viewport_len: usize) -> Self {
self.viewport_len = viewport_len;
self
}
/// Sets the current scroll offset in logical units.
///
/// Offsets are clamped to `content_len - viewport_len` during rendering.
pub const fn offset(mut self, offset: usize) -> Self {
self.offset = offset;
self
}
/// Sets the style applied to track glyphs.
///
/// Track styling applies only where the thumb is not rendered.
pub const fn track_style(mut self, style: Style) -> Self {
self.track_style = style;
self
}
/// Sets the style applied to thumb glyphs.
///
/// Thumb styling overrides track styling for covered cells.
pub const fn thumb_style(mut self, style: Style) -> Self {
self.thumb_style = style;
self
}
/// Sets the style applied to arrow glyphs.
///
/// Defaults to white on dark gray.
pub const fn arrow_style(mut self, style: Style) -> Self {
self.arrow_style = Some(style);
self
}
/// Selects the glyph set used to render the track and thumb.
///
/// [`GlyphSet::symbols_for_legacy_computing`] uses additional symbols for 1/8th upper/right
/// fills. Use [`GlyphSet::unicode`] if you want to avoid the legacy supplement.
pub const fn glyph_set(mut self, glyph_set: GlyphSet) -> Self {
self.glyph_set = glyph_set;
self
}
/// Sets which arrow endcaps are rendered.
pub const fn arrows(mut self, arrows: ScrollBarArrows) -> Self {
self.arrows = arrows;
self
}
/// Sets behavior for clicks on the track outside the thumb.
///
/// Use [`TrackClickBehavior::Page`] for classic page-up/down behavior, or
/// [`TrackClickBehavior::JumpToClick`] to move the thumb toward the click.
pub const fn track_click_behavior(mut self, behavior: TrackClickBehavior) -> Self {
self.track_click_behavior = behavior;
self
}
/// Sets the scroll step used for wheel events.
///
/// The wheel delta is multiplied by this value (in your logical units) and then clamped.
pub fn scroll_step(mut self, step: usize) -> Self {
self.scroll_step = step.max(1);
self
}
/// Computes the inner track area and arrow cell positions for this orientation.
fn arrow_layout(&self, area: Rect) -> ArrowLayout {
let mut track_area = area;
let (start, end) = match self.orientation {
ScrollBarOrientation::Vertical => {
let start_enabled = self.arrows.has_start() && area.height > 0;
let end_enabled = self.arrows.has_end() && area.height > start_enabled as u16;
let start = start_enabled.then_some((area.x, area.y));
let end = end_enabled
.then_some((area.x, area.y.saturating_add(area.height).saturating_sub(1)));
if start_enabled {
track_area.y = track_area.y.saturating_add(1);
track_area.height = track_area.height.saturating_sub(1);
}
if end_enabled {
track_area.height = track_area.height.saturating_sub(1);
}
(start, end)
}
ScrollBarOrientation::Horizontal => {
let start_enabled = self.arrows.has_start() && area.width > 0;
let end_enabled = self.arrows.has_end() && area.width > start_enabled as u16;
let start = start_enabled.then_some((area.x, area.y));
let end = end_enabled
.then_some((area.x.saturating_add(area.width).saturating_sub(1), area.y));
if start_enabled {
track_area.x = track_area.x.saturating_add(1);
track_area.width = track_area.width.saturating_sub(1);
}
if end_enabled {
track_area.width = track_area.width.saturating_sub(1);
}
(start, end)
}
};
ArrowLayout {
track_area,
start,
end,
}
}
}
#[cfg(test)]
mod tests {
use ratatui_core::style::{Color, Style};
use super::*;
use crate::glyphs::GlyphSet;
use crate::ScrollLengths;
#[test]
fn builder_methods_update_fields() {
let lengths = ScrollLengths {
content_len: 10,
viewport_len: 4,
};
let track_style = Style::new().fg(Color::Red);
let thumb_style = Style::new().bg(Color::Blue);
let arrow_style = Style::new().fg(Color::Green);
let glyphs = GlyphSet::unicode();
let scrollbar = ScrollBar::new(ScrollBarOrientation::Vertical, lengths)
.orientation(ScrollBarOrientation::Horizontal)
.content_len(20)
.viewport_len(5)
.offset(3)
.track_style(track_style)
.thumb_style(thumb_style)
.arrow_style(arrow_style)
.glyph_set(glyphs.clone())
.arrows(ScrollBarArrows::End)
.track_click_behavior(TrackClickBehavior::JumpToClick)
.scroll_step(0);
assert_eq!(scrollbar.orientation, ScrollBarOrientation::Horizontal);
assert_eq!(scrollbar.content_len, 20);
assert_eq!(scrollbar.viewport_len, 5);
assert_eq!(scrollbar.offset, 3);
assert_eq!(scrollbar.track_style, track_style);
assert_eq!(scrollbar.thumb_style, thumb_style);
assert_eq!(scrollbar.arrow_style, Some(arrow_style));
assert_eq!(scrollbar.glyph_set, glyphs);
assert_eq!(scrollbar.arrows, ScrollBarArrows::End);
assert_eq!(
scrollbar.track_click_behavior,
TrackClickBehavior::JumpToClick
);
assert_eq!(scrollbar.scroll_step, 1);
}
#[test]
fn constructors_set_orientation() {
let lengths = ScrollLengths {
content_len: 10,
viewport_len: 4,
};
let vertical = ScrollBar::vertical(lengths);
let horizontal = ScrollBar::horizontal(lengths);
assert_eq!(vertical.orientation, ScrollBarOrientation::Vertical);
assert_eq!(horizontal.orientation, ScrollBarOrientation::Horizontal);
}
#[test]
fn reserves_track_cells_for_arrows() {
let lengths = ScrollLengths {
content_len: 10,
viewport_len: 4,
};
let scrollbar = ScrollBar::vertical(lengths).arrows(ScrollBarArrows::Both);
let area = Rect::new(0, 0, 1, 5);
let layout = scrollbar.arrow_layout(area);
assert_eq!(layout.track_area.height, 3);
assert_eq!(layout.start, Some((area.x, area.y)));
assert_eq!(
layout.end,
Some((area.x, area.y.saturating_add(area.height).saturating_sub(1)))
);
}
#[test]
fn reserves_track_cells_for_horizontal_arrows() {
let lengths = ScrollLengths {
content_len: 10,
viewport_len: 4,
};
let scrollbar = ScrollBar::horizontal(lengths).arrows(ScrollBarArrows::Both);
let area = Rect::new(0, 0, 5, 1);
let layout = scrollbar.arrow_layout(area);
assert_eq!(layout.track_area.width, 3);
assert_eq!(layout.start, Some((area.x, area.y)));
assert_eq!(
layout.end,
Some((area.x.saturating_add(area.width).saturating_sub(1), area.y))
);
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-scrollbar/examples/scrollbar_mouse.rs | tui-scrollbar/examples/scrollbar_mouse.rs | //! Mouse + keyboard-driven scrollbar demo with smooth subcell movement.
//!
//! If you are new to this crate, this is the fastest way to see the full interaction model:
//! a horizontal scrollbar on the bottom edge and a vertical scrollbar on the right edge, both
//! wired to the same input flow your app would use. The example keeps the scroll offsets in app
//! state, renders the scrollbars each frame, and applies the commands returned by
//! [`ScrollBar::handle_mouse_event`].
//!
//! ## Why this example exists
//!
//! The demo uses subcell units so the thumb glides smoothly even when you step with the keyboard.
//! It also shows how to keep scroll offsets clamped when the terminal resizes.
//!
//! ## Implementation choices
//!
//! - The app owns the offsets and clamps them after each resize or input event.
//! - `ScrollMetrics` is used to derive the `ScrollLengths` and max offsets for each axis.
//! - `handle_mouse_event` stays thin by building scrollbars from the latest metrics, mirroring how
//! an app would typically handle input per frame.
//!
//! ## Controls
//!
//! - Arrow keys: move the scrollbars in subcell steps.
//! - Mouse wheel: scroll the matching axis.
//! - Click + drag: grab the thumb and drag.
//! - `q` or `Esc`: exit the demo.
use std::io;
use color_eyre::Result;
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEventKind};
use ratatui::crossterm::execute;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Style, Stylize};
use ratatui::text::Line;
use ratatui::widgets::{Block, Borders, Paragraph};
use ratatui::DefaultTerminal;
use tui_scrollbar::{
GlyphSet, ScrollBar, ScrollBarArrows, ScrollBarInteraction, ScrollCommand, ScrollLengths,
ScrollMetrics, SUBCELL,
};
const KEY_STEP: usize = 1;
const TITLE_FG: Color = Color::Rgb(196, 206, 224);
const TITLE_BG: Color = Color::Rgb(32, 43, 64);
const BLOCK_FG: Color = Color::Rgb(196, 206, 224);
const BLOCK_BG: Color = Color::Rgb(13, 23, 38);
const SCROLLBAR_TRACK_BG: Color = Color::Rgb(40, 40, 40);
const SCROLLBAR_THUMB_BG: Color = SCROLLBAR_TRACK_BG;
const SCROLLBAR_THUMB_FG: Color = Color::Rgb(224, 224, 224);
const SCROLLBAR_ARROW_FG: Color = Color::Rgb(224, 224, 224);
fn main() -> Result<()> {
color_eyre::install()?;
let mut terminal = ratatui::init();
execute!(io::stdout(), event::EnableMouseCapture)?;
let result = App::new().run(&mut terminal);
execute!(io::stdout(), event::DisableMouseCapture)?;
ratatui::restore();
result
}
#[derive(Debug, Default)]
struct App {
/// Current run state, toggled to `Quit` when the user exits.
state: AppState,
/// Latest layout rectangles used to place the scrollbars.
layout: Option<LayoutState>,
/// Vertical scroll offset in logical units (subcells for this demo).
vertical_offset: usize,
/// Horizontal scroll offset in logical units (subcells for this demo).
horizontal_offset: usize,
/// Drag state for the vertical scrollbar.
vertical_interaction: ScrollBarInteraction,
/// Drag state for the horizontal scrollbar.
horizontal_interaction: ScrollBarInteraction,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
enum AppState {
#[default]
/// Keep running the event loop and rendering frames.
Running,
/// Exit the application on the next loop iteration.
Quit,
}
#[derive(Debug, Clone, Copy)]
struct LayoutState {
/// The content area used to compute scroll metrics.
content: Rect,
/// Rect for the vertical scrollbar (right edge).
vertical_bar: Rect,
/// Rect for the horizontal scrollbar (bottom edge).
horizontal_bar: Rect,
}
impl App {
/// Builds a fresh app state with zero offsets.
fn new() -> Self {
Self {
state: AppState::Running,
layout: None,
vertical_offset: 0,
horizontal_offset: 0,
vertical_interaction: ScrollBarInteraction::new(),
horizontal_interaction: ScrollBarInteraction::new(),
}
}
/// Runs the event loop until the user exits.
fn run(&mut self, terminal: &mut DefaultTerminal) -> Result<()> {
while self.state == AppState::Running {
terminal.draw(|frame| self.render(frame))?;
self.handle_events()?;
}
Ok(())
}
/// Renders the title block and the two scrollbars.
fn render(&mut self, frame: &mut ratatui::Frame) {
let area = frame.area();
if area.width < 2 || area.height < 2 {
return;
}
let title = "tui-scrollbar - mouse scroll demo";
let block = Block::new()
.borders(Borders::TOP)
.border_style(Style::new().fg(TITLE_FG).bg(TITLE_BG))
.style(Style::new().fg(BLOCK_FG).bg(BLOCK_BG))
.title(
Line::from(title)
.centered()
.fg(TITLE_FG)
.bg(TITLE_BG)
.bold(),
);
frame.render_widget(&block, area);
let content_area = Rect {
y: area.y.saturating_add(1),
height: area.height.saturating_sub(1),
..area
};
let help = "Arrows: move | Wheel: scroll | Drag: thumb | q/Esc: quit";
let help_area = Rect {
x: content_area.x.saturating_add(1),
y: content_area.y,
width: content_area.width.saturating_sub(1),
height: 1,
};
if help_area.width > 0 {
frame.render_widget(
Paragraph::new(help).style(Style::new().fg(TITLE_FG)),
help_area,
);
}
let content_area = Rect {
y: content_area.y.saturating_add(1),
height: content_area.height.saturating_sub(1),
..content_area
};
// Split out the bottom row and right column for the scrollbars.
let [content_row, bar_row] = content_area.layout(&Layout::vertical([
Constraint::Fill(1),
Constraint::Length(1),
]));
let [content, vertical_bar] = content_row.layout(&Layout::horizontal([
Constraint::Fill(1),
Constraint::Length(1),
]));
let [horizontal_bar, _corner] = bar_row.layout(&Layout::horizontal([
Constraint::Fill(1),
Constraint::Length(1),
]));
self.layout = Some(LayoutState {
content,
vertical_bar,
horizontal_bar,
});
// Keep offsets valid when the terminal is resized.
let (h_metrics, v_metrics) = self.metrics_for_layout(content);
self.horizontal_offset = self.horizontal_offset.min(h_metrics.max_offset());
self.vertical_offset = self.vertical_offset.min(v_metrics.max_offset());
let horizontal_lengths = ScrollLengths {
content_len: h_metrics.content_len(),
viewport_len: h_metrics.viewport_len(),
};
let track_style = Style::new().bg(SCROLLBAR_TRACK_BG);
let thumb_style = Style::new().fg(SCROLLBAR_THUMB_FG).bg(SCROLLBAR_THUMB_BG);
let arrow_style = Style::new().fg(SCROLLBAR_ARROW_FG).bg(SCROLLBAR_TRACK_BG);
let glyphs = GlyphSet {
track_vertical: ' ',
track_horizontal: ' ',
..GlyphSet::default()
};
let horizontal = ScrollBar::horizontal(horizontal_lengths)
.arrows(ScrollBarArrows::Both)
.offset(self.horizontal_offset)
.scroll_step(SUBCELL)
.track_style(track_style)
.thumb_style(thumb_style)
.arrow_style(arrow_style)
.glyph_set(glyphs.clone());
let vertical_lengths = ScrollLengths {
content_len: v_metrics.content_len(),
viewport_len: v_metrics.viewport_len(),
};
let vertical = ScrollBar::vertical(vertical_lengths)
.arrows(ScrollBarArrows::Both)
.offset(self.vertical_offset)
.scroll_step(SUBCELL)
.track_style(track_style)
.thumb_style(thumb_style)
.arrow_style(arrow_style)
.glyph_set(glyphs);
frame.render_widget(&horizontal, horizontal_bar);
frame.render_widget(&vertical, vertical_bar);
}
/// Handles keyboard and mouse events, updating offsets as needed.
fn handle_events(&mut self) -> Result<()> {
match event::read()? {
Event::Key(key) => {
if key.kind == KeyEventKind::Press {
match key.code {
KeyCode::Char('q') | KeyCode::Esc => self.state = AppState::Quit,
KeyCode::Up => self.handle_key_scroll(0, -(KEY_STEP as isize)),
KeyCode::Down => self.handle_key_scroll(0, KEY_STEP as isize),
KeyCode::Left => self.handle_key_scroll(-(KEY_STEP as isize), 0),
KeyCode::Right => self.handle_key_scroll(KEY_STEP as isize, 0),
_ => {}
}
}
}
Event::Mouse(event) => {
self.handle_mouse_event(event);
}
_ => {}
}
Ok(())
}
/// Applies a keyboard delta to the scrollbar offsets.
fn handle_key_scroll(&mut self, dx: isize, dy: isize) {
let Some(layout) = self.layout else {
return;
};
let (h_metrics, v_metrics) = self.metrics_for_layout(layout.content);
self.horizontal_offset =
Self::apply_delta(self.horizontal_offset, dx, h_metrics.max_offset());
self.vertical_offset = Self::apply_delta(self.vertical_offset, dy, v_metrics.max_offset());
}
/// Handles crossterm mouse events using the scrollbar helpers.
fn handle_mouse_event(&mut self, event: event::MouseEvent) {
let Some(layout) = self.layout else {
return;
};
let (h_metrics, v_metrics) = self.metrics_for_layout(layout.content);
let horizontal = self.horizontal_scrollbar(h_metrics);
let vertical = self.vertical_scrollbar(v_metrics);
if let Some(command) = horizontal.handle_mouse_event(
layout.horizontal_bar,
event,
&mut self.horizontal_interaction,
) {
self.apply_command(command, true);
}
if let Some(command) =
vertical.handle_mouse_event(layout.vertical_bar, event, &mut self.vertical_interaction)
{
self.apply_command(command, false);
}
}
/// Applies a scroll command to the current axis offset.
fn apply_command(&mut self, command: ScrollCommand, is_horizontal: bool) {
let ScrollCommand::SetOffset(offset) = command;
if is_horizontal {
self.horizontal_offset = offset;
} else {
self.vertical_offset = offset;
}
}
/// Builds a horizontal scrollbar from the current metrics.
fn horizontal_scrollbar(&self, metrics: ScrollMetrics) -> ScrollBar {
let lengths = ScrollLengths {
content_len: metrics.content_len(),
viewport_len: metrics.viewport_len(),
};
ScrollBar::horizontal(lengths)
.arrows(ScrollBarArrows::Both)
.offset(self.horizontal_offset)
.scroll_step(SUBCELL)
}
/// Builds a vertical scrollbar from the current metrics.
fn vertical_scrollbar(&self, metrics: ScrollMetrics) -> ScrollBar {
let lengths = ScrollLengths {
content_len: metrics.content_len(),
viewport_len: metrics.viewport_len(),
};
ScrollBar::vertical(lengths)
.arrows(ScrollBarArrows::Both)
.offset(self.vertical_offset)
.scroll_step(SUBCELL)
}
/// Derives metrics based on the current layout and desired scroll range.
fn metrics_for_layout(&self, content: Rect) -> (ScrollMetrics, ScrollMetrics) {
// Use subcell units so wheel/drag updates line up with the fractional renderer.
let h_cells = content.width.max(1) as usize;
let v_cells = content.height.max(1) as usize;
let h_content = h_cells.saturating_mul(SUBCELL).max(1);
let v_content = v_cells.saturating_mul(SUBCELL).max(1);
let h_viewport = h_content.saturating_sub(100).max(1);
let v_viewport = v_content.saturating_sub(100).max(1);
(
ScrollMetrics::new(
ScrollLengths {
content_len: h_content,
viewport_len: h_viewport,
},
self.horizontal_offset,
content.width,
),
ScrollMetrics::new(
ScrollLengths {
content_len: v_content,
viewport_len: v_viewport,
},
self.vertical_offset,
content.height,
),
)
}
/// Adds a signed delta while clamping to the provided maximum.
fn apply_delta(current: usize, delta: isize, max: usize) -> usize {
if delta < 0 {
current.saturating_sub(delta.unsigned_abs())
} else {
current.saturating_add(delta as usize).min(max)
}
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
joshka/tui-widgets | https://github.com/joshka/tui-widgets/blob/8521548a9e8348d029bd1721dfee4b6e0e71bf52/tui-scrollbar/examples/scrollbar.rs | tui-scrollbar/examples/scrollbar.rs | //! Fractional scrollbar step showcase.
//!
//! This example renders every 1/8th thumb step for both horizontal and vertical scrollbars so
//! you can visually compare partial glyphs and track alignment.
//!
//! Press `q` or `Esc` to exit.
//!
//! ## Structure
//!
//! - Calculation helpers (`build_metrics`, `step_entry`) derive `ScrollMetrics` and offsets so the
//! demo can cover all 1/8th positions. These functions are not required for normal usage.
//! - Rendering helpers (`render_horizontal_steps`, `render_vertical_steps`) instantiate
//! [`ScrollBar`] widgets and render them into each cell.
//!
//! ## Why this example exists
//!
//! Fractional glyphs can be hard to reason about without a full sweep. This example deliberately
//! draws every 1/8th step from both ends so you can verify the glyph ordering and thumb symmetry.
use color_eyre::Result;
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEventKind};
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::widgets::Paragraph;
use ratatui::DefaultTerminal;
use tui_scrollbar::{ScrollBar, ScrollBarArrows, ScrollLengths, ScrollMetrics, SUBCELL};
fn main() -> Result<()> {
color_eyre::install()?;
let terminal = ratatui::init();
let result = App::new().run(terminal);
ratatui::restore();
result
}
#[derive(Debug, Default)]
struct App {
/// Current run state for the render loop.
state: AppState,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
enum AppState {
#[default]
/// Continue drawing frames and handling input.
Running,
/// Exit the demo on the next tick.
Quit,
}
impl App {
/// Creates the demo app in its initial running state.
const fn new() -> Self {
Self {
state: AppState::Running,
}
}
/// Runs the draw loop until a quit key is pressed.
fn run(&mut self, mut terminal: DefaultTerminal) -> Result<()> {
while self.state == AppState::Running {
terminal.draw(|frame| {
render_scrollbars(frame.area(), frame);
})?;
self.handle_events()?;
}
Ok(())
}
/// Handles a single input event and updates the run state.
fn handle_events(&mut self) -> Result<()> {
if let Event::Key(key) = event::read()? {
if key.kind == KeyEventKind::Press
&& matches!(key.code, KeyCode::Char('q') | KeyCode::Esc)
{
self.state = AppState::Quit;
}
}
Ok(())
}
}
/// Splits the area into horizontal and vertical showcases and renders all 1/8th steps.
fn render_scrollbars(area: Rect, frame: &mut ratatui::Frame) {
if area.height < 8 {
return;
}
let title = "Fractional scrollbar steps (q/Esc to quit)";
frame.render_widget(Paragraph::new(title), area);
let content_area = Rect {
y: area.y.saturating_add(1),
height: area.height.saturating_sub(1),
..area
};
if content_area.height == 0 {
return;
}
// Reserve enough width for 34 vertical bars (2 columns each) on the right.
let min_left_width = 12;
let max_right_width = 68;
let right_width = max_right_width.min(content_area.width.saturating_sub(min_left_width));
let [left_column, right_column] = content_area.layout(&Layout::horizontal([
Constraint::Fill(1),
Constraint::Length(right_width),
]));
// Stack up to 34 horizontal bars top-to-bottom in the left column.
let max_rows = left_column.height as usize;
let row_count = 34.min(max_rows);
let left_cells =
left_column.layout_vec(&Layout::vertical(vec![Constraint::Length(1); row_count]));
// Arrange up to 34 vertical bars left-to-right in the right column.
let bar_width = if right_column.width >= 68 { 2 } else { 1 };
let max_cols = (right_column.width / bar_width) as usize;
let col_count = 34.min(max_cols);
let right_cells =
right_column.layout_vec(&Layout::horizontal(vec![
Constraint::Length(bar_width);
col_count
]));
render_horizontal_steps(frame, left_cells);
render_vertical_steps(frame, right_cells);
}
/// Draws horizontal scrollbars that sweep every 1/8th thumb position, top to bottom.
fn render_horizontal_steps(frame: &mut ratatui::Frame, cells: Vec<Rect>) {
for (index, area) in cells.iter().enumerate() {
let [label_area, bar_area] = area.layout(&Layout::horizontal([
Constraint::Length(2),
Constraint::Fill(1),
]));
if bar_area.width == 0 {
continue;
}
let metrics = build_metrics(bar_area.width as usize, 6);
let (label, thumb_start) = step_entry(&metrics, index);
let label = (label % 8).to_string();
let offset = metrics.offset_for_thumb_start(thumb_start);
let lengths = ScrollLengths {
content_len: metrics.content_len(),
viewport_len: metrics.viewport_len(),
};
let scrollbar = ScrollBar::horizontal(lengths)
.arrows(ScrollBarArrows::Both)
.offset(offset);
render_label(frame, label_area, &label);
frame.render_widget(&scrollbar, bar_area);
}
}
/// Draws vertical scrollbars that sweep every 1/8th thumb position, left to right.
fn render_vertical_steps(frame: &mut ratatui::Frame, cells: Vec<Rect>) {
for (index, area) in cells.iter().enumerate() {
let [label_area, bar_area] = area.layout(&Layout::vertical([
Constraint::Length(1),
Constraint::Fill(1),
]));
if bar_area.height == 0 {
continue;
}
let metrics = build_metrics(bar_area.height as usize, 3);
let (label, thumb_start) = step_entry(&metrics, index);
let label = (label % 8).to_string();
let offset = metrics.offset_for_thumb_start(thumb_start);
let lengths = ScrollLengths {
content_len: metrics.content_len(),
viewport_len: metrics.viewport_len(),
};
let scrollbar = ScrollBar::vertical(lengths)
.arrows(ScrollBarArrows::Both)
.offset(offset);
render_label(frame, label_area, &label);
frame.render_widget(&scrollbar, bar_area);
}
}
/// Renders the small modulo-8 label that marks the fractional step.
fn render_label(frame: &mut ratatui::Frame, area: Rect, label: &str) {
if area.width == 0 || area.height == 0 {
return;
}
frame.render_widget(Paragraph::new(label), area);
}
/// Builds metrics where the thumb occupies a fixed number of cells on the track.
fn build_metrics(track_cells: usize, desired_thumb_cells: usize) -> ScrollMetrics {
let track_len = track_cells.saturating_mul(SUBCELL);
let viewport_len = track_len.max(1);
let desired_thumb_len = desired_thumb_cells.saturating_mul(SUBCELL).max(1);
let content_len =
((track_len as u128) * (viewport_len as u128) / (desired_thumb_len as u128)) as usize;
let content_len = content_len.max(viewport_len.saturating_add(1));
ScrollMetrics::new(
ScrollLengths {
content_len,
viewport_len,
},
0,
track_cells as u16,
)
}
/// Returns the label index and thumb start for the 0..=16 or trailing sweep.
fn step_entry(metrics: &ScrollMetrics, index: usize) -> (usize, usize) {
let max_start = metrics.thumb_travel();
let local = index % 17;
if index < 17 {
(local, local.min(max_start))
} else {
let base = max_start.saturating_sub(16);
(local, base.saturating_add(local).min(max_start))
}
}
| rust | Apache-2.0 | 8521548a9e8348d029bd1721dfee4b6e0e71bf52 | 2026-01-04T20:22:07.469528Z | false |
timothebot/lacy | https://github.com/timothebot/lacy/blob/12f056c9f4eca7af8afbda8ba33a0c5e23c33742/src/lib.rs | src/lib.rs | pub mod directory;
pub mod fuzzy;
pub mod query;
pub mod query_part;
| rust | MIT | 12f056c9f4eca7af8afbda8ba33a0c5e23c33742 | 2026-01-04T20:22:09.206135Z | false |
timothebot/lacy | https://github.com/timothebot/lacy/blob/12f056c9f4eca7af8afbda8ba33a0c5e23c33742/src/query_part.rs | src/query_part.rs | use std::{env::home_dir, path::PathBuf};
use crate::directory::{scored_directories, sub_directories, Directory};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum QueryPart {
/// ~
Tilde,
/// .. (two or more dots)
Back(u32),
/// /
Root,
/// - (one or more dashes)
Skip(u32),
/// Anything else
Text(String),
}
impl From<&str> for QueryPart {
fn from(part: &str) -> Self {
match part {
"" => QueryPart::Root,
"~" => QueryPart::Tilde,
_ if part.starts_with("-") && part.replace("-", "").is_empty() => {
QueryPart::Skip(part.len() as u32 - 1)
}
_ if part.starts_with("..") && part.replace(".", "").is_empty() => {
QueryPart::Back(part.len() as u32 - 1)
}
_ => QueryPart::Text(part.to_string()),
}
}
}
impl QueryPart {
pub fn matching_directories(&self, dirs: &[Directory]) -> Vec<Directory> {
match &self {
QueryPart::Tilde => {
let Ok(dir) =
Directory::try_from(home_dir().unwrap_or(PathBuf::from("/")).as_path())
else {
return vec![];
};
vec![dir]
}
QueryPart::Root => {
let Ok(dir) = Directory::try_from(PathBuf::from("/").as_path()) else {
eprintln!("Couldn't create Directory from root!");
return vec![];
};
vec![dir]
}
QueryPart::Skip(depth) => dirs
.iter()
.flat_map(|dir| sub_directories(dir.location().as_path(), *depth))
.collect(),
QueryPart::Back(amount) => {
let Some(target_dir) = dirs.first() else {
return vec![];
};
let mut target_location = target_dir.location().clone();
for _ in 0..*amount {
target_location.push("..");
}
let Ok(dir) = Directory::try_from(target_location.as_path()) else {
return vec![];
};
vec![dir]
}
QueryPart::Text(text) => {
let mut scored_dirs = scored_directories(
dirs.iter()
.flat_map(|dir| sub_directories(dir.location().as_path(), 0))
.collect(),
text.as_str(),
);
let average_score: f64 = scored_dirs
.iter()
.map(|scored_dir| scored_dir.score() as f64)
.sum::<f64>()
/ scored_dirs.len() as f64;
let half_of_highest_score = scored_dirs
.iter()
.map(|scored_dir| scored_dir.score())
.max()
.unwrap_or(0_i32)
/ 2;
// sort by alphabetical order, then by score
scored_dirs.sort_by(|a, b| a.directory().location().cmp(b.directory().location()));
scored_dirs.sort_by_key(|a| a.score());
scored_dirs
.iter()
// remove dirs with low score
.filter(|scored_dir| {
scored_dir.score() as f64 > 0.0
&& scored_dir.score() as f64 >= average_score
&& scored_dir.score() >= half_of_highest_score
})
.map(|scored_dir| scored_dir.directory().clone())
.collect()
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_from() {
assert_eq!(QueryPart::Tilde, QueryPart::from("~"));
assert_eq!(QueryPart::Back(1), QueryPart::from(".."));
assert_eq!(QueryPart::Back(2), QueryPart::from("..."));
assert_eq!(QueryPart::Root, QueryPart::from(""));
assert_eq!(QueryPart::Skip(0), QueryPart::from("-"));
assert_eq!(QueryPart::Skip(1), QueryPart::from("--"));
assert_eq!(
QueryPart::Text(String::from("hello")),
QueryPart::from("hello")
);
}
}
| rust | MIT | 12f056c9f4eca7af8afbda8ba33a0c5e23c33742 | 2026-01-04T20:22:09.206135Z | false |
timothebot/lacy | https://github.com/timothebot/lacy/blob/12f056c9f4eca7af8afbda8ba33a0c5e23c33742/src/ui.rs | src/ui.rs | use dialoguer::{theme::ColorfulTheme, Select};
pub fn select(title: &str, options: Vec<String>) -> Option<String> {
if let Some(selection) = Select::with_theme(&ColorfulTheme::default())
.with_prompt(title)
.items(&options)
.default(0)
.interact_opt()
.unwrap()
{
return Some(options[selection].to_string());
}
None
}
| rust | MIT | 12f056c9f4eca7af8afbda8ba33a0c5e23c33742 | 2026-01-04T20:22:09.206135Z | false |
timothebot/lacy | https://github.com/timothebot/lacy/blob/12f056c9f4eca7af8afbda8ba33a0c5e23c33742/src/query.rs | src/query.rs | use crate::directory::{sub_directories, Directory};
use crate::query_part::QueryPart;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Query {
query: String,
parts: Vec<QueryPart>,
}
impl From<String> for Query {
fn from(query: String) -> Self {
let mut enhanced_query = query.clone().trim().replace(" ", " ");
if enhanced_query.starts_with("/") {
enhanced_query = format!("##ROOT## {}", enhanced_query.strip_prefix("/").unwrap());
}
if enhanced_query.ends_with("/") {
enhanced_query = enhanced_query.strip_suffix("/").unwrap().to_string();
}
enhanced_query = enhanced_query
.replace(" / ", " ##ROOT## ")
.replace(" ", "/")
.replace("//", "/");
let query_parts: Vec<QueryPart> = enhanced_query
.split("/")
.map(|part| {
if part == "##ROOT##" {
return QueryPart::Root;
}
QueryPart::from(part)
})
.collect();
Self {
query,
parts: query_parts,
}
}
}
impl Query {
pub fn results(&self, cwd: &Path) -> Vec<PathBuf> {
let Some(start_dir) = Directory::try_from(cwd).ok() else {
return vec![];
};
let mut directories = vec![start_dir];
for part in self.parts() {
directories = part.matching_directories(&directories);
}
directories
.iter()
.map(|dir| dir.location().clone())
.collect()
}
pub fn completions(&self, cwd: &Path) -> Vec<PathBuf> {
let query = self.query.clone();
if query.trim().is_empty() {
return sub_directories(cwd, 0)
.iter()
.map(|dir| dir.location().clone())
.collect();
}
if query.ends_with(" ") {
return self
.results(cwd)
.iter()
.flat_map(|dir| sub_directories(dir, 0))
.map(|dir| dir.location().clone())
.collect();
}
if let QueryPart::Text(_) = &self.parts.last().unwrap_or(&QueryPart::Root) {
return self.results(cwd);
}
vec![]
}
pub fn parts(&self) -> &Vec<QueryPart> {
&self.parts
}
}
#[cfg(test)]
mod tests {
use super::*;
// TODO: optimize this by smart removing parts before
// parts like .., / or ~
#[test]
#[should_panic]
fn test_smart_query_creation_tilde() {
assert_eq!(
&vec![QueryPart::Tilde],
Query::from(String::from("hello world ~")).parts()
);
assert_eq!(
&vec![QueryPart::Tilde],
Query::from(String::from("hello world ~ ~")).parts()
);
assert_eq!(
&vec![QueryPart::Tilde, QueryPart::Text(String::from("hello"))],
Query::from(String::from("hello world ~ hello")).parts()
);
}
#[test]
#[should_panic]
fn test_smart_query_creation_root() {
assert_eq!(
&vec![QueryPart::Root],
Query::from(String::from("hello /")).parts()
);
assert_eq!(
&vec![QueryPart::Root],
Query::from(String::from("hello / /")).parts()
);
assert_eq!(
&vec![QueryPart::Root],
Query::from(String::from("/ hello /")).parts()
);
assert_eq!(
&vec![QueryPart::Root],
Query::from(String::from("/")).parts()
);
}
#[test]
#[should_panic]
fn test_smart_query_creation_back() {
assert_eq!(
&vec![QueryPart::Root],
Query::from(String::from("/ hello world ...")).parts()
);
assert_eq!(
&vec![QueryPart::Root],
Query::from(String::from("/ ...")).parts()
);
assert_eq!(
&vec![QueryPart::Tilde],
Query::from(String::from("~ ..")).parts()
);
}
}
| rust | MIT | 12f056c9f4eca7af8afbda8ba33a0c5e23c33742 | 2026-01-04T20:22:09.206135Z | false |
timothebot/lacy | https://github.com/timothebot/lacy/blob/12f056c9f4eca7af8afbda8ba33a0c5e23c33742/src/main.rs | src/main.rs | use clap::Parser;
use cmd::LacyCli;
use crate::cmd::Run;
mod cmd;
mod directory;
mod fuzzy;
mod query;
mod query_part;
mod ui;
fn main() {
LacyCli::parse().run();
}
| rust | MIT | 12f056c9f4eca7af8afbda8ba33a0c5e23c33742 | 2026-01-04T20:22:09.206135Z | false |
timothebot/lacy | https://github.com/timothebot/lacy/blob/12f056c9f4eca7af8afbda8ba33a0c5e23c33742/src/directory.rs | src/directory.rs | use std::{
env, fs,
path::{Path, PathBuf},
};
use crate::fuzzy::fuzzy_match_score;
pub fn get_current_directory() -> PathBuf {
env::current_dir().unwrap_or(PathBuf::from("/"))
}
/// Returns all directories for the given path
pub fn get_all_directories_in(path: &Path) -> Vec<Directory> {
let dirs_res = fs::read_dir(path);
let Ok(dirs) = dirs_res else {
return vec![];
};
dirs.filter_map(|entry| Directory::try_from(entry.ok()?.path().as_path()).ok())
.collect()
}
/// Get the sub directories at a specified depth relative to the given cwd.
///
/// ### Example
///
/// With this dir structure:
///
/// ```text
/// User/ <-- CWD
/// Desktop/
/// Wallpapers/
/// Documents/
/// FirstProject/
/// SecondProject/
/// ```
///
/// Depth 0 returns `Desktop` and `Documents`.
///
/// Depth 1 returns `Wallpapers`, `FirstProject` and `SecondProject`.
pub fn sub_directories(cwd: &Path, depth: u32) -> Vec<Directory> {
let mut directories = get_all_directories_in(cwd);
for _ in 0..depth {
let mut next_directories: Vec<Directory> = vec![];
for dir in directories {
next_directories.append(&mut get_all_directories_in(dir.location.as_path()));
}
directories = next_directories;
}
directories
}
#[derive(Debug)]
pub struct ScoredDirectory {
directory: Directory,
score: i32,
}
impl ScoredDirectory {
pub fn new(directory: Directory, score: i32) -> Self {
Self { directory, score }
}
pub fn directory(&self) -> &Directory {
&self.directory
}
pub fn score(&self) -> i32 {
self.score
}
}
pub fn scored_directories(directories: Vec<Directory>, query: &str) -> Vec<ScoredDirectory> {
directories
.iter()
.map(|directory| {
let score = fuzzy_match_score(directory.name(), query);
ScoredDirectory::new(directory.clone(), score)
})
.collect()
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Directory {
/// The name of the directory
name: String,
/// The actual path of the directory, with symlinks resolved
location: PathBuf,
}
impl Directory {
pub fn new(name: String, location: PathBuf) -> Self {
Self { name, location }
}
pub fn name(&self) -> &str {
&self.name
}
pub fn location(&self) -> &PathBuf {
&self.location
}
}
impl TryFrom<&Path> for Directory {
type Error = ();
fn try_from(path: &Path) -> Result<Self, Self::Error> {
if path.is_symlink() {
return Ok(Directory::new(
path.file_name().ok_or(())?.display().to_string(),
path.to_path_buf(),
));
}
if path.is_dir() {
let Some(file_name) = path.file_name() else {
return Ok(Directory::new(String::new(), path.to_path_buf()));
};
return Ok(Directory::new(
file_name.display().to_string(),
path.to_path_buf(),
));
}
Err(())
}
}
| rust | MIT | 12f056c9f4eca7af8afbda8ba33a0c5e23c33742 | 2026-01-04T20:22:09.206135Z | false |
timothebot/lacy | https://github.com/timothebot/lacy/blob/12f056c9f4eca7af8afbda8ba33a0c5e23c33742/src/fuzzy.rs | src/fuzzy.rs | /// Creates a score of how much the input and the pattern match
///
/// The higher the score the better. There is no max score.
pub fn fuzzy_match_score(input: &str, pattern: &str) -> i32 {
let mut score = 0;
if input
.to_lowercase()
.contains(pattern.to_lowercase().as_str())
{
score += 10;
}
let mut dir_name_mut = input.to_string();
for c in pattern.chars() {
if dir_name_mut.to_lowercase().contains(c.to_ascii_lowercase()) {
score += 1;
// strip the char to avoid multiple matches
dir_name_mut = dir_name_mut.replacen(c, "", 1);
} else {
score -= 5;
}
}
if input.to_lowercase() == pattern.to_lowercase() {
score += 50;
}
if score < 0 {
score = 0;
}
score
}
#[cfg(test)]
mod tests {
use super::fuzzy_match_score as score;
#[test]
#[should_panic]
fn not_yet_implemented() {
// TODO: Should give more points if parts of query match
// beginning parts of input parts
assert!(score("test", "tt") > score("test", "t"));
assert!(score("test-abc", "ta") > score("test-abc", "te"));
assert!(score("test abc", "ta") > score("test abc", "te"));
assert!(score("test_abc", "ta") > score("test_abc", "te"));
assert!(score("test_abc_a", "taa") > score("test_abc_a", "te"));
assert!(score("test_abc_a", "taa") > score("test_abc_a", "tea"));
assert!(score("testAbc", "ta") > score("testAbc", "te"));
}
#[test]
fn test_simple() {
assert_eq!(score("test", "test"), score("test", "test"));
assert_eq!(score("test", "uoa"), 0);
assert!(score("test", "test") > score("test", "tes"));
assert!(score("ttest", "tt") > score("ttest", "t"));
}
#[test]
fn test_advanced() {
assert!(score("helloworld", "world") > score("helloworld", "elwo"));
assert!(score("helloworld", "hello") > score("helloworld", "hellohello"));
}
#[test]
fn test_negative_queries() {
assert!(score("helloworld", "ellovvvv") == 0);
assert!(score("helloworld", "ww") == 0);
}
}
| rust | MIT | 12f056c9f4eca7af8afbda8ba33a0c5e23c33742 | 2026-01-04T20:22:09.206135Z | false |
timothebot/lacy | https://github.com/timothebot/lacy/blob/12f056c9f4eca7af8afbda8ba33a0c5e23c33742/src/cmd/complete.rs | src/cmd/complete.rs | use crate::{
cmd::{Complete, Run},
directory::get_current_directory,
query::Query,
};
impl Run for Complete {
fn run(&self) {
let query = Query::from(self.query.clone());
println!(
"{}",
query
.completions(get_current_directory().as_path())
.iter()
.filter_map(|path_buf| {
if self.basename {
Some(path_buf.file_name()?.display().to_string())
} else {
Some(path_buf.display().to_string())
}
})
.collect::<Vec<String>>()
.join(" ")
);
}
}
| rust | MIT | 12f056c9f4eca7af8afbda8ba33a0c5e23c33742 | 2026-01-04T20:22:09.206135Z | false |
timothebot/lacy | https://github.com/timothebot/lacy/blob/12f056c9f4eca7af8afbda8ba33a0c5e23c33742/src/cmd/prompt.rs | src/cmd/prompt.rs | use std::{collections::HashSet, fs, path::PathBuf};
use crate::{
cmd::{Prompt, Run},
directory::get_current_directory,
query::Query,
ui,
};
impl Run for Prompt {
fn run(&self) {
let query = Query::from(self.query.clone());
/*
_ if first_query_part.starts_with("-")
&& !first_query_part
.strip_prefix("-")
.unwrap_or_default()
.contains("-") =>
{
if let Ok(number) = first_query_part
.strip_prefix("-")
.unwrap_or_default()
.parse::<i32>()
{
}
get_current_directory()
}
*/
let results: Vec<PathBuf> = query.results(get_current_directory().as_path());
match results.len() {
0 => {}
1 => {
println!("{}", results.first().unwrap().display());
}
_ => {
let paths = results
.iter()
.map(|path_buf| path_buf.display().to_string())
.collect::<Vec<String>>();
// Canonicalize the paths to see if we have two different paths pointing
// to the same location
let filtered_paths = paths
.clone()
.into_iter()
.map(|path| {
fs::canonicalize(&path)
.map(|canonicalized| canonicalized.display().to_string())
.unwrap_or(path.to_string())
})
.collect::<HashSet<_>>()
.into_iter()
.collect::<Vec<String>>();
if filtered_paths.len() == 1 {
println!("{}", filtered_paths.first().unwrap());
return;
}
if self.return_all {
println!("{}", paths.join("\n"));
return;
}
if let Some(selected) = ui::select("Multiple possibilities found!", paths) {
println!("{}", selected);
}
}
};
}
}
| rust | MIT | 12f056c9f4eca7af8afbda8ba33a0c5e23c33742 | 2026-01-04T20:22:09.206135Z | false |
timothebot/lacy | https://github.com/timothebot/lacy/blob/12f056c9f4eca7af8afbda8ba33a0c5e23c33742/src/cmd/commands.rs | src/cmd/commands.rs | use clap::{Parser, Subcommand};
const HELP_TEMPLATE: &str = "
_ _ ____ __
| | / \\ / _\\ V /
| |_ | o ( (_ \\ /
|___||_n_|\\__||_|
v{version}
https://github.com/timothebot/lacy
{about}{before-help}
{usage-heading}
{tab}{usage}
{all-args}{after-help}
";
#[derive(Parser, Debug)]
#[command(
version,
about,
override_usage="lacy init --help",
help_template=HELP_TEMPLATE
)]
pub struct LacyCli {
#[command(subcommand)]
pub command: LacyCommand,
}
#[derive(Subcommand, Debug)]
#[command(version, help_template=HELP_TEMPLATE)]
pub enum LacyCommand {
/// Return all paths matching the given query.
Prompt(Prompt),
/// Generate the shell configuration
Init(Init),
/// Get shell completions for the given query.
Complete(Complete),
}
#[derive(Debug, Parser)]
#[command(version, help_template=HELP_TEMPLATE)]
pub struct Prompt {
pub query: String,
/// Returns all result separated by \n instead of showing selector ui
///
/// This is allows you to integrate a custom fuzzy tool if want
#[arg(long)]
pub return_all: bool,
}
#[derive(Debug, Parser)]
#[command(
version,
help_template=HELP_TEMPLATE,
after_help = "
To get started, you must include lacy in your shell config.
You can find more about why this is required in the docs.
If you don't know what shell you are using, run:
$ echo $SHELL
ZSH:
$ echo \"eval \\\"\\$(lacy init zsh)\\\"\" >> ~/.zshrc
Bash:
$ echo \"eval \\\"\\$(lacy init bash)\\\"\" >> ~/.bashrc
Fish:
$ echo \"lacy init fish | source\" >> ~/.config/fish/config.fish"
)]
pub struct Init {
/// Currently supported shells: bash, fish, zsh
pub shell: String,
/// Allows you to specify another command than cd, e.g. z
#[arg(long, default_value = "cd")]
pub cd_cmd: String,
/// Define what alias the lacy command has
#[arg(long, default_value = "y")]
pub cmd: String,
/// What fuzzy tool should be used for cases where lacy finds multiple
/// matching folders. If not specified, lacy will use a custom UI.
#[arg(long)]
pub custom_fuzzy: Option<String>,
}
#[derive(Debug, Parser)]
#[command(version, help_template=HELP_TEMPLATE)]
pub struct Complete {
#[arg(default_value = "")]
pub query: String,
/// Return only the names of the folder instead of the whole path
#[arg(long)]
pub basename: bool,
}
| rust | MIT | 12f056c9f4eca7af8afbda8ba33a0c5e23c33742 | 2026-01-04T20:22:09.206135Z | false |
timothebot/lacy | https://github.com/timothebot/lacy/blob/12f056c9f4eca7af8afbda8ba33a0c5e23c33742/src/cmd/mod.rs | src/cmd/mod.rs | mod commands;
mod complete;
mod init;
mod prompt;
pub use crate::cmd::commands::*;
pub trait Run {
fn run(&self);
}
impl Run for LacyCli {
fn run(&self) {
match &self.command {
LacyCommand::Prompt(cmd) => cmd.run(),
LacyCommand::Init(cmd) => cmd.run(),
LacyCommand::Complete(cmd) => cmd.run(),
}
}
}
| rust | MIT | 12f056c9f4eca7af8afbda8ba33a0c5e23c33742 | 2026-01-04T20:22:09.206135Z | false |
timothebot/lacy | https://github.com/timothebot/lacy/blob/12f056c9f4eca7af8afbda8ba33a0c5e23c33742/src/cmd/init.rs | src/cmd/init.rs | use upon::{value, Engine, Error};
use crate::cmd::{Init, Run};
impl Run for Init {
fn run(&self) {
println!(
"{}",
match shell_config(
self.shell.as_str(),
&self.cd_cmd,
&self.cmd,
&self.custom_fuzzy
) {
Ok(config) => config,
Err(err) => format!("An error occurred: {}", err),
}
);
}
}
pub fn shell_config(
shell: &str,
cd_cmd: &String,
cmd: &String,
custom_fuzzy: &Option<String>,
) -> Result<String, Error> {
let mut engine = Engine::new();
let _ = engine.add_template("bash", include_str!("../../templates/bash.sh"));
let _ = engine.add_template("zsh", include_str!("../../templates/zsh.sh"));
let _ = engine.add_template("fish", include_str!("../../templates/fish.fish"));
engine
.template(shell)
.render(value! {
cd: cd_cmd,
lacy_cmd: cmd,
return_all: if custom_fuzzy.is_some() {
String::from("--return-all ")
} else {
String::new()
},
custom_fuzzy: {
enabled: &custom_fuzzy.is_some(),
cmd: custom_fuzzy.clone().unwrap_or_default()
}
})
.to_string()
}
#[cfg(test)]
mod tests {
#[test]
fn test_templates_compile() {
let mut engine = upon::Engine::new();
engine
.add_template("bash", include_str!("../../templates/bash.sh"))
.unwrap();
engine
.add_template("zsh", include_str!("../../templates/zsh.sh"))
.unwrap();
engine
.add_template("fish", include_str!("../../templates/fish.fish"))
.unwrap();
}
}
| rust | MIT | 12f056c9f4eca7af8afbda8ba33a0c5e23c33742 | 2026-01-04T20:22:09.206135Z | false |
timothebot/lacy | https://github.com/timothebot/lacy/blob/12f056c9f4eca7af8afbda8ba33a0c5e23c33742/tests/integration_tests.rs | tests/integration_tests.rs | use std::{fs, os::unix::fs::symlink, path::PathBuf};
use lacy::query::Query;
use tempfile::TempDir;
struct TempEnv {
dir: TempDir,
}
impl TempEnv {
fn new() -> Self {
let tmpdir = tempfile::tempdir().unwrap();
let dir_list = vec![
"alpha/beta/gamma3",
"alpha/beta/delta6",
"alpha/beta/epsil@on8",
"alpha/betabeta/epsil0n/zeta1",
"alpha/betabeta/epsil#on/eta4",
"alpha/betabetaa/thet@a/iota7",
"alpha/alpha/thet#a/iota0/kappa1",
"alpha/alpha/beta/theta3/lambda4",
"beta/mu6/n@u7",
"beta/mu9/xi0",
"beta/mu2/omicron3/pi4",
"beta/mu6/rho7",
"gamma/sigma9/t@u0",
"gamma/sigm#a/upsilon3",
"gamma/ph!i/chi6",
"gamma/ph!i/psi9/omega0",
"gamma/alpha2",
"gamma/alpha4/beta5",
"delta/gamma7",
"delta/delta9/epsilon0",
"delta/del@ta/zeta2/eta3",
"delta/thet#a/iota5",
"delta/kapp@a/lambda7",
"delta/mu9",
"epsilon/nu1/x2",
"epsilon/xi4",
"epsilon/omicron6/pi7",
"epsilon/omicron9/rh0",
"epsilon/sigm#a/tau2",
"epsilon/upsil@on/phi4",
"epsilon/beta/chi6/ps!i7",
"epsilon/beta/omega9/alpha0",
"epsilon/beta/beta2/gamma3",
"epsilon/beta/del@ta/epsilon5",
"epsilon/beta/eta7/theta8",
"epsilon/beta/iot@a/kappa0",
];
for dir in dir_list {
let path = tmpdir.path().join("test").join(dir);
if !path.exists() {
let result = fs::create_dir_all(path);
if result.is_err() {
panic!("Error, couldn't create test folder in tempdir!");
}
}
}
symlink(
tmpdir.path().join("test/alpha"),
tmpdir.path().join("test/link"),
)
.unwrap();
Self { dir: tmpdir }
}
fn resolve_query(&self, query: &str) -> Vec<PathBuf> {
let query = Query::from(query.to_string());
query.results(self.dir.path())
}
fn abs_path(&self, path: &str) -> PathBuf {
let abs_path = PathBuf::from(path);
if abs_path.is_absolute() {
return abs_path;
}
self.dir.path().to_path_buf().join(path)
}
}
#[test]
fn test_absolute() {
let env = TempEnv::new();
assert_eq!(env.resolve_query("/"), vec![env.abs_path("/")]);
}
#[test]
fn test_nonexisting() {
let env = TempEnv::new();
assert!(env.resolve_query("test zzzzzzzzz zzzzzzzzz").is_empty());
}
#[test]
fn test_alpha() {
let env = TempEnv::new();
assert_eq!(
env.resolve_query("test alph alp"),
vec![env.abs_path("test/alpha/alpha")]
);
assert_eq!(
env.resolve_query("tst eps bta om9 0"),
vec![env.abs_path("test/epsilon/beta/omega9/alpha0")]
);
assert_eq!(
env.resolve_query("test delta gamma"),
vec![env.abs_path("test/delta/gamma7")]
);
assert_eq!(
env.resolve_query("test delta gamma "),
vec![env.abs_path("test/delta/gamma7")]
);
}
#[test]
fn test_multiple_matches() {
let env = TempEnv::new();
assert_eq!(
env.resolve_query("test alpha beta a"),
vec![
env.abs_path("test/alpha/beta/delta6"),
env.abs_path("test/alpha/beta/gamma3"),
]
);
}
#[test]
fn test_alpha_with_slashes() {
let env = TempEnv::new();
assert_eq!(
env.resolve_query("test alph/alp"),
vec![env.abs_path("test/alpha/alpha")]
);
assert_eq!(
env.resolve_query("tst/eps/bta/om9/0"),
vec![env.abs_path("test/epsilon/beta/omega9/alpha0")]
);
assert_eq!(
env.resolve_query("test/delta gamma"),
vec![env.abs_path("test/delta/gamma7")]
);
assert_eq!(
env.resolve_query("test delta gamma"),
vec![env.abs_path("test/delta/gamma7")]
);
}
#[test]
fn test_multiple_spaces_or_slashes() {
let env = TempEnv::new();
assert_eq!(
env.resolve_query("test alph alp"),
vec![env.abs_path("test/alpha/alpha")]
);
assert_eq!(
env.resolve_query("tst eps bta om9 0"),
vec![env.abs_path("test/epsilon/beta/omega9/alpha0")]
);
assert_eq!(
env.resolve_query("test /delta gamma"),
vec![env.abs_path("test/delta/gamma7")]
);
}
#[test]
fn test_dir_skip() {
let env = TempEnv::new();
assert_eq!(
env.resolve_query("test gamma - u"),
vec!(
env.abs_path("test/gamma/sigm#a/upsilon3"),
env.abs_path("test/gamma/sigma9/t@u0"),
)
);
assert_eq!(
env.resolve_query("test alpha - epsil#on et4"),
vec![env.abs_path("test/alpha/betabeta/epsil#on/eta4")]
);
assert_eq!(
env.resolve_query("test alpha - - et4"),
vec![env.abs_path("test/alpha/betabeta/epsil#on/eta4")]
);
assert_eq!(
env.resolve_query("- alpha"),
vec![env.abs_path("test/alpha")]
);
}
#[test]
fn test_numeric_suffixes() {
let env = TempEnv::new();
assert_eq!(
env.resolve_query("test epsilon beta beta2 3"),
vec![env.abs_path("test/epsilon/beta/beta2/gamma3")]
);
assert_eq!(
env.resolve_query("test beta 9"),
vec![env.abs_path("test/beta/mu9")]
);
}
#[test]
fn test_real_paths() {
let env = TempEnv::new();
assert_eq!(
env.resolve_query("test alpha/beta del6"),
vec![env.abs_path("test/alpha/beta/delta6")]
);
assert_eq!(
env.resolve_query("test /alpha/beta del6"),
vec![env.abs_path("test/alpha/beta/delta6")]
);
assert_eq!(
env.resolve_query("test /alpha/beta/ del6"),
vec![env.abs_path("test/alpha/beta/delta6")]
);
}
#[test]
fn test_symlinks() {
let env = TempEnv::new();
assert_eq!(
env.resolve_query("test link beta"),
vec![env.abs_path("test/link/beta")]
);
assert_eq!(
env.resolve_query("test link - gamma3"),
vec![env.abs_path("test/link/beta/gamma3")]
);
assert_eq!(
env.resolve_query("test - beta gamma3"),
vec![
env.abs_path("test/alpha/beta/gamma3"),
env.abs_path("test/link/beta/gamma3")
]
);
}
| rust | MIT | 12f056c9f4eca7af8afbda8ba33a0c5e23c33742 | 2026-01-04T20:22:09.206135Z | false |
darfink/region-rs | https://github.com/darfink/region-rs/blob/7302d9c166e63a4c7aa8e951904d0b33f399a924/src/page.rs | src/page.rs | //! Page related functions.
use crate::os;
use std::sync::Once;
/// Returns the operating system's page size.
///
/// This function uses an internally cached page size, and can be called
/// repeatedly without incurring a significant performance penalty.
///
/// # Examples
///
/// ```
/// # use region::page;
/// let size = page::size(); // Most likely 4096
/// ```
#[inline]
pub fn size() -> usize {
static INIT: Once = Once::new();
static mut PAGE_SIZE: usize = 0;
unsafe {
INIT.call_once(|| PAGE_SIZE = os::page_size());
PAGE_SIZE
}
}
/// Rounds an address down to its closest page boundary.
///
/// # Examples
///
/// ```
/// # use region::page;
/// let unaligned_pointer = (page::size() + 1) as *const ();
///
/// assert_eq!(page::floor(unaligned_pointer), page::size() as *const _);
/// ```
#[inline]
pub fn floor<T>(address: *const T) -> *const T {
(address as usize & !(size() - 1)) as *const T
}
/// Rounds an address up to its closest page boundary.
///
/// # Examples
///
/// ```
/// # use region::page;
/// let unaligned_pointer = (page::size() - 1) as *const ();
///
/// assert_eq!(page::ceil(unaligned_pointer), page::size() as *const _);
/// ```
#[inline]
pub fn ceil<T>(address: *const T) -> *const T {
match (address as usize).checked_add(size()) {
Some(offset) => ((offset - 1) & !(size() - 1)) as *const T,
None => floor(address),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn page_size_is_reasonable() {
let pz = size();
assert!(pz > 0);
assert_eq!(pz % 2, 0);
assert_eq!(pz, size());
}
#[test]
fn page_rounding_works() {
let pz = size();
let point = 1 as *const ();
assert_eq!(floor(point) as usize, 0);
assert_eq!(floor(pz as *const ()) as usize, pz);
assert_eq!(floor(usize::max_value() as *const ()) as usize % pz, 0);
assert_eq!(ceil(point) as usize, pz);
assert_eq!(ceil(pz as *const ()) as usize, pz);
assert_eq!(ceil(usize::max_value() as *const ()) as usize % pz, 0);
}
}
| rust | MIT | 7302d9c166e63a4c7aa8e951904d0b33f399a924 | 2026-01-04T20:21:40.023200Z | false |
darfink/region-rs | https://github.com/darfink/region-rs/blob/7302d9c166e63a4c7aa8e951904d0b33f399a924/src/lib.rs | src/lib.rs | #![deny(
clippy::all,
clippy::missing_inline_in_public_items,
clippy::ptr_as_ptr,
clippy::print_stdout,
missing_docs,
nonstandard_style,
unused,
warnings
)]
// Temporarily allow these until bitflags deps is upgraded to 2.x
#![allow(clippy::bad_bit_mask)]
//! Cross-platform virtual memory API.
//!
//! This crate provides a cross-platform Rust API for querying and manipulating
//! virtual memory. It is a thin abstraction, with the underlying interaction
//! implemented using platform specific APIs (e.g `VirtualQuery`, `VirtualLock`,
//! `mprotect`, `mlock`). Albeit not all OS specific quirks are abstracted away;
//! for instance, some OSs enforce memory pages to be readable, whilst other may
//! prevent pages from becoming executable (i.e DEP).
//!
//! This implementation operates with memory pages, which are aligned to the
//! operating system's page size. On some systems, but not all, the system calls
//! for these operations require input to be aligned to a page boundary. To
//! remedy this inconsistency, whenever applicable, input is aligned to its
//! closest page boundary.
//!
//! *Note: a region is a collection of one or more pages laying consecutively in
//! memory, with the same properties.*
//!
//! # Parallelism
//!
//! The properties of virtual memory pages can change at any time, unless all
//! threads that are unaccounted for in a process are stopped. Therefore to
//! obtain, e.g., a true picture of a process' virtual memory, all other threads
//! must be halted. Otherwise, a region descriptor only represents a snapshot in
//! time.
//!
//! # Installation
//!
//! This crate is [on crates.io](https://crates.io/crates/region) and can be
//! used by adding `region` to your dependencies in your project's `Cargo.toml`.
//!
//! ```toml
//! [dependencies]
//! region = "3.0.2"
//! ```
//!
//! # Examples
//!
//! - Cross-platform equivalents.
//!
//! ```rust
//! # unsafe fn example() -> region::Result<()> {
//! # use region::Protection;
//! let data = [0xDE, 0xAD, 0xBE, 0xEF];
//!
//! // Page size
//! let pz = region::page::size();
//! let pc = region::page::ceil(data.as_ptr());
//! let pf = region::page::floor(data.as_ptr());
//!
//! // VirtualQuery | '/proc/self/maps'
//! let q = region::query(data.as_ptr())?;
//! let qr = region::query_range(data.as_ptr(), data.len())?;
//!
//! // VirtualAlloc | mmap
//! let alloc = region::alloc(100, Protection::READ_WRITE)?;
//!
//! // VirtualProtect | mprotect
//! region::protect(data.as_ptr(), data.len(), Protection::READ_WRITE_EXECUTE)?;
//!
//! // ... you can also temporarily change one or more pages' protection
//! let handle = region::protect_with_handle(data.as_ptr(), data.len(), Protection::READ_WRITE_EXECUTE)?;
//!
//! // VirtualLock | mlock
//! let guard = region::lock(data.as_ptr(), data.len())?;
//! # Ok(())
//! # }
//! ```
#[macro_use]
extern crate bitflags;
pub use alloc::{alloc, alloc_at, Allocation};
pub use error::{Error, Result};
pub use lock::{lock, unlock, LockGuard};
pub use protect::{protect, protect_with_handle, ProtectGuard};
pub use query::{query, query_range, QueryIter};
mod alloc;
mod error;
mod lock;
mod os;
pub mod page;
mod protect;
mod query;
mod util;
/// A descriptor for a mapped memory region.
///
/// The region encompasses zero or more pages (e.g. OpenBSD can have null-sized
/// virtual pages).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Region {
/// Base address of the region
base: *const (),
/// Whether the region is reserved or not
reserved: bool,
/// Whether the region is guarded or not
guarded: bool,
/// Protection of the region
protection: Protection,
/// Maximum protection of the region
max_protection: Protection,
/// Whether the region is shared or not
shared: bool,
/// Size of the region (multiple of page size)
size: usize,
}
impl Region {
/// Returns a pointer to the region's base address.
///
/// The address is always aligned to the operating system's page size.
#[inline(always)]
pub fn as_ptr<T>(&self) -> *const T {
self.base.cast()
}
/// Returns a mutable pointer to the region's base address.
#[inline(always)]
pub fn as_mut_ptr<T>(&mut self) -> *mut T {
self.base as *mut T
}
/// Returns two raw pointers spanning the region's address space.
///
/// The returned range is half-open, which means that the end pointer points
/// one past the last element of the region. This way, an empty region is
/// represented by two equal pointers, and the difference between the two
/// pointers represents the size of the region.
#[inline(always)]
pub fn as_ptr_range<T>(&self) -> std::ops::Range<*const T> {
let range = self.as_range();
(range.start as *const T)..(range.end as *const T)
}
/// Returns two mutable raw pointers spanning the region's address space.
#[inline(always)]
pub fn as_mut_ptr_range<T>(&mut self) -> std::ops::Range<*mut T> {
let range = self.as_range();
(range.start as *mut T)..(range.end as *mut T)
}
/// Returns a range spanning the region's address space.
#[inline(always)]
pub fn as_range(&self) -> std::ops::Range<usize> {
(self.base as usize)..(self.base as usize).saturating_add(self.size)
}
/// Returns whether the region is committed or not.
///
/// This is always true for all operating system's, the exception being
/// `MEM_RESERVE` pages on Windows.
#[inline(always)]
pub fn is_committed(&self) -> bool {
!self.reserved
}
/// Returns whether the region is readable or not.
#[inline(always)]
pub fn is_readable(&self) -> bool {
self.protection & Protection::READ == Protection::READ
}
/// Returns whether the region is writable or not.
#[inline(always)]
pub fn is_writable(&self) -> bool {
self.protection & Protection::WRITE == Protection::WRITE
}
/// Returns whether the region is executable or not.
#[inline(always)]
pub fn is_executable(&self) -> bool {
self.protection & Protection::EXECUTE == Protection::EXECUTE
}
/// Returns whether the region is guarded or not.
#[inline(always)]
pub fn is_guarded(&self) -> bool {
self.guarded
}
/// Returns whether the region is shared between processes or not.
#[inline(always)]
pub fn is_shared(&self) -> bool {
self.shared
}
/// Returns the size of the region in bytes.
///
/// The size is always aligned to a multiple of the operating system's page
/// size.
#[inline(always)]
pub fn len(&self) -> usize {
self.size
}
/// Returns whether region is empty or not.
#[inline(always)]
pub fn is_empty(&self) -> bool {
self.size == 0
}
/// Returns the protection attributes of the region.
#[inline(always)]
pub fn protection(&self) -> Protection {
self.protection
}
}
impl Default for Region {
#[inline]
fn default() -> Self {
Self {
base: std::ptr::null(),
reserved: false,
guarded: false,
protection: Protection::NONE,
max_protection: Protection::NONE,
shared: false,
size: 0,
}
}
}
unsafe impl Send for Region {}
unsafe impl Sync for Region {}
bitflags! {
/// A bitflag of zero or more protection attributes.
///
/// Determines the access rights for a specific page and/or region. Some
/// combination of flags may not be applicable, depending on the OS (e.g macOS
/// enforces executable pages to be readable, OpenBSD requires W^X).
///
/// # OS-Specific Behavior
///
/// On Unix `Protection::from_bits_unchecked` can be used to apply
/// non-standard flags (e.g. `PROT_BTI`).
///
/// # Examples
///
/// ```
/// use region::Protection;
///
/// let combine = Protection::READ | Protection::WRITE;
/// let shorthand = Protection::READ_WRITE;
/// ```
#[derive(Default)]
pub struct Protection: usize {
/// No access allowed at all.
const NONE = 0;
/// Read access; writing and/or executing data will panic.
const READ = (1 << 0);
/// Write access; this flag alone may not be supported on all OSs.
const WRITE = (1 << 1);
/// Execute access; this may not be allowed depending on DEP.
const EXECUTE = (1 << 2);
/// Read and execute shorthand.
const READ_EXECUTE = (Self::READ.bits | Self::EXECUTE.bits);
/// Read and write shorthand.
const READ_WRITE = (Self::READ.bits | Self::WRITE.bits);
/// Read, write and execute shorthand.
const READ_WRITE_EXECUTE = (Self::READ.bits | Self::WRITE.bits | Self::EXECUTE.bits);
/// Write and execute shorthand.
const WRITE_EXECUTE = (Self::WRITE.bits | Self::EXECUTE.bits);
}
}
impl std::fmt::Display for Protection {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
const MAPPINGS: &[(Protection, char)] = &[
(Protection::READ, 'r'),
(Protection::WRITE, 'w'),
(Protection::EXECUTE, 'x'),
];
for (flag, symbol) in MAPPINGS {
if self.contains(*flag) {
write!(f, "{}", symbol)?;
} else {
write!(f, "-")?;
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn protection_implements_display() {
assert_eq!(Protection::READ.to_string(), "r--");
assert_eq!(Protection::READ_WRITE.to_string(), "rw-");
assert_eq!(Protection::READ_WRITE_EXECUTE.to_string(), "rwx");
assert_eq!(Protection::WRITE.to_string(), "-w-");
}
#[cfg(unix)]
pub mod util {
use crate::{page, Protection};
use mmap::{MapOption, MemoryMap};
use std::ops::Deref;
struct AllocatedPages(Vec<MemoryMap>);
impl Deref for AllocatedPages {
type Target = [u8];
fn deref(&self) -> &Self::Target {
unsafe { std::slice::from_raw_parts(self.0[0].data().cast(), self.0.len() * page::size()) }
}
}
#[allow(clippy::fallible_impl_from)]
impl From<Protection> for &'static [MapOption] {
fn from(protection: Protection) -> Self {
match protection {
Protection::NONE => &[],
Protection::READ => &[MapOption::MapReadable],
Protection::READ_WRITE => &[MapOption::MapReadable, MapOption::MapWritable],
Protection::READ_EXECUTE => &[MapOption::MapReadable, MapOption::MapExecutable],
_ => panic!("Unsupported protection {:?}", protection),
}
}
}
/// Allocates one or more sequential pages for each protection flag.
pub fn alloc_pages(pages: &[Protection]) -> impl Deref<Target = [u8]> {
// Find a region that fits all pages
let region = MemoryMap::new(page::size() * pages.len(), &[]).expect("allocating pages");
let mut page_address = region.data();
// Drop the region to ensure it's free
std::mem::forget(region);
// Allocate one page at a time, with explicit page permissions. This would
// normally introduce a race condition, but since only one thread is used
// during testing, it ensures each page remains available (in general,
// only one thread should ever be active when querying and/or manipulating
// memory regions).
let allocated_pages = pages
.iter()
.map(|protection| {
let mut options = vec![MapOption::MapAddr(page_address)];
options.extend_from_slice(Into::into(*protection));
let map = MemoryMap::new(page::size(), &options).expect("allocating page");
assert_eq!(map.data(), page_address);
assert_eq!(map.len(), page::size());
page_address = (page_address as usize + page::size()) as *mut _;
map
})
.collect::<Vec<_>>();
AllocatedPages(allocated_pages)
}
}
#[cfg(windows)]
pub mod util {
use crate::{page, Protection};
use std::ops::Deref;
use windows_sys::Win32::System::Memory::{
VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS,
};
struct AllocatedPages(*const (), usize);
impl Deref for AllocatedPages {
type Target = [u8];
fn deref(&self) -> &Self::Target {
unsafe { std::slice::from_raw_parts(self.0 as *const _, self.1) }
}
}
impl Drop for AllocatedPages {
fn drop(&mut self) {
unsafe {
assert_ne!(VirtualFree(self.0 as *mut _, 0, MEM_RELEASE), 0);
}
}
}
/// Allocates one or more sequential pages for each protection flag.
pub fn alloc_pages(pages: &[Protection]) -> impl Deref<Target = [u8]> {
// Reserve enough memory to fit each page
let total_size = page::size() * pages.len();
let allocation_base =
unsafe { VirtualAlloc(std::ptr::null_mut(), total_size, MEM_RESERVE, PAGE_NOACCESS) };
assert_ne!(allocation_base, std::ptr::null_mut());
let mut page_address = allocation_base;
// Commit one page at a time with the expected permissions
for protection in pages {
let address = unsafe {
VirtualAlloc(
page_address,
page::size(),
MEM_COMMIT,
protection.to_native(),
)
};
assert_eq!(address, page_address);
page_address = (address as usize + page::size()) as *mut _;
}
AllocatedPages(allocation_base as *const _, total_size)
}
}
}
| rust | MIT | 7302d9c166e63a4c7aa8e951904d0b33f399a924 | 2026-01-04T20:21:40.023200Z | false |
darfink/region-rs | https://github.com/darfink/region-rs/blob/7302d9c166e63a4c7aa8e951904d0b33f399a924/src/lock.rs | src/lock.rs | use crate::{os, util, Result};
/// Locks one or more memory regions to RAM.
///
/// The memory pages within the address range is guaranteed to stay in RAM
/// except for specials cases, such as hibernation and memory starvation. It
/// returns a [`LockGuard`], which [`unlock`]s the affected regions once
/// dropped.
///
/// # Parameters
///
/// - The range is `[address, address + size)`
/// - The address is rounded down to the closest page boundary.
/// - The size may not be zero.
/// - The size is rounded up to the closest page boundary, relative to the
/// address.
///
/// # Errors
///
/// - If an interaction with the underlying operating system fails, an error
/// will be returned.
/// - If size is zero,
/// [`Error::InvalidParameter`](crate::Error::InvalidParameter) will be
/// returned.
///
/// # Examples
///
/// ```
/// # fn main() -> region::Result<()> {
/// let data = [0; 100];
/// let _guard = region::lock(data.as_ptr(), data.len())?;
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn lock<T>(address: *const T, size: usize) -> Result<LockGuard> {
let (address, size) = util::round_to_page_boundaries(address, size)?;
os::lock(address.cast(), size).map(|_| LockGuard::new(address, size))
}
/// Unlocks one or more memory regions from RAM.
///
/// If possible, prefer to use [`lock`] combined with the [`LockGuard`].
///
/// # Parameters
///
/// - The range is `[address, address + size)`
/// - The address is rounded down to the closest page boundary.
/// - The size may not be zero.
/// - The size is rounded up to the closest page boundary, relative to the
/// address.
///
/// # Errors
///
/// - If an interaction with the underlying operating system fails, an error
/// will be returned.
/// - If size is zero,
/// [`Error::InvalidParameter`](crate::Error::InvalidParameter) will be
/// returned.
#[inline]
pub fn unlock<T>(address: *const T, size: usize) -> Result<()> {
let (address, size) = util::round_to_page_boundaries(address, size)?;
os::unlock(address.cast(), size)
}
/// A RAII implementation of a scoped lock.
///
/// When this structure is dropped (falls out of scope), the virtual lock will be
/// released.
#[must_use]
pub struct LockGuard {
address: *const (),
size: usize,
}
impl LockGuard {
#[inline(always)]
fn new<T>(address: *const T, size: usize) -> Self {
Self {
address: address.cast(),
size,
}
}
}
impl Drop for LockGuard {
#[inline]
fn drop(&mut self) {
let result = os::unlock(self.address, self.size);
debug_assert!(result.is_ok(), "unlocking region: {:?}", result);
}
}
unsafe impl Send for LockGuard {}
unsafe impl Sync for LockGuard {}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::util::alloc_pages;
use crate::{page, Protection};
#[test]
fn lock_mapped_pages_succeeds() -> Result<()> {
let map = alloc_pages(&[Protection::READ_WRITE]);
let _guard = lock(map.as_ptr(), page::size())?;
Ok(())
}
#[test]
fn unlock_mapped_pages_succeeds() -> Result<()> {
let map = alloc_pages(&[Protection::READ_WRITE]);
std::mem::forget(lock(map.as_ptr(), page::size())?);
unlock(map.as_ptr(), page::size())
}
}
| rust | MIT | 7302d9c166e63a4c7aa8e951904d0b33f399a924 | 2026-01-04T20:21:40.023200Z | false |
darfink/region-rs | https://github.com/darfink/region-rs/blob/7302d9c166e63a4c7aa8e951904d0b33f399a924/src/alloc.rs | src/alloc.rs | use std::mem::ManuallyDrop;
use crate::{os, page, util, Error, Protection, Result};
/// A handle to an owned region of memory.
///
/// This handle does not dereference to a slice, since the underlying memory may
/// have been created with [`Protection::NONE`].
#[allow(clippy::len_without_is_empty)]
pub struct Allocation {
base: *const (),
size: usize,
}
impl Allocation {
/// Returns a pointer to the allocation's base address.
///
/// The address is always aligned to the operating system's page size.
#[inline(always)]
pub fn as_ptr<T>(&self) -> *const T {
self.base.cast()
}
/// Returns a mutable pointer to the allocation's base address.
#[inline(always)]
pub fn as_mut_ptr<T>(&mut self) -> *mut T {
self.base as *mut T
}
/// Returns two raw pointers spanning the allocation's address space.
///
/// The returned range is half-open, which means that the end pointer points
/// one past the last element of the allocation. This way, an empty allocation
/// is represented by two equal pointers, and the difference between the two
/// pointers represents the size of the allocation.
#[inline(always)]
pub fn as_ptr_range<T>(&self) -> std::ops::Range<*const T> {
let range = self.as_range();
(range.start as *const T)..(range.end as *const T)
}
/// Returns two mutable raw pointers spanning the allocation's address space.
#[inline(always)]
pub fn as_mut_ptr_range<T>(&mut self) -> std::ops::Range<*mut T> {
let range = self.as_range();
(range.start as *mut T)..(range.end as *mut T)
}
/// Returns a range spanning the allocation's address space.
#[inline(always)]
pub fn as_range(&self) -> std::ops::Range<usize> {
(self.base as usize)..(self.base as usize).saturating_add(self.size)
}
/// Returns the size of the allocation in bytes.
///
/// The size is always aligned to a multiple of the operating system's page
/// size.
#[inline(always)]
pub fn len(&self) -> usize {
self.size
}
/// Decomposes an `Allocation` into its raw components: `(pointer, length)`.
///
/// After calling this function, the caller is responsible for the previously
/// managed allocation.
///
/// For creating an `Allocation` from raw components, see [`Self::from_raw_parts`].
#[inline]
pub fn into_raw_parts<T>(self) -> (*mut T, usize) {
let mut this = ManuallyDrop::new(self);
(this.as_mut_ptr(), this.len())
}
/// Creates a `Allocation` directly from a pointer, and a length.
///
/// For decomposing an `Allocation` into raw components, see
/// [`Self::into_raw_parts`].
///
/// # Safety
///
/// This is highly unsafe because given `ptr` and `length` could not
/// be checked as valid allocation, and the caller should guarantee
/// that they are valid parts.
#[inline(always)]
pub unsafe fn from_raw_parts<T>(ptr: *mut T, length: usize) -> Self {
Self {
base: ptr as *const (),
size: length,
}
}
}
impl Drop for Allocation {
#[inline]
fn drop(&mut self) {
let result = unsafe { os::free(self.base, self.size) };
debug_assert!(result.is_ok(), "freeing region: {:?}", result);
}
}
/// Allocates one or more pages of memory, with a defined protection.
///
/// This function provides a very simple interface for allocating anonymous
/// virtual pages. The allocation address will be decided by the operating
/// system.
///
/// # Parameters
///
/// - The size may not be zero.
/// - The size is rounded up to the closest page boundary.
///
/// # Errors
///
/// - If an interaction with the underlying operating system fails, an error
/// will be returned.
/// - If size is zero, [`Error::InvalidParameter`] will be returned.
///
/// # OS-Specific Behavior
///
/// On NetBSD pages will be allocated without PaX memory protection restrictions
/// (i.e. pages will be allowed to be modified to any combination of `RWX`).
///
/// # Examples
///
/// ```
/// # fn main() -> region::Result<()> {
/// # if cfg!(any(target_arch = "x86", target_arch = "x86_64"))
/// # && !cfg!(any(target_os = "openbsd", target_os = "netbsd")) {
/// use region::Protection;
/// let ret5 = [0xB8, 0x05, 0x00, 0x00, 0x00, 0xC3u8];
///
/// let memory = region::alloc(100, Protection::READ_WRITE_EXECUTE)?;
/// let slice = unsafe {
/// std::slice::from_raw_parts_mut(memory.as_ptr::<u8>() as *mut u8, memory.len())
/// };
///
/// slice[..6].copy_from_slice(&ret5);
/// let x: extern "C" fn() -> i32 = unsafe { std::mem::transmute(slice.as_ptr()) };
///
/// assert_eq!(x(), 5);
/// # }
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn alloc(size: usize, protection: Protection) -> Result<Allocation> {
if size == 0 {
return Err(Error::InvalidParameter("size"));
}
let size = page::ceil(size as *const ()) as usize;
unsafe {
let base = os::alloc(std::ptr::null::<()>(), size, protection)?;
Ok(Allocation { base, size })
}
}
/// Allocates one or more pages of memory, at a specific address, with a defined
/// protection.
///
/// The returned memory allocation is not guaranteed to reside at the provided
/// address. E.g. on Windows, new allocations that do not reside within already
/// reserved memory, are aligned to the operating system's allocation
/// granularity (most commonly 64KB).
///
/// # Implementation
///
/// This function is implemented using `VirtualAlloc` on Windows, and `mmap`
/// with `MAP_FIXED` on POSIX.
///
/// # Parameters
///
/// - The address is rounded down to the closest page boundary.
/// - The size may not be zero.
/// - The size is rounded up to the closest page boundary, relative to the
/// address.
///
/// # Errors
///
/// - If an interaction with the underlying operating system fails, an error
/// will be returned.
/// - If size is zero, [`Error::InvalidParameter`] will be returned.
#[inline]
pub fn alloc_at<T>(address: *const T, size: usize, protection: Protection) -> Result<Allocation> {
let (address, size) = util::round_to_page_boundaries(address, size)?;
unsafe {
let base = os::alloc(address.cast(), size, protection)?;
Ok(Allocation { base, size })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn alloc_size_is_aligned_to_page_size() -> Result<()> {
let memory = alloc(1, Protection::NONE)?;
assert_eq!(memory.len(), page::size());
Ok(())
}
#[test]
fn alloc_rejects_empty_allocation() {
assert!(matches!(
alloc(0, Protection::NONE),
Err(Error::InvalidParameter(_))
));
}
#[test]
fn alloc_obtains_correct_properties() -> Result<()> {
let memory = alloc(1, Protection::READ_WRITE)?;
let region = crate::query(memory.as_ptr::<()>())?;
assert_eq!(region.protection(), Protection::READ_WRITE);
assert!(region.len() >= memory.len());
assert!(!region.is_guarded());
assert!(!region.is_shared());
assert!(region.is_committed());
Ok(())
}
#[test]
fn alloc_frees_memory_when_dropped() -> Result<()> {
// Designing these tests can be quite tricky sometimes. When a page is
// allocated and then released, a subsequent `query` may allocate memory in
// the same location that has just been freed. For instance, NetBSD's
// kinfo_getvmmap uses `mmap` internally, which can lead to potentially
// confusing outcomes. To mitigate this, an additional buffer region is
// allocated to ensure that any memory allocated indirectly through `query`
// occupies a separate location in memory.
let (start, _buffer) = (
alloc(1, Protection::READ_WRITE)?,
alloc(1, Protection::READ_WRITE)?,
);
let base = start.as_ptr::<()>();
std::mem::drop(start);
let query = crate::query(base);
assert!(matches!(query, Err(Error::UnmappedRegion)));
Ok(())
}
#[test]
fn alloc_can_allocate_unused_region() -> Result<()> {
let base = alloc(1, Protection::NONE)?.as_ptr::<()>();
let memory = alloc_at(base, 1, Protection::READ_WRITE)?;
assert_eq!(memory.as_ptr(), base);
Ok(())
}
#[test]
#[cfg(not(any(target_os = "openbsd", target_os = "netbsd")))]
fn alloc_can_allocate_executable_region() -> Result<()> {
let memory = alloc(1, Protection::WRITE_EXECUTE)?;
assert_eq!(memory.len(), page::size());
Ok(())
}
}
| rust | MIT | 7302d9c166e63a4c7aa8e951904d0b33f399a924 | 2026-01-04T20:21:40.023200Z | false |
darfink/region-rs | https://github.com/darfink/region-rs/blob/7302d9c166e63a4c7aa8e951904d0b33f399a924/src/error.rs | src/error.rs | //! Error types and utilities.
use std::error::Error as StdError;
use std::{fmt, io};
/// The result type used by this library.
pub type Result<T> = std::result::Result<T, Error>;
/// A collection of possible errors.
#[derive(Debug)]
pub enum Error {
/// The queried memory is unmapped.
///
/// This does not necessarily mean that the memory region is available for
/// allocation. Besides OS-specific semantics, queried addresses outside of a
/// process' adress range are also identified as unmapped regions.
UnmappedRegion,
/// A supplied parameter is invalid.
InvalidParameter(&'static str),
/// A procfs region could not be parsed.
ProcfsInput(String),
/// A system call failed.
SystemCall(io::Error),
/// A macOS kernel call failed
MachCall(libc::c_int),
}
impl fmt::Display for Error {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::UnmappedRegion => write!(f, "Queried memory is unmapped"),
Error::InvalidParameter(param) => write!(f, "Invalid parameter value: {}", param),
Error::ProcfsInput(ref input) => write!(f, "Invalid procfs input: {}", input),
Error::SystemCall(ref error) => write!(f, "System call failed: {}", error),
Error::MachCall(code) => write!(f, "macOS kernel call failed: {}", code),
}
}
}
impl StdError for Error {}
| rust | MIT | 7302d9c166e63a4c7aa8e951904d0b33f399a924 | 2026-01-04T20:21:40.023200Z | false |
darfink/region-rs | https://github.com/darfink/region-rs/blob/7302d9c166e63a4c7aa8e951904d0b33f399a924/src/util.rs | src/util.rs | use crate::{page, Error, Result};
/// Validates & rounds an address-size pair to their respective page boundary.
pub fn round_to_page_boundaries<T>(address: *const T, size: usize) -> Result<(*const T, usize)> {
if size == 0 {
return Err(Error::InvalidParameter("size"));
}
let size = (address as usize % page::size()).saturating_add(size);
let size = page::ceil(size as *const T) as usize;
Ok((page::floor(address), size))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_to_page_boundaries_works() -> Result<()> {
let pz = page::size();
let values = &[
((1, pz), (0, pz * 2)),
((0, pz - 1), (0, pz)),
((0, pz + 1), (0, pz * 2)),
((pz - 1, 1), (0, pz)),
((pz + 1, pz), (pz, pz * 2)),
((pz, pz), (pz, pz)),
];
for ((before_address, before_size), (after_address, after_size)) in values {
let (address, size) = round_to_page_boundaries(*before_address as *const (), *before_size)?;
assert_eq!((address, size), (*after_address as *const (), *after_size));
}
Ok(())
}
}
| rust | MIT | 7302d9c166e63a4c7aa8e951904d0b33f399a924 | 2026-01-04T20:21:40.023200Z | false |
darfink/region-rs | https://github.com/darfink/region-rs/blob/7302d9c166e63a4c7aa8e951904d0b33f399a924/src/protect.rs | src/protect.rs | use crate::{os, util, Protection, QueryIter, Region, Result};
/// Changes the memory protection of one or more pages.
///
/// The address range may overlap one or more pages, and if so, all pages
/// spanning the range will be modified. The previous protection flags are not
/// preserved (if you desire to preserve the protection flags, use
/// [`protect_with_handle`]).
///
/// # Parameters
///
/// - The range is `[address, address + size)`
/// - The address is rounded down to the closest page boundary.
/// - The size may not be zero.
/// - The size is rounded up to the closest page boundary, relative to the
/// address.
///
/// # Errors
///
/// - If an interaction with the underlying operating system fails, an error
/// will be returned.
/// - If size is zero,
/// [`Error::InvalidParameter`](crate::Error::InvalidParameter) will be
/// returned.
///
/// # Safety
///
/// This function can violate memory safety in a myriad of ways. Read-only memory
/// can become writable, the executable properties of code segments can be
/// removed, etc.
///
/// # Examples
///
/// - Make an array of x86 assembly instructions executable.
///
/// ```
/// # fn main() -> region::Result<()> {
/// # if cfg!(any(target_arch = "x86", target_arch = "x86_64"))
/// # && !cfg!(any(target_os = "openbsd", target_os = "netbsd")) {
/// use region::Protection;
/// let ret5 = [0xB8, 0x05, 0x00, 0x00, 0x00, 0xC3u8];
///
/// let x: extern "C" fn() -> i32 = unsafe {
/// region::protect(ret5.as_ptr(), ret5.len(), region::Protection::READ_WRITE_EXECUTE)?;
/// std::mem::transmute(ret5.as_ptr())
/// };
///
/// assert_eq!(x(), 5);
/// # }
/// # Ok(())
/// # }
/// ```
#[inline]
pub unsafe fn protect<T>(address: *const T, size: usize, protection: Protection) -> Result<()> {
let (address, size) = util::round_to_page_boundaries(address, size)?;
os::protect(address.cast(), size, protection)
}
/// Temporarily changes the memory protection of one or more pages.
///
/// The address range may overlap one or more pages, and if so, all pages within
/// the range will be modified. The protection flag for each page will be reset
/// once the handle is dropped. To conditionally prevent a reset, use
/// [`std::mem::forget`].
///
/// This function uses [`query_range`](crate::query_range) internally and is
/// therefore less performant than [`protect`]. Use this function only if you
/// need to reapply the memory protection flags of one or more regions after
/// operations.
///
/// # Guard
///
/// Remember not to conflate the *black hole* syntax with the ignored, but
/// unused, variable syntax. Otherwise the [`ProtectGuard`] instantly resets the
/// protection flags of all pages.
///
/// ```ignore
/// let _ = protect_with_handle(...); // Pages are instantly reset
/// let _guard = protect_with_handle(...); // Pages are reset once `_guard` is dropped.
/// ```
///
/// # Parameters
///
/// - The range is `[address, address + size)`
/// - The address is rounded down to the closest page boundary.
/// - The size may not be zero.
/// - The size is rounded up to the closest page boundary, relative to the
/// address.
///
/// # Errors
///
/// - If an interaction with the underlying operating system fails, an error
/// will be returned.
/// - If size is zero,
/// [`Error::InvalidParameter`](crate::Error::InvalidParameter) will be
/// returned.
///
/// # Safety
///
/// See [protect].
#[allow(clippy::missing_inline_in_public_items)]
pub unsafe fn protect_with_handle<T>(
address: *const T,
size: usize,
protection: Protection,
) -> Result<ProtectGuard> {
let (address, size) = util::round_to_page_boundaries(address, size)?;
// Preserve the current regions' flags
let mut regions = QueryIter::new(address, size)?.collect::<Result<Vec<_>>>()?;
// Apply the desired protection flags
protect(address, size, protection)?;
if let Some(region) = regions.first_mut() {
// Offset the lower region to the smallest page boundary
region.base = address.cast();
region.size -= address as usize - region.as_range().start;
}
if let Some(region) = regions.last_mut() {
// Truncate the upper region to the smallest page boundary
let protect_end = address as usize + size;
region.size -= region.as_range().end - protect_end;
}
Ok(ProtectGuard::new(regions))
}
/// A RAII implementation of a scoped protection guard.
///
/// When this structure is dropped (falls out of scope), the memory regions'
/// protection will be reset.
#[must_use]
pub struct ProtectGuard {
regions: Vec<Region>,
}
impl ProtectGuard {
#[inline(always)]
fn new(regions: Vec<Region>) -> Self {
Self { regions }
}
}
impl Drop for ProtectGuard {
#[inline]
fn drop(&mut self) {
let result = self
.regions
.iter()
.try_for_each(|region| unsafe { protect(region.base, region.size, region.protection) });
debug_assert!(result.is_ok(), "restoring region protection: {:?}", result);
}
}
unsafe impl Send for ProtectGuard {}
unsafe impl Sync for ProtectGuard {}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::util::alloc_pages;
use crate::{page, query, query_range};
#[test]
fn protect_null_fails() {
assert!(unsafe { protect(std::ptr::null::<()>(), 0, Protection::NONE) }.is_err());
}
#[test]
#[cfg(not(any(
target_os = "openbsd",
target_os = "netbsd",
all(target_vendor = "apple", target_arch = "aarch64")
)))]
fn protect_can_alter_text_segments() {
#[allow(clippy::ptr_as_ptr)]
let address = &mut protect_can_alter_text_segments as *mut _ as *mut u8;
unsafe {
protect(address, 1, Protection::READ_WRITE_EXECUTE).unwrap();
*address = 0x90;
}
}
#[test]
fn protect_updates_both_pages_for_straddling_range() -> Result<()> {
let pz = page::size();
// Create a page boundary with different protection flags in the upper and
// lower span, so the intermediate region sizes are fixed to one page.
let map = alloc_pages(&[
Protection::READ,
Protection::READ_EXECUTE,
Protection::READ_WRITE,
Protection::READ,
]);
let exec_page = unsafe { map.as_ptr().add(pz) };
let exec_page_end = unsafe { exec_page.add(pz - 1) };
// Change the protection over two page boundaries
unsafe {
protect(exec_page_end, 2, Protection::NONE)?;
}
// Query the two inner pages
let result = query_range(exec_page, pz * 2)?.collect::<Result<Vec<_>>>()?;
// On some OSs the pages are merged into one region
assert!(matches!(result.len(), 1 | 2));
assert_eq!(result.iter().map(Region::len).sum::<usize>(), pz * 2);
assert_eq!(result[0].protection(), Protection::NONE);
Ok(())
}
#[test]
fn protect_has_inclusive_lower_and_exclusive_upper_bound() -> Result<()> {
let map = alloc_pages(&[
Protection::READ_WRITE,
Protection::READ,
Protection::READ_WRITE,
Protection::READ,
]);
// Alter the protection of the second page
let second_page = unsafe { map.as_ptr().add(page::size()) };
unsafe {
let second_page_end = second_page.offset(page::size() as isize - 1);
protect(second_page_end, 1, Protection::NONE)?;
}
let regions = query_range(map.as_ptr(), page::size() * 3)?.collect::<Result<Vec<_>>>()?;
assert_eq!(regions.len(), 3);
assert_eq!(regions[0].protection(), Protection::READ_WRITE);
assert_eq!(regions[1].protection(), Protection::NONE);
assert_eq!(regions[2].protection(), Protection::READ_WRITE);
// Alter the protection of '2nd_page_start .. 2nd_page_end + 1'
unsafe {
protect(second_page, page::size() + 1, Protection::READ_EXECUTE)?;
}
let regions = query_range(map.as_ptr(), page::size() * 3)?.collect::<Result<Vec<_>>>()?;
assert!(regions.len() >= 2);
assert_eq!(regions[0].protection(), Protection::READ_WRITE);
assert_eq!(regions[1].protection(), Protection::READ_EXECUTE);
assert!(regions[1].len() >= page::size());
Ok(())
}
#[test]
fn protect_with_handle_resets_protection() -> Result<()> {
let map = alloc_pages(&[Protection::READ]);
unsafe {
let _handle = protect_with_handle(map.as_ptr(), page::size(), Protection::READ_WRITE)?;
assert_eq!(query(map.as_ptr())?.protection(), Protection::READ_WRITE);
};
assert_eq!(query(map.as_ptr())?.protection(), Protection::READ);
Ok(())
}
#[test]
fn protect_with_handle_only_alters_protection_of_affected_pages() -> Result<()> {
let pages = [
Protection::READ_WRITE,
Protection::READ,
Protection::READ_WRITE,
Protection::READ_EXECUTE,
Protection::NONE,
];
let map = alloc_pages(&pages);
let second_page = unsafe { map.as_ptr().add(page::size()) };
let region_size = page::size() * 3;
unsafe {
let _handle = protect_with_handle(second_page, region_size, Protection::NONE)?;
let region = query(second_page)?;
assert_eq!(region.protection(), Protection::NONE);
assert_eq!(region.as_ptr(), second_page);
}
let regions =
query_range(map.as_ptr(), page::size() * pages.len())?.collect::<Result<Vec<_>>>()?;
assert_eq!(regions.len(), 5);
assert_eq!(regions[0].as_ptr(), map.as_ptr());
for i in 0..pages.len() {
assert_eq!(regions[i].protection(), pages[i]);
}
Ok(())
}
}
| rust | MIT | 7302d9c166e63a4c7aa8e951904d0b33f399a924 | 2026-01-04T20:21:40.023200Z | false |
darfink/region-rs | https://github.com/darfink/region-rs/blob/7302d9c166e63a4c7aa8e951904d0b33f399a924/src/query.rs | src/query.rs | use crate::{os, util, Error, Region, Result};
/// An iterator over the [`Region`]s that encompass an address range.
///
/// This `struct` is created by [`query_range`]. See its documentation for more.
pub struct QueryIter {
iterator: Option<os::QueryIter>,
origin: *const (),
}
impl QueryIter {
pub(crate) fn new<T>(origin: *const T, size: usize) -> Result<Self> {
let origin = origin.cast();
os::QueryIter::new(origin, size).map(|iterator| Self {
iterator: Some(iterator),
origin,
})
}
}
impl Iterator for QueryIter {
type Item = Result<Region>;
/// Advances the iterator and returns the next region.
///
/// If the iterator has been exhausted (i.e. all [`Region`]s have been
/// queried), or if an error is encountered during iteration, all further
/// invocations will return [`None`] (in the case of an error, the error will
/// be the last item that is yielded before the iterator is fused).
#[allow(clippy::missing_inline_in_public_items)]
fn next(&mut self) -> Option<Self::Item> {
let regions = self.iterator.as_mut()?;
while let Some(result) = regions.next() {
match result {
Ok(region) => {
let range = region.as_range();
// Skip the region if it precedes the queried range
if range.end <= self.origin as usize {
continue;
}
// Stop iteration if the region is past the queried range
if range.start >= regions.upper_bound() {
break;
}
return Some(Ok(region));
}
Err(error) => {
self.iterator.take();
return Some(Err(error));
}
}
}
self.iterator.take();
None
}
}
impl std::iter::FusedIterator for QueryIter {}
unsafe impl Send for QueryIter {}
unsafe impl Sync for QueryIter {}
/// Queries the OS with an address, returning the region it resides within.
///
/// If the queried address does not reside within any mapped region, or if it's
/// outside the process' address space, the function will error with
/// [`Error::UnmappedRegion`].
///
/// # Parameters
///
/// - The enclosing region can be of multiple page sizes.
/// - The address is rounded down to the closest page boundary.
///
/// # Errors
///
/// - If an interaction with the underlying operating system fails, an error
/// will be returned.
///
/// # Examples
///
/// ```
/// # fn main() -> region::Result<()> {
/// use region::Protection;
///
/// let data = [0; 100];
/// let region = region::query(data.as_ptr())?;
///
/// assert_eq!(region.protection(), Protection::READ_WRITE);
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn query<T>(address: *const T) -> Result<Region> {
// For UNIX systems, the address must be aligned to the closest page boundary
let (address, size) = util::round_to_page_boundaries(address, 1)?;
QueryIter::new(address, size)?
.next()
.ok_or(Error::UnmappedRegion)?
}
/// Queries the OS for mapped regions that overlap with the specified range.
///
/// The implementation clamps any input that exceeds the boundaries of a
/// process' address space. Therefore it's safe to, e.g., pass in
/// [`std::ptr::null`] and [`usize::max_value`] to iterate the mapped memory
/// pages of an entire process.
///
/// If an error is encountered during iteration, the error will be the last item
/// that is yielded. Thereafter the iterator becomes fused.
///
/// A 2-byte range straddling a page boundary, will return both pages (or one
/// region, if the pages share the same properties).
///
/// This function only returns mapped regions. If required, unmapped regions can
/// be manually identified by inspecting the potential gaps between two
/// neighboring regions.
///
/// # Parameters
///
/// - The range is `[address, address + size)`
/// - The address is rounded down to the closest page boundary.
/// - The size may not be zero.
/// - The size is rounded up to the closest page boundary, relative to the
/// address.
///
/// # Errors
///
/// - If an interaction with the underlying operating system fails, an error
/// will be returned.
/// - If size is zero, [`Error::InvalidParameter`] will be returned.
///
/// # Examples
///
/// ```
/// # use region::Result;
/// # fn main() -> Result<()> {
/// let data = [0; 100];
/// let region = region::query_range(data.as_ptr(), data.len())?
/// .collect::<Result<Vec<_>>>()?;
///
/// assert_eq!(region.len(), 1);
/// assert_eq!(region[0].protection(), region::Protection::READ_WRITE);
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn query_range<T>(address: *const T, size: usize) -> Result<QueryIter> {
let (address, size) = util::round_to_page_boundaries(address, size)?;
QueryIter::new(address, size)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::util::alloc_pages;
use crate::{page, Protection};
const TEXT_SEGMENT_PROT: Protection = if cfg!(target_os = "openbsd") {
Protection::EXECUTE
} else {
Protection::READ_EXECUTE
};
#[test]
fn query_returns_unmapped_for_oob_address() {
let (min, max) = (std::ptr::null::<()>(), usize::max_value() as *const ());
assert!(matches!(query(min), Err(Error::UnmappedRegion)));
assert!(matches!(query(max), Err(Error::UnmappedRegion)));
}
#[test]
fn query_returns_correct_descriptor_for_text_segment() -> Result<()> {
let region = query(query_returns_correct_descriptor_for_text_segment as *const ())?;
assert_eq!(region.protection(), TEXT_SEGMENT_PROT);
assert_eq!(region.is_shared(), cfg!(windows));
assert!(!region.is_guarded());
Ok(())
}
#[test]
fn query_returns_one_region_for_multiple_page_allocation() -> Result<()> {
let alloc = crate::alloc(page::size() + 1, Protection::READ_EXECUTE)?;
let region = query(alloc.as_ptr::<()>())?;
assert_eq!(region.protection(), Protection::READ_EXECUTE);
assert_eq!(region.as_ptr::<()>(), alloc.as_ptr());
assert_eq!(region.len(), alloc.len());
assert!(!region.is_guarded());
Ok(())
}
#[test]
#[cfg(not(target_os = "android"))] // TODO: Determine why this fails on Android in QEMU
fn query_is_not_off_by_one() -> Result<()> {
let pages = [Protection::READ, Protection::READ_EXECUTE, Protection::READ];
let map = alloc_pages(&pages);
let page_mid = unsafe { map.as_ptr().add(page::size()) };
let region = query(page_mid)?;
assert_eq!(region.protection(), Protection::READ_EXECUTE);
assert_eq!(region.len(), page::size());
let region = query(unsafe { page_mid.offset(-1) })?;
assert_eq!(region.protection(), Protection::READ);
assert_eq!(region.len(), page::size());
Ok(())
}
#[test]
fn query_range_does_not_return_unmapped_regions() -> Result<()> {
let regions = query_range(std::ptr::null::<()>(), 1)?.collect::<Result<Vec<_>>>()?;
assert!(regions.is_empty());
Ok(())
}
#[test]
fn query_range_returns_both_regions_for_straddling_range() -> Result<()> {
let pages = [Protection::READ_EXECUTE, Protection::READ_WRITE];
let map = alloc_pages(&pages);
// Query an area that overlaps both pages
let address = unsafe { map.as_ptr().offset(page::size() as isize - 1) };
let regions = query_range(address, 2)?.collect::<Result<Vec<_>>>()?;
assert_eq!(regions.len(), pages.len());
for (page, region) in pages.iter().zip(regions.iter()) {
assert_eq!(*page, region.protection);
}
Ok(())
}
#[test]
fn query_range_has_inclusive_lower_and_exclusive_upper_bound() -> Result<()> {
let pages = [Protection::READ, Protection::READ_WRITE, Protection::READ];
let map = alloc_pages(&pages);
let regions = query_range(map.as_ptr(), page::size())?.collect::<Result<Vec<_>>>()?;
assert_eq!(regions.len(), 1);
assert_eq!(regions[0].protection(), Protection::READ);
let regions = query_range(map.as_ptr(), page::size() + 1)?.collect::<Result<Vec<_>>>()?;
assert_eq!(regions.len(), 2);
assert_eq!(regions[0].protection(), Protection::READ);
assert_eq!(regions[1].protection(), Protection::READ_WRITE);
Ok(())
}
#[test]
fn query_range_can_iterate_over_entire_process() -> Result<()> {
let regions =
query_range(std::ptr::null::<()>(), usize::max_value())?.collect::<Result<Vec<_>>>()?;
// This test is a bit rough around the edges
assert!(regions
.iter()
.any(|region| region.protection() == Protection::READ));
assert!(regions
.iter()
.any(|region| region.protection() == Protection::READ_WRITE));
assert!(regions
.iter()
.any(|region| region.protection() == TEXT_SEGMENT_PROT));
assert!(regions.len() > 5);
Ok(())
}
#[test]
fn query_range_iterator_is_fused_after_exhaustion() -> Result<()> {
let pages = [Protection::READ, Protection::READ_WRITE];
let map = alloc_pages(&pages);
let mut iter = query_range(map.as_ptr(), page::size() + 1)?;
assert_eq!(
iter.next().transpose()?.map(|r| r.protection()),
Some(Protection::READ)
);
assert_eq!(
iter.next().transpose()?.map(|r| r.protection()),
Some(Protection::READ_WRITE)
);
assert_eq!(iter.next().transpose()?, None);
assert_eq!(iter.next().transpose()?, None);
Ok(())
}
}
| rust | MIT | 7302d9c166e63a4c7aa8e951904d0b33f399a924 | 2026-01-04T20:21:40.023200Z | false |
darfink/region-rs | https://github.com/darfink/region-rs/blob/7302d9c166e63a4c7aa8e951904d0b33f399a924/src/os/unix.rs | src/os/unix.rs | use crate::{Error, Protection, Result};
use libc::{MAP_ANON, MAP_FAILED, MAP_FIXED, MAP_PRIVATE};
use libc::{PROT_EXEC, PROT_READ, PROT_WRITE};
use std::io;
pub fn page_size() -> usize {
unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize }
}
pub unsafe fn alloc(base: *const (), size: usize, protection: Protection) -> Result<*const ()> {
let mut native_prot = protection.to_native();
// This adjustment ensures that the behavior of memory allocation is
// orthogonal across all platforms by aligning NetBSD's protection flags and
// PaX behavior with those of other operating systems.
if cfg!(target_os = "netbsd") {
let max_protection = (PROT_READ | PROT_WRITE | PROT_EXEC) << 3;
native_prot |= max_protection;
}
let mut flags = MAP_PRIVATE | MAP_ANON;
if !base.is_null() {
flags |= MAP_FIXED;
}
#[cfg(all(target_vendor = "apple", target_arch = "aarch64"))]
if matches!(
protection,
Protection::WRITE_EXECUTE | Protection::READ_WRITE_EXECUTE
) {
// On hardened context, MAP_JIT is necessary (on arm64) to allow W/X'ed regions.
flags |= libc::MAP_JIT;
}
match libc::mmap(base as *mut _, size, native_prot, flags, -1, 0) {
MAP_FAILED => Err(Error::SystemCall(io::Error::last_os_error())),
address => Ok(address as *const ()),
}
}
pub unsafe fn free(base: *const (), size: usize) -> Result<()> {
match libc::munmap(base as *mut _, size) {
0 => Ok(()),
_ => Err(Error::SystemCall(io::Error::last_os_error())),
}
}
pub unsafe fn protect(base: *const (), size: usize, protection: Protection) -> Result<()> {
match libc::mprotect(base as *mut _, size, protection.to_native()) {
0 => Ok(()),
_ => Err(Error::SystemCall(io::Error::last_os_error())),
}
}
pub fn lock(base: *const (), size: usize) -> Result<()> {
match unsafe { libc::mlock(base.cast(), size) } {
0 => Ok(()),
_ => Err(Error::SystemCall(io::Error::last_os_error())),
}
}
pub fn unlock(base: *const (), size: usize) -> Result<()> {
match unsafe { libc::munlock(base.cast(), size) } {
0 => Ok(()),
_ => Err(Error::SystemCall(io::Error::last_os_error())),
}
}
impl Protection {
fn to_native(self) -> libc::c_int {
// This is directly mapped to its native counterpart to allow users to
// include non-standard flags with `Protection::from_bits_unchecked`.
self.bits as libc::c_int
}
}
#[cfg(test)]
mod tests {
use super::*;
use libc::PROT_NONE;
#[test]
fn protection_flags_match_unix_constants() {
assert_eq!(Protection::NONE.bits, PROT_NONE as usize);
assert_eq!(Protection::READ.bits, PROT_READ as usize);
assert_eq!(Protection::WRITE.bits, PROT_WRITE as usize);
assert_eq!(
Protection::READ_WRITE_EXECUTE,
Protection::from_bits_truncate((PROT_READ | PROT_WRITE | PROT_EXEC) as usize)
);
}
#[test]
fn protection_flags_are_mapped_to_native() {
let rwx = PROT_READ | PROT_WRITE | PROT_EXEC;
assert_eq!(Protection::NONE.to_native(), 0);
assert_eq!(Protection::READ.to_native(), PROT_READ);
assert_eq!(Protection::READ_WRITE.to_native(), PROT_READ | PROT_WRITE);
assert_eq!(Protection::READ_WRITE_EXECUTE.to_native(), rwx);
}
}
| rust | MIT | 7302d9c166e63a4c7aa8e951904d0b33f399a924 | 2026-01-04T20:21:40.023200Z | false |
darfink/region-rs | https://github.com/darfink/region-rs/blob/7302d9c166e63a4c7aa8e951904d0b33f399a924/src/os/illumos.rs | src/os/illumos.rs | use crate::{Error, Protection, Region, Result};
use std::fs::File;
use std::io::Read;
pub struct QueryIter {
vmmap: Vec<u8>,
vmmap_index: usize,
upper_bound: usize,
}
impl QueryIter {
pub fn new(origin: *const (), size: usize) -> Result<QueryIter> {
// Do not use a buffered reader here to avoid multiple read(2) calls to the
// proc file, ensuring a consistent snapshot of the virtual memory.
let mut file = File::open("/proc/self/map").map_err(Error::SystemCall)?;
let mut vmmap: Vec<u8> = Vec::with_capacity(8 * PRMAP_SIZE);
let bytes_read = file.read_to_end(&mut vmmap).map_err(Error::SystemCall)?;
if bytes_read % PRMAP_SIZE != 0 {
return Err(Error::ProcfsInput(format!(
"file size {} is not a multiple of prmap_t size ({})",
bytes_read, PRMAP_SIZE
)));
}
Ok(QueryIter {
vmmap,
vmmap_index: 0,
upper_bound: (origin as usize).saturating_add(size),
})
}
pub fn upper_bound(&self) -> usize {
self.upper_bound
}
}
impl Iterator for QueryIter {
type Item = Result<Region>;
fn next(&mut self) -> Option<Self::Item> {
let (pfx, maps, sfx) = unsafe { self.vmmap.align_to::<PrMap>() };
if !pfx.is_empty() || !sfx.is_empty() {
panic!(
"data was not aligned ({}; {}/{}/{})?",
self.vmmap.len(),
pfx.len(),
maps.len(),
sfx.len()
);
}
let map = maps.get(self.vmmap_index)?;
self.vmmap_index += 1;
Some(Ok(Region {
base: map.pr_vaddr,
protection: Protection::from_native(map.pr_mflags),
shared: map.pr_mflags & MA_SHARED != 0,
size: map.pr_size,
..Default::default()
}))
}
}
impl Protection {
fn from_native(protection: i32) -> Self {
const MAPPINGS: &[(i32, Protection)] = &[
(MA_READ, Protection::READ),
(MA_WRITE, Protection::WRITE),
(MA_EXEC, Protection::EXECUTE),
];
MAPPINGS
.iter()
.filter(|(flag, _)| protection & *flag == *flag)
.fold(Protection::NONE, |acc, (_, prot)| acc | *prot)
}
}
// As per proc(4), the file `/proc/$PID/map` contains an array of C structs of
// type `prmap_t`. The layout of this struct, and thus this file, is a stable
// interface.
#[repr(C)]
struct PrMap {
pr_vaddr: *const (),
pr_size: usize,
pr_mapname: [i8; 64],
pr_offset: isize,
pr_mflags: i32,
pr_pagesize: i32,
pr_shmid: i32,
_pr_filler: [i32; 1],
}
const PRMAP_SIZE: usize = std::mem::size_of::<PrMap>();
// These come from <sys/procfs.h>, describing bits in the pr_mflags member:
const MA_EXEC: i32 = 0x1;
const MA_WRITE: i32 = 0x2;
const MA_READ: i32 = 0x4;
const MA_SHARED: i32 = 0x8;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn protection_flags_are_mapped_from_native() {
let rw = MA_READ | MA_WRITE;
let rwx = rw | MA_EXEC;
assert_eq!(Protection::from_native(0), Protection::NONE);
assert_eq!(Protection::from_native(MA_READ), Protection::READ);
assert_eq!(Protection::from_native(rw), Protection::READ_WRITE);
assert_eq!(Protection::from_native(rwx), Protection::READ_WRITE_EXECUTE);
}
}
| rust | MIT | 7302d9c166e63a4c7aa8e951904d0b33f399a924 | 2026-01-04T20:21:40.023200Z | false |
darfink/region-rs | https://github.com/darfink/region-rs/blob/7302d9c166e63a4c7aa8e951904d0b33f399a924/src/os/macos.rs | src/os/macos.rs | use crate::{Error, Protection, Region, Result};
use mach2::vm_prot::*;
pub struct QueryIter {
region_address: mach2::vm_types::mach_vm_address_t,
upper_bound: usize,
}
impl QueryIter {
pub fn new(origin: *const (), size: usize) -> Result<QueryIter> {
Ok(QueryIter {
region_address: origin as _,
upper_bound: (origin as usize).saturating_add(size),
})
}
pub fn upper_bound(&self) -> usize {
self.upper_bound
}
}
impl Iterator for QueryIter {
type Item = Result<Region>;
fn next(&mut self) -> Option<Self::Item> {
// The possible memory share modes
const SHARE_MODES: [u8; 3] = [
mach2::vm_region::SM_SHARED,
mach2::vm_region::SM_TRUESHARED,
mach2::vm_region::SM_SHARED_ALIASED,
];
// Check if the search area has been passed
if self.region_address as usize >= self.upper_bound {
return None;
}
let mut region_size: mach2::vm_types::mach_vm_size_t = 0;
let mut info: mach2::vm_region::vm_region_submap_info_64 =
mach2::vm_region::vm_region_submap_info_64::default();
let mut depth = u32::MAX;
let result = unsafe {
mach2::vm::mach_vm_region_recurse(
mach2::traps::mach_task_self(),
&mut self.region_address,
&mut region_size,
&mut depth,
(&mut info as *mut _) as mach2::vm_region::vm_region_recurse_info_t,
&mut mach2::vm_region::vm_region_submap_info_64::count(),
)
};
match result {
// The end of the process' address space has been reached
mach2::kern_return::KERN_INVALID_ADDRESS => None,
mach2::kern_return::KERN_SUCCESS => {
// The returned region may have a different address than the request
if self.region_address as usize >= self.upper_bound {
return None;
}
let region = Region {
base: self.region_address as *const _,
guarded: (info.user_tag == mach2::vm_statistics::VM_MEMORY_GUARD),
protection: Protection::from_native(info.protection),
max_protection: Protection::from_native(info.max_protection),
shared: SHARE_MODES.contains(&info.share_mode),
size: region_size as usize,
..Default::default()
};
self.region_address = self.region_address.saturating_add(region_size);
Some(Ok(region))
}
_ => Some(Err(Error::MachCall(result))),
}
}
}
impl Protection {
fn from_native(protection: vm_prot_t) -> Self {
const MAPPINGS: &[(vm_prot_t, Protection)] = &[
(VM_PROT_READ, Protection::READ),
(VM_PROT_WRITE, Protection::WRITE),
(VM_PROT_EXECUTE, Protection::EXECUTE),
];
MAPPINGS
.iter()
.filter(|(flag, _)| protection & *flag == *flag)
.fold(Protection::NONE, |acc, (_, prot)| acc | *prot)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn protection_flags_are_mapped_from_native() {
let rw = VM_PROT_READ | VM_PROT_WRITE;
let rwx = rw | VM_PROT_EXECUTE;
assert_eq!(Protection::from_native(0), Protection::NONE);
assert_eq!(Protection::from_native(VM_PROT_READ), Protection::READ);
assert_eq!(Protection::from_native(rw), Protection::READ_WRITE);
assert_eq!(Protection::from_native(rwx), Protection::READ_WRITE_EXECUTE);
}
}
| rust | MIT | 7302d9c166e63a4c7aa8e951904d0b33f399a924 | 2026-01-04T20:21:40.023200Z | false |
darfink/region-rs | https://github.com/darfink/region-rs/blob/7302d9c166e63a4c7aa8e951904d0b33f399a924/src/os/linux.rs | src/os/linux.rs | use crate::{Error, Protection, Region, Result};
use std::fs;
pub struct QueryIter {
proc_maps: String,
upper_bound: usize,
offset: usize,
}
impl QueryIter {
pub fn new(origin: *const (), size: usize) -> Result<Self> {
// Do not use a buffered reader here to avoid multiple read(2) calls to the
// proc file, ensuring a consistent snapshot of the virtual memory.
let proc_maps = fs::read_to_string("/proc/self/maps").map_err(Error::SystemCall)?;
Ok(Self {
proc_maps,
upper_bound: (origin as usize).saturating_add(size),
offset: 0,
})
}
pub fn upper_bound(&self) -> usize {
self.upper_bound
}
}
impl Iterator for QueryIter {
type Item = Result<Region>;
fn next(&mut self) -> Option<Self::Item> {
let (line, _) = self.proc_maps.get(self.offset..)?.split_once('\n')?;
self.offset += line.len() + 1;
Some(parse_procfs_line(line).ok_or_else(|| Error::ProcfsInput(line.to_string())))
}
}
/// Parses flags from /proc/[pid]/maps (e.g 'r--p').
fn parse_procfs_flags(protection: &str) -> (Protection, bool) {
const MAPPINGS: &[Protection] = &[Protection::READ, Protection::WRITE, Protection::EXECUTE];
let result = protection
.chars()
.zip(MAPPINGS.iter())
.filter(|(c, _)| *c != '-')
.fold(Protection::NONE, |acc, (_, prot)| acc | *prot);
(result, protection.ends_with('s'))
}
/// Parses a line from /proc/[pid]/maps.
fn parse_procfs_line(input: &str) -> Option<Region> {
let mut parts = input.split_whitespace();
let mut memory = parts
.next()?
.split('-')
.filter_map(|value| usize::from_str_radix(value, 16).ok());
let (lower, upper) = (memory.next()?, memory.next()?);
let flags = parts.next()?;
let (protection, shared) = parse_procfs_flags(flags);
Some(Region {
base: lower as *const _,
protection,
shared,
size: upper - lower,
..Region::default()
})
}
#[cfg(test)]
mod tests {
use super::{parse_procfs_flags, parse_procfs_line};
use crate::Protection;
#[test]
fn procfs_flags_are_parsed() {
let rwx = Protection::READ_WRITE_EXECUTE;
assert_eq!(parse_procfs_flags("r--s"), (Protection::READ, true));
assert_eq!(parse_procfs_flags("rw-p"), (Protection::READ_WRITE, false));
assert_eq!(parse_procfs_flags("r-xs"), (Protection::READ_EXECUTE, true));
assert_eq!(parse_procfs_flags("rwxs"), (rwx, true));
assert_eq!(parse_procfs_flags("--xp"), (Protection::EXECUTE, false));
assert_eq!(parse_procfs_flags("-w-s"), (Protection::WRITE, true));
}
#[test]
fn procfs_regions_are_parsed() {
let line = "00400000-00409000 r-xs 00000000 08:00 16088 /usr/bin/head";
let region = parse_procfs_line(line).unwrap();
assert_eq!(region.as_ptr(), 0x40_0000 as *mut ());
assert_eq!(region.protection(), Protection::READ_EXECUTE);
assert_eq!(region.len(), 0x9000);
assert!(!region.is_guarded());
assert!(region.is_shared());
}
}
| rust | MIT | 7302d9c166e63a4c7aa8e951904d0b33f399a924 | 2026-01-04T20:21:40.023200Z | false |
darfink/region-rs | https://github.com/darfink/region-rs/blob/7302d9c166e63a4c7aa8e951904d0b33f399a924/src/os/netbsd.rs | src/os/netbsd.rs | use crate::{Error, Protection, Region, Result};
use libc::{c_char, c_int, c_void, free, getpid, pid_t};
use std::io;
pub struct QueryIter {
vmmap: *mut kinfo_vmentry,
vmmap_len: usize,
vmmap_index: usize,
upper_bound: usize,
}
impl QueryIter {
pub fn new(origin: *const (), size: usize) -> Result<QueryIter> {
let mut vmmap_len = 0;
let vmmap = unsafe { kinfo_getvmmap(getpid(), &mut vmmap_len) };
if vmmap.is_null() {
return Err(Error::SystemCall(io::Error::last_os_error()));
}
Ok(QueryIter {
vmmap,
vmmap_len: vmmap_len as usize,
vmmap_index: 0,
upper_bound: (origin as usize).saturating_add(size),
})
}
pub fn upper_bound(&self) -> usize {
self.upper_bound
}
}
impl Iterator for QueryIter {
type Item = Result<Region>;
fn next(&mut self) -> Option<Self::Item> {
if self.vmmap_index >= self.vmmap_len {
return None;
}
let offset = self.vmmap_index * std::mem::size_of::<kinfo_vmentry>();
let entry = unsafe { &*((self.vmmap as *const c_void).add(offset) as *const kinfo_vmentry) };
self.vmmap_index += 1;
Some(Ok(Region {
base: entry.kve_start as *const _,
protection: Protection::from_native(entry.kve_protection as i32),
max_protection: Protection::from_native(entry.kve_max_protection as i32),
shared: (entry.kve_flags & KVME_FLAG_COW as u32) == 0,
size: (entry.kve_end - entry.kve_start) as _,
..Default::default()
}))
}
}
impl Drop for QueryIter {
fn drop(&mut self) {
unsafe { free(self.vmmap as *mut c_void) }
}
}
impl Protection {
fn from_native(protection: c_int) -> Self {
const MAPPINGS: &[(c_int, Protection)] = &[
(KVME_PROT_READ, Protection::READ),
(KVME_PROT_WRITE, Protection::WRITE),
(KVME_PROT_EXEC, Protection::EXECUTE),
];
MAPPINGS
.iter()
.filter(|(flag, _)| protection & *flag == *flag)
.fold(Protection::NONE, |acc, (_, prot)| acc | *prot)
}
}
// These defintions come from <sys/sysctl.h>, describing data returned by the
// `kinfo_getvmmap` system call.
#[repr(C)]
struct kinfo_vmentry {
kve_start: u64,
kve_end: u64,
kve_offset: u64,
kve_type: u32,
kve_flags: u32,
kve_count: u32,
kve_wired_count: u32,
kve_advice: u32,
kve_attributes: u32,
kve_protection: u32,
kve_max_protection: u32,
kve_ref_count: u32,
kve_inheritance: u32,
kve_vn_fileid: u64,
kve_vn_size: u64,
kve_vn_fsid: u64,
kve_vn_rdev: u64,
kve_vn_type: u32,
kve_vn_mode: u32,
kve_path: [[c_char; 32]; 32],
}
const KVME_FLAG_COW: c_int = 0x00000001;
const KVME_PROT_READ: c_int = 0x00000001;
const KVME_PROT_WRITE: c_int = 0x00000002;
const KVME_PROT_EXEC: c_int = 0x00000004;
#[link(name = "util")]
extern "C" {
fn kinfo_getvmmap(pid: pid_t, cntp: *mut c_int) -> *mut kinfo_vmentry;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn protection_flags_are_mapped_from_native() {
let rw = KVME_PROT_READ | KVME_PROT_WRITE;
let rwx = rw | KVME_PROT_EXEC;
assert_eq!(Protection::from_native(0), Protection::NONE);
assert_eq!(Protection::from_native(KVME_PROT_READ), Protection::READ);
assert_eq!(Protection::from_native(rw), Protection::READ_WRITE);
assert_eq!(Protection::from_native(rwx), Protection::READ_WRITE_EXECUTE);
}
}
| rust | MIT | 7302d9c166e63a4c7aa8e951904d0b33f399a924 | 2026-01-04T20:21:40.023200Z | false |
darfink/region-rs | https://github.com/darfink/region-rs/blob/7302d9c166e63a4c7aa8e951904d0b33f399a924/src/os/windows.rs | src/os/windows.rs | use crate::{Error, Protection, Region, Result};
use std::cmp::{max, min};
use std::ffi::c_void;
use std::io;
use std::mem::{size_of, MaybeUninit};
use std::sync::Once;
use windows_sys::Win32::System::Memory::{
VirtualAlloc, VirtualFree, VirtualLock, VirtualProtect, VirtualQuery, VirtualUnlock,
MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_PRIVATE, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE,
PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY, PAGE_GUARD, PAGE_NOACCESS,
PAGE_NOCACHE, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOMBINE, PAGE_WRITECOPY,
};
use windows_sys::Win32::System::SystemInformation::{GetNativeSystemInfo, SYSTEM_INFO};
pub struct QueryIter {
region_address: usize,
upper_bound: usize,
}
impl QueryIter {
pub fn new(origin: *const (), size: usize) -> Result<QueryIter> {
let system = system_info();
Ok(QueryIter {
region_address: max(origin as usize, system.lpMinimumApplicationAddress as usize),
upper_bound: min(
(origin as usize).saturating_add(size),
system.lpMaximumApplicationAddress as usize,
),
})
}
pub fn upper_bound(&self) -> usize {
self.upper_bound
}
}
impl Iterator for QueryIter {
type Item = Result<Region>;
fn next(&mut self) -> Option<Self::Item> {
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
while self.region_address < self.upper_bound {
let bytes = unsafe {
VirtualQuery(
self.region_address as *mut c_void,
&mut info,
size_of::<MEMORY_BASIC_INFORMATION>(),
)
};
if bytes == 0 {
return Some(Err(Error::SystemCall(io::Error::last_os_error())));
}
self.region_address = (info.BaseAddress as usize).saturating_add(info.RegionSize);
// Only mapped memory regions are of interest
if info.State == MEM_RESERVE || info.State == MEM_COMMIT {
let mut region = Region {
base: info.BaseAddress as *const _,
reserved: info.State != MEM_COMMIT,
guarded: (info.Protect & PAGE_GUARD) != 0,
shared: (info.Type & MEM_PRIVATE) == 0,
size: info.RegionSize as usize,
..Default::default()
};
if region.is_committed() {
region.protection = Protection::from_native(info.Protect);
}
return Some(Ok(region));
}
}
None
}
}
pub fn page_size() -> usize {
system_info().dwPageSize as usize
}
pub unsafe fn alloc(base: *const (), size: usize, protection: Protection) -> Result<*const ()> {
let allocation = VirtualAlloc(
base as *mut c_void,
size,
MEM_COMMIT | MEM_RESERVE,
protection.to_native(),
);
if allocation.is_null() {
return Err(Error::SystemCall(io::Error::last_os_error()));
}
Ok(allocation as *const ())
}
pub unsafe fn free(base: *const (), _size: usize) -> Result<()> {
match VirtualFree(base as *mut c_void, 0, MEM_RELEASE) {
0 => Err(Error::SystemCall(io::Error::last_os_error())),
_ => Ok(()),
}
}
pub unsafe fn protect(base: *const (), size: usize, protection: Protection) -> Result<()> {
let result = VirtualProtect(base as *mut c_void, size, protection.to_native(), &mut 0);
if result == 0 {
Err(Error::SystemCall(io::Error::last_os_error()))
} else {
Ok(())
}
}
pub fn lock(base: *const (), size: usize) -> Result<()> {
let result = unsafe { VirtualLock(base as *mut c_void, size) };
if result == 0 {
Err(Error::SystemCall(io::Error::last_os_error()))
} else {
Ok(())
}
}
pub fn unlock(base: *const (), size: usize) -> Result<()> {
let result = unsafe { VirtualUnlock(base as *mut c_void, size) };
if result == 0 {
Err(Error::SystemCall(io::Error::last_os_error()))
} else {
Ok(())
}
}
fn system_info() -> &'static SYSTEM_INFO {
static INIT: Once = Once::new();
static mut INFO: MaybeUninit<SYSTEM_INFO> = MaybeUninit::uninit();
unsafe {
INIT.call_once(|| GetNativeSystemInfo(INFO.as_mut_ptr()));
&*INFO.as_ptr()
}
}
impl Protection {
fn from_native(protection: u32) -> Self {
// Ignore unsupported flags (TODO: Preserve this information?)
let ignored = PAGE_GUARD | PAGE_NOCACHE | PAGE_WRITECOMBINE;
match protection & !ignored {
PAGE_EXECUTE => Protection::EXECUTE,
PAGE_EXECUTE_READ => Protection::READ_EXECUTE,
PAGE_EXECUTE_READWRITE => Protection::READ_WRITE_EXECUTE,
PAGE_EXECUTE_WRITECOPY => Protection::READ_WRITE_EXECUTE,
PAGE_NOACCESS => Protection::NONE,
PAGE_READONLY => Protection::READ,
PAGE_READWRITE => Protection::READ_WRITE,
PAGE_WRITECOPY => Protection::READ_WRITE,
_ => unreachable!("Protection: 0x{:X}", protection),
}
}
pub(crate) fn to_native(self) -> u32 {
match self {
Protection::NONE => PAGE_NOACCESS,
Protection::READ => PAGE_READONLY,
Protection::EXECUTE => PAGE_EXECUTE,
Protection::READ_EXECUTE => PAGE_EXECUTE_READ,
Protection::READ_WRITE => PAGE_READWRITE,
Protection::READ_WRITE_EXECUTE => PAGE_EXECUTE_READWRITE,
Protection::WRITE_EXECUTE => PAGE_EXECUTE_READWRITE,
_ => unreachable!("Protection: {:?}", self),
}
}
}
| rust | MIT | 7302d9c166e63a4c7aa8e951904d0b33f399a924 | 2026-01-04T20:21:40.023200Z | false |
darfink/region-rs | https://github.com/darfink/region-rs/blob/7302d9c166e63a4c7aa8e951904d0b33f399a924/src/os/mod.rs | src/os/mod.rs | #[cfg(windows)]
mod windows;
#[cfg(windows)]
pub use self::windows::*;
#[cfg(unix)]
mod unix;
#[cfg(unix)]
pub use self::unix::*;
#[cfg(any(target_os = "macos", target_os = "ios"))]
mod macos;
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub use self::macos::*;
#[cfg(any(target_os = "linux", target_os = "android"))]
mod linux;
#[cfg(any(target_os = "linux", target_os = "android"))]
pub use self::linux::*;
#[cfg(target_os = "freebsd")]
mod freebsd;
#[cfg(target_os = "freebsd")]
pub use self::freebsd::*;
#[cfg(target_os = "illumos")]
mod illumos;
#[cfg(target_os = "illumos")]
pub use self::illumos::*;
#[cfg(target_os = "openbsd")]
mod openbsd;
#[cfg(target_os = "openbsd")]
pub use self::openbsd::*;
#[cfg(target_os = "netbsd")]
mod netbsd;
#[cfg(target_os = "netbsd")]
pub use self::netbsd::*;
| rust | MIT | 7302d9c166e63a4c7aa8e951904d0b33f399a924 | 2026-01-04T20:21:40.023200Z | false |
darfink/region-rs | https://github.com/darfink/region-rs/blob/7302d9c166e63a4c7aa8e951904d0b33f399a924/src/os/openbsd.rs | src/os/openbsd.rs | use crate::{Error, Protection, Region, Result};
use libc::{c_int, c_uint, c_ulong, getpid, sysctl, CTL_KERN, KERN_PROC_VMMAP};
use std::io;
pub struct QueryIter {
mib: [c_int; 3],
vmentry: kinfo_vmentry,
previous_boundary: usize,
upper_bound: usize,
}
impl QueryIter {
pub fn new(origin: *const (), size: usize) -> Result<QueryIter> {
Ok(QueryIter {
mib: [CTL_KERN, KERN_PROC_VMMAP, unsafe { getpid() }],
vmentry: unsafe { std::mem::zeroed() },
upper_bound: (origin as usize).saturating_add(size),
previous_boundary: 0,
})
}
pub fn upper_bound(&self) -> usize {
self.upper_bound
}
}
impl Iterator for QueryIter {
type Item = Result<Region>;
fn next(&mut self) -> Option<Self::Item> {
let mut len = std::mem::size_of::<kinfo_vmentry>();
// Although it would be preferred to query the information for all virtual
// pages at once, the system call does not seem to respond consistently. If
// called once during a process' lifetime, it returns all pages, but if
// called again, it returns an empty buffer. This may be caused due to an
// oversight, but in this case, the solution is to query one memory region
// at a time.
let result = unsafe {
sysctl(
self.mib.as_ptr(),
self.mib.len() as c_uint,
&mut self.vmentry as *mut _ as *mut _,
&mut len,
std::ptr::null_mut(),
0,
)
};
if result == -1 {
return Some(Err(Error::SystemCall(io::Error::last_os_error())));
}
if len == 0 || self.vmentry.kve_end as usize == self.previous_boundary {
return None;
}
let region = Region {
base: self.vmentry.kve_start as *const _,
protection: Protection::from_native(self.vmentry.kve_protection),
max_protection: Protection::from_native(self.vmentry.kve_max_protection),
shared: (self.vmentry.kve_etype & KVE_ET_COPYONWRITE) == 0,
size: (self.vmentry.kve_end - self.vmentry.kve_start) as _,
..Default::default()
};
// Since OpenBSD returns the first region whose base address is at, or after
// `kve_start`, the address can simply be incremented by one to retrieve the
// next region.
self.vmentry.kve_start += 1;
self.previous_boundary = self.vmentry.kve_end as usize;
Some(Ok(region))
}
}
impl Protection {
fn from_native(protection: c_int) -> Self {
const MAPPINGS: &[(c_int, Protection)] = &[
(KVE_PROT_READ, Protection::READ),
(KVE_PROT_WRITE, Protection::WRITE),
(KVE_PROT_EXEC, Protection::EXECUTE),
];
MAPPINGS
.iter()
.filter(|(flag, _)| protection & *flag == *flag)
.fold(Protection::NONE, |acc, (_, prot)| acc | *prot)
}
}
// These defintions come from <sys/sysctl.h>, describing data returned by the
// `KERN_PROC_VMMAP` system call.
#[repr(C)]
struct kinfo_vmentry {
kve_start: c_ulong,
kve_end: c_ulong,
kve_guard: c_ulong,
kve_fspace: c_ulong,
kve_fspace_augment: c_ulong,
kve_offset: u64,
kve_wired_count: c_int,
kve_etype: c_int,
kve_protection: c_int,
kve_max_protection: c_int,
kve_advice: c_int,
kve_inheritance: c_int,
kve_flags: u8,
}
const KVE_PROT_READ: c_int = 1;
const KVE_PROT_WRITE: c_int = 2;
const KVE_PROT_EXEC: c_int = 4;
const KVE_ET_COPYONWRITE: c_int = 4;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn protection_flags_are_mapped_from_native() {
let rw = KVE_PROT_READ | KVE_PROT_WRITE;
let rwx = rw | KVE_PROT_EXEC;
assert_eq!(Protection::from_native(0), Protection::NONE);
assert_eq!(Protection::from_native(KVE_PROT_READ), Protection::READ);
assert_eq!(Protection::from_native(rw), Protection::READ_WRITE);
assert_eq!(Protection::from_native(rwx), Protection::READ_WRITE_EXECUTE);
}
}
| rust | MIT | 7302d9c166e63a4c7aa8e951904d0b33f399a924 | 2026-01-04T20:21:40.023200Z | false |
darfink/region-rs | https://github.com/darfink/region-rs/blob/7302d9c166e63a4c7aa8e951904d0b33f399a924/src/os/freebsd.rs | src/os/freebsd.rs | use crate::{Error, Protection, Region, Result};
use libc::{
c_int, c_void, free, getpid, kinfo_getvmmap, kinfo_vmentry, KVME_PROT_EXEC, KVME_PROT_READ,
KVME_PROT_WRITE, KVME_TYPE_DEFAULT,
};
use std::io;
pub struct QueryIter {
vmmap: *mut kinfo_vmentry,
vmmap_len: usize,
vmmap_index: usize,
upper_bound: usize,
}
impl QueryIter {
pub fn new(origin: *const (), size: usize) -> Result<QueryIter> {
let mut vmmap_len = 0;
let vmmap = unsafe { kinfo_getvmmap(getpid(), &mut vmmap_len) };
if vmmap.is_null() {
return Err(Error::SystemCall(io::Error::last_os_error()));
}
Ok(QueryIter {
vmmap,
vmmap_len: vmmap_len as usize,
vmmap_index: 0,
upper_bound: (origin as usize).saturating_add(size),
})
}
pub fn upper_bound(&self) -> usize {
self.upper_bound
}
}
impl Iterator for QueryIter {
type Item = Result<Region>;
fn next(&mut self) -> Option<Self::Item> {
if self.vmmap_index >= self.vmmap_len {
return None;
}
// Since the struct size is given in the struct, it can be used future-proof
// (the definition is not required to be updated when new fields are added).
let offset = unsafe { self.vmmap_index * (*self.vmmap).kve_structsize as usize };
let entry = unsafe { &*((self.vmmap as *const c_void).add(offset) as *const kinfo_vmentry) };
self.vmmap_index += 1;
Some(Ok(Region {
base: entry.kve_start as *const _,
protection: Protection::from_native(entry.kve_protection),
shared: entry.kve_type == KVME_TYPE_DEFAULT,
size: (entry.kve_end - entry.kve_start) as _,
..Default::default()
}))
}
}
impl Drop for QueryIter {
fn drop(&mut self) {
unsafe { free(self.vmmap as *mut c_void) }
}
}
impl Protection {
fn from_native(protection: c_int) -> Self {
const MAPPINGS: &[(c_int, Protection)] = &[
(KVME_PROT_READ, Protection::READ),
(KVME_PROT_WRITE, Protection::WRITE),
(KVME_PROT_EXEC, Protection::EXECUTE),
];
MAPPINGS
.iter()
.filter(|(flag, _)| protection & *flag == *flag)
.fold(Protection::NONE, |acc, (_, prot)| acc | *prot)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn protection_flags_are_mapped_from_native() {
let rw = KVME_PROT_READ | KVME_PROT_WRITE;
let rwx = rw | KVME_PROT_EXEC;
assert_eq!(Protection::from_native(0), Protection::NONE);
assert_eq!(Protection::from_native(KVME_PROT_READ), Protection::READ);
assert_eq!(Protection::from_native(rw), Protection::READ_WRITE);
assert_eq!(Protection::from_native(rwx), Protection::READ_WRITE_EXECUTE);
}
}
| rust | MIT | 7302d9c166e63a4c7aa8e951904d0b33f399a924 | 2026-01-04T20:21:40.023200Z | false |
Charlie-XIAO/tauri-plugin-desktop-underlay | https://github.com/Charlie-XIAO/tauri-plugin-desktop-underlay/blob/d5200ed0a70ecec83dd707087bbbcda2c7abeef3/build.rs | build.rs | const COMMANDS: &[&str] = &[
"is_desktop_underlay",
"set_desktop_underlay",
"toggle_desktop_underlay",
];
fn main() {
tauri_plugin::Builder::new(COMMANDS).build();
}
| rust | MIT | d5200ed0a70ecec83dd707087bbbcda2c7abeef3 | 2026-01-04T20:21:17.039147Z | false |
Charlie-XIAO/tauri-plugin-desktop-underlay | https://github.com/Charlie-XIAO/tauri-plugin-desktop-underlay/blob/d5200ed0a70ecec83dd707087bbbcda2c7abeef3/src/lib.rs | src/lib.rs | #![doc = include_str!("../README.md")]
use tauri::plugin::{Builder, TauriPlugin};
use tauri::{generate_handler, Manager, Runtime};
mod commands;
mod core;
mod ext;
pub use ext::DesktopUnderlayExt;
/// Initialize the desktop-underlay plugin.
pub fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::new("desktop-underlay")
.setup(|app_handle, _api| {
app_handle.manage(core::DesktopUnderlayState::default());
Ok(())
})
.invoke_handler(generate_handler![
commands::is_desktop_underlay,
commands::set_desktop_underlay,
commands::toggle_desktop_underlay,
])
.build()
}
| rust | MIT | d5200ed0a70ecec83dd707087bbbcda2c7abeef3 | 2026-01-04T20:21:17.039147Z | false |
Charlie-XIAO/tauri-plugin-desktop-underlay | https://github.com/Charlie-XIAO/tauri-plugin-desktop-underlay/blob/d5200ed0a70ecec83dd707087bbbcda2c7abeef3/src/ext.rs | src/ext.rs | use anyhow::Result;
use tauri::{Runtime, WebviewWindow, Window};
/// A window extension that provides desktop underlay functionalities.
pub trait DesktopUnderlayExt {
/// Check whether the window is desktop underlay.
fn is_desktop_underlay(&self) -> bool;
/// Set the window as desktop underlay or revert it to normal.
///
/// If `desktop_underlay` is `true`, the window will be set as desktop
/// underlay (no-op if it already is). If `desktop_underlay` is `false`,
/// the window will be reverted to normal (no-op if it is not yet
/// desktop underlay).
fn set_desktop_underlay(&self, desktop_underlay: bool) -> Result<()>;
/// Toggle the desktop underlay state of the window.
///
/// If the window is currently desktop underlay, it will be reverted to
/// normal. Otherwise, it will be set as desktop underlay. Returns whether
/// the window is desktop underlay after the operation.
fn toggle_desktop_underlay(&self) -> Result<bool>;
}
impl<R: Runtime> DesktopUnderlayExt for Window<R> {
fn is_desktop_underlay(&self) -> bool {
crate::core::is_desktop_underlay(self)
}
fn set_desktop_underlay(&self, desktop_underlay: bool) -> Result<()> {
crate::core::set_desktop_underlay(self, desktop_underlay)
}
fn toggle_desktop_underlay(&self) -> Result<bool> {
crate::core::toggle_desktop_underlay(self)
}
}
impl<R: Runtime> DesktopUnderlayExt for WebviewWindow<R> {
fn is_desktop_underlay(&self) -> bool {
self.as_ref().window().is_desktop_underlay()
}
fn set_desktop_underlay(&self, desktop_underlay: bool) -> Result<()> {
self.as_ref()
.window()
.set_desktop_underlay(desktop_underlay)
}
fn toggle_desktop_underlay(&self) -> Result<bool> {
self.as_ref().window().toggle_desktop_underlay()
}
}
| rust | MIT | d5200ed0a70ecec83dd707087bbbcda2c7abeef3 | 2026-01-04T20:21:17.039147Z | false |
Charlie-XIAO/tauri-plugin-desktop-underlay | https://github.com/Charlie-XIAO/tauri-plugin-desktop-underlay/blob/d5200ed0a70ecec83dd707087bbbcda2c7abeef3/src/commands.rs | src/commands.rs | use tauri::{command, Manager, Runtime, Window};
use crate::DesktopUnderlayExt;
#[command]
pub async fn is_desktop_underlay<R: Runtime>(
window: Window<R>,
label: Option<String>,
) -> tauri::Result<bool> {
let target_window = {
if let Some(label) = label {
window
.get_webview_window(label.as_str())
.ok_or(anyhow::anyhow!("Window not found: {label}"))?
.as_ref()
.window()
} else {
window
}
};
Ok(target_window.is_desktop_underlay())
}
#[command]
pub async fn set_desktop_underlay<R: Runtime>(
window: Window<R>,
desktop_underlay: bool,
label: Option<String>,
) -> tauri::Result<()> {
let target_window = {
if let Some(label) = label {
window
.get_webview_window(label.as_str())
.ok_or(anyhow::anyhow!("Window not found: {label}"))?
.as_ref()
.window()
} else {
window
}
};
target_window
.set_desktop_underlay(desktop_underlay)
.map_err(Into::into)
}
#[command]
pub async fn toggle_desktop_underlay<R: Runtime>(
window: Window<R>,
label: Option<String>,
) -> tauri::Result<bool> {
let target_window = {
if let Some(label) = label {
window
.get_webview_window(label.as_str())
.ok_or(anyhow::anyhow!("Window not found: {label}"))?
.as_ref()
.window()
} else {
window
}
};
target_window.toggle_desktop_underlay().map_err(Into::into)
}
| rust | MIT | d5200ed0a70ecec83dd707087bbbcda2c7abeef3 | 2026-01-04T20:21:17.039147Z | false |
Charlie-XIAO/tauri-plugin-desktop-underlay | https://github.com/Charlie-XIAO/tauri-plugin-desktop-underlay/blob/d5200ed0a70ecec83dd707087bbbcda2c7abeef3/src/core/macos.rs | src/core/macos.rs | use std::ffi::c_void;
use std::os::raw::c_ulong;
use anyhow::Result;
use objc2::msg_send;
use objc2::runtime::AnyObject;
extern "C" {
fn CGWindowLevelForKey(key: i32) -> i32;
}
// 1 << 0 - NSWindowCollectionBehaviorCanJoinAllSpaces
// 1 << 4 - NSWindowCollectionBehaviorStationary
// 1 << 6 - NSWindowCollectionBehaviorIgnoresCycle
// https://developer.apple.com/documentation/appkit/nswindowcollectionbehavior
const UNDERLAY_COLLECTION_BEHAVIOR: c_ulong = 1 << 0 | 1 << 4 | 1 << 6;
/// Set the window as a desktop underlay.
pub(super) unsafe fn set_underlay(ns_window: *mut c_void) -> Result<()> {
let ns_window = ns_window as *mut AnyObject;
// 2 - CGWindowLevelKey.desktopWindow
// https://developer.apple.com/documentation/coregraphics/cgwindowlevelkey
let () = msg_send![ns_window, setLevel: CGWindowLevelForKey(2) - 1];
let behavior: c_ulong = msg_send![ns_window, collectionBehavior];
let () = msg_send![ns_window, setCollectionBehavior: behavior | UNDERLAY_COLLECTION_BEHAVIOR];
Ok(())
}
/// Unset the window from being a desktop underlay.
pub(super) unsafe fn unset_underlay(ns_window: *mut c_void) -> Result<()> {
let ns_window = ns_window as *mut AnyObject;
// 4 - CGWindowLevelKey.normalWindow
// https://developer.apple.com/documentation/coregraphics/cgwindowlevelkey
let () = msg_send![ns_window, setLevel: CGWindowLevelForKey(4)];
let behavior: c_ulong = msg_send![ns_window, collectionBehavior];
let () = msg_send![ns_window, setCollectionBehavior: behavior & !UNDERLAY_COLLECTION_BEHAVIOR];
Ok(())
}
| rust | MIT | d5200ed0a70ecec83dd707087bbbcda2c7abeef3 | 2026-01-04T20:21:17.039147Z | false |
Charlie-XIAO/tauri-plugin-desktop-underlay | https://github.com/Charlie-XIAO/tauri-plugin-desktop-underlay/blob/d5200ed0a70ecec83dd707087bbbcda2c7abeef3/src/core/linux.rs | src/core/linux.rs | use anyhow::Result;
use gdk::WindowTypeHint;
use gtk::prelude::GtkWindowExt;
use gtk::ApplicationWindow;
/// Set the window as a desktop underlay.
pub(super) unsafe fn set_underlay(gtk_window: ApplicationWindow) -> Result<()> {
gtk_window.set_type_hint(WindowTypeHint::Desktop);
Ok(())
}
/// Unset the window from being a desktop underlay.
pub(super) unsafe fn unset_underlay(gtk_window: ApplicationWindow) -> Result<()> {
gtk_window.set_type_hint(WindowTypeHint::Normal);
Ok(())
}
| rust | MIT | d5200ed0a70ecec83dd707087bbbcda2c7abeef3 | 2026-01-04T20:21:17.039147Z | false |
Charlie-XIAO/tauri-plugin-desktop-underlay | https://github.com/Charlie-XIAO/tauri-plugin-desktop-underlay/blob/d5200ed0a70ecec83dd707087bbbcda2c7abeef3/src/core/windows.rs | src/core/windows.rs | use anyhow::{bail, Result};
use windows::core::{s, BOOL};
use windows::Win32::Foundation::{HWND, LPARAM, WPARAM};
use windows::Win32::UI::WindowsAndMessaging::{
EnumWindows, FindWindowA, FindWindowExA, SendMessageTimeoutA, SetParent, SMTO_NORMAL,
};
/// Helper function to find the WorkerW window.
unsafe extern "system" fn enum_window(window: HWND, ref_worker_w: LPARAM) -> BOOL {
let shell_dll_def_view =
FindWindowExA(Some(window), None, s!("SHELLDLL_DefView"), None).unwrap_or_default();
if HWND::is_invalid(&shell_dll_def_view) {
return true.into();
}
let worker_w = FindWindowExA(None, Some(window), s!("WorkerW"), None).unwrap_or_default();
if HWND::is_invalid(&worker_w) {
return true.into();
}
*(ref_worker_w.0 as *mut HWND) = worker_w;
true.into()
}
/// Set the window as a desktop underlay.
pub(super) unsafe fn set_underlay(hwnd: HWND) -> Result<()> {
let progman = FindWindowA(s!("Progman"), None)?;
SendMessageTimeoutA(
progman,
0x052C,
WPARAM(0x0000000D),
LPARAM(0x00000001),
SMTO_NORMAL,
1000,
None,
);
let mut worker_w = HWND::default();
EnumWindows(Some(enum_window), LPARAM(&mut worker_w as *mut HWND as _))?;
if HWND::is_invalid(&worker_w) {
worker_w = FindWindowExA(Some(progman), None, s!("WorkerW"), None)?;
if HWND::is_invalid(&worker_w) {
bail!("Failed to find WorkerW");
}
}
SetParent(hwnd, Some(worker_w))?;
Ok(())
}
/// Unset the window from being a desktop underlay.
pub(super) unsafe fn unset_underlay(hwnd: HWND) -> Result<()> {
SetParent(hwnd, None)?;
Ok(())
}
| rust | MIT | d5200ed0a70ecec83dd707087bbbcda2c7abeef3 | 2026-01-04T20:21:17.039147Z | false |
Charlie-XIAO/tauri-plugin-desktop-underlay | https://github.com/Charlie-XIAO/tauri-plugin-desktop-underlay/blob/d5200ed0a70ecec83dd707087bbbcda2c7abeef3/src/core/mod.rs | src/core/mod.rs | use std::sync::Mutex;
use anyhow::Result;
use tauri::{Manager, Runtime, Window};
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "windows")]
mod windows;
macro_rules! dispatch_to_main_thread {
($window:expr, $f:expr) => {{
let (tx, rx) = std::sync::mpsc::channel();
let window = $window.clone();
$window.run_on_main_thread(move || {
let _ = tx.send($f(window));
})?;
rx.recv()?
}};
}
/// A Tauri state to keep track of the desktop underlay windows.
#[derive(Default)]
pub struct DesktopUnderlayState(Mutex<Vec<String>>);
fn unchecked_set_desktop_underlay<R: Runtime>(
window: &Window<R>,
desktop_underlay: bool,
) -> Result<()> {
if desktop_underlay {
dispatch_to_main_thread!(window, |w: Window<R>| -> Result<()> {
unsafe {
#[cfg(target_os = "linux")]
linux::set_underlay(w.gtk_window()?)?;
#[cfg(target_os = "macos")]
macos::set_underlay(w.ns_window()?)?;
#[cfg(target_os = "windows")]
windows::set_underlay(w.hwnd()?)?;
}
Ok(())
})?;
window
.state::<DesktopUnderlayState>()
.0
.lock()
.unwrap()
.push(window.label().to_string());
} else {
dispatch_to_main_thread!(window, |w: Window<R>| -> Result<()> {
unsafe {
#[cfg(target_os = "linux")]
linux::unset_underlay(w.gtk_window()?)?;
#[cfg(target_os = "macos")]
macos::unset_underlay(w.ns_window()?)?;
#[cfg(target_os = "windows")]
windows::unset_underlay(w.hwnd()?)?;
}
Ok(())
})?;
window
.state::<DesktopUnderlayState>()
.0
.lock()
.unwrap()
.retain(|label| label != &window.label().to_string());
}
Ok(())
}
pub fn is_desktop_underlay<R: Runtime>(window: &Window<R>) -> bool {
window
.state::<DesktopUnderlayState>()
.0
.lock()
.unwrap()
.contains(&window.label().to_string())
}
pub fn set_desktop_underlay<R: Runtime>(window: &Window<R>, desktop_underlay: bool) -> Result<()> {
if desktop_underlay == is_desktop_underlay(window) {
return Ok(());
}
unchecked_set_desktop_underlay(window, desktop_underlay)
}
pub fn toggle_desktop_underlay<R: Runtime>(window: &Window<R>) -> Result<bool> {
let desktop_underlay = !is_desktop_underlay(window);
unchecked_set_desktop_underlay(window, desktop_underlay)?;
Ok(desktop_underlay)
}
| rust | MIT | d5200ed0a70ecec83dd707087bbbcda2c7abeef3 | 2026-01-04T20:21:17.039147Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.