rust_widgets 2.7.0

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Keyboard widget — on-screen virtual keyboard (BLUE13 R2.6).
//!
//! Displays a grid of keys (QWERTY layout by default). Each key generates
//! a [`Signal1<(u32, u32)>`] with the key code and modifiers on press.
//! Special keys (Enter, Backspace, Space) also emit dedicated signals.

use crate::compat::{format, vec, String, ToString, Vec};
use crate::core::{Color, Font, HorizontalAlignment, Point, Rect, Size};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::{GenericSignal, Signal1};
use crate::widget::capability::coercion::{expect_bool, expect_string};
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};

/// Layout variants for the on-screen keyboard.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyboardLayout {
    /// Standard QWERTY letter layout (default).
    Qwerty,
    /// Numeric/symbol layout.
    Numeric,
}

/// Virtual keyboard key definition.
#[derive(Debug, Clone)]
pub struct KeyDefinition {
    /// Display label (e.g. "A", "Space", "Enter").
    pub label: String,
    /// Key code emitted when this key is pressed.
    pub key_code: u32,
    /// Width multiplier relative to a standard key (1.0 = normal, 1.5 = wider, 2.0+ = wide).
    pub width_ratio: f32,
}

/// On-screen virtual keyboard widget.
///
/// Displays rows of clickable keys. Pressing a key emits the [`key_pressed`]
/// signal and, for the three special keys, their dedicated signal as well.
///
/// [`key_pressed`]: #structfield.key_pressed
pub struct Keyboard {
    base: BaseWidget,
    layout: KeyboardLayout,
    keys: Vec<Vec<KeyDefinition>>,
    /// Current shift state (`true` = uppercase).
    shift: bool,
    /// Whether to show lowercase when shift is off.
    lowercase: bool,
    /// The key currently held down, as `(row, column)`, or `None` when none is.
    ///
    /// # Why the keyboard needed this while the mouse is "pressed"
    ///
    /// `BaseWidget` records that the **control** is pressed, not which of its keys is, and a
    /// keyboard is a grid of independent targets: pressing one key and seeing the whole board react
    /// would be a lie about which key is being activated. Until this field existed a key down gave
    /// no visual confirmation at all — the signal fired, and the board looked exactly as it did a
    /// moment before, which is the one affordance a virtual keyboard most needs because the user's
    /// finger is covering the key they pressed.
    ///
    /// The pair rather than the key code: the layout has two keys with the same code in different
    /// rows (a numeric row and a keypad column both carry digit codes), so a code alone cannot name
    /// the key to highlight.
    pressed_key: Option<(usize, usize)>,
    /// Signal emitted with `(key_code, modifiers)` when any key is pressed.
    pub key_pressed: Signal1<(u32, u32)>,
    /// Signal emitted when Enter (key code 13) is pressed.
    pub enter_pressed: GenericSignal,
    /// Signal emitted when Backspace (key code 8) is pressed.
    pub backspace_pressed: GenericSignal,
    /// Signal emitted when Space (key code 32) is pressed.
    pub space_pressed: GenericSignal,
}

impl Keyboard {
    /// Create a new keyboard widget with the given bounding rectangle.
    ///
    /// Initial layout is QWERTY, shift is off, lowercase is enabled.
    pub fn new(rect: Rect) -> Self {
        let base = BaseWidget::new(WidgetKind::Keyboard, rect, "Keyboard");
        let mut kbd = Self {
            base,
            layout: KeyboardLayout::Qwerty,
            keys: Vec::new(),
            shift: false,
            lowercase: true,
            pressed_key: None,
            key_pressed: Signal1::new(),
            enter_pressed: GenericSignal::new(),
            backspace_pressed: GenericSignal::new(),
            space_pressed: GenericSignal::new(),
        };
        kbd.build_qwerty_layout();
        kbd
    }

    /// Set the keyboard layout and rebuild the key grid.
    pub fn set_layout(&mut self, layout: KeyboardLayout) {
        self.layout = layout;
        match layout {
            KeyboardLayout::Qwerty => self.build_qwerty_layout(),
            KeyboardLayout::Numeric => self.build_numeric_layout(),
        }
        self.base.request_redraw();
    }

    /// Return the current layout variant.
    pub fn layout(&self) -> KeyboardLayout {
        self.layout
    }

    /// Get the key at the given position (in widget-local coordinates).
    ///
    /// Returns `Some((row_index, col_index))` if a key covers that position,
    /// or `None` if the position is outside the keyboard or in a gap.
    pub fn key_at_position(&self, pos: Point) -> Option<(usize, usize)> {
        let rect = self.geometry();
        if !rect.contains_point(pos) {
            return None;
        }
        if self.keys.is_empty() {
            return None;
        }

        let total_height = rect.height as f32;
        let row_count = self.keys.len() as f32;
        let row_height = total_height / row_count;

        let local_x = pos.x as f32 - rect.x as f32;
        let local_y = pos.y as f32 - rect.y as f32;

        let row = (local_y / row_height) as usize;
        if row >= self.keys.len() {
            return None;
        }

        let row_keys = &self.keys[row];
        let total_ratio: f32 = row_keys.iter().map(|k| k.width_ratio).sum();
        let row_width = rect.width as f32;

        let mut cursor_x = 0.0f32;
        for (col, key) in row_keys.iter().enumerate() {
            let key_w = row_width * key.width_ratio / total_ratio;
            if local_x >= cursor_x && local_x < cursor_x + key_w {
                return Some((row, col));
            }
            cursor_x += key_w;
        }

        None
    }

    /// Toggle the shift state between uppercase and lowercase.
    pub fn toggle_shift(&mut self) {
        self.shift = !self.shift;
        self.base.request_redraw();
    }

    /// Return the current shift state.
    pub fn is_shifted(&self) -> bool {
        self.shift
    }

    /// Set whether lowercase letters are shown when shift is off.
    pub fn set_lowercase(&mut self, enabled: bool) {
        self.lowercase = enabled;
        self.base.request_redraw();
    }

    /// Return whether lowercase mode is enabled.
    pub fn lowercase(&self) -> bool {
        self.lowercase
    }

    // ── Internal helpers ──────────────────────────────────────────────────────

    fn build_qwerty_layout(&mut self) {
        self.keys = vec![
            // Row 0: q w e r t y u i o p
            vec![
                KeyDefinition { label: "q".into(), key_code: 81, width_ratio: 1.0 },
                KeyDefinition { label: "w".into(), key_code: 87, width_ratio: 1.0 },
                KeyDefinition { label: "e".into(), key_code: 69, width_ratio: 1.0 },
                KeyDefinition { label: "r".into(), key_code: 82, width_ratio: 1.0 },
                KeyDefinition { label: "t".into(), key_code: 84, width_ratio: 1.0 },
                KeyDefinition { label: "y".into(), key_code: 89, width_ratio: 1.0 },
                KeyDefinition { label: "u".into(), key_code: 85, width_ratio: 1.0 },
                KeyDefinition { label: "i".into(), key_code: 73, width_ratio: 1.0 },
                KeyDefinition { label: "o".into(), key_code: 79, width_ratio: 1.0 },
                KeyDefinition { label: "p".into(), key_code: 80, width_ratio: 1.0 },
            ],
            // Row 1: a s d f g h j k l
            vec![
                KeyDefinition { label: "a".into(), key_code: 65, width_ratio: 1.0 },
                KeyDefinition { label: "s".into(), key_code: 83, width_ratio: 1.0 },
                KeyDefinition { label: "d".into(), key_code: 68, width_ratio: 1.0 },
                KeyDefinition { label: "f".into(), key_code: 70, width_ratio: 1.0 },
                KeyDefinition { label: "g".into(), key_code: 71, width_ratio: 1.0 },
                KeyDefinition { label: "h".into(), key_code: 72, width_ratio: 1.0 },
                KeyDefinition { label: "j".into(), key_code: 74, width_ratio: 1.0 },
                KeyDefinition { label: "k".into(), key_code: 75, width_ratio: 1.0 },
                KeyDefinition { label: "l".into(), key_code: 76, width_ratio: 1.0 },
            ],
            // Row 2: Shift, z x c v b n m, Backspace
            vec![
                KeyDefinition { label: "Shift".into(), key_code: 16, width_ratio: 1.5 },
                KeyDefinition { label: "z".into(), key_code: 90, width_ratio: 1.0 },
                KeyDefinition { label: "x".into(), key_code: 88, width_ratio: 1.0 },
                KeyDefinition { label: "c".into(), key_code: 67, width_ratio: 1.0 },
                KeyDefinition { label: "v".into(), key_code: 86, width_ratio: 1.0 },
                KeyDefinition { label: "b".into(), key_code: 66, width_ratio: 1.0 },
                KeyDefinition { label: "n".into(), key_code: 78, width_ratio: 1.0 },
                KeyDefinition { label: "m".into(), key_code: 77, width_ratio: 1.0 },
                KeyDefinition { label: "Bksp".into(), key_code: 8, width_ratio: 1.5 },
            ],
            // Row 3: 123?, Space (width 4), Enter
            vec![
                KeyDefinition { label: "123".into(), key_code: 0, width_ratio: 1.5 },
                KeyDefinition { label: "Space".into(), key_code: 32, width_ratio: 4.0 },
                KeyDefinition { label: "Enter".into(), key_code: 13, width_ratio: 1.5 },
            ],
        ];
    }

    fn build_numeric_layout(&mut self) {
        self.keys = vec![
            // Row 0: 1 2 3 4 5 6 7 8 9 0
            (0..=9)
                .map(|d| KeyDefinition {
                    label: format!("{d}"),
                    key_code: if d == 0 { 48 } else { 48 + d as u32 },
                    width_ratio: 1.0,
                })
                .collect(),
            // Row 1: - / : ; ( ) $ & @ "
            vec![
                KeyDefinition { label: "-".into(), key_code: 45, width_ratio: 1.0 },
                KeyDefinition { label: "/".into(), key_code: 47, width_ratio: 1.0 },
                KeyDefinition { label: ":".into(), key_code: 58, width_ratio: 1.0 },
                KeyDefinition { label: ";".into(), key_code: 59, width_ratio: 1.0 },
                KeyDefinition { label: "(".into(), key_code: 40, width_ratio: 1.0 },
                KeyDefinition { label: ")".into(), key_code: 41, width_ratio: 1.0 },
                KeyDefinition { label: "$".into(), key_code: 36, width_ratio: 1.0 },
                KeyDefinition { label: "&".into(), key_code: 38, width_ratio: 1.0 },
                KeyDefinition { label: "@".into(), key_code: 64, width_ratio: 1.0 },
                KeyDefinition { label: "\"".into(), key_code: 34, width_ratio: 1.0 },
            ],
            // Row 2: . , ? ! ' ` ~ ^
            vec![
                KeyDefinition { label: ".".into(), key_code: 46, width_ratio: 1.0 },
                KeyDefinition { label: ",".into(), key_code: 44, width_ratio: 1.0 },
                KeyDefinition { label: "?".into(), key_code: 63, width_ratio: 1.0 },
                KeyDefinition { label: "!".into(), key_code: 33, width_ratio: 1.0 },
                KeyDefinition { label: "'".into(), key_code: 39, width_ratio: 1.0 },
                KeyDefinition { label: "`".into(), key_code: 96, width_ratio: 1.0 },
                KeyDefinition { label: "~".into(), key_code: 126, width_ratio: 1.0 },
                KeyDefinition { label: "^".into(), key_code: 94, width_ratio: 1.0 },
            ],
            // Row 3: ABC?, Space, Enter
            vec![
                KeyDefinition { label: "ABC".into(), key_code: 0, width_ratio: 1.5 },
                KeyDefinition { label: "Space".into(), key_code: 32, width_ratio: 4.0 },
                KeyDefinition { label: "Enter".into(), key_code: 13, width_ratio: 1.5 },
            ],
        ];
    }

    /// Emit the appropriate signals for a key press.
    fn emit_key_signals(&self, key_code: u32) {
        self.key_pressed.emit((key_code, 0));
        match key_code {
            13 => self.enter_pressed.emit(),
            8 => self.backspace_pressed.emit(),
            32 => self.space_pressed.emit(),
            _ => {}
        }
    }

    /// Get the display label for a key, respecting shift/lowercase state.
    fn key_display_label(&self, key: &KeyDefinition) -> String {
        // Only letter keys are affected by shift.
        if key.key_code >= 65 && key.key_code <= 90 {
            if self.shift || !self.lowercase {
                key.label.to_uppercase()
            } else {
                key.label.to_lowercase()
            }
        } else {
            key.label.clone()
        }
    }
}

impl Widget for Keyboard {
    fn base(&self) -> &BaseWidget {
        &self.base
    }

    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> Size {
        Size::new(320, 160)
    }
    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

/// `Keyboard`'s property contract.
///
/// `layout` maps to and from the two lower-case tokens the old arms used
/// (`qwerty`, `numeric`); anything else is a type mismatch, not a silent
/// fallback to QWERTY.
impl WidgetProperties for Keyboard {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "layout" => {
                let token = match self.layout() {
                    KeyboardLayout::Qwerty => "qwerty",
                    KeyboardLayout::Numeric => "numeric",
                };
                Ok(CapabilityValue::String(token.to_string()))
            }
            "lowercase" => Ok(CapabilityValue::Bool(self.lowercase())),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "layout" => {
                let token = expect_string(value)?;
                let layout = match token.as_str() {
                    "qwerty" => KeyboardLayout::Qwerty,
                    "numeric" => KeyboardLayout::Numeric,
                    _ => return Err(CapabilityAccessError::TypeMismatch),
                };
                self.set_layout(layout);
                Ok(())
            }
            "lowercase" => {
                self.set_lowercase(expect_bool(value)?);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        // Mirrors `KEYBOARD_PROPERTIES`.
        property_names_of!["layout", "lowercase", BASE_PROPERTY_NAMES]
    }

    /// Runs one of the commands `keyboard` publishes.
    ///
    /// `toggle_shift` is the zero-argument action — the same one the on-screen Shift key
    /// performs — so it goes through the control's own method. `set_layout` and
    /// `set_lowercase` assign state and need a payload, so they are answered through the
    /// property route; `layout`'s accepted tokens are published by `property_tokens`.
    fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
        match name {
            "toggle_shift" => {
                self.toggle_shift();
                Ok(())
            }
            "set_layout" | "set_lowercase" => Err(CapabilityAccessError::OutOfRange),
            _ => Err(CapabilityAccessError::UnknownCommand),
        }
    }
}

impl EventHandler for Keyboard {
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
        if !self.base.is_enabled() {
            return;
        }

        match event {
            // Only handle MousePress (modern variant) to avoid double-trigger
            // with MouseDown (legacy variant).
            Event::MousePress { pos, button: _ } => {
                let hit = self.key_at_position(*pos);
                let key_code = hit.and_then(|(r, c)| {
                    self.keys.get(r).and_then(|row| row.get(c)).map(|k| k.key_code)
                });
                if let Some(code) = key_code {
                    // The latch is what the draw path reads, so the key the user pressed is the
                    // key that lights up. Set from the **hit test**, the same function the click
                    // itself uses, so the highlight and the action can never name different keys.
                    if let Some(at) = hit {
                        self.pressed_key = Some(at);
                        self.base.request_redraw();
                    }
                    if code == 16 {
                        self.toggle_shift();
                    } else {
                        self.emit_key_signals(code);
                    }
                    self.base.clicked.emit();
                }
            }
            // The press ends when the pointer goes up, wherever it went up: the key was activated
            // on the press (that is this control's contract), so the confirmation is released with
            // the pointer rather than being latched until the next press.
            Event::MouseRelease { .. } => {
                if self.pressed_key.take().is_some() {
                    self.base.request_redraw();
                }
            }
            #[cfg(feature = "touch")]
            Event::TouchBegin { pos, .. } => {
                let hit = self.key_at_position(*pos);
                let key_code = hit.and_then(|(r, c)| {
                    self.keys.get(r).and_then(|row| row.get(c)).map(|k| k.key_code)
                });
                if let Some(code) = key_code {
                    if let Some(at) = hit {
                        self.pressed_key = Some(at);
                        self.base.request_redraw();
                    }
                    if code == 16 {
                        self.toggle_shift();
                    } else {
                        self.emit_key_signals(code);
                    }
                    self.base.clicked.emit();
                }
            }
            #[cfg(feature = "touch")]
            Event::TouchEnd { .. } => {
                if self.pressed_key.take().is_some() {
                    self.base.request_redraw();
                }
            }
            Event::KeyPress { key, modifiers: _ } => {
                match *key {
                    8 => {
                        // Backspace
                        self.backspace_pressed.emit();
                        self.key_pressed.emit((8, 0));
                    }
                    13 => {
                        // Enter
                        self.enter_pressed.emit();
                        self.key_pressed.emit((13, 0));
                    }
                    32 => {
                        // Space
                        self.space_pressed.emit();
                        self.key_pressed.emit((32, 0));
                    }
                    _ => {}
                }
            }
            _ => {}
        }
    }
}

impl Draw for Keyboard {
    fn draw(&mut self, context: &mut RenderContext) {
        let rect = self.geometry();
        if rect.width == 0 || rect.height == 0 {
            return;
        }

        // Chrome colours resolve the explicit style first, then the theme's resolved style for
        // this control, and only then fall back to a literal. `keyboard` is not in the role table,
        // so it classifies as `Surface` and its resolved background is the window fill itself —
        // which is why the board below derives its own distinct surface rather than painting the
        // window's. Every key colour used to be a literal too, so a light/dark switch left the
        // whole board unchanged and the census reported the control as theme-blind.
        //
        // The theme read is a separate manager lock, taken and released inside
        // `resolved_theme_style`, so it is not held across the draw — the global manager's mutex
        // is not re-entrant.
        let style = self.base.style().clone();
        let theme = crate::style::resolved_theme_style("keyboard");
        // Read as its own lock acquisition and copied out as values, so the guard is dropped
        // before anything else touches the theme. A stripped device build has no theme
        // module, so the literals are its only rung — the same ones the `None` arm uses.
        #[cfg(device_profile)]
        let (window_fill, foreground, primary, muted) = {
            let manager = crate::style::theme_manager();
            match manager.current_theme() {
                Some(active) => (
                    active.colors.background,
                    active.colors.foreground,
                    active.colors.primary,
                    active.colors.secondary,
                ),
                None => (
                    Color::rgb(240, 240, 240),
                    Color::BLACK,
                    Color::rgb(33, 150, 243),
                    Color::rgb(158, 158, 158),
                ),
            }
        };
        #[cfg(not(device_profile))]
        let (window_fill, foreground, primary, muted) = (
            Color::rgb(240, 240, 240),
            Color::BLACK,
            Color::rgb(33, 150, 243),
            Color::rgb(158, 158, 158),
        );

        let ink = style
            .text_color
            .or_else(|| theme.as_ref().and_then(|t| t.text_color))
            .unwrap_or(foreground);
        // The board: one step from the window fill toward the text colour, so it is a distinct
        // element on a light theme and on a dark one. The filter is on the **resolved** value, not
        // only on the theme's: the active theme is applied to every control before it is drawn, so
        // `style.background_color` already holds `Surface`'s window fill and letting it through
        // unfiltered is exactly the invisible-board defect this guards against. A caller's own
        // colour still wins.
        let board_from_theme = window_fill.blend(&ink, 0.10);
        let board = match style.background_color {
            Some(resolved) if resolved != window_fill => resolved,
            _ => board_from_theme,
        };
        context.fill_rect(rect, board);

        let row_count = self.keys.len();
        if row_count == 0 {
            return;
        }

        let total_height = rect.height as f32;
        let row_height = total_height / row_count as f32;
        let row_width = rect.width as f32;

        // Key colours are raised from the board so the grid reads on either appearance: an
        // ordinary key is one step out of the board, a modifier a further step, and a latched
        // shift carries the theme's primary so the state is visible rather than a fixed blue.
        let key_bg = board.blend(&ink, 0.10);
        let key_border = board.blend(&muted, 0.45);
        let special_bg = board.blend(&ink, 0.20);
        let shift_bg = if self.shift { primary.blend(&board, 0.45) } else { special_bg };
        // A key's label must contrast with the key it sits on, which is now a theme colour rather
        // than a fixed light grey.
        let text_color = ink;

        let default_font = Font::default();

        for (row_idx, row_keys) in self.keys.iter().enumerate() {
            let total_ratio: f32 = row_keys.iter().map(|k| k.width_ratio).sum();

            let mut cursor_x = rect.x as f32;
            for (col_idx, key) in row_keys.iter().enumerate() {
                let key_w = row_width * key.width_ratio / total_ratio;
                let key_rect = Rect::from_f32(
                    cursor_x,
                    rect.y as f32 + row_idx as f32 * row_height,
                    key_w,
                    row_height,
                );

                // Choose key background.
                let kbg = if key.key_code == 16 {
                    shift_bg
                } else if key.key_code == 13 || key.key_code == 8 || key.key_code == 0 {
                    special_bg
                } else {
                    key_bg
                };

                // A key under the pointer right now steps once more out of the board, so the press
                // is visible under the finger that is covering the key. `pressed_key` names the key
                // by position because two keys in different rows can share a key code.
                let kbg = if self.pressed_key == Some((row_idx, col_idx)) {
                    kbg.blend(&ink, 0.25)
                } else {
                    kbg
                };

                // Fill key background.
                context.fill_rect(key_rect, kbg);
                // Draw key border.
                context.draw_rect(key_rect, key_border);

                // Draw label centered in the key.
                let label = self.key_display_label(key);
                if !label.is_empty() {
                    // The fit box is the key's own interior, not a synthetically enlarged one:
                    // `draw_text_fitted` insets by `TEXT_FIT_MARGIN` at each end, so a key
                    // narrower than 2*margin yields an empty interior and the label is
                    // dropped rather than squeezed out. That is the only fitting rule that
                    // satisfies P5 on every key, because the average key at the census
                    // rectangle is narrower than "Shift".
                    let inner = Rect::new(
                        key_rect.x + 2,
                        key_rect.y + 2,
                        key_rect.width.saturating_sub(4),
                        key_rect.height.saturating_sub(4),
                    );
                    // The label is centred both ways. The horizontal `… - text_w / 2` origin
                    // rounded down to a **negative** x for a label wider than its key — the
                    // 36 px Shift key drew "Shift" at x = -3 — and the vertical term only
                    // subtracted half the line height, so the glyph box sat below centre.
                    //
                    // `draw_text_fitted` fixes the horizontal half but **not** the vertical
                    // one: its contract is *fit horizontally, align horizontally*, and its
                    // origin is `bounds.y` unchanged (see `RenderContext::draw_text_fitted`).
                    // Using it for a key cap therefore still pinned every cap to the key's top
                    // edge and left the glyph box two pixels below where a centred one belongs
                    // — the `keyboard.svg` keys drew their letters at `key_rect.y + 2` with no
                    // share of the 30 px row's remaining height. `draw_text_line` is the entry
                    // point that does both halves, and it is the one the doc-comment above
                    // already promised.
                    let key_text = if key.key_code == 16 && self.shift {
                        shift_bg.contrast_color()
                    } else {
                        text_color
                    };
                    context.draw_text_line(
                        inner,
                        &label,
                        &default_font,
                        key_text,
                        HorizontalAlignment::Center,
                    );
                }

                cursor_x += key_w;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::Rect;

    #[test]
    fn keyboard_creation_defaults() {
        let kbd = Keyboard::new(Rect::new(0, 0, 320, 160));
        assert_eq!(kbd.layout(), KeyboardLayout::Qwerty);
        assert!(!kbd.is_shifted());
        assert!(kbd.lowercase());
        assert_eq!(kbd.keys.len(), 4);
        // Row 0 should have 10 keys (q w e r t y u i o p).
        assert_eq!(kbd.keys[0].len(), 10);
        // Row 1 should have 9 keys (a s d f g h j k l).
        assert_eq!(kbd.keys[1].len(), 9);
        // Row 2 should have 9 keys (Shift, z x c v b n m, Backspace).
        assert_eq!(kbd.keys[2].len(), 9);
        // Row 3 should have 3 keys (123, Space, Enter).
        assert_eq!(kbd.keys[3].len(), 3);
    }

    #[test]
    fn keyboard_set_layout() {
        let mut kbd = Keyboard::new(Rect::new(0, 0, 320, 160));
        assert_eq!(kbd.layout(), KeyboardLayout::Qwerty);

        kbd.set_layout(KeyboardLayout::Numeric);
        assert_eq!(kbd.layout(), KeyboardLayout::Numeric);
        // Numeric row 0: 10 digits.
        assert_eq!(kbd.keys[0].len(), 10);
        // Row 3: ABC, Space, Enter.
        assert_eq!(kbd.keys[3].len(), 3);

        // Toggle back.
        kbd.set_layout(KeyboardLayout::Qwerty);
        assert_eq!(kbd.layout(), KeyboardLayout::Qwerty);
        assert_eq!(kbd.keys[0].len(), 10);
    }

    #[test]
    fn keyboard_key_at_position() {
        let kbd = Keyboard::new(Rect::new(0, 0, 320, 160));
        // Top-left corner should hit row 0, col 0 (key 'q').
        let hit = kbd.key_at_position(Point::new(5, 5));
        assert!(hit.is_some());
        let (row, col) = hit.unwrap();
        assert_eq!(row, 0);
        assert_eq!(col, 0);
        assert_eq!(kbd.keys[row][col].key_code, 81);

        // Bottom area — row 3, space key (col 1).
        let space_hit = kbd.key_at_position(Point::new(160, 140));
        assert!(space_hit.is_some());
        let (row, col) = space_hit.unwrap();
        assert_eq!(row, 3);
        // Space key has width_ratio 4.0, total row 3 ratio = 1.5 + 4.0 + 1.5 = 7.0.
        // Space starts at ratio 1.5/7.0 = ~21% width.
        // At x=160, width=320, that's 50% width → definitely in space.
        assert_eq!(kbd.keys[row][col].key_code, 32);
    }

    #[test]
    fn keyboard_key_at_position_returns_none_outside() {
        let kbd = Keyboard::new(Rect::new(0, 0, 320, 160));
        assert!(kbd.key_at_position(Point::new(500, 500)).is_none());
        assert!(kbd.key_at_position(Point::new(-1, -1)).is_none());
    }

    #[test]
    fn keyboard_toggle_shift() {
        let mut kbd = Keyboard::new(Rect::new(0, 0, 320, 160));
        assert!(!kbd.is_shifted());

        kbd.toggle_shift();
        assert!(kbd.is_shifted());

        kbd.toggle_shift();
        assert!(!kbd.is_shifted());
    }

    #[test]
    fn keyboard_key_display_label_respects_shift() {
        let kbd = Keyboard::new(Rect::new(0, 0, 320, 160));
        // Lowercase mode, shift off → lowercase.
        let key = KeyDefinition { label: "a".into(), key_code: 65, width_ratio: 1.0 };
        let label = kbd.key_display_label(&key);
        assert_eq!(label, "a");

        // Non-letter key unaffected.
        let space_key = KeyDefinition { label: "Space".into(), key_code: 32, width_ratio: 4.0 };
        assert_eq!(kbd.key_display_label(&space_key), "Space");
    }

    #[test]
    fn keyboard_set_lowercase() {
        let mut kbd = Keyboard::new(Rect::new(0, 0, 320, 160));
        assert!(kbd.lowercase());

        kbd.set_lowercase(false);
        assert!(!kbd.lowercase());
    }

    #[test]
    #[allow(unused_mut)]
    fn keyboard_draw_does_not_panic() {
        let mut kbd = Keyboard::new(Rect::new(0, 0, 320, 160));
        // Create a minimal render context. We mock by using the software
        // surface's RenderContext if available, or just verify no panic.
        // For testing we create a default RenderContext via the known path.
        #[cfg(feature = "software")]
        {
            use crate::core::Size;
            use crate::render::{PaintBackend, RenderContext, SoftwarePaintBackend};
            let mut backend = SoftwarePaintBackend::new(Size::new(320, 160), 1.0);
            backend.begin_frame(crate::core::Color::WHITE);
            let mut ctx = RenderContext::new(&mut backend);
            kbd.draw(&mut ctx);
        }
        #[cfg(not(feature = "software"))]
        {
            // If software rendering is not available, just ensure no panic
            // by verifying internal state is consistent.
            assert_eq!(kbd.keys.len(), 4);
        }
    }

    /// A key that is held down is painted differently from the same key at rest.
    ///
    /// # The defect this pins
    ///
    /// The keyboard had no press feedback at all: `handle_event` fired the signals and the board
    /// looked identical a moment later. `BaseWidget` records that the **control** is pressed, not
    /// which of its keys is, and a keyboard is a grid of independent targets — highlighting the whole
    /// board on any key press would be a worse lie than highlighting nothing. The latch is therefore
    /// per key, and it names the key by position because two keys in different rows can share a code.
    ///
    /// # Why the assertion compares one key's fill against its own resting fill
    ///
    /// A whole-document comparison would pass for a board where *any* pixel changed — including one
    /// this fix does not touch. The helper reads the fill of the rectangle at a named key's centre,
    /// so the assertion is about that key.
    #[test]
    #[cfg(all(device_profile, feature = "desktop"))]
    fn a_pressed_key_is_painted_as_pressed() {
        // The key fills are derived from the active theme, so pin the appearance and hold the
        // registry guard; otherwise a concurrently-running test can switch the theme between the
        // resting and pressed reads and the comparison is of two different appearances.
        let _guard = crate::style::theme_test_guard();
        crate::widget::census::install_preset_appearances();
        crate::theme::global_theme_manager().set_appearance(crate::theme::AppearanceMode::Light);
        let rect = Rect::new(0, 0, 320, 160);
        let mut kbd = Keyboard::new(rect);
        // A key in the middle of the first row: far enough from the edges that the sample is plainly
        // inside it whatever the row heights work out to.
        let row = 0usize;
        let col = 2usize;
        let centre = key_centre(&kbd, row, col).expect("the key must have a rectangle");

        let resting = key_fill(&mut kbd, rect, centre).expect("a key paints a fill");
        kbd.handle_event(&Event::MousePress { pos: centre, button: 1 });
        let pressed = key_fill(&mut kbd, rect, centre).expect("a pressed key paints a fill");
        assert_ne!(
            pressed, resting,
            "the key under the pointer must be visible as pressed; both fills were {resting}"
        );

        kbd.handle_event(&Event::MouseRelease { pos: centre, button: 1 });
        let released = key_fill(&mut kbd, rect, centre).expect("the key still paints a fill");
        assert_eq!(
            released, resting,
            "releasing must return the key to its resting fill, not latch it"
        );
    }

    /// The centre of the key at `(row, col)`, from the same geometry the draw path uses.
    #[cfg(all(device_profile, feature = "desktop"))]
    fn key_centre(kbd: &Keyboard, row: usize, col: usize) -> Option<Point> {
        let rect = kbd.geometry();
        let row_keys = kbd.keys.get(row)?;
        let total: f32 = row_keys.iter().map(|k| k.width_ratio).sum();
        let key = row_keys.get(col)?;
        let before: f32 = row_keys.iter().take(col).map(|k| k.width_ratio).sum();
        let row_height = rect.height as f32 / kbd.keys.len() as f32;
        let x = rect.x as f32 + (before + key.width_ratio / 2.0) / total * rect.width as f32;
        let y = rect.y as f32 + (row as f32 + 0.5) * row_height;
        Some(Point::new(x as i32, y as i32))
    }

    /// The fill of the **innermost** SVG `<rect>` that contains `at`.
    ///
    /// Innermost rather than first: the document opens with the board's own full-canvas rectangle,
    /// which also contains the sample point. Keeping the smallest-area match is what makes the
    /// returned fill the *key's*, which is the element the assertion is about — the same "name the
    /// element" rule the fill assertions elsewhere in the crate follow.
    ///
    /// Split on the self-closing tag rather than searching forward for it: an `element[..end]`
    /// cursor that slices at the *first* `/>` from a position can land inside the next element when
    /// a tag is emitted without the space before it, which read the wrong rectangle's attributes
    /// (measured: every candidate came back `320x160`).
    #[cfg(all(device_profile, feature = "desktop"))]
    fn key_fill(kbd: &mut Keyboard, rect: Rect, at: Point) -> Option<String> {
        let svg = crate::widget::svg::render_widget_to_svg(kbd, rect);
        let mut best: Option<(u32, String)> = None;
        for element in svg.split("/>") {
            let Some(open) = element.find("<rect ") else {
                continue;
            };
            let element = &element[open + "<rect ".len()..];
            let attr = |name: &str| -> Option<i32> {
                let key = format!("{name}=\"");
                let at = element.find(&key)? + key.len();
                let to = element[at..].find('"')? + at;
                element[at..to].parse().ok()
            };
            let (Some(x), Some(y), Some(w), Some(h)) =
                (attr("x"), attr("y"), attr("width"), attr("height"))
            else {
                continue;
            };
            if at.x < x || at.x >= x + w || at.y < y || at.y >= y + h {
                continue;
            }
            let Some(fill_at) = element.find("fill=\"") else {
                continue;
            };
            let from = fill_at + "fill=\"".len();
            let Some(to) = element[from..].find('"') else {
                continue;
            };
            let area = (w as u32).saturating_mul(h as u32);
            if best.as_ref().map(|(a, _)| area < *a).unwrap_or(true) {
                best = Some((area, element[from..from + to].to_string()));
            }
        }
        best.map(|(_, fill)| fill)
    }

    #[test]
    fn keyboard_signal_emission() {
        use std::sync::atomic::{AtomicBool, Ordering};
        use std::sync::Arc;

        let kbd = Keyboard::new(Rect::new(0, 0, 320, 160));

        let pressed = Arc::new(AtomicBool::new(false));
        {
            let p = pressed.clone();
            kbd.key_pressed.connect(move |args| {
                let (code, _mods) = *args;
                if code == 32 {
                    p.store(true, Ordering::SeqCst);
                }
            });
        }

        // Simulate pressing the space key through the event handler.
        // We need &mut self to call handle_event, but signals are on &self.
        // So we call emit_key_signals directly.
        kbd.emit_key_signals(32);
        assert!(pressed.load(Ordering::SeqCst));
    }

    #[test]
    fn keyboard_enter_signal() {
        use std::sync::atomic::{AtomicBool, Ordering};
        use std::sync::Arc;

        let kbd = Keyboard::new(Rect::new(0, 0, 320, 160));

        let entered = Arc::new(AtomicBool::new(false));
        let e = entered.clone();
        kbd.enter_pressed.connect(move || {
            e.store(true, Ordering::SeqCst);
        });

        kbd.emit_key_signals(13);
        assert!(entered.load(Ordering::SeqCst));
    }

    #[test]
    fn keyboard_backspace_signal() {
        use std::sync::atomic::{AtomicBool, Ordering};
        use std::sync::Arc;

        let kbd = Keyboard::new(Rect::new(0, 0, 320, 160));

        let bs = Arc::new(AtomicBool::new(false));
        let b = bs.clone();
        kbd.backspace_pressed.connect(move || {
            b.store(true, Ordering::SeqCst);
        });

        kbd.emit_key_signals(8);
        assert!(bs.load(Ordering::SeqCst));
    }

    #[test]
    fn keyboard_shift_press_toggles_via_event() {
        let mut kbd = Keyboard::new(Rect::new(0, 0, 320, 160));
        assert!(!kbd.is_shifted());

        // Row 2, col 0 is the Shift key. Simulate a click on it.
        let shift_pos = Point::new(10, 90); // Roughly in row 2.
        kbd.handle_event(&Event::MousePress { pos: shift_pos, button: 1 });
        assert!(kbd.is_shifted());

        // Press again to toggle back.
        kbd.handle_event(&Event::MousePress { pos: shift_pos, button: 1 });
        assert!(!kbd.is_shifted());
    }

    #[test]
    fn keyboard_geometry_delegation() {
        let mut kbd = Keyboard::new(Rect::new(0, 0, 320, 160));
        assert_eq!(kbd.geometry(), Rect::new(0, 0, 320, 160));

        kbd.set_geometry(Rect::new(10, 20, 300, 150));
        assert_eq!(kbd.geometry(), Rect::new(10, 20, 300, 150));
    }

    #[test]
    fn keyboard_visibility() {
        let mut kbd = Keyboard::new(Rect::new(0, 0, 320, 160));
        assert!(kbd.is_visible());
        kbd.hide();
        assert!(!kbd.is_visible());
        kbd.show();
        assert!(kbd.is_visible());
    }

    #[test]
    fn keyboard_enabled() {
        let mut kbd = Keyboard::new(Rect::new(0, 0, 320, 160));
        assert!(kbd.is_enabled());
        kbd.set_enabled(false);
        assert!(!kbd.is_enabled());
    }

    #[test]
    fn keyboard_id_kind() {
        let kbd = Keyboard::new(Rect::new(0, 0, 320, 160));
        assert_eq!(kbd.kind(), WidgetKind::Keyboard);
        // IDs should be unique across instances.
        let kbd2 = Keyboard::new(Rect::new(0, 0, 320, 160));
        assert_ne!(kbd.id(), kbd2.id());
    }

    #[test]
    fn keyboard_size_hint() {
        let kbd = Keyboard::new(Rect::new(0, 0, 320, 160));
        let hint = kbd.size_hint();
        assert_eq!(hint.width, 320);
        assert_eq!(hint.height, 160);
    }
}