Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592use crate::bar::{ Bar, component::{ Component, Value, bar::{BarComponent, Direction}, matcher::{MatchComponent, Pattern}, stack::StackComponent, text::{Display, TextComponent}, }, module::external::External,};use kdl;use miette::{Diagnostic, NamedSource, SourceSpan};use parley::{FontStack, TextStyle};use thiserror::Error;
#[derive(Error, Debug, Diagnostic)]#[error("{message}")]pub struct ConfigError { pub message: String, #[label("here")] pub span: SourceSpan, #[source_code] pub src: Option<NamedSource<String>>,}
#[derive(Error, Debug, Diagnostic)]#[diagnostic(severity(Warning))]#[error("{message}")]pub struct ConfigWarning<S: miette::SourceCode + std::fmt::Debug + 'static> { pub message: String, #[label("here")] pub span: SourceSpan, #[source_code] pub src: NamedSource<S>,}
fn get_f32(value: &kdl::KdlEntry) -> Result<f32, ConfigError> { match value.value() { kdl::KdlValue::Integer(x) => Ok(*x as f32), kdl::KdlValue::Float(x) => Ok(*x as f32), _ => Err(ConfigError { message: "expected number".to_owned(), src: None, span: value.span(), }), }}
fn get_colour(value: &kdl::KdlEntry) -> Result<[u8; 4], ConfigError> { match value.value() { kdl::KdlValue::String(str) => { let trimmed = str.trim_start_matches('#'); let raw = match u32::from_str_radix(trimmed, 16) { Ok(v) => v, Err(e) => { return Err(ConfigError { message: e.to_string(), span: value.span(), src: None, }); } };
if trimmed.len() == 6 { Ok(((raw << 8) + 0xff).to_be_bytes()) } else if trimmed.len() == 8 { Ok(raw.to_be_bytes()) } else { Err(ConfigError { message: "expected hex string of length 6 or 8".to_owned(), span: value.span(), src: None, }) } } _ => Err(ConfigError { message: "expected hex string".to_owned(), span: value.span(), src: None, }), }}
fn parse_style<S>( node: &kdl::KdlNode, source: &NamedSource<S>,) -> Result<TextStyle<'static, [u8; 4]>, ConfigError>where S: miette::SourceCode + std::fmt::Debug + Clone,{ let mut style = TextStyle::<[u8; 4]>::default();
for entry in node.entries() { match entry.name() { Some(name) if name.value() == "font" => { style.font_stack = FontStack::Source(entry.value().to_string().into()) } Some(name) if name.value() == "size" => style.font_size = get_f32(entry)?, Some(name) if name.value() == "colour" => { style.brush = get_colour(entry)?; } Some(name) => eprintln!( "{:?}", miette::Report::from(ConfigWarning { message: format!("ignoring unknown field {name}"), span: name.span(), src: source.clone(), }) ),
None => eprintln!( "{:?}", miette::Report::from(ConfigWarning { message: "ignoring unnamed field".to_owned(), span: entry.span(), src: source.clone(), }) ), } }
Ok(style)}
fn parse_text_component<S>( node: &kdl::KdlNode, default_font: TextStyle<'static, [u8; 4]>, source: &NamedSource<S>,) -> Result<TextComponent, ConfigError>where S: miette::SourceCode + std::fmt::Debug + Clone,{ let mut text = TextComponent::new(Display::default(), default_font); match node.entry(0) { Some(data) => match data.value() { kdl::KdlValue::String(data) => { text.display = data.parse::<Display>().map_err(|err| ConfigError { message: err.to_string(), span: node.span(), src: None, })?; } _ => { return Err(ConfigError { message: "expected string".to_owned(), span: node.span(), src: None, }); } }, _ => { return Err(ConfigError { message: "expected 1 argument, found 0".to_owned(), span: node.span(), src: None, }); } }
for child in node.iter_children() { match child.name().value() { "style" => text.style = parse_style(child, source)?, x => eprintln!( "{:?}", miette::Report::from(ConfigWarning { message: format!("ignoring unknown field {x}"), span: child.name().span(), src: source.clone(), }) ), } }
Ok(text)}
fn parse_bar_component<S>( node: &kdl::KdlNode, source: &NamedSource<S>,) -> Result<BarComponent, ConfigError>where S: miette::SourceCode + std::fmt::Debug + Clone,{ let mut bar = BarComponent::default();
match node.entry(0) { Some(measure) => match measure.value() { kdl::KdlValue::String(val) => { bar.measure = val.to_owned(); } _ => { return Err(ConfigError { message: "expected string".to_owned(), src: None, span: node.span(), }); } }, None => { return Err(ConfigError { message: "expected 1 argument, found 0".to_owned(), src: None, span: node.span(), }); } }
for child in node.iter_children() { match child.name().value() { "min" => { if let Some(min) = child.entry(0) { bar.min = get_f32(min)?; } else { return Err(ConfigError { message: "expected 1 argument".to_string(), span: child.span(), src: None, }); } } "max" => { if let Some(max) = child.entry(0) { bar.max = get_f32(max)?; } else { return Err(ConfigError { message: "expected 1 argument".to_string(), span: child.span(), src: None, }); } } "width" => { if let Some(width) = child.entry(0) { bar.width = get_f32(width)?; } else { return Err(ConfigError { message: "expected 1 argument".to_string(), span: child.span(), src: None, }); } } "height" => { if let Some(height) = child.entry(0) { bar.height = get_f32(height)?; } else { return Err(ConfigError { message: "expected 1 argument".to_string(), span: child.span(), src: None, }); } } "border_width" => { if let Some(border_width) = child.entry(0) { bar.border_width = get_f32(border_width)?; } else { return Err(ConfigError { message: "expected 1 argument".to_string(), span: child.span(), src: None, }); } } "padding" => { if let Some(padding) = child.entry(0) { bar.padding = get_f32(padding)?; } else { return Err(ConfigError { message: "expected 1 argument".to_string(), span: child.span(), src: None, }); } } "direction" => { if let Some(dir) = child.entry(0) { match dir.value() { kdl::KdlValue::String(val) if val == "top-to-bottom" => { bar.direction = Direction::TopToBottom } kdl::KdlValue::String(val) if val == "bottom-to-top" => { bar.direction = Direction::BottomToTop } kdl::KdlValue::String(val) if val == "left-to-right" => { bar.direction = Direction::LeftToRight } kdl::KdlValue::String(val) if val == "right-to-left" => { bar.direction = Direction::RightToLeft } _ => { return Err(ConfigError { message: "expected one of 'top-to-bottom', 'bottom-to-top', 'left-to-right', or 'right-to-left'".to_owned(), src: None, span: dir.span(), }); } } } else { return Err(ConfigError { message: "expected 1 argument".to_string(), span: child.span(), src: None, }); } } "full_colour" => { if let Some(full_colour) = child.entry(0) { bar.full_colour = get_colour(full_colour)?; } else { return Err(ConfigError { message: "expected 1 argument".to_string(), span: child.span(), src: None, }); } } "empty_colour" => { if let Some(empty_colour) = child.entry(0) { bar.empty_colour = get_colour(empty_colour)?; } else { return Err(ConfigError { message: "expected 1 argument".to_string(), span: child.span(), src: None, }); } } "border_colour" => { if let Some(border_colour) = child.entry(0) { bar.border_colour = get_colour(border_colour)?; } else { return Err(ConfigError { message: "expected 1 argument".to_string(), span: child.span(), src: None, }); } } "offset" => { if let Some(offset) = child.entry(0) { bar.offset = get_f32(offset)?; } else { return Err(ConfigError { message: "expected 1 argument".to_string(), span: child.span(), src: None, }); } } x => { eprintln!( "{:?}", miette::Report::from(ConfigWarning { message: format!("ignoring unknown field {x}"), span: child.name().span(), src: source.clone(), }) ); } } } Ok(bar)}
fn parse_stack_component<S>( node: &kdl::KdlNode, default_font: &TextStyle<'static, [u8; 4]>, source: &NamedSource<S>,) -> Result<StackComponent, ConfigError>where S: miette::SourceCode + std::fmt::Debug + Clone,{ Ok(StackComponent { contents: parse_components(node, default_font, source)?.into_vec(), })}
fn parse_pattern<S>(node: &kdl::KdlNode, source: &NamedSource<S>) -> Result<Pattern, ConfigError>where S: miette::SourceCode + std::fmt::Debug + Clone,{ match node.name().value() { "case" => { let Some(entry) = node.entries().get(0) else { return Err(ConfigError { message: "expected value".to_owned(), span: node.span(), src: None, }); };
if node.entries().len() != 1 { eprintln!( "{:?}", miette::Report::from(ConfigWarning { message: "case only expects 1 entry".to_owned(), span: node.span(), src: source.clone(), }) ); }
let pattern_val = match entry.value() { kdl::KdlValue::String(str) => Value::String(str.to_owned()), kdl::KdlValue::Integer(int) => Value::Num(*int as f32), kdl::KdlValue::Float(float) => Value::Num(*float as f32), _ => Value::Placeholder, };
Ok(Pattern::Value(pattern_val)) } "range" => { if node.entries().len() != 2 { eprintln!( "{:?}", miette::Report::from(ConfigWarning { message: "range expects 2 entries".to_owned(), span: node.span(), src: source.clone(), }) ); }
Ok(Pattern::NumRange( get_f32(&node.entries()[0])?, get_f32(&node.entries()[1])?, )) } "otherwise" => Ok(Pattern::Otherwise), _ => Err(ConfigError { message: "expected one of 'case', 'range' or 'otherwise'".to_owned(), span: node.name().span(), src: None, }), }}
fn parse_match_component<S>( node: &kdl::KdlNode, default_font: &TextStyle<'static, [u8; 4]>, source: &NamedSource<S>,) -> Result<MatchComponent, ConfigError>where S: miette::SourceCode + std::fmt::Debug + Clone,{ let Some(entry) = node.entries().get(0) else { return Err(ConfigError { message: "expected name".to_owned(), span: node.span(), src: None, }); };
Ok(MatchComponent::new( entry.value().to_string(), node.iter_children() .map(|child| -> Result<(Pattern, Vec<Component>), ConfigError> { Ok(( parse_pattern(child, source)?, parse_components(child, default_font, source)?.into_vec(), )) }) .collect::<Result<Vec<_>, _>>()?, ))}
fn parse_components<S>( node: &kdl::KdlNode, default_font: &TextStyle<'static, [u8; 4]>, source: &NamedSource<S>,) -> Result<Box<[Component]>, ConfigError>where S: miette::SourceCode + Clone + std::fmt::Debug,{ Ok(node .iter_children() .filter(|node| match node.name().value() { "text" | "bar" | "stack" | "match" => true, x => { eprintln!( "{:?}", miette::Report::from(ConfigWarning { message: format!("ignoring unknown component {x}"), span: node.span(), src: source.clone(), }) ); false } }) .map(|node| match node.name().value() { "text" => Ok(Component::Text(parse_text_component( node, default_font.clone(), source, )?)), "bar" => Ok(Component::Bar(parse_bar_component(node, source)?)), "stack" => Ok(Component::Stack(parse_stack_component( node, default_font, source, )?)), "match" => Ok(Component::Match(parse_match_component( node, default_font, source, )?)), _ => unreachable!(), }) .collect::<Result<Box<[_]>, ConfigError>>()?)}
pub fn parse_bar_config<S>( config: &kdl::KdlDocument, source: &NamedSource<S>,) -> Result<Bar, ConfigError>where S: miette::SourceCode + std::fmt::Debug + Clone,{ let modules = config .nodes() .iter() .filter(|v| v.name().value() == "module") .flat_map(|module| { let Some(name) = module.entry(0) else { return vec![]; };
let prefix = name.to_string();
let mut out = vec![]; for child in module.iter_children() { if child.name().value() == "command" { let command = child .entries() .iter() .map(|v| { if let Some(name) = v.name() { String::from(name.value()) + "=" + &v.value().to_string() } else { v.value().to_string() } }) .collect::<Box<[_]>>();
out.push(External { command, prefix: prefix.clone(), }); } else { log::warn!("ignored unknown field {}", child.name()) } } out }) .collect::<Vec<_>>();
let default_font = config .get("style") .map(|v| parse_style(v, source)) .transpose()? .unwrap_or_default();
let left = config.get("left").map_or_else( || Ok(Default::default()), |v| parse_components(v, &default_font, &source), )?;
let right = config.get("right").map_or_else( || Ok(Default::default()), |v| parse_components(v, &default_font, &source), )?;
let height = match config.get("height").and_then(|v| v.entry(0)) { Some(height) => match height.value() { kdl::KdlValue::Integer(height) => *height as u32, _ => { return Err(ConfigError { message: "expected integer".to_owned(), span: height.span(), src: None, }); } }, None => 30, };
Ok(Bar::new(modules, left, right, height).unwrap())}