embedded-graphics-keyboard 0.1.3

no_std on-screen keyboard and text field widgets for embedded-graphics, driven by buttons or touch
Documentation
//! Font adapters, frames and keyboard themes.

use embedded_graphics::{
    Drawable,
    draw_target::DrawTarget,
    geometry::{AnchorPoint, Point, Size},
    mono_font::MonoTextStyle,
    pixelcolor::PixelColor,
    primitives::{
        Primitive, PrimitiveStyle, PrimitiveStyleBuilder, Rectangle, RoundedRectangle,
        StrokeAlignment,
    },
    text::{Baseline, Text, TextStyleBuilder, renderer::TextRenderer},
};

/// Font backend abstraction shared by every widget of this crate.
///
/// Implemented for [`MonoTextStyle`] and, with the `glyphix` feature, for
/// `embedded_graphics_glyphix::GlyphixStyle`.
pub trait FontStyle<C: PixelColor> {
    /// Returns the size of the bounding box of `text`.
    fn measure(&self, text: &str) -> Size;

    /// Draws `text` so that its `anchor` point lands on `position`.
    fn draw_anchored<D: DrawTarget<Color = C>>(
        &self,
        target: &mut D,
        text: &str,
        position: Point,
        anchor: AnchorPoint,
    ) -> Result<(), D::Error>;

    /// Draws `text` centered on `center`.
    fn draw_centered<D: DrawTarget<Color = C>>(
        &self,
        target: &mut D,
        text: &str,
        center: Point,
    ) -> Result<(), D::Error> {
        self.draw_anchored(target, text, center, AnchorPoint::Center)
    }
}

impl<C: PixelColor> FontStyle<C> for MonoTextStyle<'_, C> {
    fn measure(&self, text: &str) -> Size {
        self.measure_string(text, Point::zero(), Baseline::Top)
            .bounding_box
            .size
    }

    fn draw_anchored<D: DrawTarget<Color = C>>(
        &self,
        target: &mut D,
        text: &str,
        position: Point,
        anchor: AnchorPoint,
    ) -> Result<(), D::Error> {
        let offset = Rectangle::new(Point::zero(), self.measure(text)).anchor_point(anchor);
        let style = TextStyleBuilder::new().baseline(Baseline::Top).build();
        Text::with_text_style(text, position - offset, *self, style)
            .draw(target)
            .map(drop)
    }
}

#[cfg(feature = "glyphix")]
impl<C: PixelColor> FontStyle<C> for embedded_graphics_glyphix::GlyphixStyle<'_, C> {
    fn measure(&self, text: &str) -> Size {
        embedded_graphics_glyphix::GlyphixStyle::measure(self, text)
    }

    fn draw_anchored<D: DrawTarget<Color = C>>(
        &self,
        target: &mut D,
        text: &str,
        position: Point,
        anchor: AnchorPoint,
    ) -> Result<(), D::Error> {
        embedded_graphics_glyphix::GlyphixStyle::draw_anchored(self, target, text, position, anchor)
    }
}

/// Visual style of a rectangular frame: background, border and rounded corners.
///
/// The border is drawn *inside* the frame bounds, so a frame never paints outside
/// the rectangle it is given.
///
/// ```
/// # use embedded_graphics::pixelcolor::Rgb565;
/// # use embedded_graphics::prelude::*;
/// # use embedded_graphics_keyboard::FrameStyle;
/// let frame = FrameStyle::new()
///     .with_fill(Rgb565::BLACK)
///     .with_border(Rgb565::WHITE, 2)
///     .with_corner_radius(6);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct FrameStyle<C> {
    /// Background color, or `None` for a transparent frame.
    pub fill_color: Option<C>,
    /// Border color, or `None` for no border.
    pub border_color: Option<C>,
    /// Border thickness in pixels.
    pub border_width: u32,
    /// Corner radius in pixels (`0` for square corners).
    pub corner_radius: u32,
}

impl<C: PixelColor> FrameStyle<C> {
    /// Creates an invisible frame (no fill, no border, square corners).
    pub const fn new() -> Self {
        Self {
            fill_color: None,
            border_color: None,
            border_width: 0,
            corner_radius: 0,
        }
    }

    /// Sets the background color.
    pub const fn with_fill(mut self, color: C) -> Self {
        self.fill_color = Some(color);
        self
    }

    /// Sets the border color and thickness.
    pub const fn with_border(mut self, color: C, width: u32) -> Self {
        self.border_color = Some(color);
        self.border_width = width;
        self
    }

    /// Sets the corner radius.
    pub const fn with_corner_radius(mut self, radius: u32) -> Self {
        self.corner_radius = radius;
        self
    }

    /// Width actually taken by the border (`0` when there is no border).
    pub const fn effective_border_width(&self) -> u32 {
        if self.border_color.is_some() {
            self.border_width
        } else {
            0
        }
    }

    /// Returns `bounds` shrunk by the border width: the area left for content.
    pub fn content_area(&self, bounds: Rectangle) -> Rectangle {
        bounds.offset(-(self.effective_border_width() as i32))
    }

    fn primitive_style(&self) -> PrimitiveStyle<C> {
        let mut builder = PrimitiveStyleBuilder::new().stroke_alignment(StrokeAlignment::Inside);
        if let Some(fill) = self.fill_color {
            builder = builder.fill_color(fill);
        }
        if let Some(border) = self.border_color {
            builder = builder.stroke_color(border).stroke_width(self.border_width);
        }
        builder.build()
    }

    /// Draws the frame into `bounds`.
    pub fn draw<D: DrawTarget<Color = C>>(
        &self,
        target: &mut D,
        bounds: Rectangle,
    ) -> Result<(), D::Error> {
        if self.fill_color.is_none() && self.effective_border_width() == 0 {
            return Ok(());
        }

        let style = self.primitive_style();
        if self.corner_radius > 0 {
            let radius = Size::new_equal(self.corner_radius);
            RoundedRectangle::with_equal_corners(bounds, radius)
                .into_styled(style)
                .draw(target)
        } else {
            bounds.into_styled(style).draw(target)
        }
    }
}

/// Look of a key in one interaction state: its frame and the font of its label.
///
/// The font carries the text color, so each state can use a different one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KeyStyle<C, S> {
    /// Background, border and corners of the key.
    pub frame: FrameStyle<C>,
    /// Font (and color) of the label.
    pub font: S,
}

impl<C: PixelColor, S> KeyStyle<C, S> {
    /// Creates a style with `font` and an invisible frame.
    pub const fn new(font: S) -> Self {
        Self {
            frame: FrameStyle::new(),
            font,
        }
    }

    /// Sets the font.
    pub fn with_font(mut self, font: S) -> Self {
        self.font = font;
        self
    }

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

    /// Sets the background color.
    pub fn with_fill(mut self, color: C) -> Self {
        self.frame = self.frame.with_fill(color);
        self
    }

    /// Sets the border color and thickness.
    pub fn with_border(mut self, color: C, width: u32) -> Self {
        self.frame = self.frame.with_border(color, width);
        self
    }

    /// Sets the corner radius.
    pub fn with_corner_radius(mut self, radius: u32) -> Self {
        self.frame = self.frame.with_corner_radius(radius);
        self
    }
}

/// Look of the keys, one [`KeyStyle`] per interaction state.
///
/// Derive the other states from `idle` so they only differ where needed:
///
/// ```
/// # use embedded_graphics::{mono_font::{ascii::FONT_10X20, MonoTextStyle}, pixelcolor::Rgb565, prelude::*};
/// # use embedded_graphics_keyboard::{KeyStyle, KeyboardTheme};
/// let idle = KeyStyle::new(MonoTextStyle::new(&FONT_10X20, Rgb565::WHITE))
///     .with_fill(Rgb565::CSS_DARK_SLATE_GRAY)
///     .with_border(Rgb565::CSS_GRAY, 1)
///     .with_corner_radius(8);
/// let dark_text = MonoTextStyle::new(&FONT_10X20, Rgb565::BLACK);
///
/// let theme = KeyboardTheme {
///     idle,
///     selected: idle.with_fill(Rgb565::CSS_DODGER_BLUE).with_font(dark_text),
///     pressed: idle.with_fill(Rgb565::WHITE).with_font(dark_text),
/// };
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KeyboardTheme<C, S> {
    /// Key at rest.
    pub idle: KeyStyle<C, S>,
    /// Key under the navigation cursor, or Shift while it is on.
    pub selected: KeyStyle<C, S>,
    /// Key held down.
    pub pressed: KeyStyle<C, S>,
}

impl<C, S> KeyboardTheme<C, S> {
    /// Iterates over the three styles.
    pub(crate) fn styles(&self) -> [&KeyStyle<C, S>; 3] {
        [&self.idle, &self.selected, &self.pressed]
    }
}