embedded-graphics-keyboard 0.1.3

no_std on-screen keyboard and text field widgets for embedded-graphics, driven by buttons or touch
Documentation
//! Single-line text field with an optional title above its frame.

use embedded_graphics::{
    Drawable,
    draw_target::{DrawTarget, DrawTargetExt},
    geometry::{AnchorPoint, Dimensions, Point, Size},
    pixelcolor::PixelColor,
    primitives::{Primitive, PrimitiveStyle, Rectangle},
};

use crate::style::{FontStyle, FrameStyle};

/// Text cursor appearance.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CursorStyle<C> {
    /// Bar color.
    pub color: C,
    /// Bar thickness in pixels.
    pub width: u32,
    /// Gap in pixels between the end of the text and the cursor.
    pub gap: u32,
}

/// Appearance of a [`TextField`].
#[derive(Debug, Clone, Copy)]
pub struct TextFieldStyle<C, S> {
    /// Frame around the value.
    pub frame: FrameStyle<C>,
    /// Font of the value.
    pub font: S,
    /// Font of the title.
    pub title_font: S,
    /// Vertical gap in pixels between the title and the frame.
    pub title_gap: u32,
    /// Margin in pixels between the frame border and the text.
    pub padding: u32,
    /// Cursor drawn after the text, or `None` for no cursor.
    pub cursor: Option<CursorStyle<C>>,
}

impl<C: PixelColor, S> TextFieldStyle<C, S> {
    /// Creates a style with an invisible frame, `title_gap = 4`, `padding = 8` and no cursor.
    pub const fn new(font: S, title_font: S) -> Self {
        Self {
            frame: FrameStyle::new(),
            font,
            title_font,
            title_gap: 4,
            padding: 8,
            cursor: None,
        }
    }

    /// Sets the frame style.
    pub const fn with_frame(mut self, frame: FrameStyle<C>) -> Self {
        self.frame = frame;
        self
    }

    /// Sets the gap between the title and the frame.
    pub const fn with_title_gap(mut self, gap: u32) -> Self {
        self.title_gap = gap;
        self
    }

    /// Sets the horizontal text padding inside the frame.
    pub const fn with_padding(mut self, padding: u32) -> Self {
        self.padding = padding;
        self
    }

    /// Sets the cursor style.
    pub const fn with_cursor(mut self, cursor: CursorStyle<C>) -> Self {
        self.cursor = Some(cursor);
        self
    }
}

impl<C: PixelColor, S: FontStyle<C>> TextFieldStyle<C, S> {
    /// Height of a field fitting one line of text, with `padding` above and
    /// below it, and the title if `with_title` is `true`.
    ///
    /// Use it to size the `bounds` of a [`TextField`].
    pub fn height(&self, with_title: bool) -> u32 {
        let title = if with_title {
            self.title_font.measure(REFERENCE_TEXT).height + self.title_gap
        } else {
            0
        };
        let border = self.frame.effective_border_width();
        title + self.font.measure(REFERENCE_TEXT).height + 2 * (self.padding + border)
    }
}

/// Text with an ascender and a descender, measured to get the line height of a font.
const REFERENCE_TEXT: &str = "Ag";

/// Drawable single-line text field: an optional title, then a framed value.
///
/// Like `embedded_graphics::text::Text`, it is a short-lived view built every frame
/// from the current value.
///
/// When the value is wider than the field, it is scrolled so that its end (where
/// the cursor is) stays visible.
#[derive(Debug, Clone, Copy)]
pub struct TextField<'a, C, S> {
    bounds: Rectangle,
    value: &'a str,
    title: Option<&'a str>,
    show_cursor: bool,
    style: &'a TextFieldStyle<C, S>,
}

impl<'a, C, S> TextField<'a, C, S>
where
    C: PixelColor,
    S: FontStyle<C>,
{
    /// Creates a field occupying `bounds` (title included) showing `value`.
    pub const fn new(bounds: Rectangle, value: &'a str, style: &'a TextFieldStyle<C, S>) -> Self {
        Self {
            bounds,
            value,
            title: None,
            show_cursor: true,
            style,
        }
    }

    /// Displays `title` above the frame.
    pub const fn with_title(mut self, title: &'a str) -> Self {
        self.title = Some(title);
        self
    }

    /// Shows or hides the cursor (e.g. to make it blink).
    pub const fn with_cursor_visible(mut self, visible: bool) -> Self {
        self.show_cursor = visible;
        self
    }

    /// Height taken by the title and its gap (`0` without title).
    fn title_height(&self) -> u32 {
        self.title.map_or(0, |title| {
            self.style.title_font.measure(title).height + self.style.title_gap
        })
    }

    /// Bounds of the frame, i.e. the field minus the title area.
    pub fn frame_bounds(&self) -> Rectangle {
        let title_h = self.title_height().min(self.bounds.size.height);
        Rectangle::new(
            self.bounds.top_left + Point::new(0, title_h as i32),
            Size::new(self.bounds.size.width, self.bounds.size.height - title_h),
        )
    }
}

impl<C, S> Dimensions for TextField<'_, C, S> {
    fn bounding_box(&self) -> Rectangle {
        self.bounds
    }
}

impl<C, S> Drawable for TextField<'_, C, S>
where
    C: PixelColor,
    S: FontStyle<C>,
{
    type Color = C;
    type Output = ();

    fn draw<D: DrawTarget<Color = C>>(&self, target: &mut D) -> Result<(), D::Error> {
        let style = self.style;

        if let Some(title) = self.title {
            style.title_font.draw_anchored(
                target,
                title,
                self.bounds.top_left,
                AnchorPoint::TopLeft,
            )?;
        }

        let frame = self.frame_bounds();
        style.frame.draw(target, frame)?;

        let content = style.frame.content_area(frame);
        let content = Rectangle::new(
            content.top_left + Point::new(style.padding as i32, 0),
            Size::new(
                content.size.width.saturating_sub(2 * style.padding),
                content.size.height,
            ),
        );

        let cursor = style.cursor.filter(|_| self.show_cursor);
        let cursor_w = cursor.map_or(0, |c| c.gap + c.width);
        let text_size = style.font.measure(self.value);

        // Scroll left when the text (plus cursor) overflows, keeping its end visible.
        let overflow = (text_size.width + cursor_w).saturating_sub(content.size.width);
        let text_left = content.top_left.x - overflow as i32;
        let center_y = content.center().y;

        let mut clipped = target.clipped(&content);
        style.font.draw_anchored(
            &mut clipped,
            self.value,
            Point::new(text_left, center_y),
            AnchorPoint::CenterLeft,
        )?;

        if let Some(cursor) = cursor {
            // Measure a reference string so the cursor keeps its height on empty input.
            let height = style
                .font
                .measure(REFERENCE_TEXT)
                .height
                .min(content.size.height);
            let origin = Point::new(
                text_left + (text_size.width + cursor.gap) as i32,
                center_y - (height / 2) as i32,
            );
            Rectangle::new(origin, Size::new(cursor.width, height))
                .into_styled(PrimitiveStyle::with_fill(cursor.color))
                .draw(&mut clipped)?;
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use embedded_graphics::{
        mock_display::MockDisplay,
        mono_font::{MonoTextStyle, ascii::FONT_6X10},
        pixelcolor::BinaryColor,
    };

    const BOUNDS: Rectangle = Rectangle::new(Point::new(2, 2), Size::new(60, 40));

    fn style() -> TextFieldStyle<BinaryColor, MonoTextStyle<'static, BinaryColor>> {
        let font = MonoTextStyle::new(&FONT_6X10, BinaryColor::On);
        TextFieldStyle::new(font, font)
            .with_frame(FrameStyle::new().with_border(BinaryColor::On, 2))
            .with_padding(3)
            .with_cursor(CursorStyle {
                color: BinaryColor::On,
                width: 1,
                gap: 1,
            })
    }

    #[test]
    fn title_sits_above_the_frame() {
        let style = style();
        let field = TextField::new(BOUNDS, "", &style);
        assert_eq!(field.frame_bounds(), BOUNDS);

        let field = field.with_title("Title");
        let frame = field.frame_bounds();
        assert_eq!(frame.top_left.y, BOUNDS.top_left.y + 10 + 4);
        assert_eq!(frame.bottom_right(), BOUNDS.bottom_right());
    }

    #[test]
    fn height_fits_title_text_padding_and_border() {
        let style = style();
        // FONT_6X10 lines are 10 px; padding 3 and border 2 on both sides.
        assert_eq!(style.height(false), 10 + 2 * (3 + 2));
        assert_eq!(style.height(true), 10 + 4 + 10 + 2 * (3 + 2));
    }

    #[test]
    fn long_text_is_clipped_to_the_frame() {
        let style = style();
        let field =
            TextField::new(BOUNDS, "a very long text that overflows", &style).with_title("T");

        let mut display = MockDisplay::new();
        display.set_allow_overdraw(true);
        field.draw(&mut display).unwrap();
        assert!(BOUNDS.contains(display.affected_area().top_left));
        assert!(BOUNDS.contains(display.affected_area().bottom_right().unwrap()));

        // The end of the text and the cursor stay visible: the last content
        // column (just inside the padding) is lit.
        let content = style.frame.content_area(field.frame_bounds());
        let last_x = content.top_left.x + content.size.width as i32 - 1 - 3;
        let lit = (content.top_left.y..content.top_left.y + content.size.height as i32)
            .any(|y| display.get_pixel(Point::new(last_x, y)) == Some(BinaryColor::On));
        assert!(lit);
    }
}