From f1811475cd134dfdfe6e72188e9499a6d99930d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hilmar=20G=C3=BAstafsson?= Date: Fri, 17 Jul 2020 09:21:22 +0200 Subject: [PATCH] draw: Add method for drawing text with cursor --- src/draw.rs | 64 +++++++++++++++++++++++++++++++++++++++++ src/widgets/launcher.rs | 15 ++-------- 2 files changed, 66 insertions(+), 13 deletions(-) diff --git a/src/draw.rs b/src/draw.rs index 743bf43..5e19d27 100644 --- a/src/draw.rs +++ b/src/draw.rs @@ -124,6 +124,58 @@ impl<'a> Font<'a> { Ok((x_off as u32, self.size as u32)) } + pub fn draw_text_with_cursor( + &self, + buf: &mut Buffer, + bg: &Color, + c: &Color, + s: &str, + cursor: usize, + ) -> Result<(u32, u32), ::std::io::Error> { + let mut x_off: i32 = 0; + let mut off: i32 = 0; + let mut glyphs = Vec::with_capacity(s.len()); + 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), + )) + } + }; + glyphs.push(glyph); + if glyph.origin.1 < off { + off = glyph.origin.1 + } + } + for (i, glyph) in glyphs.iter().enumerate() { + glyph.draw(buf, (x_off, -off), bg, c); + x_off += glyph.dimensions.0 as i32 + glyph.origin.0; + if i + 1 == cursor { + let height = buf.get_bounds().3; + self.draw_cursor(buf, c, x_off as u32, height)?; + } + } + + Ok((x_off as u32, self.size as u32)) + } + + pub fn draw_cursor( + &self, + buf: &mut Buffer, + c: &Color, + offset: u32, + height: u32, + ) -> Result<(), ::std::io::Error> { + // draw cursor + for i in 1..height { + buf.put((offset, i), c)? + } + Ok(()) + } + pub fn auto_widest(&mut self, s: &str) -> Result { self.add_str_to_cache(s); let mut max = 0; @@ -156,6 +208,18 @@ impl<'a> Font<'a> { self.draw_text(buf, bg, c, s) } + pub fn auto_draw_text_with_cursor( + &mut self, + buf: &mut Buffer, + bg: &Color, + c: &Color, + s: &str, + cursor: usize, + ) -> Result<(u32, u32), ::std::io::Error> { + self.add_str_to_cache(s); + self.draw_text_with_cursor(buf, bg, c, s, cursor) + } + pub fn draw_text_fixed_width( &self, buf: &mut Buffer, diff --git a/src/widgets/launcher.rs b/src/widgets/launcher.rs index f19267b..548839e 100644 --- a/src/widgets/launcher.rs +++ b/src/widgets/launcher.rs @@ -75,22 +75,10 @@ impl<'a> Launcher<'a> { Color::new(1.0, 1.0, 1.0, 1.0) }; - let dim = - self.font - .borrow_mut() - .auto_draw_text(buf, bg, &c, &self.input[..self.cursor])?; - - let cursor_placement = dim.0; - // draw cursor - for i in 1..self.font_size { - buf.put((cursor_placement, i), &Color::new(1.0, 1.0, 1.0, 1.0)) - .unwrap(); - } - let dim = self .font .borrow_mut() - .auto_draw_text(buf, bg, &c, &self.input)?; + .auto_draw_text_with_cursor(buf, bg, &c, &self.input, self.cursor)?; dim.0 + self.font_size / 4 } else { @@ -457,6 +445,7 @@ impl<'a> Widget for Launcher<'a> { } } _ => { + println!("{}", key); if let Some(v) = interpreted { self.input.insert_str(self.cursor, &v); self.cursor += 1;