embedded-graphics-keyboard 0.2.1

no_std on-screen keyboard and text field widgets for embedded-graphics, driven by buttons or touch
Documentation
//! On-screen keyboard widget: input handling and state.

mod config;
mod grid;
mod render;
#[cfg(test)]
mod tests;

use embedded_graphics::{
    geometry::{Dimensions, Point},
    pixelcolor::PixelColor,
    primitives::Rectangle,
};

pub use config::KeyboardConfig;
use grid::Grid;
use render::{Snapshot, upper};

use crate::{
    error::ConfigError,
    layout::{KeyAction, KeyEvent, Page},
    style::FontStyle,
};

/// Physical inputs used to drive the keyboard with buttons.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NavButton {
    /// Moves the selection to the row above, wrapping around.
    ///
    /// On the first row, with [`KeyboardConfig::field_navigation`], moves the
    /// focus to the text field instead.
    Up,
    /// Moves the selection to the row below, wrapping around.
    ///
    /// When the text field has the focus, gives it back to the keys.
    Down,
    /// Moves the selection to the previous key of the row, wrapping around.
    ///
    /// When the text field has the focus, emits [`KeyEvent::CursorLeft`].
    Left,
    /// Moves the selection to the next key of the row, wrapping around.
    ///
    /// When the text field has the focus, emits [`KeyEvent::CursorRight`].
    Right,
    /// Presses the selected key.
    ///
    /// When the text field has the focus, gives it back to the keys.
    Validate,
}

/// State of the Shift key.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ShiftState {
    /// Lower case.
    #[default]
    Off,
    /// Upper case for the next character only.
    Once,
    /// Caps lock: upper case until Shift is pressed again.
    Locked,
}

impl ShiftState {
    const fn next(self) -> Self {
        match self {
            Self::Off => Self::Once,
            Self::Once => Self::Locked,
            Self::Locked => Self::Off,
        }
    }

    const fn is_on(self) -> bool {
        !matches!(self, Self::Off)
    }
}

/// A key of the current page, with its on-screen bounds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Key {
    /// Index of the row in the page.
    pub row: usize,
    /// Index of the key in the row.
    pub col: usize,
    /// What the key does.
    pub action: KeyAction,
    /// Area covered by the key.
    pub bounds: Rectangle,
}

/// Stateful on-screen keyboard driven by navigation buttons and/or touch.
///
/// Two ways to draw it:
/// - [`Keyboard::redraw`] draws only the keys whose look changed since the
///   previous call: use it on real displays, where every pixel sent costs time.
/// - [`Drawable::draw`](embedded_graphics::Drawable::draw) draws everything, for a display (or a frame buffer)
///   cleared every frame.
#[derive(Debug, Clone)]
pub struct Keyboard<C, S> {
    config: KeyboardConfig<C, S>,
    grid: Grid,
    page: usize,
    shift: ShiftState,
    selected: (usize, usize),
    pressed: Option<(usize, usize)>,
    /// `true` while the text field has the focus (see [`KeyboardConfig::field_navigation`]).
    field_focused: bool,
    /// State shown on the display by the last [`Keyboard::redraw`], if still valid.
    drawn: Option<Snapshot>,
}

impl<C, S> Keyboard<C, S>
where
    C: PixelColor,
    S: FontStyle<C>,
{
    /// Creates a keyboard, checking that the layout is valid and that every label
    /// fits inside its key with the font of every state.
    ///
    /// # Errors
    ///
    /// - [`ConfigError::EmptyLayout`] if the layout, a page or a row is empty.
    /// - [`ConfigError::InvalidPage`] if a [`KeyAction::Page`] key points past the last page.
    /// - [`ConfigError::LabelTooLarge`] if a label does not fit inside its key.
    pub fn new(config: KeyboardConfig<C, S>) -> Result<Self, ConfigError> {
        let grid = config.validate()?;
        Ok(Self {
            config,
            grid,
            page: 0,
            shift: ShiftState::Off,
            selected: (0, 0),
            pressed: None,
            field_focused: false,
            drawn: None,
        })
    }

    /// Replaces the configuration (bounds, layout, theme…).
    ///
    /// On success the input state is kept (except the pressed key, released),
    /// unless the current page no longer exists, and the next
    /// [`Keyboard::redraw`] draws everything; on error nothing changes.
    ///
    /// # Errors
    ///
    /// Same as [`Keyboard::new`].
    pub fn set_config(&mut self, config: KeyboardConfig<C, S>) -> Result<(), ConfigError> {
        self.grid = config.validate()?;
        let on_action_row = self.on_action_row();
        self.config = config;
        self.drawn = None;
        // The held key may not exist in the new layout.
        self.pressed = None;
        self.field_focused &= self.config.field_navigation;
        if self.page >= self.config.layout.pages.len() {
            self.reset();
        } else {
            self.clamp_selection(on_action_row);
        }
        Ok(())
    }
}

impl<C, S> Keyboard<C, S> {
    /// Makes the next [`Keyboard::redraw`] draw everything, e.g. after the
    /// display was cleared or drawn over.
    pub fn invalidate(&mut self) {
        self.drawn = None;
    }

    /// Current configuration.
    #[must_use]
    pub const fn config(&self) -> &KeyboardConfig<C, S> {
        &self.config
    }

    /// Index of the page currently shown.
    #[must_use]
    pub const fn page(&self) -> usize {
        self.page
    }

    /// State of the Shift key.
    #[must_use]
    pub const fn shift_state(&self) -> ShiftState {
        self.shift
    }

    /// Back to the first page, Shift off, first key selected, focus on the keys.
    pub fn reset(&mut self) {
        self.page = 0;
        self.shift = ShiftState::Off;
        self.selected = (0, 0);
        self.pressed = None;
        self.field_focused = false;
    }

    /// `true` when the text field has the focus rather than the keys.
    ///
    /// The field gets it with [`NavButton::Up`] from the first row, when
    /// [`KeyboardConfig::field_navigation`] is enabled; no key is shown
    /// selected meanwhile. Use it to highlight the field.
    #[must_use]
    pub const fn is_field_focused(&self) -> bool {
        self.field_focused
    }

    /// Gives the focus to the text field (`true`) or to the keys (`false`),
    /// e.g. when the field is touched.
    ///
    /// Ignored when [`KeyboardConfig::field_navigation`] is disabled.
    pub fn set_field_focused(&mut self, focused: bool) {
        self.field_focused = focused && self.config.field_navigation;
        self.pressed = None;
    }

    fn current_page(&self) -> &Page {
        &self.config.layout.pages[self.page]
    }

    /// The key under the navigation cursor.
    #[must_use]
    pub fn selected_key(&self) -> Key {
        self.key(self.selected.0, self.selected.1)
    }

    /// Iterates over the keys of the current page.
    pub fn keys(&self) -> impl Iterator<Item = Key> + '_ {
        let rows = self.current_page().rows;
        rows.iter()
            .enumerate()
            .flat_map(move |(row, keys)| (0..keys.len()).map(move |col| self.key(row, col)))
    }

    /// Rectangle actually covered by the keys.
    ///
    /// It can be a few pixels smaller than the configured area, since every key
    /// has the same integer size: use it to align other widgets with the keys.
    #[must_use]
    pub fn keys_bounds(&self) -> Rectangle {
        self.grid.bounds()
    }

    fn key(&self, row: usize, col: usize) -> Key {
        let page = self.current_page();
        Key {
            row,
            col,
            action: page.rows[row][col],
            bounds: self.grid.key_rect(page, row, col),
        }
    }

    /// Handles a navigation button.
    ///
    /// Returns an event when `Validate` presses a key that emits one (see
    /// [`KeyEvent`]), or when `Left` / `Right` move the cursor of the focused
    /// text field.
    pub fn handle_button(&mut self, button: NavButton) -> Option<KeyEvent> {
        self.pressed = None;
        if self.field_focused {
            return match button {
                NavButton::Left => Some(KeyEvent::CursorLeft),
                NavButton::Right => Some(KeyEvent::CursorRight),
                NavButton::Down | NavButton::Validate => {
                    self.field_focused = false;
                    None
                }
                NavButton::Up => None,
            };
        }

        let (row, col) = self.selected;
        let rows = self.current_page().rows;
        let cols = rows[row].len();
        match button {
            NavButton::Left => self.selected.1 = (col + cols - 1) % cols,
            NavButton::Right => self.selected.1 = (col + 1) % cols,
            NavButton::Up if row == 0 && self.config.field_navigation => {
                self.field_focused = true;
            }
            NavButton::Up => self.move_to_row((row + rows.len() - 1) % rows.len()),
            NavButton::Down => self.move_to_row((row + 1) % rows.len()),
            NavButton::Validate => return self.press(rows[row][col]),
        }
        None
    }

    /// Handles a touch at `point`: selects and presses the key under it, if any,
    /// giving the focus back to the keys.
    pub fn handle_touch(&mut self, point: Point) -> Option<KeyEvent> {
        let Some(key) = self.keys().find(|key| key.bounds.contains(point)) else {
            self.pressed = None;
            return None;
        };
        self.field_focused = false;
        self.selected = (key.row, key.col);
        self.press(key.action)
    }

    /// Releases the pressed key (button or touch released).
    ///
    /// Events are emitted on press only: the keyboard has no clock, so key
    /// repeat (e.g. holding Backspace) is up to the application, which can call
    /// [`Keyboard::handle_button`] again while the button is held.
    pub fn release(&mut self) {
        self.pressed = None;
    }

    /// Moves the selection to `row`, on the key horizontally closest to the current one.
    fn move_to_row(&mut self, row: usize) {
        let x = self.selected_key().bounds.center().x;
        let page = self.current_page();
        let col = (0..page.rows[row].len())
            .min_by_key(|&col| (self.grid.key_rect(page, row, col).center().x - x).abs())
            .unwrap_or(0);
        self.selected = (row, col);
    }

    fn on_action_row(&self) -> bool {
        self.selected.0 + 1 == self.current_page().rows.len()
    }

    /// Keeps the selection on an existing key after a page or layout change:
    /// the action row stays the action row, a letter row stays a letter row.
    fn clamp_selection(&mut self, on_action_row: bool) {
        let rows = self.current_page().rows;
        let last = rows.len() - 1;
        let (row, col) = self.selected;
        let row = if on_action_row {
            last
        } else {
            row.min(last.saturating_sub(1))
        };
        self.selected = (row, col.min(rows[row].len() - 1));
    }

    fn press(&mut self, action: KeyAction) -> Option<KeyEvent> {
        let output = match action {
            KeyAction::Shift => {
                self.shift = self.shift.next();
                None
            }
            KeyAction::Page(page) => {
                let on_action_row = self.on_action_row();
                self.page = page as usize;
                self.clamp_selection(on_action_row);
                None
            }
            KeyAction::Char(c) if self.shift.is_on() => {
                if self.shift == ShiftState::Once {
                    self.shift = ShiftState::Off;
                }
                Some(KeyEvent::Char(upper(c)))
            }
            KeyAction::Char(c) => Some(KeyEvent::Char(c)),
            KeyAction::Space => Some(KeyEvent::Char(' ')),
            KeyAction::Backspace => Some(KeyEvent::Backspace),
            KeyAction::Enter => Some(KeyEvent::Enter),
            KeyAction::Back => Some(KeyEvent::Back),
        };
        self.pressed = Some(self.selected);
        output
    }
}

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