embedded-graphics-keyboard 0.1.3

no_std on-screen keyboard and text field widgets for embedded-graphics, driven by buttons or touch
Documentation
//! Configuration errors.

use core::fmt;

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

/// Position of a key in a [`Layout`](crate::Layout).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct KeyPosition {
    /// Index of the page.
    pub page: usize,
    /// Index of the row in the page.
    pub row: usize,
    /// Index of the key in the row.
    pub col: usize,
}

/// Invalid [`KeyboardConfig`](crate::KeyboardConfig), detected by
/// [`Keyboard::new`](crate::Keyboard::new).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ConfigError {
    /// The layout has no page, a page has no row, or a row has no key.
    EmptyLayout,
    /// A [`KeyAction::Page`](crate::KeyAction::Page) key points past the last page.
    InvalidPage(KeyPosition),
    /// A key label does not fit inside its key once the key padding is removed.
    ///
    /// Use a font whose glyphs are at most `max` pixels, shorter
    /// [`Labels`](crate::Labels), less spacing or padding, or larger bounds.
    LabelTooLarge {
        /// Key whose label does not fit.
        position: KeyPosition,
        /// Size of the label, in pixels, with the largest font of the theme.
        size: Size,
        /// Largest label that fits inside this key: its size minus the key padding.
        max: Size,
    },
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyLayout => f.write_str("the layout has an empty page or row"),
            Self::InvalidPage(p) => write!(
                f,
                "key at page {}, row {}, column {} points to a missing page",
                p.page, p.row, p.col
            ),
            Self::LabelTooLarge {
                position: p,
                size,
                max,
            } => write!(
                f,
                "label of the key at page {}, row {}, column {} is {}x{} px, \
                 but at most {}x{} px fit inside the key",
                p.page, p.row, p.col, size.width, size.height, max.width, max.height
            ),
        }
    }
}

impl core::error::Error for ConfigError {}

/// Largest text that fits inside `bounds` minus `padding` on every side.
pub(crate) fn max_label_size(bounds: Rectangle, padding: u32) -> Size {
    let margin = padding.saturating_mul(2);
    Size::new(
        bounds.size.width.saturating_sub(margin),
        bounds.size.height.saturating_sub(margin),
    )
}