Skip to main content

nadir_debug/
ui.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The debug UI's state across frames, a frame, and its windows.
16
17use std::fmt::{self, Write};
18
19use nadir_core::{Color, FastHashSet, Handle, Rect, UVec2, Vec2};
20use nadir_render::{
21    Font, SortMode, SpriteDraw, TextDraw, Texture, UiList, UiScale, UiSpace, UiView,
22};
23
24use crate::edit::Caret;
25use crate::id::{Id, split};
26use crate::input::{DebugInput, Taken};
27use crate::{Style, TextMetrics, Ui};
28
29/// The layer the debug UI draws in: the top one.
30const LAYER: u8 = u8::MAX;
31
32/// Wheel lines are this many rows.
33const ROWS_A_LINE: f32 = 3.0;
34
35/// The parts of a window that are not its content, each with an ID
36/// outside the labels'.
37#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
38enum Chrome {
39    Collapse,
40    Grip,
41    Thumb,
42    Bar,
43}
44
45/// Where a window's parts are, drawn at `rect`.
46#[derive(Clone, Copy, Debug, PartialEq)]
47struct Geometry {
48    rect: Rect,
49    bar: Rect,
50    collapse: Rect,
51    /// The title bar but its collapse box: what drags it.
52    drag: Rect,
53    /// Under the title bar.
54    view: Rect,
55    track: Rect,
56    grip: Rect,
57    /// Whether the content, as high as the last frame measured it, is
58    /// taller than the view.
59    scrollable: bool,
60    /// How far it scrolls.
61    range: f32,
62    thumb_height: f32,
63    /// How far the thumb moves.
64    room: f32,
65}
66
67impl Geometry {
68    /// The thumb at `scroll`.
69    fn thumb(&self, scroll: f32) -> Rect {
70        let share = if self.range > 0.0 {
71            scroll / self.range
72        } else {
73            0.0
74        };
75        Rect::from_min_size(
76            Vec2::new(self.track.min.x, self.track.min.y + share * self.room),
77            Vec2::new(self.track.width(), self.thumb_height),
78        )
79    }
80}
81
82impl Chrome {
83    /// A window's parts at `rect`, with rows `row` high, a scrollbar and a
84    /// grip `size` wide, and content `content` high.
85    fn geometry(rect: Rect, row: f32, size: f32, content: f32) -> Geometry {
86        let bar = Rect::new(rect.min, Vec2::new(rect.max.x, rect.min.y + row));
87        let collapse = Rect::from_min_size(rect.min, Vec2::splat(row));
88        let view = Rect::new(Vec2::new(rect.min.x, bar.max.y), rect.max);
89        let track = Rect::new(
90            Vec2::new(rect.max.x - size, bar.max.y),
91            Vec2::new(rect.max.x, rect.max.y - size),
92        );
93        let scrollable = content > view.height();
94        let thumb_height = if scrollable {
95            (view.height() / content * track.height()).max(size)
96        } else {
97            0.0
98        };
99        Geometry {
100            rect,
101            bar,
102            collapse,
103            drag: Rect::new(Vec2::new(collapse.max.x, bar.min.y), bar.max),
104            view,
105            track,
106            grip: Rect::new(rect.max - Vec2::splat(size), rect.max),
107            scrollable,
108            range: (content - view.height()).max(0.0),
109            thumb_height,
110            room: (track.height() - thumb_height).max(0.0),
111        }
112    }
113}
114
115/// How a window's content was laid out in this frame's first call: for a
116/// second call, which goes on from it.
117#[derive(Clone, Copy, Debug, PartialEq)]
118struct Part {
119    clip: Rect,
120    left: f32,
121    width: f32,
122    /// Where its first row went: its top, scrolled.
123    top: f32,
124}
125
126/// Where something is drawn and hit: a window, or the popup over them all.
127#[derive(Clone, Copy, Debug, PartialEq, Eq)]
128pub(crate) enum Layer {
129    Window(Id),
130    Popup,
131}
132
133/// A window known: one drawn, or one whose place was set.
134#[derive(Clone, Debug, PartialEq)]
135struct WindowState {
136    id: Id,
137    /// Its explicit ID, or its title: the name of its place.
138    key: String,
139    /// Its place, as the user or `set_place` left it.
140    rect: Rect,
141    collapsed: bool,
142    scroll: f32,
143    /// The height of its content in the last frame it was drawn.
144    content: f32,
145    /// Drawn in the last finished frame.
146    drawn: bool,
147    /// Drawn in this frame.
148    shown: bool,
149    /// The rect it was drawn at, which hit tests use the next frame: its
150    /// title bar alone when collapsed.
151    hit: Rect,
152    /// Where its next row goes, for a second call in one frame.
153    next_y: f32,
154    /// This frame's layout of its content.
155    part: Option<Part>,
156}
157
158/// The widget the pointer holds, from the press until the release.
159#[derive(Clone, Copy, Debug, PartialEq)]
160pub(crate) struct Active {
161    pub(crate) id: Id,
162    /// Called this frame.
163    pub(crate) seen: bool,
164    /// Where the press was.
165    pub(crate) from: Vec2,
166    /// The pointer as the widget last saw it.
167    pub(crate) last: Vec2,
168    /// What a drag started from: a window's rect, or a value.
169    pub(crate) start: Rect,
170    pub(crate) start_value: f32,
171}
172
173/// The text field that has the keyboard.
174#[derive(Clone, Copy, Debug, PartialEq)]
175pub(crate) struct Focus {
176    pub(crate) id: Id,
177    pub(crate) seen: bool,
178    pub(crate) caret: Caret,
179    /// How far the text is scrolled left, to keep the caret in view.
180    pub(crate) scroll: f32,
181    /// The text as the field left it: its length and hash, so that a text
182    /// the caller changed puts the caret at its end.
183    pub(crate) len: usize,
184    pub(crate) hash: u64,
185}
186
187/// An open combo's list.
188#[derive(Clone, Copy, Debug, PartialEq)]
189pub(crate) struct Popup {
190    pub(crate) id: Id,
191    pub(crate) seen: bool,
192    /// The combo it opened from.
193    pub(crate) anchor: Rect,
194    /// Its list.
195    pub(crate) rect: Rect,
196}
197
198/// Who has the mouse while its button is down.
199#[derive(Clone, Copy, Debug, PartialEq, Eq)]
200enum Owner {
201    Nobody,
202    Ui,
203    /// The press was outside every debug window: the game's, until the
204    /// release.
205    Game,
206}
207
208/// What a command draws.
209#[derive(Clone, Copy, Debug, PartialEq)]
210pub(crate) enum Shape {
211    Rect {
212        rect: Rect,
213        color: Color,
214    },
215    /// A window's title bar, in the front window's color or not.
216    Title {
217        rect: Rect,
218    },
219    Text {
220        at: Vec2,
221        start: u32,
222        end: u32,
223        color: Color,
224    },
225    Line {
226        from: Vec2,
227        to: Vec2,
228        color: Color,
229    },
230}
231
232/// A shape to draw, in its layer, cut to its clip.
233#[derive(Clone, Copy, Debug, PartialEq)]
234struct Cmd {
235    layer: Layer,
236    clip: Rect,
237    shape: Shape,
238}
239
240/// What an interaction with a widget did this frame.
241#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
242pub(crate) struct Interaction {
243    /// The pointer is over it, and nothing else is held.
244    pub(crate) hovered: bool,
245    /// The button went down on it this frame.
246    pub(crate) pressed: bool,
247    /// It is held: pressed this frame or before, released or not yet.
248    pub(crate) held: bool,
249    /// The button went up while it was held.
250    pub(crate) released: bool,
251    /// Released over it, having been pressed on it.
252    pub(crate) clicked: bool,
253}
254
255/// An immediate-mode debug UI: each frame, code calls a window and its
256/// widgets, and each widget says what was done to it. It keeps what lasts
257/// from frame to frame: which widget is held, which text field has the
258/// keyboard, the windows' places and which tree nodes are open.
259///
260/// Each frame: [`DebugUi::frame`] takes the frame's input, its windows are
261/// filled with [`Frame::window`], and [`Frame::finish`] pushes what they
262/// draw into a [`UiList`] (`RenderFrame::ui`), after the game's UI and in
263/// front of it.
264pub struct DebugUi {
265    pub(crate) style: Style,
266    font: Handle<Font>,
267    white: Handle<Texture>,
268    pub(crate) metrics: Box<dyn TextMetrics>,
269    /// From back to front.
270    windows: Vec<WindowState>,
271    pub(crate) active: Option<Active>,
272    pub(crate) focus: Option<Focus>,
273    /// The field the keyboard was taken from by another, which says so
274    /// when it is next called.
275    pub(crate) lost: Option<Id>,
276    pub(crate) focus_next: bool,
277    pub(crate) open: FastHashSet<Id>,
278    pub(crate) popup: Option<Popup>,
279    owner: Owner,
280    /// Whether a window was drawn in the last finished frame.
281    drawn_any: bool,
282    wants_mouse: bool,
283    wants_keyboard: bool,
284    revision: u64,
285    /// The frames begun so far: the inspector's edits know by it whether
286    /// their field was drawn in the frame before.
287    pub(crate) frames: u64,
288    // This frame.
289    pub(crate) space: UiSpace,
290    pub(crate) input: Taken,
291    pub(crate) pointer: Vec2,
292    pub(crate) press: Option<Vec2>,
293    pub(crate) release: Option<(Vec2, bool)>,
294    pub(crate) down: bool,
295    hover_layer: Option<Layer>,
296    press_layer: Option<Layer>,
297    cmds: Vec<Cmd>,
298    pub(crate) text: String,
299    scratch: String,
300    order: Vec<(u32, u32)>,
301    pub(crate) values: Vec<f32>,
302}
303
304impl DebugUi {
305    /// A debug UI that draws its text in `font`, measured by `metrics`
306    /// (for a font loaded in the game, `FontMetrics` of a copy of it), and
307    /// its boxes with `white`, a texture whose texels are white.
308    pub fn new(
309        font: Handle<Font>,
310        metrics: impl TextMetrics + 'static,
311        white: Handle<Texture>,
312    ) -> Self {
313        Self {
314            style: Style::default(),
315            font,
316            white,
317            metrics: Box::new(metrics),
318            windows: Vec::new(),
319            active: None,
320            focus: None,
321            lost: None,
322            focus_next: false,
323            open: FastHashSet::default(),
324            popup: None,
325            owner: Owner::Nobody,
326            drawn_any: false,
327            wants_mouse: false,
328            wants_keyboard: false,
329            frames: 0,
330            revision: 0,
331            space: UiSpace::new(UiScale::Free(1.0), UVec2::ONE, UVec2::ZERO),
332            input: Taken::default(),
333            pointer: Vec2::ZERO,
334            press: None,
335            release: None,
336            down: false,
337            hover_layer: None,
338            press_layer: None,
339            cmds: Vec::new(),
340            text: String::new(),
341            scratch: String::new(),
342            order: Vec::new(),
343            values: Vec::new(),
344        }
345    }
346
347    /// Draws with another font from the next frame: after the font was
348    /// reloaded, say.
349    pub fn set_font(&mut self, font: Handle<Font>, metrics: impl TextMetrics + 'static) {
350        self.font = font;
351        self.metrics = Box::new(metrics);
352    }
353
354    /// Its look.
355    pub fn style(&self) -> &Style {
356        &self.style
357    }
358
359    /// Its look, to change: its scale, the settings' UI scale, among it.
360    pub fn style_mut(&mut self) -> &mut Style {
361        &mut self.style
362    }
363
364    /// Whether the pointer is the debug UI's: over a window it drew in the
365    /// last frame, or holding one of its widgets. The game should then
366    /// leave the mouse alone. A press on a window is the debug UI's until
367    /// its release, wherever the pointer goes, and one that started outside
368    /// every window the game's, over a window or not.
369    pub fn wants_mouse(&self) -> bool {
370        self.wants_mouse
371    }
372
373    /// Whether `at`, in the output's pixels as `nadir_input::Input::pointer`
374    /// gives them, is over a window or an open combo's list drawn in the
375    /// last frame, by the space that frame was laid out in.
376    ///
377    /// [`DebugUi::wants_mouse`] is where the pointer was when the last frame
378    /// ended. This is for an engine that feeds the game's input an event at
379    /// a time and decides at each press, or each turn of the wheel, whether
380    /// the game sees it: then a press in the frame the pointer comes over a
381    /// window is the UI's, and one in the frame it leaves the game's.
382    pub fn is_over(&self, at: Vec2) -> bool {
383        self.layer_at(self.space.to_ui(at)).is_some()
384    }
385
386    /// Whether a text field drawn in the last frame has the keyboard: the
387    /// game should then leave the keys alone.
388    pub fn wants_keyboard(&self) -> bool {
389        self.wants_keyboard
390    }
391
392    /// Every window known, drawn or not, each with its place: for saving
393    /// them. A window's name is its explicit ID or its title.
394    pub fn places(&self) -> impl ExactSizeIterator<Item = WindowPlace<'_>> + '_ {
395        self.windows.iter().map(|window| WindowPlace {
396            title: &window.key,
397            rect: window.rect,
398            collapsed: window.collapsed,
399        })
400    }
401
402    /// Places the window named by `title` (its explicit ID after `##`, or
403    /// the whole title) at `rect`, collapsed or not, now or when it first
404    /// shows: for restoring a saved place. A rect with an edge that is not
405    /// finite is ignored, and one smaller than the style's `min_size` is
406    /// made that large. A window is kept on screen when it is drawn, not
407    /// moved where it is placed.
408    pub fn set_place(&mut self, title: &str, rect: Rect, collapsed: bool) {
409        let finite = [rect.min.x, rect.min.y, rect.max.x, rect.max.y]
410            .iter()
411            .all(|v| v.is_finite());
412        if !finite {
413            return;
414        }
415        let (_, key) = split(title);
416        let rect = Rect::from_min_size(rect.min, rect.size().max(self.style.min_size));
417        let index = self.window_index(Id::ROOT.with(key), key, rect);
418        let window = &mut self.windows[index];
419        window.rect = rect;
420        window.collapsed = collapsed;
421    }
422
423    /// A number that changes when the user collapses or opens a window, or
424    /// ends a move or a resize that left it elsewhere: the places then
425    /// differ from those saved.
426    pub fn places_revision(&self) -> u64 {
427        self.revision
428    }
429
430    /// Starts a frame: takes the frame's events from `input` (see
431    /// [`DebugInput`]) and lays the UI out at the style's scale for an
432    /// output of `output_size` pixels over a virtual image of
433    /// `virtual_resolution`, as [`UiSpace::new`] places it. The frame ends
434    /// when the [`Frame`] is dropped, finished or not.
435    pub fn frame(
436        &mut self,
437        input: &mut DebugInput,
438        virtual_resolution: UVec2,
439        output_size: UVec2,
440    ) -> Frame<'_> {
441        input.take(&mut self.input);
442        self.frames += 1;
443        let space = UiSpace::new(self.style.scale, virtual_resolution, output_size);
444        self.space = space;
445        self.pointer = space.to_ui(self.input.pointer);
446        self.press = self.input.press.map(|at| space.to_ui(at));
447        self.release = self
448            .input
449            .release
450            .map(|(at, cancelled)| (space.to_ui(at), cancelled));
451        self.down = self.input.down;
452        self.cmds.clear();
453        self.text.clear();
454        for window in &mut self.windows {
455            window.shown = false;
456        }
457        if let Some(active) = &mut self.active {
458            active.seen = false;
459        }
460        if let Some(focus) = &mut self.focus {
461            focus.seen = false;
462        }
463        if let Some(popup) = &mut self.popup {
464            popup.seen = false;
465        }
466
467        self.hover_layer = self.layer_at(self.pointer);
468        self.press_layer = None;
469        if let Some(at) = self.press {
470            let layer = self.layer_at(at);
471            self.press_layer = layer;
472            self.owner = if layer.is_some() {
473                Owner::Ui
474            } else {
475                Owner::Game
476            };
477            // A press outside the list and its combo closes the list.
478            if self
479                .popup
480                .is_some_and(|popup| !popup.rect.contains(at) && !popup.anchor.contains(at))
481            {
482                self.popup = None;
483            }
484            if let Some(Layer::Window(id)) = layer {
485                self.bring_to_front(id);
486            }
487        }
488        if self.owner == Owner::Game {
489            self.hover_layer = None;
490            self.press_layer = None;
491        }
492        Frame { ui: self }
493    }
494
495    /// The window or popup at `at`, by the rects drawn in the last frame.
496    fn layer_at(&self, at: Vec2) -> Option<Layer> {
497        if self.popup.is_some_and(|popup| popup.rect.contains(at)) {
498            return Some(Layer::Popup);
499        }
500        self.windows
501            .iter()
502            .rev()
503            .find(|window| window.drawn && window.hit.contains(at))
504            .map(|window| Layer::Window(window.id))
505    }
506
507    fn bring_to_front(&mut self, id: Id) {
508        if let Some(index) = self.windows.iter().position(|window| window.id == id) {
509            let window = self.windows.remove(index);
510            self.windows.push(window);
511        }
512    }
513
514    /// The index of the window `id`, made at `rect` if it is not known.
515    fn window_index(&mut self, id: Id, key: &str, rect: Rect) -> usize {
516        if let Some(index) = self.windows.iter().position(|window| window.id == id) {
517            return index;
518        }
519        self.windows.push(WindowState {
520            id,
521            key: key.to_string(),
522            rect,
523            collapsed: false,
524            scroll: 0.0,
525            content: 0.0,
526            drawn: false,
527            shown: false,
528            hit: Rect::default(),
529            next_y: 0.0,
530            part: None,
531        });
532        self.windows.len() - 1
533    }
534
535    /// A row's height: a line and its padding above and below.
536    pub(crate) fn row_height(&self) -> f32 {
537        self.metrics.line_height() + 2.0 * self.style.padding
538    }
539
540    /// How wide `text` is in the font.
541    pub(crate) fn width(&self, text: &str) -> f32 {
542        self.metrics.caret_x(text, text.len())
543    }
544
545    /// Interacts with the widget `id` at `rect`, in `layer`, cut to `clip`.
546    pub(crate) fn interact(&mut self, layer: Layer, clip: Rect, id: Id, rect: Rect) -> Interaction {
547        let inside = |at: Vec2| rect.contains(at) && clip.contains(at);
548        let mut out = Interaction::default();
549        if let Some(active) = self.active.as_mut().filter(|active| active.id == id) {
550            active.seen = true;
551        }
552        let free = self.active.is_none_or(|active| active.id == id);
553        out.hovered = free && self.hover_layer == Some(layer) && inside(self.pointer);
554        if let Some(at) = self.press
555            && self.active.is_none()
556            && self.press_layer == Some(layer)
557            && inside(at)
558        {
559            self.active = Some(Active {
560                id,
561                seen: true,
562                from: at,
563                last: at,
564                start: Rect::default(),
565                start_value: 0.0,
566            });
567            out.pressed = true;
568        }
569        if self.active.is_some_and(|active| active.id == id) {
570            out.held = true;
571            if let Some((at, cancelled)) = self.release {
572                out.released = true;
573                out.clicked = !cancelled && inside(at);
574            }
575        }
576        out
577    }
578
579    /// The wheel's lines this frame if the pointer is over `rect`, cut to
580    /// `clip`, in `layer`, the one under it; else 0.
581    pub(crate) fn wheel_over(&self, layer: Layer, clip: Rect, rect: Rect) -> f32 {
582        let at = self.pointer;
583        if self.hover_layer == Some(layer) && rect.contains(at) && clip.contains(at) {
584            self.input.wheel.y
585        } else {
586            0.0
587        }
588    }
589
590    /// The widget held, if it is `id`.
591    pub(crate) fn active_mut(&mut self, id: Id) -> Option<&mut Active> {
592        self.active.as_mut().filter(|active| active.id == id)
593    }
594
595    /// Records a box.
596    pub(crate) fn rect(&mut self, layer: Layer, clip: Rect, rect: Rect, color: Color) {
597        self.push(layer, clip, Shape::Rect { rect, color });
598    }
599
600    /// Records the text in `self.text` from `start` to `end`, its top-left
601    /// corner at `at`.
602    pub(crate) fn text_at(
603        &mut self,
604        layer: Layer,
605        clip: Rect,
606        at: Vec2,
607        (start, end): (u32, u32),
608        color: Color,
609    ) {
610        self.push(
611            layer,
612            clip,
613            Shape::Text {
614                at,
615                start,
616                end,
617                color,
618            },
619        );
620    }
621
622    /// Records a line one unit thick.
623    pub(crate) fn line(&mut self, layer: Layer, clip: Rect, from: Vec2, to: Vec2, color: Color) {
624        self.push(layer, clip, Shape::Line { from, to, color });
625    }
626
627    pub(crate) fn push(&mut self, layer: Layer, clip: Rect, shape: Shape) {
628        if !clip.is_empty() {
629            self.cmds.push(Cmd { layer, clip, shape });
630        }
631    }
632
633    /// Formats `text` into the text buffer: its start and end.
634    pub(crate) fn format(&mut self, text: impl fmt::Display) -> (u32, u32) {
635        // The buffer holds a frame's texts, far fewer than 4 GiB of them.
636        let start = self.text.len() as u32;
637        if write!(self.text, "{text}").is_err() {
638            self.text.truncate(start as usize);
639        }
640        (start, self.text.len() as u32)
641    }
642
643    /// The text from `start` to `end`.
644    pub(crate) fn text(&self, (start, end): (u32, u32)) -> &str {
645        &self.text[start as usize..end as usize]
646    }
647
648    /// Pushes the frame's shapes into `out`.
649    fn emit(&mut self, out: &mut UiList) {
650        self.order.clear();
651        let z = |layer: Layer, windows: &[WindowState]| match layer {
652            Layer::Popup => u32::MAX,
653            Layer::Window(id) => windows
654                .iter()
655                .position(|window| window.id == id)
656                .map_or(0, |index| index as u32),
657        };
658        for (seq, cmd) in (0u32..).zip(&self.cmds) {
659            self.order.push((z(cmd.layer, &self.windows), seq));
660        }
661        self.order.sort_unstable();
662        // The front window is the last drawn.
663        let front = self
664            .windows
665            .iter()
666            .rev()
667            .find(|window| window.shown)
668            .map(|window| Layer::Window(window.id));
669        let before = out.view();
670        let base = UiView::new(self.style.scale);
671        let mut clip = None;
672        for &(_, seq) in &self.order {
673            let cmd = self.cmds[seq as usize];
674            if clip != Some(cmd.clip) {
675                out.set_view(base.clipped(cmd.clip));
676                clip = Some(cmd.clip);
677            }
678            match cmd.shape {
679                Shape::Rect { rect, color } => {
680                    out.sprite(self.sprite(rect.min, rect.size(), color));
681                }
682                Shape::Title { rect } => {
683                    let color = if front == Some(cmd.layer) {
684                        self.style.title_front
685                    } else {
686                        self.style.title
687                    };
688                    out.sprite(self.sprite(rect.min, rect.size(), color));
689                }
690                Shape::Text {
691                    at,
692                    start,
693                    end,
694                    color,
695                } => {
696                    let mut draw = TextDraw::new(self.font, at);
697                    draw.layout.markup = false;
698                    draw.color = color;
699                    draw.layer = LAYER;
700                    draw.sort = SortMode::Fixed(u32::MAX);
701                    out.text(draw, &self.text[start as usize..end as usize]);
702                }
703                Shape::Line { from, to, color } => {
704                    let along = to - from;
705                    let length = along.length();
706                    if length > 0.0 && length.is_finite() {
707                        let mut sprite = self.sprite(from, Vec2::new(length, 1.0), color);
708                        sprite.pivot = Vec2::new(0.0, 0.5);
709                        sprite.rotation = along.y.atan2(along.x);
710                        out.sprite(sprite);
711                    }
712                }
713            }
714        }
715        out.set_view(before);
716    }
717
718    /// A box of the white texture, by its top-left corner.
719    fn sprite(&self, at: Vec2, size: Vec2, color: Color) -> SpriteDraw {
720        let mut sprite = SpriteDraw::new(self.white, at, size);
721        sprite.pivot = Vec2::ZERO;
722        sprite.color = color;
723        sprite.layer = LAYER;
724        sprite.sort = SortMode::Fixed(u32::MAX);
725        sprite
726    }
727
728    /// Ends the frame: what was not called this frame lets go, and what the
729    /// game should leave alone is worked out.
730    fn end(&mut self) {
731        if self.release.is_some() || self.active.is_some_and(|active| !active.seen) {
732            self.active = None;
733        }
734        if self.focus.is_some_and(|focus| !focus.seen) {
735            self.focus = None;
736        }
737        if self.popup.is_some_and(|popup| !popup.seen) {
738            self.popup = None;
739        }
740        for window in &mut self.windows {
741            window.drawn = window.shown;
742        }
743        self.drawn_any = self.windows.iter().any(|window| window.drawn);
744        let pointer = self.pointer;
745        let over = self.popup.is_some_and(|popup| popup.rect.contains(pointer))
746            || self
747                .windows
748                .iter()
749                .any(|window| window.drawn && window.hit.contains(pointer));
750        // A press on a window keeps the mouse until its release, wherever
751        // the pointer goes; one outside them all leaves it to the game.
752        self.wants_mouse = match self.owner {
753            Owner::Game => false,
754            Owner::Ui => true,
755            Owner::Nobody => over || self.active.is_some(),
756        };
757        self.wants_keyboard = self.focus.is_some();
758        if !self.down {
759            self.owner = Owner::Nobody;
760        }
761    }
762}
763
764/// A window's place, as [`DebugUi::places`] gives it.
765#[non_exhaustive]
766#[derive(Clone, Copy, Debug, PartialEq)]
767pub struct WindowPlace<'a> {
768    /// Its name: its explicit ID, or its title.
769    pub title: &'a str,
770    /// Where it is, and how large, in UI units.
771    pub rect: Rect,
772    /// Whether only its title bar shows.
773    pub collapsed: bool,
774}
775
776/// A frame of the debug UI, from [`DebugUi::frame`]: its windows are
777/// filled, then [`Frame::finish`] pushes what they draw. Dropped, it ends
778/// the frame: a frame not finished draws nothing, and its input is spent.
779pub struct Frame<'a> {
780    ui: &'a mut DebugUi,
781}
782
783impl Frame<'_> {
784    /// A window titled `title`, filled by `add`, which is not called while
785    /// the window is collapsed. Returns whether it is open: not collapsed.
786    ///
787    /// - It shows at `first` the first time, unless a place was set for it
788    ///   ([`DebugUi::set_place`]), and keeps its place after.
789    /// - It is drawn in front of the windows already open, and comes to
790    ///   the front when it is pressed.
791    /// - Its title bar drags it, kept at least partly on screen, and its
792    ///   box on the left collapses it; the grip at its bottom-right corner
793    ///   resizes it; when its content is taller than it, the wheel over it
794    ///   or its scrollbar's thumb scrolls it. A drag starts from where it is
795    ///   drawn, which is its place moved on screen if it was off it.
796    /// - `"Title##key"` shows `Title` and is the window `key`, whose place
797    ///   is kept as the title changes. A second call of one window in a
798    ///   frame continues its content.
799    /// - With no output to draw on (a size of 0), nothing is shown.
800    pub fn window(
801        &mut self,
802        title: impl fmt::Display,
803        first: Rect,
804        add: impl FnOnce(&mut Ui<'_>),
805    ) -> bool {
806        let core = &mut *self.ui;
807        let screen = core.space.size;
808        if !(screen.x > 0.0 && screen.y > 0.0) {
809            return false;
810        }
811        core.scratch.clear();
812        let _ = write!(core.scratch, "{title}");
813        let scratch = std::mem::take(&mut core.scratch);
814        let (shown, key) = split(&scratch);
815        let id = Id::ROOT.with(key);
816        let first = sanitize(first, core.style.min_size);
817        let mut index = core.window_index(id, key, first);
818        let title_range = {
819            let start = core.text.len() as u32;
820            core.text.push_str(shown);
821            (start, core.text.len() as u32)
822        };
823        core.scratch = scratch;
824        let style = core.style;
825        let row = core.row_height();
826        let layer = Layer::Window(id);
827
828        // A second call in the frame goes on from the first, laid out as the
829        // first laid it out.
830        if core.windows[index].shown {
831            let window = &core.windows[index];
832            let (collapsed, part, next_y) = (window.collapsed, window.part, window.next_y);
833            let Some(part) = part.filter(|_| !collapsed) else {
834                return !collapsed;
835            };
836            let mut ui = Ui::new(core, layer, id, part.clip, part.left, part.width, next_y);
837            add(&mut ui);
838            let end = ui.y();
839            let window = &mut core.windows[index];
840            window.next_y = end;
841            window.content = end - part.top + 2.0 * style.padding;
842            return true;
843        }
844        // Shown again while others were drawn: in front of them.
845        if !core.windows[index].drawn && core.drawn_any {
846            core.bring_to_front(id);
847            index = core.windows.len() - 1;
848        }
849        let (stored, mut collapsed, mut scroll, content) = {
850            let window = &core.windows[index];
851            (window.rect, window.collapsed, window.scroll, window.content)
852        };
853        let content = if content.is_finite() { content } else { 0.0 };
854        let size = style.scrollbar;
855
856        // The chrome, where the last frame drew it, takes its presses before
857        // the content: the box, the grip and the thumb before the bar.
858        let was = Chrome::geometry(on_screen(stored, screen, row), row, size, content);
859        let mut place = stored;
860        let pointer = core.pointer;
861        let chrome = |part: Chrome| id.with(part);
862        if core
863            .interact(layer, was.rect, chrome(Chrome::Collapse), was.collapse)
864            .clicked
865        {
866            collapsed = !collapsed;
867            core.revision += 1;
868        }
869        if !collapsed {
870            let held = core.interact(layer, was.rect, chrome(Chrome::Grip), was.grip);
871            let mut start = None;
872            if let Some(active) = core.active_mut(chrome(Chrome::Grip)) {
873                // From where it is drawn, which may not be its place.
874                if held.pressed {
875                    active.start = was.rect;
876                }
877                let grown = (active.start.size() + pointer - active.from).max(style.min_size);
878                place = Rect::from_min_size(active.start.min, grown);
879                start = Some(active.start);
880            }
881            if held.released && start.is_some_and(|start| start != place) {
882                core.revision += 1;
883            }
884            if was.scrollable {
885                let thumb = was.thumb(scroll);
886                let held = core.interact(layer, was.rect, chrome(Chrome::Thumb), thumb);
887                if let Some(active) = core.active_mut(chrome(Chrome::Thumb)) {
888                    if held.pressed {
889                        active.start_value = scroll;
890                    }
891                    if was.room > 0.0 {
892                        scroll =
893                            active.start_value + (pointer.y - active.from.y) * was.range / was.room;
894                    }
895                }
896            }
897        }
898        let held = core.interact(layer, was.rect, chrome(Chrome::Bar), was.drag);
899        let mut start = None;
900        if let Some(active) = core.active_mut(chrome(Chrome::Bar)) {
901            if held.pressed {
902                active.start = was.rect;
903            }
904            let moved = pointer - active.from;
905            place = Rect::new(active.start.min + moved, active.start.max + moved);
906            start = Some(active.start);
907        }
908        if held.released && start.is_some_and(|start| start != place) {
909            core.revision += 1;
910        }
911        if core.hover_layer == Some(layer) && was.view.contains(pointer) {
912            scroll -= core.input.wheel.y * ROWS_A_LINE * row;
913        }
914
915        // Drawn where it is now, moved or resized this frame.
916        let now = Chrome::geometry(on_screen(place, screen, row), row, size, content);
917        // Held in 0..=range, a NaN at 0, with no clamp whose bounds could
918        // cross.
919        scroll = if scroll.is_nan() {
920            0.0
921        } else {
922            scroll.min(now.range).max(0.0)
923        };
924        if !collapsed {
925            core.rect(layer, now.rect, now.rect, style.panel);
926        }
927        core.push(layer, now.rect, Shape::Title { rect: now.bar });
928        let mark = core.format(if collapsed { "+" } else { "-" });
929        let mark_at =
930            now.collapse.min + Vec2::new((row - core.width(core.text(mark))) * 0.5, style.padding);
931        core.text_at(layer, now.collapse, mark_at, mark, style.text);
932        let title_at = Vec2::new(now.collapse.max.x, now.bar.min.y + style.padding);
933        core.text_at(layer, now.drag, title_at, title_range, style.text);
934
935        let mut part = None;
936        let mut next_y = 0.0;
937        let mut measured = content;
938        if !collapsed {
939            let width = if now.scrollable {
940                now.view.width() - size
941            } else {
942                now.view.width()
943            };
944            let clip =
945                Rect::from_min_size(now.view.min, Vec2::new(width.max(0.0), now.view.height()));
946            let laid = Part {
947                clip,
948                left: now.view.min.x + style.padding,
949                width: width - 2.0 * style.padding,
950                top: now.view.min.y + style.padding - scroll,
951            };
952            let mut ui = Ui::new(core, layer, id, laid.clip, laid.left, laid.width, laid.top);
953            add(&mut ui);
954            next_y = ui.y();
955            measured = next_y - laid.top + 2.0 * style.padding;
956            part = Some(laid);
957            if now.scrollable {
958                core.rect(layer, now.rect, now.track, style.dim);
959                core.rect(layer, now.rect, now.thumb(scroll), style.widget);
960            }
961            core.rect(layer, now.rect, now.grip, style.dim);
962        }
963
964        let window = &mut core.windows[index];
965        window.rect = place;
966        window.collapsed = collapsed;
967        window.scroll = scroll;
968        window.hit = if collapsed { now.bar } else { now.rect };
969        window.content = measured;
970        window.next_y = next_y;
971        window.part = part;
972        window.shown = true;
973        !collapsed
974    }
975
976    /// Pushes what the frame's windows draw into `out`
977    /// (`RenderFrame::ui`), window by window from back to front, an open
978    /// combo's list last: in the top layer at the last depth
979    /// (`SortMode::Fixed(u32::MAX)`), at the style's scale, each cut to its
980    /// window. Call it after the game's UI is pushed, which then draws
981    /// behind it. The list's view is put back as it was.
982    pub fn finish(self, out: &mut UiList) {
983        self.ui.emit(out);
984    }
985}
986
987impl Drop for Frame<'_> {
988    fn drop(&mut self) {
989        self.ui.end();
990    }
991}
992
993/// `rect` with no NaN or infinite edge and no smaller than `min`.
994fn sanitize(rect: Rect, min: Vec2) -> Rect {
995    let finite = [rect.min.x, rect.min.y, rect.max.x, rect.max.y]
996        .iter()
997        .all(|v| v.is_finite());
998    let rect = if finite {
999        rect
1000    } else {
1001        Rect::from_min_size(Vec2::ZERO, min)
1002    };
1003    Rect::from_min_size(rect.min, rect.size().max(min))
1004}
1005
1006/// Where a window at `rect` is drawn on a screen of `screen`: moved so
1007/// that its title bar, `bar` high, is on it, at least some of its width.
1008fn on_screen(rect: Rect, screen: Vec2, bar: f32) -> Rect {
1009    let size = rect.size();
1010    let keep = (2.0 * bar).min(size.x);
1011    let x = rect.min.x.max(keep - size.x).min(screen.x - keep);
1012    let y = rect.min.y.min(screen.y - bar).max(0.0);
1013    Rect::from_min_size(Vec2::new(x, y), size)
1014}
1015
1016#[cfg(test)]
1017mod tests {
1018    use super::*;
1019
1020    #[test]
1021    fn a_window_is_kept_with_its_title_bar_on_screen() {
1022        let screen = Vec2::new(100.0, 80.0);
1023        let rect = |x: f32, y: f32| Rect::from_min_size(Vec2::new(x, y), Vec2::new(40.0, 30.0));
1024        assert_eq!(on_screen(rect(10.0, 10.0), screen, 10.0), rect(10.0, 10.0));
1025        // Off to the right, the left and the bottom; above the top.
1026        assert_eq!(on_screen(rect(500.0, 10.0), screen, 10.0).min.x, 80.0);
1027        assert_eq!(on_screen(rect(-500.0, 10.0), screen, 10.0).min.x, -20.0);
1028        assert_eq!(on_screen(rect(10.0, 500.0), screen, 10.0).min.y, 70.0);
1029        assert_eq!(on_screen(rect(10.0, -5.0), screen, 10.0).min.y, 0.0);
1030        // Its size is kept.
1031        assert_eq!(
1032            on_screen(rect(500.0, 500.0), screen, 10.0).size(),
1033            Vec2::new(40.0, 30.0)
1034        );
1035    }
1036
1037    #[test]
1038    fn a_rect_that_is_not_finite_or_too_small_is_made_a_window_s() {
1039        let min = Vec2::new(60.0, 40.0);
1040        let nan = Rect::new(Vec2::new(f32::NAN, 0.0), Vec2::ONE);
1041        assert_eq!(sanitize(nan, min), Rect::from_min_size(Vec2::ZERO, min));
1042        let small = Rect::from_min_size(Vec2::new(5.0, 5.0), Vec2::new(10.0, 100.0));
1043        assert_eq!(sanitize(small, min).size(), Vec2::new(60.0, 100.0));
1044    }
1045}