feat: debug infos

NOTE: only debug mode is available
This commit is contained in:
Pihkaal
2024-01-20 20:25:14 +01:00
parent 8bb7c4c07d
commit 435699e8a1
5 changed files with 213 additions and 95 deletions

View File

@@ -5,7 +5,7 @@ edition = "2021"
[dependencies] [dependencies]
chrono = "0.4.31" chrono = "0.4.31"
clap = { version = "4.4.18", features = ["derive"] } clap = { version = "4.4.18", features = ["derive", "cargo"] }
crossterm = "0.27.0" crossterm = "0.27.0"
dirs = "5.0.1" dirs = "5.0.1"
ini = "1.3.0" ini = "1.3.0"

95
src/color.rs Normal file
View File

@@ -0,0 +1,95 @@
use crossterm::style::Color;
pub struct ComputableColor {
values: Vec<Color>,
current: usize,
}
impl ComputableColor {
pub fn from(color: Color) -> ComputableColor {
return ComputableColor {
values: vec![color],
current: 0,
};
}
pub fn update(&mut self) -> () {
self.current = (self.current + 1) % self.values.len();
}
pub fn get_value(&self) -> Color {
return *self.values.get(self.current).unwrap();
}
pub fn get_keys_count(&self) -> usize {
return self.values.len();
}
}
fn clamp01(v: f32) -> f32 {
return if v < 0.0 {
0.0
} else if v > 1.0 {
1.0
} else {
v
};
}
fn lerp(a: u8, b: u8, t: f32) -> u8 {
let v = a as f32 + (b as f32 - a as f32) as f32 * clamp01(t);
return v as u8;
}
pub fn generate_gradient(keys: Vec<(u8, u8, u8)>, steps: usize) -> ComputableColor {
let mut gradient = Vec::with_capacity(steps);
let step_size = 1.0 / (steps as f32 / (keys.len() as f32 - 1.0));
for i in 0..keys.len() - 1 {
let current = keys.get(i).unwrap();
let next = keys.get(i + 1).unwrap();
let mut t = 0.0;
while t <= 1.0 {
t += step_size;
let r = lerp(current.0, next.0, t);
let g = lerp(current.1, next.1, t);
let b = lerp(current.2, next.2, t);
gradient.push(Color::Rgb { r, g, b });
}
}
return ComputableColor {
values: gradient,
current: 0,
};
}
pub fn parse_hex_color(value: &str) -> (u8, u8, u8) {
// Expand #XXX colors
let value = if value.len() == 3 {
format!(
"{}{}{}{}{}{}",
&value[0..1],
&value[0..1],
&value[1..2],
&value[1..2],
&value[2..3],
&value[2..3]
)
} else {
value.to_owned()
};
if value.len() != 6 {
panic!("ERROR: Invalid hex color: {}", value);
}
let r = u8::from_str_radix(&value[0..2], 16).unwrap();
let g = u8::from_str_radix(&value[2..4], 16).unwrap();
let b = u8::from_str_radix(&value[4..6], 16).unwrap();
return (r, g, b);
}

View File

@@ -4,27 +4,10 @@ use std::{fs, path::PathBuf};
use crossterm::style::Color; use crossterm::style::Color;
use ini::configparser::ini::Ini; use ini::configparser::ini::Ini;
pub struct ComputableColor { use crate::{
values: Vec<Color>, color::{generate_gradient, parse_hex_color, ComputableColor},
current: usize, debug,
}
impl ComputableColor {
fn from(color: Color) -> ComputableColor {
return ComputableColor {
values: vec![color],
current: 0,
}; };
}
pub fn update(&mut self) {
self.current = (self.current + 1) % self.values.len();
}
pub fn get_value(&self) -> Color {
return *self.values.get(self.current).unwrap();
}
}
pub struct Config { pub struct Config {
pub be_polite: bool, pub be_polite: bool,
@@ -102,33 +85,6 @@ fn load_term_color(value: i64) -> Color {
} }
} }
fn parse_hex_color(value: &str) -> (u8, u8, u8) {
// Expand #XXX colors
let value = if value.len() == 3 {
format!(
"{}{}{}{}{}{}",
&value[0..1],
&value[0..1],
&value[1..2],
&value[1..2],
&value[2..3],
&value[2..3]
)
} else {
value.to_owned()
};
if value.len() != 6 {
panic!("ERROR: Invalid hex color: {}", value);
}
let r = u8::from_str_radix(&value[0..2], 16).unwrap();
let g = u8::from_str_radix(&value[2..4], 16).unwrap();
let b = u8::from_str_radix(&value[4..6], 16).unwrap();
return (r, g, b);
}
fn load_hex_color(value: &str) -> Color { fn load_hex_color(value: &str) -> Color {
let rgb = parse_hex_color(value); let rgb = parse_hex_color(value);
return Color::Rgb { return Color::Rgb {
@@ -142,21 +98,6 @@ fn load_ansi_color(value: i64) -> Color {
return Color::AnsiValue(value.try_into().unwrap()); return Color::AnsiValue(value.try_into().unwrap());
} }
fn clamp01(v: f32) -> f32 {
return if v < 0.0 {
0.0
} else if v > 1.0 {
1.0
} else {
v
};
}
fn lerp(a: u8, b: u8, t: f32) -> u8 {
let v = a as f32 + (b as f32 - a as f32) as f32 * clamp01(t);
return v as u8;
}
fn load_gradient(ini: &Ini) -> ComputableColor { fn load_gradient(ini: &Ini) -> ComputableColor {
let mut keys = Vec::new(); let mut keys = Vec::new();
@@ -166,7 +107,7 @@ fn load_gradient(ini: &Ini) -> ComputableColor {
i += 1; i += 1;
} }
if ini.getbool("gradient", "gradient_loop").unwrap().unwrap() { if !debug::is_debug() && ini.getbool("gradient", "gradient_loop").unwrap().unwrap() {
let mut loop_keys = keys.clone(); let mut loop_keys = keys.clone();
loop_keys.reverse(); loop_keys.reverse();
for i in 1..loop_keys.len() { for i in 1..loop_keys.len() {
@@ -174,28 +115,14 @@ fn load_gradient(ini: &Ini) -> ComputableColor {
} }
} }
let steps = ini.getuint("gradient", "gradient_steps").unwrap().unwrap(); let steps: usize = if debug::is_debug() {
let mut gradient = Vec::with_capacity(steps.try_into().unwrap()); debug::DEBUG_COLOR_DISPLAY_SIZE * 2
} else {
let step_size = 1.0 / (steps as f32 / (keys.len() as f32 - 1.0)); ini.getuint("gradient", "gradient_steps")
for i in 0..keys.len() - 1 { .unwrap()
let current = keys.get(i).unwrap(); .unwrap()
let next = keys.get(i + 1).unwrap(); .try_into()
.unwrap()
let mut t = 0.0;
while t <= 1.0 {
t += step_size;
let r = lerp(current.0, next.0, t);
let g = lerp(current.1, next.1, t);
let b = lerp(current.2, next.2, t);
gradient.push(Color::Rgb { r, g, b });
}
}
return ComputableColor {
values: gradient,
current: 0,
}; };
return generate_gradient(keys, steps - 1);
} }

72
src/debug.rs Normal file
View File

@@ -0,0 +1,72 @@
use std::{
io::{self, Write},
sync::atomic::{AtomicBool, Ordering},
};
use clap::crate_version;
use crossterm::{
queue,
style::{self, Attribute},
};
use crate::config::Config;
pub const DEBUG_COLOR_DISPLAY_SIZE: usize = 50;
static DEBUG_MODE: AtomicBool = AtomicBool::new(false);
pub fn print_debug_infos(config: &mut Config) -> io::Result<()> {
let mut stdout = io::stdout();
print_debug_label("Version")?;
writeln!(stdout, "{}", crate_version!())?;
print_debug_label("FPS")?;
writeln!(stdout, "{}", config.fps)?;
print_debug_label("Time format")?;
writeln!(stdout, "{}", config.time_format)?;
print_debug_label("Date format")?;
writeln!(stdout, "{}", config.date_format)?;
print_debug_label("Color scheme")?;
let width = config.color.get_keys_count();
if width == 1 {
queue!(stdout, style::SetBackgroundColor(config.color.get_value()))?;
write!(stdout, "{}", " ".repeat(DEBUG_COLOR_DISPLAY_SIZE))?;
} else {
for _ in 0..width / 2 {
queue!(stdout, style::SetForegroundColor(config.color.get_value()))?;
config.color.update();
queue!(stdout, style::SetBackgroundColor(config.color.get_value()))?;
config.color.update();
write!(stdout, "")?;
}
}
writeln!(stdout)?;
queue!(stdout, style::ResetColor)?;
let _ = stdout.flush();
return Ok(());
}
fn print_debug_label(key: &str) -> io::Result<()> {
let mut stdout = io::stdout();
queue!(stdout, style::SetAttribute(Attribute::Bold))?;
write!(stdout, "{}: ", key)?;
queue!(stdout, style::ResetColor)?;
return Ok(());
}
pub fn enable_debug_mode() -> () {
DEBUG_MODE.store(true, Ordering::Relaxed);
}
pub fn is_debug() -> bool {
return DEBUG_MODE.load(Ordering::Relaxed);
}

View File

@@ -7,7 +7,7 @@ use std::{
}; };
use chrono::Local; use chrono::Local;
use clap::Parser; use clap::{Parser, Subcommand};
use config::{write_default_config, Config}; use config::{write_default_config, Config};
use crossterm::{ use crossterm::{
cursor, cursor,
@@ -16,14 +16,18 @@ use crossterm::{
style::{self, Attribute, Color}, style::{self, Attribute, Color},
terminal::{self, ClearType}, terminal::{self, ClearType},
}; };
use debug::print_debug_infos;
use dirs::config_dir; use dirs::config_dir;
mod color;
mod config; mod config;
mod debug;
mod symbols; mod symbols;
#[derive(Parser, Debug)] #[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)] #[command(author, version, about, long_about = None)]
struct Args { #[command(propagate_version = true)]
struct Cli {
#[arg(short, long, value_name = "FILE")] #[arg(short, long, value_name = "FILE")]
config: Option<String>, config: Option<String>,
@@ -32,14 +36,28 @@ struct Args {
#[arg(short, long, action)] #[arg(short, long, action)]
yes: bool, yes: bool,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug)]
enum Commands {
Debug {},
} }
fn main() -> io::Result<()> { fn main() -> io::Result<()> {
let args = Args::parse(); let cli = Cli::parse();
match &cli.command {
Commands::Debug {} => {
debug::enable_debug_mode();
}
}
// Load config // Load config
let mut default_generated = false; let mut default_generated = false;
let config_file = if let Some(custom_config) = args.config { let config_file = if let Some(custom_config) = cli.config {
PathBuf::from(custom_config) PathBuf::from(custom_config)
} else { } else {
let config_file = config_dir().unwrap().join("tlock").join("config"); let config_file = config_dir().unwrap().join("tlock").join("config");
@@ -51,8 +69,8 @@ fn main() -> io::Result<()> {
config_file config_file
}; };
if args.regenerate_default { if cli.regenerate_default {
if !default_generated && config_file.exists() && !args.yes { if !default_generated && config_file.exists() && !cli.yes {
println!("A config file is already located at {:?}", config_file); println!("A config file is already located at {:?}", config_file);
print!("Do you really want to recreate it ? [y/N] "); print!("Do you really want to recreate it ? [y/N] ");
@@ -78,9 +96,15 @@ fn main() -> io::Result<()> {
} }
let mut config = config::load_from_file(config_file); let mut config = config::load_from_file(config_file);
let mut stdout = io::stdout(); let mut stdout = io::stdout();
match &cli.command {
Commands::Debug {} => {
print_debug_infos(&mut config)?;
return Ok(());
}
}
// Switch to alternate screen, hide the cursor and enable raw mode // Switch to alternate screen, hide the cursor and enable raw mode
execute!(stdout, terminal::EnterAlternateScreen, cursor::Hide)?; execute!(stdout, terminal::EnterAlternateScreen, cursor::Hide)?;
let _ = terminal::enable_raw_mode()?; let _ = terminal::enable_raw_mode()?;