use embedded_graphics::{
Drawable,
draw_target::DrawTarget,
geometry::{Dimensions, Point, Size},
pixelcolor::PixelColor,
primitives::{Primitive, PrimitiveStyle, Rectangle},
};
use crate::{
error::{ConfigError, KeyPosition, max_label_size},
layout::{KeyAction, KeyEvent, Labels, Layout, Page},
style::{FontStyle, FrameStyle, KeyStyle, KeyboardTheme},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NavButton {
Up,
Down,
Left,
Right,
Validate,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ShiftState {
#[default]
Off,
Once,
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)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Key {
pub row: usize,
pub col: usize,
pub action: KeyAction,
pub bounds: Rectangle,
}
#[derive(Debug, Clone, Copy)]
pub struct KeyboardConfig<C, S> {
pub bounds: Rectangle,
pub theme: KeyboardTheme<C, S>,
pub layout: Layout,
pub labels: Labels,
pub spacing: u32,
pub padding: u32,
pub key_padding: u32,
pub frame: FrameStyle<C>,
}
impl<C: PixelColor, S> KeyboardConfig<C, S> {
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(),
}
}
pub const fn with_layout(mut self, layout: Layout) -> Self {
self.layout = layout;
self
}
pub const fn with_labels(mut self, labels: Labels) -> Self {
self.labels = labels;
self
}
pub const fn with_spacing(mut self, spacing: u32) -> Self {
self.spacing = spacing;
self
}
pub const fn with_padding(mut self, padding: u32) -> Self {
self.padding = padding;
self
}
pub const fn with_key_padding(mut self, key_padding: u32) -> Self {
self.key_padding = key_padding;
self
}
pub const fn with_frame(mut self, frame: FrameStyle<C>) -> Self {
self.frame = frame;
self
}
fn keys_area(&self) -> Rectangle {
self.frame
.content_area(self.bounds)
.offset(-(self.padding as i32))
}
}
#[derive(Debug, Clone, Copy)]
struct Grid {
origin: Point,
width: u32,
height: u32,
key_size: Size,
spacing: u32,
rows: u32,
}
impl Grid {
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,
}
}
fn bounds(&self) -> Rectangle {
Rectangle::new(self.origin, Size::new(self.width, self.height))
}
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 {
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)
}
}
}
fn upper(c: char) -> char {
let mut chars = c.to_uppercase();
match (chars.next(), chars.next()) {
(Some(u), None) => u,
_ => c,
}
}
fn label<'b>(
action: KeyAction,
shift: ShiftState,
layout: &Layout,
labels: &Labels,
buf: &'b mut [u8; 4],
) -> &'b str {
match action {
KeyAction::Char(c) if shift.is_on() => upper(c).encode_utf8(buf),
KeyAction::Char(c) => c.encode_utf8(buf),
KeyAction::Shift if shift == ShiftState::Locked => labels.caps_lock,
KeyAction::Shift => labels.shift,
KeyAction::Backspace => labels.backspace,
KeyAction::Space => labels.space,
KeyAction::Enter => labels.enter,
KeyAction::Back => labels.back,
KeyAction::Page(page) => layout.pages.get(page as usize).map_or("", |p| p.label),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum KeyLook {
Idle,
Selected,
Pressed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Snapshot {
page: usize,
shift: ShiftState,
selected: (usize, usize),
pressed: Option<(usize, usize)>,
}
impl Snapshot {
fn look_of(&self, key: &Key) -> KeyLook {
let position = (key.row, key.col);
if self.pressed == Some(position) {
KeyLook::Pressed
} else if self.selected == position
|| (key.action == KeyAction::Shift && self.shift.is_on())
{
KeyLook::Selected
} else {
KeyLook::Idle
}
}
}
#[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)>,
drawn: Option<Snapshot>,
}
impl<C, S> Keyboard<C, S>
where
C: PixelColor,
S: FontStyle<C>,
{
pub fn new(config: KeyboardConfig<C, S>) -> Result<Self, ConfigError> {
let grid = Self::validate(&config)?;
Ok(Self {
config,
grid,
page: 0,
shift: ShiftState::Off,
selected: (0, 0),
pressed: None,
drawn: None,
})
}
pub fn set_config(&mut self, config: KeyboardConfig<C, S>) -> Result<(), ConfigError> {
self.grid = Self::validate(&config)?;
let on_action_row = self.on_action_row();
self.config = config;
self.drawn = None;
if self.page >= self.config.layout.pages.len() {
self.reset();
} else {
self.clamp_selection(on_action_row);
}
Ok(())
}
fn validate(config: &KeyboardConfig<C, S>) -> Result<Grid, ConfigError> {
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)
}
}
impl<C, S> Keyboard<C, S>
where
C: PixelColor,
S: FontStyle<C>,
{
pub fn redraw<D: DrawTarget<Color = C>>(
&mut self,
target: &mut D,
background: C,
) -> Result<(), D::Error> {
let now = self.snapshot();
let backdrop = self.config.frame.fill_color.unwrap_or(background);
match self.drawn {
Some(old) if old == now => {}
Some(old) if old.page == now.page && old.shift == now.shift => {
let candidates = [
Some(old.selected),
Some(now.selected),
old.pressed,
now.pressed,
];
for (i, &position) in candidates.iter().enumerate() {
let Some((row, col)) = position else {
continue;
};
if candidates[..i].contains(&position) {
continue;
}
let key = self.key(row, col);
let (before, after) = (old.look_of(&key), now.look_of(&key));
if before == after {
continue;
}
let (before, after) = (self.style(before), self.style(after));
let covers = after.frame.fill_color.is_some()
&& after.frame.corner_radius <= before.frame.corner_radius;
if !covers {
key.bounds
.into_styled(PrimitiveStyle::with_fill(backdrop))
.draw(target)?;
}
self.draw_key(target, &key, after)?;
}
}
_ => {
if self.config.frame.fill_color.is_none() {
self.config
.bounds
.into_styled(PrimitiveStyle::with_fill(background))
.draw(target)?;
}
self.draw(target)?;
}
}
self.drawn = Some(now);
Ok(())
}
fn draw_key<D: DrawTarget<Color = C>>(
&self,
target: &mut D,
key: &Key,
style: &KeyStyle<C, S>,
) -> Result<(), D::Error> {
let config = &self.config;
let mut buf = [0; 4];
let text = label(
key.action,
self.shift,
&config.layout,
&config.labels,
&mut buf,
);
style.frame.draw(target, key.bounds)?;
style.font.draw_centered(target, text, key.bounds.center())
}
}
impl<C, S> Keyboard<C, S> {
pub fn invalidate(&mut self) {
self.drawn = None;
}
pub const fn config(&self) -> &KeyboardConfig<C, S> {
&self.config
}
pub const fn page(&self) -> usize {
self.page
}
pub const fn shift_state(&self) -> ShiftState {
self.shift
}
pub fn reset(&mut self) {
self.page = 0;
self.shift = ShiftState::Off;
self.selected = (0, 0);
self.pressed = None;
}
fn current_page(&self) -> &Page {
&self.config.layout.pages[self.page]
}
pub fn selected_key(&self) -> Key {
self.key(self.selected.0, self.selected.1)
}
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)))
}
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),
}
}
pub fn handle_button(&mut self, button: NavButton) -> Option<KeyEvent> {
let (row, col) = self.selected;
let rows = self.current_page().rows;
let cols = rows[row].len();
self.pressed = None;
match button {
NavButton::Left => self.selected.1 = (col + cols - 1) % cols,
NavButton::Right => self.selected.1 = (col + 1) % cols,
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
}
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.selected = (key.row, key.col);
self.press(key.action)
}
pub fn release(&mut self) {
self.pressed = None;
}
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 snapshot(&self) -> Snapshot {
Snapshot {
page: self.page,
shift: self.shift,
selected: self.selected,
pressed: self.pressed,
}
}
fn style(&self, look: KeyLook) -> &KeyStyle<C, S> {
let theme = &self.config.theme;
match look {
KeyLook::Idle => &theme.idle,
KeyLook::Selected => &theme.selected,
KeyLook::Pressed => &theme.pressed,
}
}
fn on_action_row(&self) -> bool {
self.selected.0 + 1 == self.current_page().rows.len()
}
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
}
}
impl<C, S> Drawable for Keyboard<C, S>
where
C: PixelColor,
S: FontStyle<C>,
{
type Color = C;
type Output = ();
fn draw<D: DrawTarget<Color = C>>(&self, target: &mut D) -> Result<(), D::Error> {
self.config.frame.draw(target, self.config.bounds)?;
let now = self.snapshot();
for key in self.keys() {
self.draw_key(target, &key, self.style(now.look_of(&key)))?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{KeyStyle, KeyboardTheme};
use embedded_graphics::{
mono_font::{MonoTextStyle, ascii::FONT_6X10},
pixelcolor::BinaryColor,
};
const KEYPAD: Layout = Layout::new(&[Page::new(
"123",
&[
&KeyAction::chars(b"123"),
&KeyAction::chars(b"456"),
&KeyAction::chars(b"789"),
&[KeyAction::Backspace, KeyAction::Char('0'), KeyAction::Enter],
],
)]);
type TestKeyboard = Keyboard<BinaryColor, MonoTextStyle<'static, BinaryColor>>;
const BOUNDS: Rectangle = Rectangle::new(Point::new(3, 7), Size::new(397, 203));
fn config(layout: Layout) -> KeyboardConfig<BinaryColor, MonoTextStyle<'static, BinaryColor>> {
let font = MonoTextStyle::new(&FONT_6X10, BinaryColor::On);
let idle = KeyStyle::new(font).with_border(BinaryColor::On, 1);
let theme = KeyboardTheme {
idle,
selected: idle.with_fill(BinaryColor::On),
pressed: idle.with_fill(BinaryColor::On),
};
KeyboardConfig::new(BOUNDS, theme).with_layout(layout)
}
fn keyboard(layout: Layout) -> TestKeyboard {
Keyboard::new(config(layout)).unwrap()
}
fn all_pages(kb: &mut TestKeyboard) -> impl Iterator<Item = alloc_free::PageKeys> + '_ {
let count = kb.config.layout.pages.len();
(0..count).map(move |page| {
kb.page = page;
kb.clamp_selection(false);
alloc_free::PageKeys::from(&*kb)
})
}
mod alloc_free {
use super::*;
pub struct PageKeys {
pub keys: [Option<Key>; 64],
pub rows: usize,
}
impl From<&TestKeyboard> for PageKeys {
fn from(kb: &TestKeyboard) -> Self {
let mut keys = [None; 64];
for (slot, key) in keys.iter_mut().zip(kb.keys()) {
*slot = Some(key);
}
Self {
keys,
rows: kb.current_page().rows.len(),
}
}
}
impl PageKeys {
pub fn iter(&self) -> impl Iterator<Item = Key> + '_ {
self.keys.iter().flatten().copied()
}
}
}
#[test]
fn regular_keys_share_one_size_across_pages() {
for layout in [Layout::QWERTY, KEYPAD] {
let mut kb = keyboard(layout);
let size = kb.grid.key_size;
for page in all_pages(&mut kb) {
for key in page.iter().filter(|k| k.row + 1 < page.rows) {
assert_eq!(key.bounds.size, size, "{key:?}");
}
}
}
}
#[test]
fn action_row_spans_the_grid_without_gaps() {
for layout in [Layout::QWERTY, KEYPAD] {
let mut kb = keyboard(layout);
let grid = kb.keys_bounds();
let spacing = kb.config.spacing as i32;
for page in all_pages(&mut kb) {
let mut action = page.iter().filter(|k| k.row + 1 == page.rows);
let first = action.next().unwrap();
assert_eq!(first.bounds.top_left.x, grid.top_left.x);
let last = action.fold(first, |prev, key| {
let prev_end = prev.bounds.top_left.x + prev.bounds.size.width as i32;
assert_eq!(prev_end + spacing, key.bounds.top_left.x);
key
});
assert_eq!(
last.bounds.bottom_right().unwrap(),
grid.bottom_right().unwrap()
);
}
}
}
#[test]
fn keys_stay_inside_bounds_and_grid_is_tight() {
let mut kb = keyboard(Layout::QWERTY);
let grid = kb.keys_bounds();
assert!(BOUNDS.size.width - grid.size.width < 10);
for page in all_pages(&mut kb) {
for key in page.iter() {
assert!(grid.contains(key.bounds.top_left));
assert!(grid.contains(key.bounds.bottom_right().unwrap()));
}
}
}
#[test]
fn horizontal_navigation_wraps() {
let mut kb = keyboard(Layout::QWERTY);
kb.handle_button(NavButton::Left);
assert_eq!(kb.selected_key().action, KeyAction::Char('p'));
kb.handle_button(NavButton::Right);
assert_eq!(kb.selected_key().action, KeyAction::Char('q'));
}
#[test]
fn vertical_navigation_picks_the_closest_key() {
let mut kb = keyboard(Layout::QWERTY);
kb.handle_button(NavButton::Down);
assert_eq!(kb.selected_key().action, KeyAction::Char('a'));
kb.handle_button(NavButton::Down);
assert_eq!(kb.selected_key().action, KeyAction::Char('z'));
kb.handle_button(NavButton::Down);
assert_eq!(kb.selected_key().action, KeyAction::Page(1));
kb.reset();
kb.handle_button(NavButton::Up);
assert_eq!(kb.selected_key().action, KeyAction::Shift);
kb.handle_button(NavButton::Down);
assert_eq!(kb.selected_key().action, KeyAction::Char('q'));
}
#[test]
fn shift_once_then_caps_lock_then_off() {
let mut kb = keyboard(Layout::QWERTY);
let type_q = |kb: &mut TestKeyboard| kb.handle_touch(kb.key(0, 0).bounds.center());
let shift = kb.key(3, 0).bounds.center();
kb.handle_touch(shift);
assert_eq!(kb.shift_state(), ShiftState::Once);
assert_eq!(type_q(&mut kb), Some(KeyEvent::Char('Q')));
assert_eq!(type_q(&mut kb), Some(KeyEvent::Char('q')));
kb.handle_touch(shift);
kb.handle_touch(shift);
assert_eq!(kb.shift_state(), ShiftState::Locked);
assert_eq!(type_q(&mut kb), Some(KeyEvent::Char('Q')));
assert_eq!(type_q(&mut kb), Some(KeyEvent::Char('Q')));
kb.handle_touch(shift);
assert_eq!(kb.shift_state(), ShiftState::Off);
assert_eq!(type_q(&mut kb), Some(KeyEvent::Char('q')));
}
#[test]
fn page_keys_switch_pages_and_keep_the_action_row_selected() {
let mut kb = keyboard(Layout::QWERTY);
kb.selected = (3, 1);
assert_eq!(kb.handle_button(NavButton::Validate), None);
assert_eq!(kb.page(), 1);
assert_eq!(kb.selected.0, 3);
assert_eq!(kb.selected_key().action, KeyAction::Space);
kb.handle_button(NavButton::Left);
assert_eq!(kb.handle_button(NavButton::Validate), None);
assert_eq!(kb.page(), 0);
}
#[test]
fn page_switch_keeps_a_letter_row_off_the_action_row() {
const TALL: Layout = Layout::new(&[
Page::new(
"abc",
&[
&KeyAction::chars(b"ab"),
&KeyAction::chars(b"cd"),
&KeyAction::chars(b"ef"),
&[KeyAction::Page(1), KeyAction::Char('g')],
&[KeyAction::Enter],
],
),
Page::new(
"123",
&[
&KeyAction::chars(b"12"),
&KeyAction::chars(b"34"),
&KeyAction::chars(b"56"),
&[KeyAction::Page(0)],
],
),
]);
let mut kb = keyboard(TALL);
kb.selected = (3, 0);
kb.handle_button(NavButton::Validate);
assert_eq!(kb.page(), 1);
assert_eq!(kb.selected, (2, 0));
}
#[test]
fn space_emits_a_space_character() {
let mut kb = keyboard(Layout::QWERTY);
let space = kb.keys().find(|k| k.action == KeyAction::Space).unwrap();
assert_eq!(
kb.handle_touch(space.bounds.center()),
Some(KeyEvent::Char(' '))
);
}
struct Screen {
pixels: [[BinaryColor; 410]; 220],
drawn: usize,
touched: Option<Rectangle>,
}
impl Screen {
fn new() -> Self {
Self {
pixels: [[BinaryColor::Off; 410]; 220],
drawn: 0,
touched: None,
}
}
fn reset_stats(&mut self) {
self.drawn = 0;
self.touched = None;
}
}
impl Dimensions for Screen {
fn bounding_box(&self) -> Rectangle {
Rectangle::new(Point::zero(), Size::new(410, 220))
}
}
impl DrawTarget for Screen {
type Color = BinaryColor;
type Error = core::convert::Infallible;
fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
where
I: IntoIterator<Item = embedded_graphics::Pixel<BinaryColor>>,
{
for embedded_graphics::Pixel(p, color) in pixels {
self.pixels[p.y as usize][p.x as usize] = color;
self.drawn += 1;
let pixel = Rectangle::new(p, Size::new(1, 1));
self.touched = Some(match self.touched {
Some(r) => Rectangle::with_corners(
r.top_left.component_min(p),
r.bottom_right().unwrap().component_max(p),
),
None => pixel,
});
}
Ok(())
}
}
#[test]
fn redraw_matches_a_full_draw() {
let font = MonoTextStyle::new(&FONT_6X10, BinaryColor::Off);
let rounded = KeyStyle::new(font)
.with_fill(BinaryColor::On)
.with_corner_radius(8);
let rounded = KeyboardConfig::new(
BOUNDS,
KeyboardTheme {
idle: rounded,
selected: rounded
.with_corner_radius(0)
.with_fill(BinaryColor::Off)
.with_border(BinaryColor::On, 1)
.with_font(MonoTextStyle::new(&FONT_6X10, BinaryColor::On)),
pressed: rounded.with_corner_radius(4),
},
);
for config in [config(Layout::QWERTY), rounded] {
check_redraw(Keyboard::new(config).unwrap());
}
}
fn check_redraw(mut kb: TestKeyboard) {
let mut screen = Screen::new();
let shift = kb.key(3, 0).bounds.center();
let page = kb.key(3, 1).bounds.center();
let steps: &[&dyn Fn(&mut TestKeyboard)] = &[
&|_| {},
&|kb| {
kb.handle_button(NavButton::Right);
},
&|kb| {
kb.handle_button(NavButton::Down);
},
&|kb| {
kb.handle_button(NavButton::Validate);
},
&|kb| kb.release(),
&|kb| {
kb.handle_touch(shift);
},
&|kb| kb.release(),
&|kb| {
kb.handle_button(NavButton::Up);
},
&|kb| {
kb.handle_button(NavButton::Validate);
},
&|kb| {
kb.handle_touch(page);
},
&|kb| kb.release(),
&|kb| {
kb.handle_button(NavButton::Left);
},
&|kb| kb.reset(),
];
for (i, step) in steps.iter().enumerate() {
step(&mut kb);
kb.redraw(&mut screen, BinaryColor::Off).unwrap();
let mut expected = Screen::new();
kb.draw(&mut expected).unwrap();
assert!(screen.pixels == expected.pixels, "step {i}");
}
}
#[test]
fn redraw_only_touches_changed_keys() {
let mut kb = keyboard(Layout::QWERTY);
let mut screen = Screen::new();
kb.redraw(&mut screen, BinaryColor::Off).unwrap();
let full = screen.drawn;
screen.reset_stats();
kb.redraw(&mut screen, BinaryColor::Off).unwrap();
assert_eq!(screen.drawn, 0);
let (q, w) = (kb.key(0, 0).bounds, kb.key(0, 1).bounds);
kb.handle_button(NavButton::Right);
kb.redraw(&mut screen, BinaryColor::Off).unwrap();
let both = Rectangle::with_corners(q.top_left, w.bottom_right().unwrap());
assert_eq!(screen.touched, Some(both));
assert!(screen.drawn * 10 < full);
}
#[test]
fn touch_outside_keys_does_nothing() {
let mut kb = keyboard(Layout::QWERTY);
assert_eq!(kb.handle_touch(Point::zero()), None);
assert_eq!(kb.pressed, None);
}
#[test]
fn invalid_configs_are_rejected() {
const EMPTY_ROW: Layout = Layout::new(&[Page::new("x", &[&[]])]);
const BAD_PAGE: Layout = Layout::new(&[Page::new("x", &[&[KeyAction::Page(1)]])]);
assert_eq!(
Keyboard::new(config(Layout::new(&[]))).err(),
Some(ConfigError::EmptyLayout)
);
assert_eq!(
Keyboard::new(config(EMPTY_ROW)).err(),
Some(ConfigError::EmptyLayout)
);
assert_eq!(
Keyboard::new(config(BAD_PAGE)).err(),
Some(ConfigError::InvalidPage(KeyPosition {
page: 0,
row: 0,
col: 0
}))
);
let mut tiny = config(Layout::QWERTY);
tiny.bounds.size = Size::new(80, 40);
let Err(ConfigError::LabelTooLarge { size, max, .. }) = Keyboard::new(tiny) else {
panic!("expected LabelTooLarge");
};
assert!(size.width > max.width || size.height > max.height);
}
#[test]
fn set_config_keeps_state_or_fails_atomically() {
let mut kb = keyboard(Layout::QWERTY);
kb.handle_touch(kb.key(3, 1).bounds.center());
assert_eq!(kb.page(), 1);
let mut tiny = config(Layout::QWERTY);
tiny.bounds.size = Size::new(10, 10);
assert!(kb.set_config(tiny).is_err());
assert_eq!(kb.page(), 1);
kb.set_config(config(KEYPAD)).unwrap();
assert_eq!(kb.page(), 0);
}
}