use 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>, } #[derive(Error, Debug, Diagnostic)] #[diagnostic(severity(Warning))] #[error("{message}")] pub struct ConfigWarning { pub message: String, #[label("here")] pub span: SourceSpan, #[source_code] pub src: NamedSource, } fn get_f32(value: &kdl::KdlEntry) -> Result { 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( node: &kdl::KdlNode, source: &NamedSource, ) -> Result, 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( node: &kdl::KdlNode, default_font: TextStyle<'static, [u8; 4]>, source: &NamedSource, ) -> Result 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::().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( node: &kdl::KdlNode, source: &NamedSource, ) -> Result 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( node: &kdl::KdlNode, default_font: &TextStyle<'static, [u8; 4]>, source: &NamedSource, ) -> Result where S: miette::SourceCode + std::fmt::Debug + Clone, { Ok(StackComponent { contents: parse_components(node, default_font, source)?.into_vec(), }) } fn parse_pattern(node: &kdl::KdlNode, source: &NamedSource) -> Result 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( node: &kdl::KdlNode, default_font: &TextStyle<'static, [u8; 4]>, source: &NamedSource, ) -> Result 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), ConfigError> { Ok(( parse_pattern(child, source)?, parse_components(child, default_font, source)?.into_vec(), )) }) .collect::, _>>()?, )) } fn parse_components( node: &kdl::KdlNode, default_font: &TextStyle<'static, [u8; 4]>, source: &NamedSource, ) -> Result, 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::, ConfigError>>()?) } pub fn parse_bar_config( config: &kdl::KdlDocument, source: &NamedSource, ) -> Result 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::>(); out.push(External { command, prefix: prefix.clone(), }); } else { log::warn!("ignored unknown field {}", child.name()) } } out }) .collect::>(); 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()) }