embedded-graphics-keyboard 0.2.0

no_std on-screen keyboard and text field widgets for embedded-graphics, driven by buttons or touch
Documentation
//! Keyboard configuration and its validation.

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

use super::{ShiftState, grid::Grid, render::label};
use crate::{
    error::{ConfigError, KeyPosition, max_label_size},
    layout::{KeyAction, Labels, Layout, Page},
    style::{FontStyle, FrameStyle, KeyboardTheme},
};

/// Configuration of a [`Keyboard`](super::Keyboard).
///
/// `S` is the font type, see [`FontStyle`].
#[derive(Debug, Clone, Copy)]
pub struct KeyboardConfig<C, S> {
    /// Area allocated to the keyboard.
    pub bounds: Rectangle,
    /// Look of the keys.
    pub theme: KeyboardTheme<C, S>,
    /// Keys and pages.
    pub layout: Layout,
    /// Labels of the control keys.
    pub labels: Labels,
    /// Gap in pixels between adjacent keys.
    pub spacing: u32,
    /// Margin in pixels between the frame (or the bounds) and the keys.
    pub padding: u32,
    /// Minimum margin in pixels kept around each key label.
    pub key_padding: u32,
    /// Frame drawn behind the keys (invisible by default).
    pub frame: FrameStyle<C>,
    /// When `true`, [`NavButton::Up`](super::NavButton::Up) on the first row moves the focus to the
    /// text field above the keyboard instead of wrapping to the last row.
    ///
    /// See [`Keyboard::is_field_focused`](super::Keyboard::is_field_focused).
    pub field_navigation: bool,
}

impl<C: PixelColor, S> KeyboardConfig<C, S> {
    /// Creates a configuration with the QWERTY layout, default labels,
    /// `spacing = 4`, `padding = 0`, `key_padding = 2` and no frame: the keys
    /// then span the whole width of `bounds`.
    pub const fn new(bounds: Rectangle, theme: KeyboardTheme<C, S>) -> Self {
        Self {
            bounds,
            theme,
            layout: Layout::QWERTY,
            labels: Labels::DEFAULT,
            spacing: 4,
            padding: 0,
            key_padding: 2,
            frame: FrameStyle::new(),
            field_navigation: false,
        }
    }

    /// Sets the layout.
    pub const fn with_layout(mut self, layout: Layout) -> Self {
        self.layout = layout;
        self
    }

    /// Sets the labels of the control keys.
    pub const fn with_labels(mut self, labels: Labels) -> Self {
        self.labels = labels;
        self
    }

    /// Sets the gap between keys.
    pub const fn with_spacing(mut self, spacing: u32) -> Self {
        self.spacing = spacing;
        self
    }

    /// Sets the margin between the frame (or the bounds) and the keys.
    pub const fn with_padding(mut self, padding: u32) -> Self {
        self.padding = padding;
        self
    }

    /// Sets the minimum margin around key labels.
    pub const fn with_key_padding(mut self, key_padding: u32) -> Self {
        self.key_padding = key_padding;
        self
    }

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

    /// Enables or disables moving the focus to the text field with
    /// [`NavButton::Up`](super::NavButton::Up) from the first row.
    pub const fn with_field_navigation(mut self, enabled: bool) -> Self {
        self.field_navigation = enabled;
        self
    }

    /// Area in which the keys are laid out: the bounds minus the frame border and padding.
    pub(super) fn keys_area(&self) -> Rectangle {
        self.frame
            .content_area(self.bounds)
            .offset(-(self.padding as i32))
    }
}

impl<C: PixelColor, S: FontStyle<C>> KeyboardConfig<C, S> {
    /// Checks that the layout is valid and that every label fits inside its key
    /// with the font of every state, and returns the key grid.
    pub(super) fn validate(&self) -> Result<Grid, ConfigError> {
        let config = self;
        let layout = &config.layout;
        let has_empty =
            |page: &Page| page.rows.is_empty() || page.rows.iter().any(|r| r.is_empty());
        if layout.pages.is_empty() || layout.pages.iter().any(has_empty) {
            return Err(ConfigError::EmptyLayout);
        }

        let grid = Grid::new(layout, config.keys_area(), config.spacing);
        let mut buf = [0; 4];
        for (page_idx, page) in layout.pages.iter().enumerate() {
            for (row, keys) in page.rows.iter().enumerate() {
                for (col, &action) in keys.iter().enumerate() {
                    let position = KeyPosition {
                        page: page_idx,
                        row,
                        col,
                    };
                    let pages = layout.pages.len();
                    if matches!(action, KeyAction::Page(target) if target as usize >= pages) {
                        return Err(ConfigError::InvalidPage(position));
                    }

                    let max = max_label_size(grid.key_rect(page, row, col), config.key_padding);
                    let mut size = Size::zero();
                    for shift in [ShiftState::Off, ShiftState::Locked] {
                        let text = label(action, shift, layout, &config.labels, &mut buf);
                        for style in config.theme.styles() {
                            size = size.component_max(style.font.measure(text));
                        }
                    }
                    if size.width > max.width || size.height > max.height {
                        return Err(ConfigError::LabelTooLarge {
                            position,
                            size,
                            max,
                        });
                    }
                }
            }
        }
        Ok(grid)
    }
}