embedded-graphics-keyboard 0.2.0

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

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

use crate::layout::{Layout, Page};

/// Key geometry shared by every page of a layout.
///
/// All pages use the same grid, so switching page never changes the key size.
#[derive(Debug, Clone, Copy)]
pub(super) struct Grid {
    /// Top-left corner of the grid.
    pub(super) origin: Point,
    /// Width of the widest row (= width of the action rows).
    pub(super) width: u32,
    pub(super) height: u32,
    pub(super) key_size: Size,
    pub(super) spacing: u32,
    pub(super) rows: u32,
}

impl Grid {
    /// Fits the largest grid of same-sized keys for `layout` inside `area`, centered.
    ///
    /// The integer key size may leave a few pixels unused (fewer than one per
    /// column or row): they are split evenly on both sides.
    pub(super) fn new(layout: &Layout, area: Rectangle, spacing: u32) -> Self {
        let pages = layout.pages.iter();
        let rows = pages
            .clone()
            .map(|p| p.rows.len())
            .max()
            .unwrap_or(0)
            .max(1) as u32;
        let columns = pages
            .flat_map(|p| p.rows.split_last().map_or(&[][..], |(_, rows)| rows))
            .map(|row| row.len())
            .max()
            .unwrap_or(0)
            .max(1) as u32;

        let inner_w = area.size.width.saturating_sub(spacing * (columns - 1));
        let inner_h = area.size.height.saturating_sub(spacing * (rows - 1));
        let key_size = Size::new(inner_w / columns, inner_h / rows);

        let width = key_size.width * columns + spacing * (columns - 1);
        let height = key_size.height * rows + spacing * (rows - 1);
        let origin = area.top_left
            + Point::new(
                (area.size.width.saturating_sub(width) / 2) as i32,
                (area.size.height.saturating_sub(height) / 2) as i32,
            );

        Self {
            origin,
            width,
            height,
            key_size,
            spacing,
            rows,
        }
    }

    pub(super) fn bounds(&self) -> Rectangle {
        Rectangle::new(self.origin, Size::new(self.width, self.height))
    }

    /// Bounds of the key at `row`, `col` of `page`.
    ///
    /// Regular rows are centered; the action row (last row of the page) is always
    /// drawn on the bottom grid row and spans the full grid width.
    pub(super) fn key_rect(&self, page: &Page, row: usize, col: usize) -> Rectangle {
        let is_action_row = row + 1 == page.rows.len();
        let grid_row = if is_action_row {
            self.rows - 1
        } else {
            row as u32
        };
        let y = self.origin.y + (grid_row * (self.key_size.height + self.spacing)) as i32;

        if is_action_row {
            // Edges come from cumulative weights so rounding never leaves a gap.
            let keys = page.rows[row];
            let total: u32 = keys.iter().map(|k| k.weight()).sum();
            let available = self
                .width
                .saturating_sub(self.spacing * (keys.len() as u32 - 1));
            let edge = |c: usize| {
                let weight: u32 = keys[..c].iter().map(|k| k.weight()).sum();
                available * weight / total
            };
            let (start, end) = (edge(col), edge(col + 1));
            let x = self.origin.x + (start + col as u32 * self.spacing) as i32;
            Rectangle::new(
                Point::new(x, y),
                Size::new(end - start, self.key_size.height),
            )
        } else {
            let step = self.key_size.width + self.spacing;
            let count = page.rows[row].len() as u32;
            let row_w = (step * count).saturating_sub(self.spacing);
            let offset = self.width.saturating_sub(row_w) / 2 + col as u32 * step;
            Rectangle::new(Point::new(self.origin.x + offset as i32, y), self.key_size)
        }
    }
}