Skip to main content

nadir_debug/
widgets.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//! A window's content: its layout and its widgets.
16
17use std::fmt;
18use std::hash::Hash;
19use std::ops::RangeInclusive;
20
21use nadir_core::hash::fnv1a64;
22use nadir_core::{Color, Key, Rect, Vec2};
23
24use crate::edit::{Caret, apply};
25use crate::id::{Id, split};
26use crate::input::Edit;
27use crate::ui::{DebugUi, Focus, Interaction, Layer, Popup};
28
29/// Marks a `with_id` key apart from a widget's label.
30const SCOPE: u64 = 0x7363_6f70_655f_6964;
31
32/// A plot's height unless it says another.
33const DEFAULT_PLOT_HEIGHT: f32 = 30.0;
34
35/// What a widget did this frame.
36#[non_exhaustive]
37#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
38pub struct Response {
39    /// The pointer is over it, and no other widget is held.
40    pub hovered: bool,
41    /// It is held: the button went down on it and is not up yet, or went
42    /// up this frame.
43    pub active: bool,
44    /// The button went down on it and up over it, the press and the
45    /// release each where they happened.
46    pub clicked: bool,
47    /// Its value changed.
48    pub changed: bool,
49    /// A text field: Enter was pressed while it had the keyboard, which it
50    /// keeps.
51    pub submitted: bool,
52    /// A text field: it lost the keyboard, to Escape or to a press
53    /// elsewhere.
54    pub lost_focus: bool,
55}
56
57impl From<Interaction> for Response {
58    fn from(interaction: Interaction) -> Self {
59        Self {
60            hovered: interaction.hovered,
61            active: interaction.held,
62            clicked: interaction.clicked,
63            ..Self::default()
64        }
65    }
66}
67
68/// How [`Ui::plot`] draws its values.
69#[non_exhaustive]
70#[derive(Clone, Debug, PartialEq)]
71pub struct Plot {
72    /// The values at its bottom and top: a value outside is drawn at the
73    /// edge; a reversed range is swapped, and one with no width, or a NaN
74    /// bound, draws every value in the middle.
75    pub range: RangeInclusive<f32>,
76    /// Its height, in UI units: one that is not finite or not above 0 is
77    /// the default, 30.
78    pub height: f32,
79    /// The value marked with a line across it, if any.
80    pub selected: Option<usize>,
81}
82
83impl Plot {
84    /// A plot of the values in `range`, 30 units high, nothing marked.
85    pub fn new(range: RangeInclusive<f32>) -> Self {
86        Self {
87            range,
88            height: DEFAULT_PLOT_HEIGHT,
89            selected: None,
90        }
91    }
92}
93
94/// What a plot did this frame.
95#[non_exhaustive]
96#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
97pub struct PlotResponse {
98    /// As any widget's.
99    pub response: Response,
100    /// The value under the pointer.
101    pub hovered: Option<usize>,
102    /// The value clicked.
103    pub clicked: Option<usize>,
104}
105
106/// A row of widgets side by side, being laid out.
107#[derive(Clone, Copy, Debug)]
108struct Row {
109    x: f32,
110    top: f32,
111    height: f32,
112}
113
114/// A window's content, being filled: each widget takes a row, from the
115/// top, or a place in a row of [`Ui::horizontal`].
116///
117/// A widget's text is formatted with `Display`, into a buffer the frames
118/// reuse. Its identity is the hash of its scope's (its window's, a tree
119/// node's, a [`Ui::with_id`]'s) and its text, or its explicit ID:
120/// `"Pause (3)##pause"` shows `Pause (3)` and is the widget `pause`, which
121/// stays the one held, or the field with the keyboard, as its count
122/// changes. Two widgets of one text in one scope are one widget: give them
123/// IDs, or scopes.
124pub struct Ui<'a> {
125    core: &'a mut DebugUi,
126    layer: Layer,
127    scope: Id,
128    clip: Rect,
129    left: f32,
130    width: f32,
131    indent: f32,
132    y: f32,
133    row: Option<Row>,
134}
135
136impl<'a> Ui<'a> {
137    pub(crate) fn new(
138        core: &'a mut DebugUi,
139        layer: Layer,
140        scope: Id,
141        clip: Rect,
142        left: f32,
143        width: f32,
144        y: f32,
145    ) -> Self {
146        Self {
147            core,
148            layer,
149            scope,
150            clip,
151            left,
152            width,
153            indent: 0.0,
154            y,
155            row: None,
156        }
157    }
158
159    /// Where the next row goes.
160    pub(crate) fn y(&self) -> f32 {
161        self.y
162    }
163
164    /// The number of the frame being filled: one more each frame.
165    pub(crate) fn frame_number(&self) -> u64 {
166        self.core.frames
167    }
168
169    /// The UI's look.
170    pub(crate) fn style(&self) -> crate::Style {
171        self.core.style
172    }
173
174    /// How far down a row moves the next: a row and the space under it.
175    pub(crate) fn row_step(&self) -> f32 {
176        self.core.row_height() + self.core.style.spacing
177    }
178
179    /// How much of the window is left below the next row's top, inside
180    /// its padding: rows that fit in it do not make the window scroll.
181    pub(crate) fn room(&self) -> f32 {
182        self.clip.max.y - self.core.style.padding - self.y
183    }
184
185    /// Leaves `rows` rows empty, in a column.
186    pub(crate) fn skip_rows(&mut self, rows: usize) {
187        if self.row.is_none() {
188            self.y += self.row_step() * rows as f32;
189        }
190    }
191
192    /// The wheel's lines this frame, up positive, if the pointer is over
193    /// the next `height` of the window and the window is under it.
194    pub(crate) fn wheel_over(&self, height: f32) -> f32 {
195        let rect = Rect::from_min_size(
196            Vec2::new(self.left + self.indent, self.y),
197            Vec2::new(self.width - self.indent, height),
198        );
199        self.core.wheel_over(self.layer, self.clip, rect)
200    }
201
202    /// Fills `add` with the widgets of `key`'s scope: for the same texts
203    /// in a loop, say, `ui.with_id(index, |ui| ...)`.
204    pub fn with_id(&mut self, key: impl Hash, add: impl FnOnce(&mut Ui<'_>)) {
205        let scope = self.scope;
206        self.scope = scope.with((SCOPE, key));
207        add(self);
208        self.scope = scope;
209    }
210
211    /// Lays the widgets of `add` side by side in one row, as high as the
212    /// highest. A control with a label takes the style's `control_width`
213    /// there, its label after it; a button, a checkbox or a label, its
214    /// text's width.
215    pub fn horizontal(&mut self, add: impl FnOnce(&mut Ui<'_>)) {
216        if self.row.is_some() {
217            add(self);
218            return;
219        }
220        self.row = Some(Row {
221            x: self.left + self.indent,
222            top: self.y,
223            height: 0.0,
224        });
225        add(self);
226        if let Some(row) = self.row.take()
227            && row.height > 0.0
228        {
229            self.y += row.height + self.core.style.spacing;
230        }
231    }
232
233    /// Whether `key` was pressed this frame, or repeated: for keys a text
234    /// field does not use, Up, Down, Tab, PageUp and PageDown, while it has
235    /// the keyboard, as a console's history and completion want.
236    pub fn key_pressed(&self, key: Key) -> bool {
237        self.core
238            .input
239            .edits
240            .iter()
241            .any(|edit| matches!(*edit, Edit::Key { key: pressed, .. } if pressed == key))
242    }
243
244    /// Gives the keyboard to the next text field called, its caret at its
245    /// end: a console's command line when it opens, say. The field takes
246    /// none of this frame's edits, which were typed before it had the
247    /// keyboard: the key that opened the console is not typed into it.
248    pub fn focus_next(&mut self) {
249        self.core.focus_next = true;
250    }
251
252    /// A line of text.
253    pub fn label(&mut self, text: impl fmt::Display) {
254        let color = self.core.style.text;
255        self.label_colored(color, text);
256    }
257
258    /// A line of text in `color`. One out of the window's view is not
259    /// formatted, in a column of rows, which keeps a long log cheap.
260    pub fn label_colored(&mut self, color: Color, text: impl fmt::Display) {
261        let height = self.core.row_height();
262        if self.row.is_none() {
263            let probe = Rect::from_min_size(
264                Vec2::new(self.left + self.indent, self.y),
265                Vec2::new(self.width - self.indent, height),
266            );
267            if !probe.intersects(self.clip) {
268                self.allocate(None, height);
269                return;
270            }
271        }
272        let shown = self.core.format(text);
273        let width = self.core.width(self.core.text(shown));
274        let rect = self.allocate(Some(width), height);
275        let at = rect.min + Vec2::new(0.0, self.core.style.padding);
276        self.core.text_at(self.layer, self.clip, at, shown, color);
277    }
278
279    /// A button, as wide as its text. Clicked when the button goes down on
280    /// it and up over it.
281    pub fn button(&mut self, text: impl fmt::Display) -> Response {
282        let (id, shown) = self.labeled(text);
283        let padding = self.core.style.padding;
284        let width = self.core.width(self.core.text(shown)) + 4.0 * padding;
285        let height = self.core.row_height();
286        let rect = self.allocate(Some(width), height);
287        let interaction = self.interact(id, rect);
288        let color = self.state_color(interaction);
289        self.fill(rect, color);
290        let at = rect.min + Vec2::new(2.0 * padding, padding);
291        self.write(at, shown, self.core.style.text, rect);
292        interaction.into()
293    }
294
295    /// A box ticked when `value` is true, and its text: a click on either
296    /// flips it.
297    pub fn checkbox(&mut self, text: impl fmt::Display, value: &mut bool) -> Response {
298        let (id, shown) = self.labeled(text);
299        let style = self.core.style;
300        let height = self.core.row_height();
301        let width = height + style.spacing + self.core.width(self.core.text(shown));
302        let rect = self.allocate(Some(width), height);
303        let interaction = self.interact(id, rect);
304        let mut response = Response::from(interaction);
305        if interaction.clicked {
306            *value = !*value;
307            response.changed = true;
308        }
309        let side = height - 2.0 * style.padding;
310        let mark = Rect::from_min_size(rect.min + Vec2::splat(style.padding), Vec2::splat(side));
311        let color = self.state_color(interaction);
312        self.fill(mark, color);
313        if *value {
314            let inner = Rect::new(mark.min + Vec2::splat(2.0), mark.max - Vec2::splat(2.0));
315            self.fill(inner, style.accent);
316        }
317        let at = Vec2::new(
318            rect.min.x + height + style.spacing,
319            rect.min.y + style.padding,
320        );
321        self.write(at, shown, style.text, rect);
322        response
323    }
324
325    /// A slider of `value` in `range`: pressing or dragging on it sets the
326    /// value under the pointer, held in the range. A value outside the range
327    /// is left as it is until the slider is moved; a reversed range is
328    /// swapped; with a NaN bound, it changes nothing.
329    pub fn slider_f32(
330        &mut self,
331        text: impl fmt::Display,
332        value: &mut f32,
333        range: RangeInclusive<f32>,
334    ) -> Response {
335        let (id, shown) = self.labeled(text);
336        let (control, label) = self.control_row(shown);
337        let interaction = self.interact(id, control);
338        let mut response = Response::from(interaction);
339        let (low, high) = ordered(*range.start(), *range.end());
340        let usable = low.is_finite() && high.is_finite();
341        if interaction.held && usable {
342            let t = fraction(self.core.pointer.x, control);
343            // Exact at the ends, and no overflow over a wide range.
344            let next = low * (1.0 - t) + high * t;
345            if next != *value {
346                *value = next;
347                response.changed = true;
348            }
349        }
350        let t = if usable && high > low {
351            unit((*value - low) / (high - low))
352        } else {
353            0.0
354        };
355        let shown_value = self.core.format(format_args!("{:.3}", *value));
356        self.draw_slider(interaction, control, t, shown_value);
357        self.write_label(label, shown);
358        response
359    }
360
361    /// A slider of whole numbers, as [`Ui::slider_f32`]: the value under the
362    /// pointer is rounded to the nearest, over any range of `i32`.
363    pub fn slider_i32(
364        &mut self,
365        text: impl fmt::Display,
366        value: &mut i32,
367        range: RangeInclusive<i32>,
368    ) -> Response {
369        let (id, shown) = self.labeled(text);
370        let (control, label) = self.control_row(shown);
371        let interaction = self.interact(id, control);
372        let mut response = Response::from(interaction);
373        let (low, high) = {
374            let (a, b) = (i64::from(*range.start()), i64::from(*range.end()));
375            (a.min(b), a.max(b))
376        };
377        let span = (high - low) as f64;
378        if interaction.held {
379            let t = f64::from(fraction(self.core.pointer.x, control));
380            let next = (low + (span * t).round() as i64).clamp(low, high);
381            // Inside two i32 bounds.
382            let next = next as i32;
383            if next != *value {
384                *value = next;
385                response.changed = true;
386            }
387        }
388        let t = if span > 0.0 {
389            ((i64::from(*value) - low) as f64 / span).clamp(0.0, 1.0) as f32
390        } else {
391            0.0
392        };
393        let shown_value = self.core.format(*value);
394        self.draw_slider(interaction, control, t, shown_value);
395        self.write_label(label, shown);
396        response
397    }
398
399    /// A number changed by dragging across it: `per_unit` for each UI unit
400    /// the pointer moves right, less moving left. A step or a result that
401    /// is not finite changes nothing.
402    pub fn drag_f32(
403        &mut self,
404        text: impl fmt::Display,
405        value: &mut f32,
406        per_unit: f32,
407    ) -> Response {
408        let (id, shown) = self.labeled(text);
409        let (control, label) = self.control_row(shown);
410        let interaction = self.interact(id, control);
411        let mut response = Response::from(interaction);
412        let pointer = self.core.pointer;
413        if let Some(active) = self.core.active_mut(id) {
414            let moved = pointer.x - active.last.x;
415            active.last = pointer;
416            let next = *value + moved * per_unit;
417            if next.is_finite() && next != *value {
418                *value = next;
419                response.changed = true;
420            }
421        }
422        let color = self.state_color(interaction);
423        self.fill(control, color);
424        let shown_value = self.core.format(format_args!("{:.3}", *value));
425        self.write_centered(control, shown_value);
426        self.write_label(label, shown);
427        response
428    }
429
430    /// A one-line text field editing `value`.
431    ///
432    /// A press on it gives it the keyboard, the caret where it was pressed;
433    /// a press elsewhere, Escape, or another field taking the keyboard,
434    /// takes it back (`lost_focus`, when the field is next called). With the
435    /// keyboard, typed text goes in at the caret, replacing a selection;
436    /// Backspace and Delete remove; Left, Right, Home and End move the
437    /// caret, selecting with Shift; Control or Super with A selects all;
438    /// Enter is `submitted`, and the field keeps the keyboard. Other keys
439    /// are the caller's ([`Ui::key_pressed`]). A `value` the caller changed
440    /// puts the caret at its end. Copy and paste are not built.
441    pub fn text_input(&mut self, text: impl fmt::Display, value: &mut String) -> Response {
442        self.text_field(text, value, false).0
443    }
444
445    /// A text field across the whole row, its text not shown: a console's
446    /// command line. As [`Ui::text_input`]; and whether it has the keyboard
447    /// once this frame's edits are in.
448    pub(crate) fn text_line(
449        &mut self,
450        text: impl fmt::Display,
451        value: &mut String,
452    ) -> (Response, bool) {
453        self.text_field(text, value, true)
454    }
455
456    /// A text field, its label after it, or across the row with no label
457    /// if `whole`; and whether it has the keyboard.
458    fn text_field(
459        &mut self,
460        text: impl fmt::Display,
461        value: &mut String,
462        whole: bool,
463    ) -> (Response, bool) {
464        let (id, shown) = self.labeled(text);
465        let (control, label) = if whole {
466            let height = self.core.row_height();
467            let rect = self.allocate(None, height);
468            (rect, None)
469        } else {
470            let (control, label) = self.control_row(shown);
471            (control, Some(label))
472        };
473        let interaction = self.interact(id, control);
474        let mut response = Response::from(interaction);
475        let style = self.core.style;
476        let inner = Rect::new(
477            control.min + Vec2::new(style.padding, 0.0),
478            control.max - Vec2::new(style.padding, 0.0),
479        );
480        let core = &mut *self.core;
481        // The keyboard taken by another field since this one last ran.
482        if core.lost == Some(id) {
483            core.lost = None;
484            response.lost_focus = true;
485        }
486        let mut focused = core.focus.is_some_and(|focus| focus.id == id);
487        // Given the keyboard by `focus_next`, the field takes none of this
488        // frame's edits, typed before it had it: the key that opened a
489        // console, say.
490        let mut fresh = false;
491        if interaction.pressed {
492            if !focused {
493                take_focus(core, id, value);
494                focused = true;
495            }
496            if let (Some(focus), Some(at)) = (core.focus.as_mut(), core.press) {
497                let x = at.x - inner.min.x + focus.scroll;
498                focus.caret = Caret::at(nearest_caret(&*core.metrics, value, x));
499            }
500        } else if focused && core.press.is_some() {
501            core.focus = None;
502            focused = false;
503            response.lost_focus = true;
504        }
505        if core.focus_next {
506            core.focus_next = false;
507            if !focused {
508                take_focus(core, id, value);
509                focused = true;
510                fresh = true;
511            }
512        }
513        if focused && let Some(focus) = core.focus.as_mut() {
514            focus.seen = true;
515            if value.len() != focus.len || fnv1a64(value.as_bytes()) != focus.hash {
516                focus.caret = Caret::at(value.len());
517                focus.scroll = 0.0;
518            }
519            focus.caret.fit(value);
520            let mut escaped = false;
521            for &edit in core.input.edits.iter().filter(|_| !fresh) {
522                let edited = apply(value, &mut focus.caret, edit);
523                response.changed |= edited.changed;
524                response.submitted |= edited.submitted;
525                if edited.escaped {
526                    escaped = true;
527                    break;
528                }
529            }
530            focus.len = value.len();
531            focus.hash = fnv1a64(value.as_bytes());
532            // Scrolled to keep the caret in view, and no further than the
533            // text's end needs.
534            let caret_x = core.metrics.caret_x(value, focus.caret.caret);
535            let end_x = core.metrics.caret_x(value, value.len());
536            let room = (inner.width() - 1.0).max(0.0);
537            if caret_x - focus.scroll > room {
538                focus.scroll = caret_x - room;
539            }
540            if caret_x < focus.scroll {
541                focus.scroll = caret_x;
542            }
543            focus.scroll = focus.scroll.min(end_x - room).max(0.0);
544            if escaped {
545                core.focus = None;
546                focused = false;
547                response.lost_focus = true;
548            }
549        }
550
551        let color = if focused {
552            style.active
553        } else {
554            self.state_color(interaction)
555        };
556        self.fill(control, color);
557        let field = self.clip.intersection(inner);
558        let focus = self.core.focus.filter(|_| focused);
559        let scroll = focus.map_or(0.0, |focus| focus.scroll);
560        let start = inner.min.x - scroll;
561        if let (Some(focus), Some(field)) = (focus, field) {
562            let (from, to) = focus.caret.selection();
563            if from != to {
564                let x0 = start + self.core.metrics.caret_x(value, from);
565                let x1 = start + self.core.metrics.caret_x(value, to);
566                let selection = Rect::new(
567                    Vec2::new(x0, control.min.y + style.padding),
568                    Vec2::new(x1, control.max.y - style.padding),
569                );
570                self.core
571                    .rect(self.layer, field, selection, style.selection);
572            }
573        }
574        if let Some(field) = field {
575            let range = self.core.format(&*value);
576            let at = Vec2::new(start, control.min.y + style.padding);
577            self.core.text_at(self.layer, field, at, range, style.text);
578        }
579        if let (Some(focus), Some(field)) = (focus, field) {
580            let x = start + self.core.metrics.caret_x(value, focus.caret.caret);
581            let caret = Rect::from_min_size(
582                Vec2::new(x, control.min.y + style.padding),
583                Vec2::new(1.0, self.core.metrics.line_height()),
584            );
585            self.core.rect(self.layer, field, caret, style.text);
586        }
587        if let Some(label) = label {
588            self.write_label(label, shown);
589        }
590        (response, focused)
591    }
592
593    /// A choice of `items`, `selected` the one shown: a click opens their
594    /// list over everything, and a click on one picks it; a press elsewhere
595    /// closes the list. With no items, or `selected` past them, it shows
596    /// nothing and changes nothing until one is picked.
597    pub fn combo(
598        &mut self,
599        text: impl fmt::Display,
600        selected: &mut usize,
601        items: &[&str],
602    ) -> Response {
603        let (id, shown) = self.labeled(text);
604        let (control, label) = self.control_row(shown);
605        let interaction = self.interact(id, control);
606        let mut response = Response::from(interaction);
607        let style = self.core.style;
608        let row = self.core.row_height();
609        let open = self.core.popup.is_some_and(|popup| popup.id == id);
610        if interaction.clicked {
611            self.core.popup = (!open).then_some(Popup {
612                id,
613                seen: true,
614                anchor: control,
615                rect: control,
616            });
617        }
618        let color = self.state_color(interaction);
619        self.fill(control, color);
620        if let Some(item) = items.get(*selected) {
621            let range = self.core.format(item);
622            let at = control.min + Vec2::splat(style.padding);
623            self.write(at, range, style.text, control);
624        }
625        self.write_label(label, shown);
626
627        if self.core.popup.is_some_and(|popup| popup.id == id) {
628            let screen = self.core.space.size;
629            let height = row * items.len() as f32;
630            let mut top = control.max.y;
631            if top + height > screen.y && control.min.y - height >= 0.0 {
632                top = control.min.y - height;
633            }
634            let rect = Rect::from_min_size(
635                Vec2::new(control.min.x, top),
636                Vec2::new(control.width(), height),
637            );
638            if let Some(popup) = self.core.popup.as_mut() {
639                popup.seen = true;
640                popup.anchor = control;
641                popup.rect = rect;
642            }
643            let (layer, clip) = (self.layer, self.clip);
644            self.layer = Layer::Popup;
645            self.clip = rect;
646            self.fill(rect, style.panel);
647            for (index, item) in items.iter().enumerate() {
648                let at = Rect::from_min_size(
649                    Vec2::new(rect.min.x, rect.min.y + row * index as f32),
650                    Vec2::new(rect.width(), row),
651                );
652                let picked = self.interact(id.with(index), at);
653                if picked.hovered || picked.held {
654                    self.fill(at, style.hot);
655                }
656                let range = self.core.format(item);
657                self.write(at.min + Vec2::splat(style.padding), range, style.text, at);
658                if picked.clicked {
659                    *selected = index;
660                    response.changed = true;
661                    self.core.popup = None;
662                }
663            }
664            self.layer = layer;
665            self.clip = clip;
666        }
667        response
668    }
669
670    /// A node of a tree, open or closed by a click, `add` filling its
671    /// children, moved in, while it is open. It keeps its state by its
672    /// identity, and is the scope of its children's.
673    pub fn tree_node(
674        &mut self,
675        text: impl fmt::Display,
676        add: impl FnOnce(&mut Ui<'_>),
677    ) -> Response {
678        let (id, shown) = self.labeled(text);
679        let style = self.core.style;
680        let height = self.core.row_height();
681        let rect = self.allocate(None, height);
682        let interaction = self.interact(id, rect);
683        let mut response = Response::from(interaction);
684        let mut open = self.core.open.contains(&id);
685        if interaction.clicked {
686            open = !open;
687            if open {
688                self.core.open.insert(id);
689            } else {
690                self.core.open.remove(&id);
691            }
692            response.changed = true;
693        }
694        if interaction.hovered || interaction.held {
695            self.fill(rect, style.hot);
696        }
697        let mark = self.core.format(if open { "-" } else { "+" });
698        let at = rect.min + Vec2::splat(style.padding);
699        self.write(at, mark, style.text, rect);
700        let at = Vec2::new(rect.min.x + height, rect.min.y + style.padding);
701        self.write(at, shown, style.text, rect);
702        if open {
703            let (scope, indent) = (self.scope, self.indent);
704            self.scope = id;
705            self.indent += style.indent;
706            add(self);
707            self.scope = scope;
708            self.indent = indent;
709        }
710        response
711    }
712
713    /// A line across the window.
714    pub fn separator(&mut self) {
715        let style = self.core.style;
716        let rect = self.allocate(None, style.spacing + 1.0);
717        let line = Rect::from_min_size(
718            Vec2::new(rect.min.x, rect.min.y + (style.spacing * 0.5).floor()),
719            Vec2::new(rect.width(), 1.0),
720        );
721        self.fill(line, style.dim);
722    }
723
724    /// A line graph of `values`, from the left edge to the right, each
725    /// value `i` of `n` at `i / (n − 1)` of the width, as `plot` says;
726    /// values that are not finite break the line, and a value with no
727    /// finite one beside it is a dot. It says which value is under the
728    /// pointer, and which was clicked.
729    pub fn plot(
730        &mut self,
731        text: impl fmt::Display,
732        values: impl IntoIterator<Item = f32>,
733        plot: Plot,
734    ) -> PlotResponse {
735        let (id, shown) = self.labeled(text);
736        let style = self.core.style;
737        let text_width = self.core.width(self.core.text(shown));
738        let height = if plot.height.is_finite() && plot.height > 0.0 {
739            plot.height.max(1.0)
740        } else {
741            DEFAULT_PLOT_HEIGHT
742        };
743        let (graph, label) = self.control_rects(text_width, height);
744        let interaction = self.interact(id, graph);
745        self.core.values.clear();
746        self.core.values.extend(values);
747        let count = self.core.values.len();
748        let x_of = |index: usize| {
749            if count > 1 {
750                graph.min.x + graph.width() * index as f32 / (count - 1) as f32
751            } else {
752                graph.center().x
753            }
754        };
755        let index_at = |x: f32| {
756            if count == 0 {
757                return None;
758            }
759            let share = fraction(x, graph);
760            Some(((share * (count - 1) as f32).round() as usize).min(count - 1))
761        };
762        let (low, high) = ordered(*plot.range.start(), *plot.range.end());
763        let usable = low.is_finite() && high.is_finite() && high > low;
764        let y_of = |value: f32| {
765            let share = if usable {
766                unit((value - low) / (high - low))
767            } else {
768                0.5
769            };
770            graph.max.y - 0.5 - share * (graph.height() - 1.0)
771        };
772        self.fill(graph, style.widget);
773        let clip = self.clip.intersection(graph);
774        if let Some(clip) = clip {
775            if let Some(selected) = plot.selected.filter(|&index| index < count) {
776                // Inside the graph, the last value's mark too.
777                let x = x_of(selected).min(graph.max.x - 1.0);
778                let line =
779                    Rect::from_min_size(Vec2::new(x, graph.min.y), Vec2::new(1.0, graph.height()));
780                self.core.rect(self.layer, clip, line, style.hot);
781            }
782            let mut previous: Option<Vec2> = None;
783            for index in 0..count {
784                let value = self.core.values[index];
785                let point = value
786                    .is_finite()
787                    .then(|| Vec2::new(x_of(index), y_of(value)));
788                match (previous, point) {
789                    (Some(from), Some(to)) => {
790                        self.core.line(self.layer, clip, from, to, style.accent);
791                    }
792                    // A value alone, between gaps or at an end: a dot.
793                    (None, Some(at))
794                        if !self
795                            .core
796                            .values
797                            .get(index + 1)
798                            .is_some_and(|next| next.is_finite()) =>
799                    {
800                        let dot = Rect::from_min_size(at - Vec2::splat(0.5), Vec2::ONE);
801                        self.core.rect(self.layer, clip, dot, style.accent);
802                    }
803                    _ => {}
804                }
805                previous = point;
806            }
807        }
808        self.write_label(label, shown);
809        let pointer = self.core.pointer;
810        let release = self.core.release.map(|(at, _)| at);
811        PlotResponse {
812            response: interaction.into(),
813            hovered: if interaction.hovered {
814                index_at(pointer.x)
815            } else {
816                None
817            },
818            clicked: if interaction.clicked {
819                release.and_then(|at| index_at(at.x))
820            } else {
821                None
822            },
823        }
824    }
825
826    /// A color: a swatch and its text, then a slider of 0 to 255 for each
827    /// of red, green, blue and alpha, in its own scope.
828    pub fn color_edit(&mut self, text: impl fmt::Display, color: &mut Color) -> Response {
829        let (id, shown) = self.labeled(text);
830        let style = self.core.style;
831        let height = self.core.row_height();
832        let width = height + style.spacing + self.core.width(self.core.text(shown));
833        let rect = self.allocate(Some(width), height);
834        let swatch = Rect::from_min_size(
835            rect.min + Vec2::splat(style.padding),
836            Vec2::splat(height - 2.0 * style.padding),
837        );
838        self.fill(swatch, *color);
839        let at = Vec2::new(
840            rect.min.x + height + style.spacing,
841            rect.min.y + style.padding,
842        );
843        self.write(at, shown, style.text, rect);
844        let mut response = Response::default();
845        let scope = self.scope;
846        self.scope = id;
847        let mut channels = [color.r, color.g, color.b, color.a].map(i32::from);
848        for (name, channel) in ["R", "G", "B", "A"].into_iter().zip(&mut channels) {
849            let moved = self.slider_i32(name, channel, 0..=255);
850            response.changed |= moved.changed;
851            response.active |= moved.active;
852            response.hovered |= moved.hovered;
853        }
854        self.scope = scope;
855        if response.changed {
856            // Held in 0..=255 by the sliders.
857            let [r, g, b, a] = channels.map(|channel| channel.clamp(0, 255) as u8);
858            *color = Color::rgba(r, g, b, a);
859        }
860        response
861    }
862
863    /// Formats a widget's text: its identity, and what it shows.
864    fn labeled(&mut self, text: impl fmt::Display) -> (Id, (u32, u32)) {
865        let (start, end) = self.core.format(text);
866        let (shown, key) = split(self.core.text((start, end)));
867        let id = self.scope.with(key);
868        (id, (start, start + shown.len() as u32))
869    }
870
871    /// The rect of the next widget, `width` wide or the row's width, and
872    /// `height` high, and moves the layout past it.
873    fn allocate(&mut self, width: Option<f32>, height: f32) -> Rect {
874        let spacing = self.core.style.spacing;
875        if let Some(row) = self.row.as_mut() {
876            let width = width.unwrap_or(self.core.style.control_width);
877            let rect = Rect::from_min_size(Vec2::new(row.x, row.top), Vec2::new(width, height));
878            row.x += width + spacing;
879            row.height = row.height.max(height);
880            return rect;
881        }
882        let x = self.left + self.indent;
883        let width = width.unwrap_or(self.width - self.indent);
884        let rect = Rect::from_min_size(Vec2::new(x, self.y), Vec2::new(width, height));
885        self.y += height + spacing;
886        rect
887    }
888
889    /// A control with a label after it, a row high: the control's rect and
890    /// where the label goes.
891    fn control_row(&mut self, shown: (u32, u32)) -> (Rect, Vec2) {
892        let width = self.core.width(self.core.text(shown));
893        let height = self.core.row_height();
894        self.control_rects(width, height)
895    }
896
897    /// A control `height` high with a label `text_width` wide after it.
898    fn control_rects(&mut self, text_width: f32, height: f32) -> (Rect, Vec2) {
899        let style = self.core.style;
900        let (rect, control) = if self.row.is_some() {
901            let control = style.control_width;
902            (
903                self.allocate(Some(control + style.spacing + text_width), height),
904                control,
905            )
906        } else {
907            let rect = self.allocate(None, height);
908            (rect, (rect.width() * style.control_share).floor().max(0.0))
909        };
910        let control = Rect::from_min_size(rect.min, Vec2::new(control, height));
911        let label = Vec2::new(control.max.x + style.spacing, rect.min.y + style.padding);
912        (control, label)
913    }
914
915    fn interact(&mut self, id: Id, rect: Rect) -> Interaction {
916        self.core.interact(self.layer, self.clip, id, rect)
917    }
918
919    /// The color of a control in `interaction`'s state.
920    fn state_color(&self, interaction: Interaction) -> Color {
921        let style = &self.core.style;
922        if interaction.held {
923            style.active
924        } else if interaction.hovered {
925            style.hot
926        } else {
927            style.widget
928        }
929    }
930
931    fn fill(&mut self, rect: Rect, color: Color) {
932        self.core.rect(self.layer, self.clip, rect, color);
933    }
934
935    /// Writes the text `range` at `at`, cut to `within` and the clip.
936    fn write(&mut self, at: Vec2, range: (u32, u32), color: Color, within: Rect) {
937        if let Some(clip) = self.clip.intersection(within) {
938            self.core.text_at(self.layer, clip, at, range, color);
939        }
940    }
941
942    /// Writes the text `range` in the middle of `control`.
943    fn write_centered(&mut self, control: Rect, range: (u32, u32)) {
944        let width = self.core.width(self.core.text(range));
945        let at = Vec2::new(
946            (control.center().x - width * 0.5).floor(),
947            control.min.y + self.core.style.padding,
948        );
949        let color = self.core.style.text;
950        self.write(at, range, color, control);
951    }
952
953    /// Writes a control's label at `at`.
954    fn write_label(&mut self, at: Vec2, range: (u32, u32)) {
955        let color = self.core.style.text;
956        self.core.text_at(self.layer, self.clip, at, range, color);
957    }
958
959    fn draw_slider(&mut self, interaction: Interaction, control: Rect, t: f32, value: (u32, u32)) {
960        let style = self.core.style;
961        let color = self.state_color(interaction);
962        self.fill(control, color);
963        let handle_width = (control.height() * 0.5).floor().max(1.0);
964        let x = control.min.x + t * (control.width() - handle_width).max(0.0);
965        let handle = Rect::from_min_size(
966            Vec2::new(x, control.min.y),
967            Vec2::new(handle_width, control.height()),
968        );
969        self.fill(handle, style.accent);
970        self.write_centered(control, value);
971    }
972}
973
974/// `a` and `b`, the smaller first; a NaN stays where it is.
975fn ordered(a: f32, b: f32) -> (f32, f32) {
976    if b < a { (b, a) } else { (a, b) }
977}
978
979/// How far across `rect` `x` is, held in 0 to 1; 0 for a rect with no
980/// width.
981fn fraction(x: f32, rect: Rect) -> f32 {
982    unit((x - rect.min.x) / rect.width())
983}
984
985/// `share` held in 0 to 1, a NaN at 0.
986fn unit(share: f32) -> f32 {
987    if share.is_nan() {
988        0.0
989    } else {
990        share.clamp(0.0, 1.0)
991    }
992}
993
994/// Gives the keyboard to the field `id`, editing `value`, its caret at the
995/// end; a field that had it says so when it is next called.
996fn take_focus(core: &mut DebugUi, id: Id, value: &str) {
997    if let Some(old) = core.focus.filter(|old| old.id != id) {
998        core.lost = Some(old.id);
999    }
1000    if core.lost == Some(id) {
1001        core.lost = None;
1002    }
1003    core.focus = Some(Focus {
1004        id,
1005        seen: true,
1006        caret: Caret::at(value.len()),
1007        scroll: 0.0,
1008        len: value.len(),
1009        hash: fnv1a64(value.as_bytes()),
1010    });
1011}
1012
1013/// The character boundary of `text` nearest `x`, the pen's distance from
1014/// its start.
1015fn nearest_caret(metrics: &dyn crate::TextMetrics, text: &str, x: f32) -> usize {
1016    let mut best = (f32::INFINITY, 0);
1017    for byte in text
1018        .char_indices()
1019        .map(|(byte, _)| byte)
1020        .chain([text.len()])
1021    {
1022        let distance = (metrics.caret_x(text, byte) - x).abs();
1023        if distance < best.0 {
1024            best = (distance, byte);
1025        }
1026    }
1027    best.1
1028}