embedded-graphics-keyboard 0.2.0

no_std on-screen keyboard and text field widgets for embedded-graphics, driven by buttons or touch
Documentation
//! Drawing: key labels and looks, full and partial redraws.

use embedded_graphics::{
    Drawable,
    draw_target::DrawTarget,
    pixelcolor::PixelColor,
    primitives::{Primitive, PrimitiveStyle},
};

use super::{Key, Keyboard, ShiftState};
use crate::{
    layout::{KeyAction, Labels, Layout},
    style::{FontStyle, KeyStyle},
};

/// Upper-cases `c` when it maps to a single character, otherwise returns it unchanged.
pub(super) fn upper(c: char) -> char {
    let mut chars = c.to_uppercase();
    match (chars.next(), chars.next()) {
        (Some(u), None) => u,
        _ => c,
    }
}

/// Text shown on a key.
pub(super) fn label<'b>(
    action: KeyAction,
    shift: ShiftState,
    layout: &Layout,
    labels: &Labels,
    buf: &'b mut [u8; 4],
) -> &'b str {
    match action {
        KeyAction::Char(c) if shift.is_on() => upper(c).encode_utf8(buf),
        KeyAction::Char(c) => c.encode_utf8(buf),
        KeyAction::Shift if shift == ShiftState::Locked => labels.caps_lock,
        KeyAction::Shift => labels.shift,
        KeyAction::Backspace => labels.backspace,
        KeyAction::Space => labels.space,
        KeyAction::Enter => labels.enter,
        KeyAction::Back => labels.back,
        KeyAction::Page(page) => layout.pages.get(page as usize).map_or("", |p| p.label),
    }
}

/// Look of a key, picking its [`KeyStyle`] in the theme.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum KeyLook {
    Idle,
    Selected,
    Pressed,
}

/// The input state that decides what the keyboard looks like.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct Snapshot {
    page: usize,
    shift: ShiftState,
    selected: (usize, usize),
    pressed: Option<(usize, usize)>,
    field_focused: bool,
}

impl Snapshot {
    /// `Pressed` if held down, `Selected` if under the cursor (while the keys
    /// have the focus) or if it is Shift while on, `Idle` otherwise.
    pub(super) fn look_of(&self, key: &Key) -> KeyLook {
        let position = (key.row, key.col);
        if self.pressed == Some(position) {
            KeyLook::Pressed
        } else if (self.selected == position && !self.field_focused)
            || (key.action == KeyAction::Shift && self.shift.is_on())
        {
            KeyLook::Selected
        } else {
            KeyLook::Idle
        }
    }
}

impl<C, S> Keyboard<C, S>
where
    C: PixelColor,
    S: FontStyle<C>,
{
    /// Draws only what changed since the previous call: usually the two keys
    /// whose selection or press state changed.
    ///
    /// Everything is drawn on the first call, after a page or Shift change
    /// (the labels change), after [`Keyboard::set_config`] and after
    /// [`Keyboard::invalidate`].
    ///
    /// `background` is the color behind the keyboard. Keys are erased with it
    /// before being drawn again (or with the fill of the
    /// [`frame`](super::KeyboardConfig::frame), when it has one), except when the new
    /// style fully covers the old one.
    pub fn redraw<D: DrawTarget<Color = C>>(
        &mut self,
        target: &mut D,
        background: C,
    ) -> Result<(), D::Error> {
        let now = self.snapshot();
        let backdrop = self.config.frame.fill_color.unwrap_or(background);
        match self.drawn {
            Some(old) if old == now => {}
            Some(old) if old.page == now.page && old.shift == now.shift => {
                let candidates = [
                    Some(old.selected),
                    Some(now.selected),
                    old.pressed,
                    now.pressed,
                ];
                for (i, &position) in candidates.iter().enumerate() {
                    let Some((row, col)) = position else {
                        continue;
                    };
                    if candidates[..i].contains(&position) {
                        continue;
                    }
                    let key = self.key(row, col);
                    let (before, after) = (old.look_of(&key), now.look_of(&key));
                    if before == after {
                        continue;
                    }
                    let (before, after) = (self.style(before), self.style(after));
                    let covers = after.frame.fill_color.is_some()
                        && after.frame.corner_radius <= before.frame.corner_radius;
                    if !covers {
                        key.bounds
                            .into_styled(PrimitiveStyle::with_fill(backdrop))
                            .draw(target)?;
                    }
                    self.draw_key(target, &key, after)?;
                }
            }
            _ => {
                if self.config.frame.fill_color.is_none() {
                    self.config
                        .bounds
                        .into_styled(PrimitiveStyle::with_fill(background))
                        .draw(target)?;
                }
                self.draw(target)?;
            }
        }
        self.drawn = Some(now);
        Ok(())
    }

    fn draw_key<D: DrawTarget<Color = C>>(
        &self,
        target: &mut D,
        key: &Key,
        style: &KeyStyle<C, S>,
    ) -> Result<(), D::Error> {
        let config = &self.config;
        let mut buf = [0; 4];
        let text = label(
            key.action,
            self.shift,
            &config.layout,
            &config.labels,
            &mut buf,
        );
        style.frame.draw(target, key.bounds)?;
        style.font.draw_centered(target, text, key.bounds.center())
    }
}

impl<C, S> Keyboard<C, S> {
    pub(super) fn snapshot(&self) -> Snapshot {
        Snapshot {
            page: self.page,
            shift: self.shift,
            selected: self.selected,
            pressed: self.pressed,
            field_focused: self.field_focused,
        }
    }

    fn style(&self, look: KeyLook) -> &KeyStyle<C, S> {
        let theme = &self.config.theme;
        match look {
            KeyLook::Idle => &theme.idle,
            KeyLook::Selected => &theme.selected,
            KeyLook::Pressed => &theme.pressed,
        }
    }
}

impl<C, S> Drawable for Keyboard<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> {
        self.config.frame.draw(target, self.config.bounds)?;
        let now = self.snapshot();
        for key in self.keys() {
            self.draw_key(target, &key, self.style(now.look_of(&key)))?;
        }
        Ok(())
    }
}