Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343use std::str::FromStr;
use parley::{Alignment, AlignmentOptions, Layout, StyleProperty, TextStyle};
use crate::bar::{component::Value, module::Data, text_renderer::TextRenderer};
#[derive(Clone)]pub struct TextComponent { pub layout: Layout<[u8; 4]>, pub display: Display, pub style: TextStyle<'static, [u8; 4]>,}
impl TextComponent { pub fn new(display: Display, style: TextStyle<'static, [u8; 4]>) -> Self { TextComponent { layout: Layout::default(), display, style, } }
pub fn update( &mut self, text_renderer: &mut TextRenderer, data: &Data, width: f32, height: f32, align: Alignment, ) { let mut layout = text_renderer.layout_builder(1.0, true, &self.style); layout.push_style_modification_span(&[StyleProperty::LineHeight( // pure eyeball. i don't know why i need to add 2 to make it centered. parley::LineHeight::Absolute(height + 2.0), )]); layout.push_text(&self.display.get_string(&data)); let (new_layout, _) = layout.build(); self.layout = new_layout; self.layout.break_all_lines(None); self.layout .align(Some(width as f32), align, AlignmentOptions::default());
self.display.update_tick(data.tick()); }}
#[derive(Clone, Debug, Default)]pub struct Display { fragments: Vec<DisplayFragment>, tick: u64,}
impl Display { pub fn get_string(&self, data: &Data) -> String { let mut output = String::new(); for component in &self.fragments { match component { DisplayFragment::Text { text } => { output.push_str(text); } DisplayFragment::Data { value, format } => { let str = match data.get_value(value) { Some(Value::String(str)) => match format.align { Align::Left => format!("{:<1$}", str, format.width as usize), Align::Right => format!("{:>1$}", str, format.width as usize), Align::Center => format!("{:^1$}", str, format.width as usize), }, Some(Value::Num(num)) => { let scaled_num = num / format.divisor; if format.digits == 0 { match format.align { Align::Left => { format!("{:<1$}", scaled_num, format.width as usize) } Align::Right => { format!("{:>1$}", scaled_num, format.width as usize) } Align::Center => { format!("{:^1$}", scaled_num, format.width as usize) } } } else { match format.align { Align::Left => format!( "{0:<1$.2$}", scaled_num, format.width as usize, format.digits as usize ), Align::Right => format!( "{0:>1$.2$}", scaled_num, format.width as usize, format.digits as usize ), Align::Center => format!( "{0:^1$.2$}", scaled_num, format.width as usize, format.digits as usize ), } } } Some(Value::Placeholder) => "...".into(), None => "[N/A]".into(), };
output.push_str(&str); } } }
output }
pub fn values(&self) -> impl Iterator<Item = &str> { self.fragments.iter().filter_map(|v| match v { DisplayFragment::Text { .. } => None, DisplayFragment::Data { value, .. } => Some(value.as_str()), }) }
pub fn needs_update(&self, data: &Data) -> bool { self.tick == 0 || self.values().any(|v| data.get_tick(v).unwrap() > self.tick) }
pub fn update_tick(&mut self, tick: u64) { self.tick = tick; }}
#[derive(Debug, thiserror::Error)]pub enum ParseError { #[error("unclosed data delimiter")] UnclosedData, #[error("unmatched closing delimiter")] UnmatchedData, #[error("unknown escape")] UnknownEscape, #[error("unknown formatting modifier")] UnknownFormat,}
// impl std::fmt::Display for ParseError {// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {// todo!()// }// }
impl FromStr for Display { type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> { enum ParseState { Text, Data, Format(DisplayFragment, Option<Format>), }
enum Format { Divisor, Digits, Width, }
let mut components = vec![]; let mut state = ParseState::Text; let mut start_byte = 0;
let mut current_string = String::new(); let mut is_escape = false; for (idx, char) in s.char_indices() { match state { ParseState::Text => { if idx < start_byte { continue; }
if is_escape { match char { '{' | '}' | '\\' => {} _ => return Err(ParseError::UnknownEscape), } is_escape = false; } else if char == '{' && !is_escape { let text = &s[start_byte..idx]; components.push(DisplayFragment::Text { text: current_string + text, }); current_string = String::new(); state = ParseState::Data; start_byte = idx + 1; } else if char == '}' && !is_escape { return Err(ParseError::UnmatchedData); } else if char == '\\' && !is_escape { is_escape = true; current_string.push_str(&s[start_byte..idx]); start_byte = idx + 1; } } ParseState::Data => match char { '}' => { let key = String::from(&s[start_byte..idx]); components.push(DisplayFragment::Data { value: key.clone(), format: DataFormat::default(), }); state = ParseState::Text; start_byte = idx + 1; } ':' => { let key = String::from(&s[start_byte..idx]); state = ParseState::Format( DisplayFragment::Data { value: key.clone(), format: DataFormat::default(), }, None, ); } _ => (), }, ParseState::Format(ref mut display_component, ref mut current_format) => { let format = match display_component { DisplayFragment::Data { format, .. } => format, _ => unreachable!(), };
let mut unmatched = false; match current_format { Some(Format::Divisor) => match char { d @ '0'..='9' => { let digit = d.to_digit(10).unwrap(); format.divisor *= 10.0; format.divisor += digit as f32; } _ => unmatched = true, }, Some(Format::Digits) => match char { d @ '0'..='9' => { let digit = d.to_digit(10).unwrap(); format.digits *= 10; format.digits += digit as u8; } _ => unmatched = true, }, Some(Format::Width) => match char { d @ '0'..='9' => { let digit = d.to_digit(10).unwrap(); format.width *= 10; format.width += digit as u8; } _ => unmatched = true, }, None => unmatched = true, }
if unmatched { match char { '/' => { *current_format = Some(Format::Divisor); format.divisor = 0.0; } '.' => { *current_format = Some(Format::Digits); } '<' => { *current_format = Some(Format::Width); format.align = Align::Left; } '>' => { *current_format = Some(Format::Width); format.align = Align::Right; } '^' => { *current_format = Some(Format::Width); format.align = Align::Center; } '}' => { let mut component = DisplayFragment::Text { text: String::from(""), };
std::mem::swap(&mut component, display_component);
components.push(component); state = ParseState::Text; start_byte = idx + 1; } ' ' => {} _ => return Err(ParseError::UnknownFormat), } } } } }
match state { ParseState::Text => { let text = &s[start_byte..]; if !text.is_empty() { components.push(DisplayFragment::Text { text: String::from(text), }); } Ok(Display { fragments: components, tick: 0, }) } ParseState::Data | ParseState::Format(..) => Err(ParseError::UnclosedData), } }}
#[derive(Clone, Debug)]pub enum DisplayFragment { Text { text: String }, Data { value: String, format: DataFormat },}
#[derive(Clone, Debug)]pub struct DataFormat { divisor: f32, digits: u8, width: u8, align: Align,}
#[derive(Clone, Debug)]pub enum Align { Left, Right, Center,}
impl Default for DataFormat { fn default() -> Self { Self { divisor: 1.0, digits: 0, width: 0, align: Align::Left, } }}