diff --git a/src/config.rs b/src/config.rs index 1ec3036..07fbcf7 100644 --- a/src/config.rs +++ b/src/config.rs @@ -111,11 +111,14 @@ impl Widget { .map(|x| x.unwrap()) .collect(), )), - Widget::Clock { font, font_size } => Some(widgets::clock::Clock::new( + Widget::Clock { font, font_size } => match widgets::clock::Clock::new( time, get_font(&font.or_else(|| Some("sans".to_string())).unwrap(), &fonts), font_size, - )), + ) { + Ok(w) => Some(w), + Err(_) => None, + }, Widget::Date { font, font_size } => Some(widgets::date::Date::new( time, get_font(&font.or_else(|| Some("sans".to_string())).unwrap(), &fonts), diff --git a/src/draw.rs b/src/draw.rs index 0921d14..743bf43 100644 --- a/src/draw.rs +++ b/src/draw.rs @@ -124,6 +124,27 @@ impl<'a> Font<'a> { Ok((x_off as u32, self.size as u32)) } + pub fn auto_widest(&mut self, s: &str) -> Result { + self.add_str_to_cache(s); + let mut max = 0; + for ch in s.chars() { + let glyph = match self.glyphs.get(&ch) { + Some(glyph) => glyph, + None => { + return Err(::std::io::Error::new( + ::std::io::ErrorKind::Other, + format!("glyph for {:} not in cache", ch), + )) + } + }; + let width = glyph.dimensions.0 as i32 + glyph.origin.0; + if width > max { + max = width + } + } + Ok(max as u32) + } + pub fn auto_draw_text( &mut self, buf: &mut Buffer, diff --git a/src/widgets/clock.rs b/src/widgets/clock.rs index 946cfd4..60ac4c7 100644 --- a/src/widgets/clock.rs +++ b/src/widgets/clock.rs @@ -11,18 +11,25 @@ pub struct Clock<'a> { cur_time: NaiveDateTime, clock_cache: Font<'a>, size: f32, + digit: u32, + colon: u32, } impl<'a> Clock<'a> { - pub fn new(time: NaiveDateTime, font: FontRef, size: f32) -> Box { + pub fn new(time: NaiveDateTime, font: FontRef, size: f32) -> ::std::io::Result> { let mut clock_cache = Font::new(font, size); clock_cache.add_str_to_cache("0123456789:"); - Box::new(Clock { + let digit = clock_cache.auto_widest("123456789")?; + let colon = (clock_cache.auto_widest(":")? as f32 * 1.25) as u32; + + Ok(Box::new(Clock { cur_time: time, clock_cache, size, - }) + digit, + colon, + })) } } @@ -38,9 +45,7 @@ impl<'a> Widget for Clock<'a> { fn enter(&mut self) {} fn leave(&mut self) {} fn size(&self) -> (u32, u32) { - let digit = (self.size * 0.45).ceil() as u32; - let colon = (self.size * 0.20).ceil() as u32; - (digit * 4 + colon, self.size.ceil() as u32) + (self.digit * 4 + self.colon, self.size.ceil() as u32) } fn draw( @@ -62,8 +67,8 @@ impl<'a> Widget for Clock<'a> { let buf = &mut ctx.buf.subdimensions((pos.0, pos.1, width, height))?; buf.memset(ctx.bg); - let digit = (self.size * 0.45).ceil() as u32; - let colon = (self.size * 0.20).ceil() as u32; + let digit = self.digit; + let colon = self.colon; self.clock_cache.draw_text_fixed_width( buf, ctx.bg,