embedded-graphics-keyboard 0.1.0

no_std on-screen keyboard and text field widgets for embedded-graphics, driven by buttons or touch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
//! On-screen keyboard widget: state machine, geometry and rendering.

use embedded_graphics::{
    Drawable,
    draw_target::DrawTarget,
    geometry::{Dimensions, Point, Size},
    pixelcolor::PixelColor,
    primitives::{Primitive, PrimitiveStyle, Rectangle},
};

use crate::{
    error::{ConfigError, KeyPosition, size_fits},
    layout::{KeyAction, KeyEvent, Labels, Layout, Page},
    style::{FontStyle, FrameStyle, KeyStyle, KeyboardTheme},
};

/// Physical inputs used to drive the keyboard with buttons.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NavButton {
    /// Moves the selection to the row above, wrapping around.
    Up,
    /// Moves the selection to the row below, wrapping around.
    Down,
    /// Moves the selection to the previous key of the row, wrapping around.
    Left,
    /// Moves the selection to the next key of the row, wrapping around.
    Right,
    /// Presses the selected key.
    Validate,
}

/// State of the Shift key.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ShiftState {
    /// Lower case.
    #[default]
    Off,
    /// Upper case for the next character only.
    Once,
    /// Caps lock: upper case until Shift is pressed again.
    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)
    }
}

/// A key of the current page, with its on-screen bounds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Key {
    /// Index of the row in the page.
    pub row: usize,
    /// Index of the key in the row.
    pub col: usize,
    /// What the key does.
    pub action: KeyAction,
    /// Area covered by the key.
    pub bounds: Rectangle,
}

/// Configuration of a [`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>,
}

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(),
        }
    }

    /// 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
    }

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

/// 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)]
struct Grid {
    /// Top-left corner of the grid.
    origin: Point,
    /// Width of the widest row (= width of the action rows).
    width: u32,
    height: u32,
    key_size: Size,
    spacing: u32,
    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.
    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))
    }

    /// 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.
    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)
        }
    }
}

/// Upper-cases `c` when it maps to a single character, otherwise returns it unchanged.
fn upper(c: char) -> char {
    let mut chars = c.to_uppercase();
    match (chars.next(), chars.next()) {
        (Some(u), None) => u,
        _ => c,
    }
}

/// Text shown on a key.
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),
    }
}

/// Look of a key, picking its [`KeyStyle`] in the theme.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum KeyLook {
    Idle,
    Selected,
    Pressed,
}

/// The input state that decides what the keyboard looks like.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Snapshot {
    page: usize,
    shift: ShiftState,
    selected: (usize, usize),
    pressed: Option<(usize, usize)>,
}

impl Snapshot {
    /// `Pressed` if held down, `Selected` if under the cursor or if it is
    /// Shift while on, `Idle` otherwise.
    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
        }
    }
}

/// Stateful on-screen keyboard driven by navigation buttons and/or touch.
///
/// Two ways to draw it:
/// - [`Keyboard::redraw`] draws only the keys whose look changed since the
///   previous call: use it on real displays, where every pixel sent costs time.
/// - [`Drawable::draw`] draws everything, for a display (or a frame buffer)
///   cleared every frame.
#[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)>,
    /// State shown on the display by the last [`Keyboard::redraw`], if still valid.
    drawn: Option<Snapshot>,
}

impl<C, S> Keyboard<C, S>
where
    C: PixelColor,
    S: FontStyle<C>,
{
    /// Creates a keyboard, checking that the layout is valid and that every label
    /// fits inside its key with the font of every state.
    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,
        })
    }

    /// Replaces the configuration (bounds, layout, theme…).
    ///
    /// On success the input state is kept, unless the current page no longer
    /// exists, and the next [`Keyboard::redraw`] draws everything; on error
    /// nothing changes.
    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 bounds = grid.key_rect(page, row, col);
                    for shift in [ShiftState::Off, ShiftState::Locked] {
                        let text = label(action, shift, layout, &config.labels, &mut buf);
                        for style in config.theme.styles() {
                            if !size_fits(style.font.measure(text), bounds, config.key_padding) {
                                return Err(ConfigError::LabelTooLarge(position));
                            }
                        }
                    }
                }
            }
        }
        Ok(grid)
    }
}

impl<C, S> Keyboard<C, S>
where
    C: PixelColor,
    S: FontStyle<C>,
{
    /// Draws only what changed since the previous call: usually the two keys
    /// whose selection or press state changed.
    ///
    /// Everything is drawn on the first call, after a page or Shift change
    /// (the labels change), after [`Keyboard::set_config`] and after
    /// [`Keyboard::invalidate`].
    ///
    /// `background` is the color behind the keyboard. Keys are erased with it
    /// before being drawn again (or with the fill of the
    /// [`frame`](KeyboardConfig::frame), when it has one), except when the new
    /// style fully covers the old one.
    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> {
    /// Makes the next [`Keyboard::redraw`] draw everything, e.g. after the
    /// display was cleared or drawn over.
    pub fn invalidate(&mut self) {
        self.drawn = None;
    }

    /// Current configuration.
    pub const fn config(&self) -> &KeyboardConfig<C, S> {
        &self.config
    }

    /// Index of the page currently shown.
    pub const fn page(&self) -> usize {
        self.page
    }

    /// State of the Shift key.
    pub const fn shift_state(&self) -> ShiftState {
        self.shift
    }

    /// Back to the first page, Shift off, first key selected.
    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]
    }

    /// The key under the navigation cursor.
    pub fn selected_key(&self) -> Key {
        self.key(self.selected.0, self.selected.1)
    }

    /// Iterates over the keys of the current page.
    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)))
    }

    /// Rectangle actually covered by the keys.
    ///
    /// It can be a few pixels smaller than the configured area, since every key
    /// has the same integer size: use it to align other widgets with the keys.
    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),
        }
    }

    /// Handles a navigation button.
    ///
    /// Returns an event when `Validate` presses a key that emits one (see [`KeyEvent`]).
    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
    }

    /// Handles a touch at `point`: selects and presses the key under it, if any.
    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)
    }

    /// Releases the pressed key (button or touch released).
    pub fn release(&mut self) {
        self.pressed = None;
    }

    /// Moves the selection to `row`, on the key horizontally closest to the current one.
    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()
    }

    /// Keeps the selection on an existing key after a page or layout change:
    /// the action row stays the action row, a letter row stays a letter row.
    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,
    };

    /// A second, differently shaped layout: 3 columns, single page.
    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)
        })
    }

    /// Fixed-capacity key list, the crate being `no_std` without `alloc`.
    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();
        // At most one unused pixel per column (10 on QWERTY).
        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'));
        // `z` sits above the "123" key, the Shift key being further left.
        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() {
        // 5 rows (4 letter rows + action row) to a 4-row page.
        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(' '))
        );
    }

    /// Frame buffer covering `BOUNDS`, counting the pixels drawn into it.
    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() {
        // Keys mixing fills and corner radii: some changes need erasing first.
        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);
        assert!(matches!(
            Keyboard::new(tiny),
            Err(ConfigError::LabelTooLarge(_))
        ));
    }

    #[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);
    }
}