sgl-2d 0.4.2

Caller-driven 2D rendering, assets, text, lighting, and immediate UI for SGL games
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
//! Immediate-mode UI over the [`DrawList`] screen channel (AR-6): the app
//! rebuilds every widget each frame; the only retained state is interaction
//! (which widget the mouse went down on, which line-edit has focus, a blink
//! clock).
//!
//! Frame shape:
//! ```text
//!   let mut frame = ui.begin(&mut text, &mut list, input); // UiInput from the app
//!   frame.panel(..); frame.button(..); frame.line_edit(..);
//!   frame.end();
//!   let uploads = text.end_frame(&mut assets.textures, &mut list);
//!   // upload `uploads` + render `list`
//! ```
//!
//! The app owns input translation: it fills [`UiInput`] (mouse in **logical**
//! pixels, printable chars, navigation/edit commands) from whatever platform
//! events it receives — `ui` never touches `platform`. Translate platform
//! select-all/copy/cut shortcuts to [`UiKey`], supply clipboard paste text in
//! [`UiInput::paste`], and drain [`Ui::take_clipboard_text`] to the clipboard.
//! After ending the frame, consult [`Ui::keyboard_captured`] before dispatching
//! world shortcuts so Tab, activation, editing and Escape have one owner.
//! Widgets use stable names for focus and edit selection. Tab traverses visible
//! widgets in the preceding frame's submission order (Shift reverses), wrapping
//! and staying inside the open popup/modal. Missing or fully clipped widgets
//! lose focus at frame end. `has_focus` retains its text-input meaning.
//!
//! [`UiTheme::default`] preserves the original translucent game palette;
//! [`UiTheme::tools_dark`] and [`UiTheme::tools_light`] provide opaque tool
//! chrome. Copy [`Ui::theme`] for caller-composed labels and surfaces. Buttons
//! **act on press-down**, not release.
//!
//! # Composing tools (including agent-authored interfaces)
//!
//! Derive layout and input from the current logical viewport in points, not a
//! fixed resolution. Map physical pointer coordinates through the platform's
//! DPI/letterbox transform once; configure text raster scale for that mapping.
//! Bound pane sizes against the viewport; [`UiFrame::splitter`] only changes a
//! caller-owned extent. Measure labels with [`TextRenderer::measure`], reserve
//! trailing row actions first, then clip or wrap the remaining label/help area.
//! Give each overflowing region one [`UiFrame::scroll_area_begin`] and its own offset,
//! passed again to [`UiFrame::scroll_area_end`]; nested areas take the wheel innermost
//! first. Restore enclosing clips and keep fixed toolbars outside scrolling content.
//!
//! Use text for unfamiliar/consequential commands and compact icons for repeated
//! familiar actions. Pair icons with [`UiFrame::tooltip_for`] using the same
//! stable name: keyboard focus also reveals help, including disabled reasons.
//! Keep hit targets larger than glyphs and retain visible focus/selection marks;
//! state must not depend only on color. Submit in useful keyboard traversal order.
//! Route keyboard/pointer capture before game shortcuts or world gestures, and
//! cancel interactions on window focus loss. The game owns layout, persistence,
//! undo and confirmation; use explicit labels such as “Delete layer”/“Cancel”.
//! See `specs/client.md` tool composition and the runnable `tool_ui` example.

// Immediate input snapshots intentionally expose independent edge/state flags;
// bounded widget indices and frame counters are converted to logical pixels.
#![allow(
    clippy::cast_precision_loss,
    clippy::float_cmp,
    clippy::items_after_statements,
    clippy::struct_excessive_bools
)]

use crate::assets::{Assets, Handle, Texture};
use crate::canvas::draw::{DrawList, Rect, SpriteInstance};
use crate::canvas::text::{HAlign, TextChannel, TextRenderer, TextStyle, VAlign};
use sgl_core::math::Vec2;

mod button;
mod input;
mod layout;
mod number_field;
mod popup;
#[cfg(test)]
mod test_ui;
mod text_edit;
mod theme;

pub use crate::fps::FpsCounter;
pub use button::IconButton;
pub use input::{UiInput, UiKey};
pub use layout::{Splitter, SplitterAxis, SplitterResponse, UiCursor};
pub use number_field::NumberField;
pub use theme::UiTheme;

use input::FocusTarget;
use layout::SplitterDrag;
use number_field::NumberDrag;
use text_edit::EditState;

// --- Godot-4-default-theme-ish palette (sRGB, straight alpha). ---

/// Panel background (Godot default `Panel` style box).
pub const PANEL_COLOR: [f32; 4] = [0.1, 0.1, 0.1, 0.6];
const BUTTON_NORMAL: [f32; 4] = [0.1, 0.1, 0.1, 0.6];
const BUTTON_HOVER: [f32; 4] = [0.225, 0.225, 0.225, 0.6];
const BUTTON_PRESSED: [f32; 4] = [0.0, 0.0, 0.0, 0.6];
const FONT_NORMAL: [f32; 4] = [0.875, 0.875, 0.875, 1.0];
const FONT_HOVER: [f32; 4] = [0.95, 0.95, 0.95, 1.0];
const FONT_PRESSED: [f32; 4] = [1.0, 1.0, 1.0, 1.0];
/// Godot default accent blue (focus/selection borders).
const ACCENT: [f32; 4] = [0.44, 0.73, 0.98, 1.0];
const CARET: [f32; 4] = [0.95, 0.95, 0.95, 1.0];
/// Caret blink period in seconds (on for the first half).
const CARET_BLINK: f32 = 1.0;
/// Non-title text carries a 1 px black outline (PR-9: outline 10 for the
/// title, 1 elsewhere).
const WIDGET_OUTLINE: f32 = 1.0;

/// Stable widget identity, hashed from the caller's name string (FNV-1a).
fn widget_id(name: &str) -> u64 {
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    for b in name.bytes() {
        hash ^= u64::from(b);
        hash = hash.wrapping_mul(0x100_0000_01b3);
    }
    hash
}

fn contains(rect: &Rect, p: Vec2) -> bool {
    p.x >= rect.min.x && p.x < rect.max.x && p.y >= rect.min.y && p.y < rect.max.y
}

const SCROLLBAR_TRACK: [f32; 4] = [0.0, 0.0, 0.0, 0.35];
const SCROLLBAR_THUMB: [f32; 4] = [0.5, 0.5, 0.5, 0.8];
const SCROLLBAR_THUMB_HOVER: [f32; 4] = [0.65, 0.65, 0.65, 0.9];
/// Millions of exactly representable integer z steps per band keep panels
/// below popovers and modals even when submitted later. Cursors saturate
/// within their band; the draw list's stable sort keeps equal-z push order.
const OVERLAY_Z: f32 = 2_097_152.0;
const POPOVER_Z: f32 = 4_194_304.0;
const MODAL_Z: f32 = 8_388_608.0;
/// f32 represents every integer through 2^24 exactly.
const MAX_UI_Z: f32 = 16_777_216.0;
/// Popover/modal backdrop colors.
const POPOVER_BG: [f32; 4] = [0.08, 0.08, 0.08, 0.98];
const MODAL_DIM: [f32; 4] = [0.0, 0.0, 0.0, 0.55];

/// Persistent UI interaction state + the shared 1×1 white texture used for
/// every flat rect. Create once; `begin` each frame.
pub struct Ui {
    white: Handle<Texture>,
    theme: UiTheme,
    /// Widget the primary button went down on (pressed visual until release).
    active: Option<u64>,
    /// Focused widget.
    focus: Option<u64>,
    focus_order: Vec<FocusTarget>,
    edit: EditState,
    keyboard_captured: bool,
    clipboard_text: Option<String>,
    /// Caret-blink clock, advanced by `UiInput::dt`.
    clock: f32,
    /// The open dropdown/popover, if any (retained across frames).
    open_popup: Option<u64>,
    /// Overlay panel regions drawn **last** frame: ordinary widgets ignore
    /// the mouse inside them this frame, so a click on a panel never falls
    /// through to the widget underneath.
    blocked: Vec<Rect>,
    /// The previous frame's popover owner and visible rect. Its shield
    /// lasts through the selection frame so the press cannot fall through.
    popover_blocked: Option<(u64, Rect)>,
    /// A modal was drawn last frame: widgets outside its scope ignore input.
    modal_blocking: bool,
    modal_scope: Option<u64>,
    /// Scrollbar-thumb drag: `(widget id, grab offset within the thumb)`.
    thumb_drag: Option<(u64, f32)>,
    /// A numeric field's value scrub in progress (see [`UiFrame::number_field`]).
    number_drag: Option<NumberDrag>,
    /// The text of the numeric field that has keyboard focus (the field
    /// re-parses it whenever it changes; dropped with the focus).
    number_edit: String,
    splitter_drag: Option<SplitterDrag>,
    pointer_consumed: bool,
}

impl Ui {
    /// Register the shared white pixel texture in `assets` and build the UI
    /// state. The app must upload [`white_texture`](Self::white_texture) to
    /// the renderer once, like any other texture.
    pub fn new(assets: &mut Assets<Texture>) -> Self {
        let white = crate::assets::white_texture(assets);
        Self {
            white,
            theme: UiTheme::default(),
            active: None,
            focus: None,
            focus_order: Vec::new(),
            edit: EditState::default(),
            keyboard_captured: false,
            clipboard_text: None,
            clock: 0.0,
            open_popup: None,
            blocked: Vec::new(),
            popover_blocked: None,
            modal_blocking: false,
            modal_scope: None,
            thumb_drag: None,
            number_drag: None,
            number_edit: String::new(),
            splitter_drag: None,
            pointer_consumed: false,
        }
    }

    /// Select semantic colors for subsequent frames. Interaction state survives
    /// theme changes; the game owns choosing and persisting the preference.
    pub fn set_theme(&mut self, theme: UiTheme) {
        self.theme = theme;
    }

    /// Current semantic colors, also available to caller-composed labels/rects.
    #[must_use]
    pub fn theme(&self) -> &UiTheme {
        &self.theme
    }

    /// The shared 1×1 white texture handle (upload once at startup). This is
    /// the same handle [`crate::assets::white_texture`] hands every other
    /// consumer, so the UI and an overlay share one upload.
    #[must_use]
    pub fn white_texture(&self) -> Handle<Texture> {
        self.white
    }

    /// Whether a splitter owns the pointer, including outside its handle.
    /// Suppress world drags while true, including the release/removal frame.
    /// Release, removal and
    /// [`cancel_interactions`](Self::cancel_interactions) end capture.
    #[must_use]
    pub fn pointer_captured(&self) -> bool {
        self.pointer_consumed || self.splitter_drag.is_some()
    }

    /// Whether a line-edit currently has keyboard focus (the app can use
    /// this to suppress game hotkeys while typing).
    #[must_use]
    pub fn has_focus(&self) -> bool {
        self.focus.is_some() && self.edit.id == self.focus
    }

    /// Whether this frame belongs to the UI keyboard interaction. Query after
    /// `UiFrame::end` before dispatching world actions; includes Tab and Escape
    /// even when those commands remove focus or dismiss a popup.
    #[must_use]
    pub fn keyboard_captured(&self) -> bool {
        self.keyboard_captured || self.focus.is_some() || self.any_popup_open()
    }

    /// Drain a copy/cut request and write it to the platform clipboard. Secret
    /// fields never export their contents. Paste arrives through `UiInput::paste`.
    pub fn take_clipboard_text(&mut self) -> Option<String> {
        self.clipboard_text.take()
    }

    #[cfg(test)]
    fn is_focused_name(&self, name: &str) -> bool {
        self.focus == Some(widget_id(name))
    }

    /// Whether any dropdown popover is open (apps close it on Esc via
    /// [`close_popups`](Self::close_popups)).
    #[must_use]
    pub fn any_popup_open(&self) -> bool {
        self.open_popup.is_some()
    }

    /// Close any open dropdown popover.
    pub fn close_popups(&mut self) {
        self.open_popup = None;
    }

    /// Drop transient pointer interaction (active widget, thumb drags) and
    /// close any open popover. Call on focus loss so a half-finished press
    /// cannot complete later and a dropdown does not linger open while the
    /// window is unfocused.
    pub fn cancel_interactions(&mut self) {
        self.active = None;
        self.thumb_drag = None;
        self.number_drag = None;
        self.splitter_drag = None;
        self.pointer_consumed = false;
        self.open_popup = None;
    }

    /// Drop keyboard focus from any line-edit (R-17/#25: closing a panel
    /// that hosts text fields must release focus, or app hotkeys sharing
    /// letters with typing — e.g. F for fullscreen — stay suppressed).
    pub fn clear_focus(&mut self) {
        self.focus = None;
    }

    /// Start a frame: widgets are drawn through the returned [`UiFrame`]
    /// into `list`'s screen channel (rects immediately, text via `text`'s
    /// queue). Call [`UiFrame::end`] when done, then `text.end_frame(..)`.
    /// A release and press in one frame with the button held count as
    /// release then press: the release ends any drag or held widget first.
    pub fn begin<'a>(
        &'a mut self,
        text: &'a mut TextRenderer,
        list: &'a mut DrawList,
        input: UiInput,
    ) -> UiFrame<'a> {
        self.clock = (self.clock + input.dt) % CARET_BLINK;
        // A release and press in one frame with the button held count as
        // release then press: the release ends any capture first, so the
        // press re-arms only what it hits.
        if input.mouse_pressed && input.mouse_released && input.mouse_down {
            self.active = None;
            self.thumb_drag = None;
            self.number_drag = None;
            self.splitter_drag = None;
        }
        self.pointer_consumed = self.splitter_drag.is_some();
        self.keyboard_captured =
            self.focus.is_some() || self.open_popup.is_some() || self.modal_blocking;
        if input.keys.contains(&UiKey::Tab) {
            let candidates: Vec<_> = self
                .focus_order
                .iter()
                .filter(|target| {
                    if let Some(popup) = self.open_popup {
                        target.popup == Some(popup)
                    } else {
                        target.popup.is_none()
                            && (!self.modal_blocking || target.modal == self.modal_scope)
                    }
                })
                .collect();
            if !candidates.is_empty() {
                let at = candidates
                    .iter()
                    .position(|target| Some(target.id) == self.focus);
                let next = match (at, input.shift) {
                    (Some(i), true) => (i + candidates.len() - 1) % candidates.len(),
                    (Some(i), false) => (i + 1) % candidates.len(),
                    (None, true) => candidates.len() - 1,
                    (None, false) => 0,
                };
                self.focus = Some(candidates[next].id);
                self.keyboard_captured = true;
            }
        }
        let popup_dismissed = input.keys.contains(&UiKey::Escape) && self.open_popup.is_some();
        if popup_dismissed {
            self.focus = self.open_popup.take();
        }
        // A popover closed by Escape, `close_popups` or `cancel_interactions`
        // is not drawn this frame, so it no longer blocks.
        if self.open_popup.is_none() {
            self.popover_blocked = None;
        }
        UiFrame {
            ui: self,
            text,
            list,
            input,
            z: 0.0,
            z_overlay: OVERLAY_Z,
            z_popover: POPOVER_Z,
            z_modal: MODAL_Z,
            overlay: false,
            clip: None,
            new_blocked: Vec::new(),
            new_popover_blocked: None,
            new_modal: None,
            modal_scope: None,
            edit_clicked: false,
            focus_order: Vec::new(),
            popup_scope: None,
            popup_dismissed,
            key_used: false,
            focus_requested: false,
            splitter_seen: false,
            popup_seen: false,
            scroll_scopes: Vec::new(),
            wheel_consumed: false,
        }
    }
}

/// One frame's widget builder — all draws go to the screen channel with
/// increasing z within each band. Each cursor saturates before the next band;
/// equal-z draws retain their screen-list push order.
/// Panels, dropdown popovers and modals draw in successively higher z
/// bands and block the widgets underneath (see [`UiFrame::dropdown`] and
/// [`UiFrame::confirm_modal`]).
pub struct UiFrame<'a> {
    ui: &'a mut Ui,
    text: &'a mut TextRenderer,
    list: &'a mut DrawList,
    input: UiInput,
    z: f32,
    /// Draw cursors for panels, popovers and modals, respectively.
    z_overlay: f32,
    z_popover: f32,
    z_modal: f32,
    /// Currently emitting overlay content (bypasses panel blockers only).
    overlay: bool,
    /// Current clip rect applied to widget draws + hit tests.
    clip: Option<Rect>,
    /// Overlay rects drawn this frame → `Ui::blocked` next frame.
    new_blocked: Vec<Rect>,
    /// The open popover's visible rect → `Ui::popover_blocked` next frame.
    new_popover_blocked: Option<(u64, Rect)>,
    /// A modal was drawn this frame → `Ui::modal_blocking` next frame.
    new_modal: Option<u64>,
    modal_scope: Option<u64>,
    /// A line-edit consumed this frame's press (suppresses unfocus).
    edit_clicked: bool,
    focus_order: Vec<FocusTarget>,
    popup_scope: Option<u64>,
    popup_dismissed: bool,
    key_used: bool,
    focus_requested: bool,
    splitter_seen: bool,
    /// The open popup's dropdown was submitted this frame.
    popup_seen: bool,
    /// Open scroll areas, innermost last.
    scroll_scopes: Vec<layout::ScrollScope>,
    /// A scroll area took this frame's wheel.
    wheel_consumed: bool,
}

impl UiFrame<'_> {
    fn next_z(&mut self) -> f32 {
        let (z, cap) = if self.modal_scope.is_some() {
            (&mut self.z_modal, MAX_UI_Z)
        } else if self.popup_scope.is_some() {
            (&mut self.z_popover, MODAL_Z - 1.0)
        } else if self.overlay {
            (&mut self.z_overlay, POPOVER_Z - 1.0)
        } else {
            (&mut self.z, OVERLAY_Z - 1.0)
        };
        *z = (*z + 1.0).min(cap);
        *z
    }

    /// Pointer blockers follow ownership: panel content bypasses panel
    /// regions, while only the open modal/popover's contents bypass its gate.
    /// A modal's contents take the pointer only once it was shown last
    /// frame, so the press that opens it cannot also resolve it.
    fn hit(&self, rect: &Rect) -> bool {
        let p = self.input.mouse_pos;
        self.ui.splitter_drag.is_none()
            && contains(rect, p)
            && self.clip.is_none_or(|c| contains(&c, p))
            && if self.modal_scope.is_some() {
                self.modal_scope == self.ui.modal_scope
            } else {
                !self.ui.modal_blocking
            }
            && self.ui.popover_blocked.is_none_or(|(owner, blocked)| {
                !contains(&blocked, p) || self.popup_scope == Some(owner)
            })
            && (self.overlay || !self.ui.blocked.iter().any(|r| contains(r, p)))
    }

    /// Whether the mouse hovers `rect` (same gating as widget interaction —
    /// custom widget compositions use this for hover states).
    #[must_use]
    pub fn hovered(&self, rect: &Rect) -> bool {
        self.hit(rect)
    }

    /// The frame's pointer position (logical pixels) — custom widget
    /// compositions (tooltips, hover accents).
    #[must_use]
    pub fn mouse_pos(&self) -> Vec2 {
        self.input.mouse_pos
    }

    /// Single-line size of `text` at `px` through the frame's font (layout
    /// helpers: wrapping, right-alignment of composed rows).
    #[must_use]
    pub fn measure_text(&self, text: &str, px: f32) -> Vec2 {
        self.text.measure(text, px)
    }

    /// Set the clip rect applied to subsequent widget draws and hit tests
    /// (`None` = unclipped). Scroll areas manage this automatically.
    pub fn set_clip(&mut self, clip: Option<Rect>) {
        self.clip = clip;
        self.text.set_clip(clip);
    }

    /// `rect` narrowed to the current clip; a zero rect, which clips
    /// everything, when they do not overlap.
    fn clip_within(&self, rect: Rect) -> Rect {
        self.clip.map_or(rect, |clip| {
            clip.intersection(&rect)
                .unwrap_or(Rect::new(0.0, 0.0, 0.0, 0.0))
        })
    }

    /// A flat colored rectangle (the 1×1 white texture scaled).
    pub fn rect(&mut self, rect: Rect, color: [f32; 4]) {
        let z = self.next_z();
        let size = rect.size();
        self.list.push_screen(SpriteInstance {
            scale: size,
            color,
            z,
            clip: self.clip,
            ..SpriteInstance::new(self.ui.white, rect.min + size * 0.5)
        });
    }

    /// A flat panel in the current theme’s panel color.
    pub fn panel(&mut self, rect: Rect) {
        self.rect(rect, self.ui.theme.panel);
    }

    /// An arbitrary sprite in the UI (screen channel) at this frame's z —
    /// icons/previews layered over widgets (PR-9: the fire/water animated
    /// body previews inside the element toggle buttons). The instance's `z`
    /// is replaced by the frame's draw order; the frame's clip applies
    /// unless the instance carries its own.
    pub fn sprite(&mut self, instance: SpriteInstance) {
        let z = self.next_z();
        let clip = instance.clip.or(self.clip);
        self.list.push_screen(SpriteInstance {
            z,
            clip,
            ..instance
        });
    }

    /// A border ring of `width` px just outside `rect` (four opaque strips —
    /// widget bodies are translucent, so an underlay rect would tint them).
    pub fn border(&mut self, rect: Rect, width: f32, color: [f32; 4]) {
        let (w, size) = (width, rect.size());
        let full_w = size.x + 2.0 * w;
        // Top, bottom, left, right.
        self.rect(Rect::new(rect.min.x - w, rect.min.y - w, full_w, w), color);
        self.rect(Rect::new(rect.min.x - w, rect.max.y, full_w, w), color);
        self.rect(Rect::new(rect.min.x - w, rect.min.y, w, size.y), color);
        self.rect(Rect::new(rect.max.x, rect.min.y, w, size.y), color);
    }

    /// One line of text aligned inside `rect` (a Godot `Label`).
    pub fn label(&mut self, rect: Rect, text: &str, style: &TextStyle, h: HAlign, v: VAlign) {
        let z = self.next_z();
        self.text
            .draw_in_rect(text, rect, h, v, style, z, TextChannel::Screen);
    }

    /// Finish the frame: a release with the button up clears the pressed
    /// widget (a release and press in one frame with the button held count
    /// as release then press, so the press's widget stays armed); a press
    /// that no line-edit consumed drops focus (click-away unfocus); a dropdown not
    /// submitted this frame closes; this frame's overlay regions become next
    /// frame's input blockers.
    pub fn end(self) {
        self.text.set_clip(None);
        // A release with the button still down means a press followed it in
        // this frame (the only order consistent with `mouse_down`); that
        // press may have re-armed a widget, so keep it.
        let released = self.input.mouse_released && !self.input.mouse_down;
        if released || !self.splitter_seen {
            self.ui.splitter_drag = None;
        }
        if !self.popup_seen {
            self.ui.open_popup = None;
        }
        if released {
            self.ui.active = None;
            self.ui.thumb_drag = None;
            self.ui.number_drag = None;
        }
        if self.input.mouse_pressed && !self.edit_clicked {
            self.ui.focus = None;
        }
        if self.ui.focus.is_none() && self.input.keys.contains(&UiKey::Tab) {
            let target = if self.input.shift {
                self.focus_order.last()
            } else {
                self.focus_order.first()
            };
            if let Some(target) = target {
                self.ui.focus = Some(target.id);
                self.ui.keyboard_captured = true;
            }
        }
        if !self.focus_requested
            && self
                .ui
                .focus
                .is_some_and(|id| !self.focus_order.iter().any(|target| target.id == id))
        {
            self.ui.focus = None;
        }
        if self.ui.edit.id != self.ui.focus {
            self.ui.edit = EditState::default();
        }
        self.ui.focus_order = self.focus_order;
        self.ui.blocked = self.new_blocked;
        self.ui.popover_blocked = self.new_popover_blocked;
        self.ui.modal_blocking = self.new_modal.is_some();
        self.ui.modal_scope = self.new_modal;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ui::test_ui::{BTN, fixture, press_at};
    use wasm_bindgen_test::wasm_bindgen_test;

    /// #255: a press exactly on a rect's far edge misses; one pixel inside
    /// hits.
    #[wasm_bindgen_test(unsupported = test)]
    fn hit_testing_is_half_open() {
        let (mut ui, mut text, _assets) = fixture();
        let mut list = DrawList::new();
        let mut f = ui.begin(&mut text, &mut list, press_at(110.0, 50.0));
        assert!(!f.button("b", BTN, "B", 20.0), "max edge is outside");
        f.end();
        let mut f = ui.begin(&mut text, &mut list, press_at(109.0, 49.0));
        assert!(f.button("b", BTN, "B", 20.0));
        f.end();
    }

    /// The UI's white pixel is the shared one: a renderer-only consumer
    /// asking `assets` for it afterwards gets the very same handle, so the
    /// UI and an overlay batch against one atlas entry instead of two.
    #[wasm_bindgen_test(unsupported = test)]
    fn ui_shares_the_canonical_white_texture() {
        let mut assets: Assets<Texture> = Assets::new();
        let ui = Ui::new(&mut assets);
        assert_eq!(
            ui.white_texture(),
            crate::assets::white_texture(&mut assets)
        );
    }

    /// `cancel_interactions` (focus loss) drops the active widget, any
    /// thumb drag, and an open popover so a stale press cannot complete
    /// later and no dropdown lingers open while the window is unfocused.
    #[wasm_bindgen_test(unsupported = test)]
    fn cancel_interactions_clears_pointer_state() {
        let (mut ui, mut text, _assets) = fixture();
        let mut list = DrawList::new();

        let mut f = ui.begin(&mut text, &mut list, press_at(50.0, 30.0));
        f.button("b", BTN, "OK", 24.0);
        f.end();
        assert!(ui.active.is_some());
        ui.cancel_interactions();
        assert!(ui.active.is_none());
        assert!(ui.thumb_drag.is_none());

        // An open dropdown popover closes too (focus loss must not leave
        // a floating popover behind).
        let dd = Rect::new(10.0, 10.0, 160.0, 30.0);
        let mut selected = 0usize;
        let mut f = ui.begin(&mut text, &mut list, press_at(50.0, 25.0));
        f.dropdown("zoom", dd, &["a", "b"], &mut selected, 16.0);
        f.end();
        assert!(ui.any_popup_open());
        ui.cancel_interactions();
        assert!(!ui.any_popup_open(), "focus loss closes the popover");
    }

    /// Panels and buttons emit screen-channel quads with increasing z, so
    /// later widgets draw over earlier ones.
    #[wasm_bindgen_test(unsupported = test)]
    fn draws_go_to_screen_channel_with_increasing_z() {
        let (mut ui, mut text, mut assets) = fixture();
        let mut list = DrawList::new();

        let mut f = ui.begin(&mut text, &mut list, UiInput::default());
        f.panel(Rect::new(40.0, 340.0, 880.0, 160.0));
        f.button("start", Rect::new(81.0, 380.0, 300.0, 80.0), "START", 48.0);
        f.end();
        text.end_frame(&mut assets, &mut list);

        assert!(list.world.is_empty());
        assert!(list.screen.len() > 2, "panel + button + glyph quads");
        // Panel first, button body second, strictly increasing z.
        assert!(list.screen[0].z < list.screen[1].z);
        // Button text z is above the button body z.
        let body_z = list.screen[1].z;
        assert!(list.screen[2..].iter().all(|i| i.z > body_z));
    }
}