embedded-graphics-keyboard 0.1.2

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 smaller font, shorter [`Labels`](crate::Labels), less spacing or
    /// larger bounds.
    LabelTooLarge(KeyPosition),
}

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(p) => write!(
                f,
                "label of the key at page {}, row {}, column {} does not fit inside the key",
                p.page, p.row, p.col
            ),
        }
    }
}

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

/// Returns `true` when `text_size` fits inside `bounds` minus `padding` on every side.
pub(crate) fn size_fits(text_size: Size, bounds: Rectangle, padding: u32) -> bool {
    let margin = padding.saturating_mul(2);
    text_size.width <= bounds.size.width.saturating_sub(margin)
        && text_size.height <= bounds.size.height.saturating_sub(margin)
}