pane_ui 0.1.0

A RON-driven, hot-reloadable wgpu UI library with spring animations and consistent scaling
Documentation
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
//! # keyboard
//!
//! On-screen QWERTY keyboard overlay for controller/mouse navigation.
//!
//! Opens automatically when a [`crate::items::TextBox`] enters edit mode (`nav_grabbed = true`)
//! and no hardware keyboard has been used recently. Driven by gamepad/arrow/mouse input;
//! typing is injected directly into the focused [`crate::items::TextBox`].

use crate::anim::{Anim, Spring, SpringValue};
use crate::draw::Rect;
use crate::items::UiItem;
use crate::loader::UiMsg;
use crate::styles::{DrawLabel, StyleCtx, StyleId, Transition, push_component};
use crate::threader::FrameCtx;
use crate::widgets::{ItemState, WidgetState};

// ── Recursive TextBox helpers ─────────────────────────────────────────────────

/// Returns `true` if the [`TextBox`] with `id` has `nav_grabbed = true` anywhere in
/// the tree rooted at `items`/`states` (paired slices from a container child list).
fn any_nav_grabbed_in(id: &str, items: &[UiItem], states: &[ItemState]) -> bool {
    for (item, state) in items.iter().zip(states.iter()) {
        match (item, state) {
            (UiItem::TextBox(tb), ItemState::TextBox(ts)) if tb.id == id => {
                if ts.nav_grabbed {
                    return true;
                }
            }
            (UiItem::ScrollPane(p), ItemState::ScrollPane(s)) => {
                if any_nav_grabbed_in(id, &p.items, &s.children) {
                    return true;
                }
            }
            (UiItem::Tab(t), ItemState::Tab(s)) => {
                for (page, page_states) in t.pages.iter().zip(s.children.iter()) {
                    if any_nav_grabbed_in(id, &page.items, page_states) {
                        return true;
                    }
                }
            }
            _ => {}
        }
    }
    false
}

/// Returns `true` if the [`TextBox`] with `id` has `nav_grabbed = true` anywhere in
/// the paired `(UiItem, ItemState)` root list (including nested containers).
pub fn any_textbox_nav_grabbed(id: &str, items: &[(UiItem, ItemState)]) -> bool {
    for (item, state) in items {
        match (item, state) {
            (UiItem::TextBox(tb), ItemState::TextBox(ts)) if tb.id == id => {
                if ts.nav_grabbed {
                    return true;
                }
            }
            (UiItem::ScrollPane(p), ItemState::ScrollPane(s)) => {
                if any_nav_grabbed_in(id, &p.items, &s.children) {
                    return true;
                }
            }
            (UiItem::Tab(t), ItemState::Tab(s)) => {
                for (page, page_states) in t.pages.iter().zip(s.children.iter()) {
                    if any_nav_grabbed_in(id, &page.items, page_states) {
                        return true;
                    }
                }
            }
            _ => {}
        }
    }
    false
}

/// Call `f` with mutable access to the [`TextBox`] and its state identified by `id`,
/// searching recursively through `items`/`states` (paired container child lists).
/// Returns `true` if the [`TextBox`] was found.
fn with_textbox_in<F>(id: &str, items: &mut [UiItem], states: &mut [ItemState], f: &mut F) -> bool
where
    F: FnMut(&mut crate::items::TextBox, &mut crate::widgets::TextBoxState),
{
    for (item, state) in items.iter_mut().zip(states.iter_mut()) {
        match (item, state) {
            (UiItem::TextBox(tb), ItemState::TextBox(ts)) if tb.id == id => {
                f(tb, ts);
                return true;
            }
            (UiItem::ScrollPane(p), ItemState::ScrollPane(s)) => {
                if with_textbox_in(id, &mut p.items, &mut s.children, f) {
                    return true;
                }
            }
            (UiItem::Tab(t), ItemState::Tab(s)) => {
                for (page, page_states) in t.pages.iter_mut().zip(s.children.iter_mut()) {
                    if with_textbox_in(id, &mut page.items, page_states, f) {
                        return true;
                    }
                }
            }
            _ => {}
        }
    }
    false
}

/// Call `f` with mutable access to the [`TextBox`] identified by `id`, searching
/// the root `(UiItem, ItemState)` list recursively through containers.
/// Returns `true` if the [`TextBox`] was found.
pub fn with_textbox_mut<F>(id: &str, items: &mut [(UiItem, ItemState)], mut f: F) -> bool
where
    F: FnMut(&mut crate::items::TextBox, &mut crate::widgets::TextBoxState),
{
    for (item, state) in items.iter_mut() {
        match (item, state) {
            (UiItem::TextBox(tb), ItemState::TextBox(ts)) if tb.id == id => {
                f(tb, ts);
                return true;
            }
            (UiItem::ScrollPane(p), ItemState::ScrollPane(s)) => {
                if with_textbox_in(id, &mut p.items, &mut s.children, &mut f) {
                    return true;
                }
            }
            (UiItem::Tab(t), ItemState::Tab(s)) => {
                for (page, page_states) in t.pages.iter_mut().zip(s.children.iter_mut()) {
                    if with_textbox_in(id, &mut page.items, page_states, &mut f) {
                        return true;
                    }
                }
            }
            _ => {}
        }
    }
    false
}

// ── Layout constants ──────────────────────────────────────────────────────────

/// Width of a standard key in unscaled OSK units.
const KEY_W: f32 = 80.0;
/// Height of every key in unscaled OSK units.
const KEY_H: f32 = 70.0;
/// Horizontal gap between adjacent keys.
const KEY_GAP: f32 = 8.0;
/// Vertical gap between rows.
const ROW_GAP: f32 = 10.0;
/// Inner padding between the panel edge and the key grid.
const PAD: f32 = 20.0;

/// Width of the SHIFT/ABC/BACK modifier keys in row 2.
///
/// Derived so that row 2 spans the same total width as row 0 (10 standard keys):
/// - `content_width` = 10·`KEY_W` + 9·`KEY_GAP` = 872
/// - `row2_letters`  =  7·`KEY_W` + 6·`KEY_GAP` = 608
/// - remaining for 2 mods + 2 gaps: 872 − 608 − 2·`KEY_GAP` = 248 → 124 each
const MOD_KEY_W: f32 = 124.0;

/// Width of the SYM/SPACE/DONE special keys in row 3.
///
/// Three keys at this width plus two `KEY_GAP`s equal the full content width.
const SPECIAL_KEY_W: f32 = 240.0;

/// Scene z-depth of the OSK panel background.
const Z_OSK: f32 = 4.0;
/// Scene z-depth of individual key quads and labels (drawn above the panel).
const Z_OSK_KEY: f32 = 4.5;

/// Unscaled width of the 10-key content area (row 0).
const BASE_CONTENT_W: f32 = 10.0 * KEY_W + 9.0 * KEY_GAP; // 872
/// Unscaled total panel width including left and right padding.
const BASE_PANEL_W: f32 = 2.0 * PAD + BASE_CONTENT_W; // 912
/// Unscaled total panel height including top and bottom padding.
const BASE_PANEL_H: f32 = 2.0 * PAD + 4.0 * KEY_H + 3.0 * ROW_GAP; // 350

// ── Key layout tables ─────────────────────────────────────────────────────────
//
// Each table has 4 rows:
//   row 0 — 10 standard letter/digit keys
//   row 1 —  9 standard letter keys (centered)
//   row 2 — left modifier (col 0), 7 letter keys (col 1-7), BACK (col 8)
//   row 3 — SYM/ABC toggle, SPACE, DONE

/// Lower-case alpha layout.
const ALPHA_ROWS: [&[&str]; 4] = [
    &["q", "w", "e", "r", "t", "y", "u", "i", "o", "p"],
    &["a", "s", "d", "f", "g", "h", "j", "k", "l"],
    &["SHIFT", "z", "x", "c", "v", "b", "n", "m", "BACK"],
    &["SYM", "SPACE", "DONE"],
];

/// Upper-case alpha layout (active while one-shot SHIFT is on).
const SHIFT_ROWS: [&[&str]; 4] = [
    &["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"],
    &["A", "S", "D", "F", "G", "H", "J", "K", "L"],
    &["SHIFT", "Z", "X", "C", "V", "B", "N", "M", "BACK"],
    &["SYM", "SPACE", "DONE"],
];

/// Digits and punctuation layout (active in [`OskLayer::Symbols`]).
const SYM_ROWS: [&[&str]; 4] = [
    &["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"],
    &["!", "@", "#", "$", "%", "^", "&", "*", "-", "+"],
    &["ABC", "(", ")", "_", "=", "[", "]", ";", "BACK"],
    &["SYM", "SPACE", "DONE"],
];

/// Return the key-label table for the given layer and shift state.
const fn get_rows(layer: OskLayer, shift: bool) -> &'static [&'static [&'static str]; 4] {
    match (layer, shift) {
        (OskLayer::Alpha, false) => &ALPHA_ROWS,
        (OskLayer::Alpha, true) => &SHIFT_ROWS,
        (OskLayer::Symbols, _) => &SYM_ROWS,
    }
}

/// Number of key-animation slots per row in the flat `key_anims` array.
///
/// Must be ≥ the widest row (10 keys in row 0). Set to 12 for alignment.
const ANIM_STRIDE: usize = 12;
/// Total slots in the flat animation array: 4 rows × `ANIM_STRIDE` columns.
const MAX_KEYS: usize = 4 * ANIM_STRIDE; // 48

/// Map `(row, col)` to a flat index into [`OskState::key_anims`].
const fn key_index(row: usize, col: usize) -> usize {
    row * ANIM_STRIDE + col
}

// ── Geometry helpers ──────────────────────────────────────────────────────────

/// Fraction of the 1080-unit screen height the OSK panel occupies.
const FILL: f32 = 0.30;

/// Uniform scale factor applied to all unscaled OSK dimensions.
///
/// Scales so that `BASE_PANEL_H * osk_scale() == 1080 * FILL`.
/// `_pw` and `_ph` are reserved for future aspect-ratio-aware scaling;
/// currently only screen height drives the scale.
fn osk_scale(_pw: f32, _ph: f32) -> f32 {
    1080.0 * FILL / BASE_PANEL_H
}

/// Vertical position of the panel top-left corner, accounting for the slide animation.
///
/// `t = 0` → fully off the bottom of the screen; `t = 1` → fully visible.
fn panel_y(slide_t: f32, scaled_ph: f32) -> f32 {
    let closed = 540.0 + 10.0;
    let open = 540.0 - scaled_ph - 10.0;
    (open - closed).mul_add(slide_t.clamp(0.0, 1.0), closed)
}

/// Compute the bounding rect of a single key in screen space.
fn key_rect(row: usize, col: usize, rows: &[&[&str]; 4], px: f32, py: f32, s: f32) -> Rect {
    let cx = PAD.mul_add(s, px);
    let cy = PAD.mul_add(s, py);
    let row_y = (row as f32).mul_add((KEY_H + ROW_GAP) * s, cy);
    let cw = BASE_CONTENT_W * s;

    match row {
        3 => {
            // Three equal special keys spanning full content width.
            let sw = SPECIAL_KEY_W * s;
            let kg = KEY_GAP * s;
            let total = 3.0f32.mul_add(sw, 2.0 * kg);
            let start_x = (cw - total).mul_add(0.5, cx);
            Rect {
                x: (col as f32).mul_add(sw + kg, start_x),
                y: row_y,
                w: sw,
                h: KEY_H * s,
            }
        }
        2 => {
            // Left modifier (col 0), 7 letter keys (col 1-7), right BACK (col 8).
            let mod_w = MOD_KEY_W * s;
            let kw = KEY_W * s;
            if col == 0 {
                Rect {
                    x: cx,
                    y: row_y,
                    w: mod_w,
                    h: KEY_H * s,
                }
            } else if col == rows[2].len() - 1 {
                // BACK is always the last key in row 2.
                let x = 7.0f32
                    .mul_add(KEY_W, 8.0f32.mul_add(KEY_GAP, MOD_KEY_W))
                    .mul_add(s, cx);
                Rect {
                    x,
                    y: row_y,
                    w: mod_w,
                    h: KEY_H * s,
                }
            } else {
                // Letter keys: col 1-7 follow the left modifier.
                let x = ((col - 1) as f32)
                    .mul_add(KEY_W, (col as f32).mul_add(KEY_GAP, MOD_KEY_W))
                    .mul_add(s, cx);
                Rect {
                    x,
                    y: row_y,
                    w: kw,
                    h: KEY_H * s,
                }
            }
        }
        _ => {
            // Rows 0-1: centered regular keys.
            let kw = KEY_W * s;
            let kg = KEY_GAP * s;
            let n = rows[row].len() as f32;
            let row_w = n.mul_add(kw, (n - 1.0) * kg);
            let start_x = (cw - row_w).mul_add(0.5, cx);
            Rect {
                x: (col as f32).mul_add(kw + kg, start_x),
                y: row_y,
                w: kw,
                h: KEY_H * s,
            }
        }
    }
}

// ── OskLayer ──────────────────────────────────────────────────────────────────

/// Which character set the on-screen keyboard is currently showing.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum OskLayer {
    /// Lower- or upper-case Latin alphabet (toggled by SHIFT).
    Alpha,
    /// Digits and punctuation symbols.
    Symbols,
}

// ── OskState ─────────────────────────────────────────────────────────────────

/// Runtime state for the on-screen keyboard overlay.
pub struct OskState {
    /// Whether the OSK is currently open (visible or animating in).
    pub open: bool,
    /// Focused row index within the current key layout (0 = top row).
    pub row: usize,
    /// Focused column index within `row`.
    pub col: usize,
    /// Which character set is displayed.
    pub layer: OskLayer,
    /// One-shot shift: active for the next character only, clears after insertion.
    pub shift: bool,
    /// Slide-in/out spring — `t = 0` fully hidden, `t = 1` fully visible.
    pub slide: SpringValue,
    /// Per-key hover/press spring animations, indexed by `key_index(row, col)`.
    pub key_anims: Vec<Anim>,
}

impl Default for OskState {
    fn default() -> Self {
        Self {
            open: false,
            row: 0,
            col: 0,
            layer: OskLayer::Alpha,
            shift: false,
            slide: SpringValue::new(0.0, Spring::BOUNCY),
            key_anims: (0..MAX_KEYS).map(|_| Anim::new(Spring::BOUNCY)).collect(),
        }
    }
}

/// Returns `true` when the mouse cursor is over the OSK panel (accounting for slide animation).
/// Used by `tick_all` to block click-through to widgets underneath.
pub fn panel_hovered(osk: &OskState, mx: f32, my: f32, pw: f32, ph: f32) -> bool {
    let slide_t = osk.slide.t();
    if slide_t <= 0.001 {
        return false;
    }
    let s = osk_scale(pw, ph);
    let spw = BASE_PANEL_W * s;
    let sph = BASE_PANEL_H * s;
    let px = -spw * 0.5;
    let py = panel_y(slide_t, sph);
    Rect {
        x: px,
        y: py,
        w: spw,
        h: sph,
    }
    .contains(mx, my)
}

// ── Main tick ─────────────────────────────────────────────────────────────────

/// Tick the on-screen keyboard: update open/close state, advance the slide spring,
/// draw all keys, and process input.
pub fn tick_osk(ctx: &mut FrameCtx) {
    // OSK requires a default style to render — without one it would silently open
    // in a phantom state (invisible and unresponsive) while permanently consuming nav.
    let Some(style_id) = ctx.persistent.default_style else {
        return;
    };

    // Clone to avoid conflicting borrows during root access.
    let focused_id = ctx.persistent.nav.focused_id.clone();
    let active = ctx.persistent.active_root.clone();

    // Determine whether the focused item is a TextBox in edit mode.
    // Searches recursively through containers (ScrollPane, Tab) so nested
    // TextBoxes trigger the OSK just like top-level ones.
    let nav_grabbed = match (&focused_id, &active) {
        (Some(id), Some(name)) => ctx
            .persistent
            .roots
            .get(name)
            .is_some_and(|root| any_textbox_nav_grabbed(id, &root.items)),
        _ => false,
    };

    let hw_present = ctx.frame.input.keyboard_present();
    let want_open = nav_grabbed && !hw_present;

    // Toggle open state; record whether this is the opening frame.
    let just_opened = want_open && !ctx.persistent.osk.open;
    if just_opened {
        ctx.persistent.osk.open = true;
        ctx.persistent.osk.row = 0;
        ctx.persistent.osk.col = 0;
        ctx.persistent.osk.layer = OskLayer::Alpha;
        ctx.persistent.osk.shift = false;
    } else if !want_open && ctx.persistent.osk.open {
        ctx.persistent.osk.open = false;
    }

    let dt = ctx.frame.dt;
    let target = if ctx.persistent.osk.open { 1.0 } else { 0.0 };
    ctx.persistent.osk.slide.update(target, dt);

    if ctx.persistent.osk.open {
        ctx.persistent.nav.consumes_nav = true;
    }

    let slide_t = ctx.persistent.osk.slide.t();
    if slide_t <= 0.001 {
        return;
    }

    let s = osk_scale(ctx.frame.pw, ctx.frame.ph);
    let pw = BASE_PANEL_W * s;
    let ph = BASE_PANEL_H * s;
    let px = -pw * 0.5;
    let py = panel_y(slide_t, ph);

    draw_osk(ctx, style_id, px, py, pw, ph, s, dt);
    handle_osk_input(
        ctx,
        px,
        py,
        pw,
        ph,
        s,
        focused_id.as_deref(),
        active.as_deref(),
        just_opened,
    );
}

// ── Draw ──────────────────────────────────────────────────────────────────────

/// Draw the panel background and all key quads for this frame.
fn draw_osk(
    ctx: &mut FrameCtx,
    style_id: StyleId,
    px: f32,
    py: f32,
    pw: f32,
    ph: f32,
    s: f32,
    dt: f32,
) {
    let osk_row = ctx.persistent.osk.row;
    let osk_col = ctx.persistent.osk.col;
    let osk_open = ctx.persistent.osk.open;
    let osk_layer = ctx.persistent.osk.layer;
    let osk_shift = ctx.persistent.osk.shift;

    let mx = ctx.frame.input.mouse_x;
    let my = ctx.frame.input.mouse_y;
    let mouse_held = ctx.frame.input.left_pressed;
    let nav_confirming = osk_open && (ctx.frame.input.space || ctx.frame.input.enter);

    // Panel background.
    {
        let registry = &ctx.persistent.styles;
        let tex: &dyn crate::textures::TextureInfo = ctx
            .persistent
            .tex_reg
            .as_ref()
            .map_or(&crate::textures::DUMMY_TEX, |r| r);
        let scene = &mut ctx.frame.scene;
        registry.draw(
            style_id,
            Rect {
                x: px,
                y: py,
                w: pw,
                h: ph,
            },
            WidgetState::default(),
            DrawLabel {
                label: None,
                z: Z_OSK,
                clip: None,
                alpha: 1.0,
            },
            scene,
            tex,
        );
    }

    let rows = get_rows(osk_layer, osk_shift);

    for (r, row_keys) in rows.iter().enumerate() {
        for (c, &key_label) in row_keys.iter().enumerate() {
            let rect = key_rect(r, c, rows, px, py, s);
            let is_focused = osk_open && r == osk_row && c == osk_col;
            let is_hovered = is_focused || rect.contains(mx, my);
            let is_pressed = (is_hovered && mouse_held) || (is_focused && nav_confirming);

            // SHIFT key glows (hovered) when shift is active.
            // SYM key glows when in Symbols layer.
            let modifier_active = (key_label == "SHIFT" && osk_shift)
                || (key_label == "SYM" && osk_layer == OskLayer::Symbols);

            let visual = WidgetState {
                focused: is_focused,
                hovered: is_hovered || modifier_active,
                pressed: is_pressed,
                ..WidgetState::default()
            };

            let ki = key_index(r, c);
            ctx.persistent.osk.key_anims[ki].transition(visual);
            ctx.persistent.osk.key_anims[ki].update(dt);
            let from = ctx.persistent.osk.key_anims[ki].prev_state();
            let t = ctx.persistent.osk.key_anims[ki].t();

            let registry = &ctx.persistent.styles;
            let tex: &dyn crate::textures::TextureInfo = ctx
                .persistent
                .tex_reg
                .as_ref()
                .map_or(&crate::textures::DUMMY_TEX, |r| r);
            let scene = &mut ctx.frame.scene;

            let vs = push_component(
                scene,
                StyleCtx {
                    registry,
                    tex_registry: tex,
                },
                style_id,
                Transition {
                    from,
                    to: visual,
                    t,
                },
                rect,
                Z_OSK_KEY,
                None,
            );

            let font_size = vs
                .font_size
                .unwrap_or_else(|| (rect.h * 0.45).clamp(10.0, 48.0));
            let color = vs.text_color.unwrap_or(crate::draw::Color::WHITE);
            scene.push_text(&crate::draw::TextDraw {
                text: key_label,
                x: rect.x + vs.text_offset_x,
                y: (rect.h - font_size).mul_add(0.5, rect.y) + vs.text_offset_y,
                w: rect.w,
                size: font_size,
                color,
                align: vs.text_align,
                font: vs.font.as_deref(),
                bold: vs.bold,
                italic: vs.italic,
                clip: None,
                z: Z_OSK_KEY,
            });
        }
    }
}

// ── Input ─────────────────────────────────────────────────────────────────────

/// Handle all OSK input for this frame: mouse clicks, arrow navigation, confirm, and close.
///
/// Skips input on the frame the OSK opens to prevent the key that triggered it
/// from immediately firing.
fn handle_osk_input(
    ctx: &mut FrameCtx,
    px: f32,
    py: f32,
    pw: f32,
    ph: f32,
    s: f32,
    focused_id: Option<&str>,
    active: Option<&str>,
    just_opened: bool,
) {
    if !ctx.persistent.osk.open || just_opened {
        return;
    }

    // Bind rows once — used by both mouse click and nav paths.
    let rows = get_rows(ctx.persistent.osk.layer, ctx.persistent.osk.shift);

    // Mouse: click on a key fires it; clicks outside are ignored (use DONE or Escape to close).
    if ctx.frame.input.left_just_pressed {
        let mx = ctx.frame.input.mouse_x;
        let my = ctx.frame.input.mouse_y;
        if !(Rect {
            x: px,
            y: py,
            w: pw,
            h: ph,
        }
        .contains(mx, my))
        {
            return;
        }
        let mut clicked_key: Option<(usize, usize)> = None;
        'hit: for (r, row_keys) in rows.iter().enumerate() {
            for (c, _) in row_keys.iter().enumerate() {
                if key_rect(r, c, rows, px, py, s).contains(mx, my) {
                    clicked_key = Some((r, c));
                    break 'hit;
                }
            }
        }
        if let Some((r, c)) = clicked_key {
            ctx.persistent.osk.row = r;
            ctx.persistent.osk.col = c;
            let label = get_rows(ctx.persistent.osk.layer, ctx.persistent.osk.shift)[r][c];
            fire_key(label, ctx, focused_id, active);
        }
        return;
    }

    // Arrow navigation.
    let (mut row, mut col) = (ctx.persistent.osk.row, ctx.persistent.osk.col);

    if ctx.frame.input.arrow_up && row > 0 {
        row -= 1;
        col = col.min(rows[row].len() - 1);
    }
    if ctx.frame.input.arrow_down && row + 1 < rows.len() {
        row += 1;
        col = col.min(rows[row].len() - 1);
    }
    if ctx.frame.input.arrow_left && col > 0 {
        col -= 1;
    }
    if ctx.frame.input.arrow_right && col + 1 < rows[row].len() {
        col += 1;
    }
    ctx.persistent.osk.row = row;
    ctx.persistent.osk.col = col;

    // B button (gamepad East) or Escape closes the OSK without submitting.
    if ctx.frame.input.escape {
        ctx.persistent.osk.open = false;
        // Release nav_grabbed so the TextBox returns to normal focus state.
        if let (Some(id), Some(name)) = (focused_id, active)
            && let Some(root) = ctx.persistent.roots.get_mut(name)
        {
            for (item, state) in &mut root.items {
                if let (UiItem::TextBox(tb), ItemState::TextBox(ts)) = (item, state)
                    && tb.id == id
                {
                    ts.nav_grabbed = false;
                }
            }
        }
        return;
    }

    if ctx.frame.input.space || ctx.frame.input.enter {
        let label = get_rows(ctx.persistent.osk.layer, ctx.persistent.osk.shift)[row][col];
        fire_key(label, ctx, focused_id, active);
    }
}

// ── Key actions ───────────────────────────────────────────────────────────────

/// Fire a single OSK key by label, mutating the focused [`crate::items::TextBox`] directly.
///
/// Searches for the [`crate::items::TextBox`] recursively so nested widgets (inside `ScrollPane`
/// or `Tab`) work the same as top-level ones.
fn fire_key(key: &str, ctx: &mut FrameCtx, focused_id: Option<&str>, active: Option<&str>) {
    match key {
        "SHIFT" => {
            ctx.persistent.osk.shift = !ctx.persistent.osk.shift;
        }
        "SYM" => {
            ctx.persistent.osk.layer = OskLayer::Symbols;
            ctx.persistent.osk.shift = false;
        }
        "ABC" => {
            ctx.persistent.osk.layer = OskLayer::Alpha;
            ctx.persistent.osk.shift = false;
        }
        "DONE" => {
            ctx.persistent.osk.open = false;
            if let (Some(id), Some(name)) = (focused_id, active)
                && let Some(root) = ctx.persistent.roots.get_mut(name)
            {
                let tx = ctx.persistent.tx.clone();
                with_textbox_mut(id, &mut root.items, |_tb, ts| {
                    ts.nav_grabbed = false;
                    let value = ts.text.clone();
                    let _ = tx.send(UiMsg::TextSubmitted(id.to_owned(), value));
                });
            }
        }
        "BACK" => {
            if let (Some(id), Some(name)) = (focused_id, active)
                && let Some(root) = ctx.persistent.roots.get_mut(name)
            {
                let tx = ctx.persistent.tx.clone();
                with_textbox_mut(id, &mut root.items, |_tb, ts| {
                    if ts.cursor_pos > 0 {
                        ts.text.remove(ts.cursor_pos - 1);
                        ts.cursor_pos -= 1;
                        let value = ts.text.clone();
                        let _ = tx.send(UiMsg::TextChanged(id.to_owned(), value));
                    }
                });
            }
        }
        _ => {
            let ch = if key == "SPACE" {
                ' '
            } else {
                key.chars().next().unwrap_or(' ')
            };
            let typed = if let (Some(id), Some(name)) = (focused_id, active)
                && let Some(root) = ctx.persistent.roots.get_mut(name)
            {
                let tx = ctx.persistent.tx.clone();
                with_textbox_mut(id, &mut root.items, |tb, ts| {
                    if tb.max_len.is_none_or(|max| ts.text.chars().count() < max) {
                        ts.text.insert(ts.cursor_pos, ch);
                        ts.cursor_pos += 1;
                        let value = ts.text.clone();
                        let _ = tx.send(UiMsg::TextChanged(id.to_owned(), value));
                    }
                })
            } else {
                false
            };
            // One-shot shift: clear only after a character was actually inserted.
            if typed {
                ctx.persistent.osk.shift = false;
            }
        }
    }
}