Skip to main content

taut/
inspect.rs

1//! Property inspector: an app's value as rows of a name and an editor, in two columns with a
2//! draggable divider, as tools and game editors show the selection.
3//!
4//! ```ignore
5//! #[derive(Clone, Default)]
6//! struct Lamp {
7//!     name: String,
8//!     power: f32,
9//!     on: bool,
10//! }
11//! taut::inspect!(Lamp { name: "Name", power: Field::new("Power").unit("W").within(0.0, 2000.0), on: "On" });
12//!
13//! ui.inspect(&mut app.inspector, &mut app.lamp);
14//! ```
15//!
16//! A struct lists its fields ([`Inspect::fields`]), each with its options ([`Field`]); the rest
17//! follows from each field's type. A number is typed and stepped, with a slider where its range
18//! is set; text is typed; a `bool` is a check box; an enum is a dropdown; colours, dates and
19//! paths (with the file dialog) have their own editors; nested lists, maps and structs are
20//! collapsible headings with rows of their own. List rows can be added, removed, and reordered
21//! by dragging or Alt+arrows.
22//!
23//! The inspector walks the value as it lists itself, counting rows, and describes only the rows
24//! in view. The rest are counted and skipped: an off-screen field costs a counter step, and a
25//! list skips its off-screen items entirely (one row each, unless expanded). So 1,000 fields,
26//! or a 10,000-item list, cost about a screenful.
27//!
28//! A run walks the first value to count rows and note those in view; walks every other
29//! inspected value, and the initial state, to compare those rows with the first; and walks the
30//! first again to describe them. What the user does to a row (edit, reset, add, undo) is then
31//! applied to each value, walking straight down to that row only.
32use crate::accessibility::Role;
33use crate::color::Color;
34use crate::date::Date;
35use crate::event::{Cursor, Key, Mods};
36use crate::file_dialog::FileDialog;
37use crate::id::{ById, Id, fold, hash};
38use crate::layout::{Align, Flow, Length};
39use crate::number::Number;
40use crate::ui::{Icon, Measure, Response, Ui};
41use crate::widgets::{Before, CROSS, DOWN, RIGHT};
42use std::any::Any;
43use std::collections::BTreeMap;
44use std::fmt::Write;
45use std::ops::Range;
46use std::path::PathBuf;
47use std::time::Duration;
48
49const PLUS: Icon = Icon::line("M8 3.5v9M3.5 8h9");
50/// A curved arrow: resets a field to its initial value.
51const BACK: Icon = Icon::line("M4.4 6.2A4.4 4.4 0 1 1 3.8 10.3M4.2 2.6v3.8H8");
52/// Indent per nesting level.
53const STEP_IN: f32 = 14.0;
54/// The index of a row that is not a list item: a field, identified by name.
55const NAMED: usize = usize::MAX;
56/// Comparison results at a row: the values differ there; it differs from the initial value;
57/// and, while comparing one of them, that it has that row at all.
58const MIXED: u8 = 1;
59const CHANGED: u8 = 2;
60const MET: u8 = 4;
61/// Undo depth, and how close together edits of one row merge into one step.
62const STEPS: usize = 100;
63const ONE_STEP: Duration = Duration::from_secs(1);
64
65/// The path to a row: each heading on the way, with its index in its list (`NAMED` for a
66/// field), and the row last.
67type Way = Vec<(Id, usize)>;
68
69/// A field's options: its name and how its editor behaves. A plain name (`"Power"`) is a field
70/// with defaults.
71///
72/// ```ignore
73/// fields.field(Field::new("Power").unit("W").within(0.0, 2000.0).step(10.0), &mut self.power);
74/// ```
75#[derive(Clone, Copy, Debug, PartialEq)]
76pub struct Field<'a> {
77    /// The row's label.
78    pub name: &'a str,
79    /// A number's unit, shown after it ("W", "m/s"); empty for none.
80    pub unit: &'a str,
81    /// A number's minimum. With a maximum too, a slider shows beside it.
82    pub min: f64,
83    /// A number's maximum.
84    pub max: f64,
85    /// What Up and Down add or subtract; 0 for one.
86    pub step: f64,
87    /// Shown disabled: not editable here.
88    pub read_only: bool,
89    /// A tooltip, shown when the pointer rests on its name.
90    pub note: &'a str,
91    /// For a path: the extensions the file dialog lists (`&[".png"]`); none for all files.
92    pub only: &'a [&'a str],
93    /// For a path: the file dialog picks a folder, not a file.
94    pub folder: bool,
95}
96
97impl<'a> Field<'a> {
98    /// A field named `name`, with defaults.
99    pub const fn new(name: &'a str) -> Self {
100        Field { name, unit: "", min: f64::NEG_INFINITY, max: f64::INFINITY, step: 0.0, read_only: false, note: "", only: &[], folder: false }
101    }
102    /// Its number's unit.
103    pub const fn unit(self, unit: &'a str) -> Self {
104        Field { unit, ..self }
105    }
106    /// Its number's minimum.
107    pub const fn min(self, least: f64) -> Self {
108        Field { min: least, ..self }
109    }
110    /// Its number's maximum.
111    pub const fn max(self, most: f64) -> Self {
112        Field { max: most, ..self }
113    }
114    /// Its number's range: a slider shows between the two.
115    pub const fn range(self, least: f64, most: f64) -> Self {
116        Field { min: least, max: most, ..self }
117    }
118    /// What Up and Down add or subtract.
119    pub const fn step(self, step: f64) -> Self {
120        Field { step, ..self }
121    }
122    /// Shown, not editable here.
123    pub const fn read_only(self) -> Self {
124        Field { read_only: true, ..self }
125    }
126    /// A tooltip.
127    pub const fn note(self, note: &'a str) -> Self {
128        Field { note, ..self }
129    }
130    /// For a path: the file dialog lists only files with one of these extensions.
131    pub const fn only(self, endings: &'a [&'a str]) -> Self {
132        Field { only: endings, ..self }
133    }
134    /// For a path: a folder, picked with the file dialog.
135    pub const fn folder(self) -> Self {
136        Field { folder: true, ..self }
137    }
138}
139
140impl<'a> From<&'a str> for Field<'a> {
141    fn from(name: &'a str) -> Self {
142        Field::new(name)
143    }
144}
145
146/// Something an inspector shows: a single-row value with an editor beside its name (a number,
147/// text, a colour), or a heading that expands to rows of its own (an app struct, a list, a
148/// map).
149///
150/// An app struct just lists its fields:
151///
152/// ```ignore
153/// impl Inspect for Lamp {
154///     fn fields(&mut self, fields: &mut Fields) {
155///         fields.field("Name", &mut self.name);
156///         fields.field(Field::new("Power").unit("W"), &mut self.power);
157///     }
158/// }
159/// ```
160///
161/// (`taut::inspect!` writes that for a plain struct, and the rest for a fieldless enum.) Every
162/// number type, `bool`, `String`, [`Color`], [`Date`], `PathBuf`, `Vec`, `BTreeMap` with
163/// `String` keys, and arrays are implemented. Values are `Clone`: a copy is kept for undo and
164/// reset.
165pub trait Inspect: Clone + 'static {
166    /// A single-row value with an editor beside its name; not a heading.
167    const ROW: bool = false;
168    /// For a heading: lists its children, each with `fields.field(..)`, in display order.
169    fn fields(&mut self, fields: &mut Fields) {
170        let _ = fields;
171    }
172    /// For a single-row value: its editor, described beside the name; `changed` is set when the
173    /// user edits it. For a heading: what shows beside its name (a list shows its length).
174    fn part(&mut self, row: &mut InspectorRow) -> Response {
175        let _ = row;
176        Response::default()
177    }
178    /// The same where the inspected values differ: an editor showing that they do; when edited
179    /// (`changed`), every value is set as the first then is. By default, a "—" box that does
180    /// that when pressed.
181    fn mixed(&mut self, row: &mut InspectorRow) -> Response {
182        row.differs()
183    }
184    /// A hash of the value: different values give different hashes. With several values
185    /// inspected it shows where they differ; compared with the initial state, what was edited.
186    /// (A struct's is 0: its rows are compared one by one.)
187    fn hashed(&self) -> u64 {
188        0
189    }
190}
191
192/// Where an inspector row's editor is described: the UI, and the field's options.
193pub struct InspectorRow<'a> {
194    /// The UI: the editor is described with it.
195    pub ui: &'a mut Ui,
196    /// The field's options.
197    pub field: Field<'a>,
198    /// The inspected values differ here.
199    pub mixed: bool,
200    ins: &'a mut Inspector,
201}
202
203/// An inspector's state between runs, kept by the app: divider position, search text, expanded
204/// headings, initial values, and the undo history.
205pub struct Inspector {
206    /// The divider position, as a fraction of the inspector's width. The user drags it.
207    pub split: f32,
208    /// Search text: only rows whose names contain it show, with their headings.
209    pub search: String,
210    /// The dialog a path row opens to pick a file or folder
211    /// ([`FileDialog::native()`](FileDialog::native) for the system's).
212    pub file_dialog: FileDialog,
213    /// The inspector's own words, for localization: "Put back", "Add one", "Take out", "items",
214    /// "Pick", "New key".
215    pub words: [&'static str; 6],
216    /// Expanded headings: each id, its parent heading, and its index in that one's list
217    /// (`NAMED` for a field).
218    opened: Vec<(Id, Id, usize)>,
219    /// The initial values, if the app set them.
220    start: Option<Box<dyn Any>>,
221    /// The undo steps, the last last; and those undone, for redo.
222    steps: Vec<Step>,
223    undone: Vec<Step>,
224    walk: Walk,
225}
226
227impl Default for Inspector {
228    fn default() -> Self {
229        let words = ["Put back", "Add one", "Take out", "items", "Pick", "New key"];
230        Inspector { split: 0.4, search: String::new(), file_dialog: FileDialog::default(), words, opened: Vec::new(), start: None, steps: Vec::new(), undone: Vec::new(), walk: Walk::default() }
231    }
232}
233
234impl std::fmt::Debug for Inspector {
235    /// Its divider, search text, and undo and redo counts.
236    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
237        f.debug_struct("Inspector").field("split", &self.split).field("search", &self.search).field("undo", &self.steps.len()).field("redo", &self.undone.len()).finish_non_exhaustive()
238    }
239}
240
241impl Inspector {
242    /// Sets the inspected values' initial state (as created, or last saved): a field that
243    /// differs is marked and gets a reset button.
244    pub fn start<T: Inspect>(&mut self, start: T) {
245        self.start = Some(Box::new(start));
246    }
247    /// Whether undo and redo are available.
248    pub fn can_undo(&self) -> [bool; 2] {
249        [!self.steps.is_empty(), !self.undone.is_empty()]
250    }
251    /// Undoes the last edit on the inspector's next run (Ctrl+Z while focused); redo is Ctrl+Y.
252    pub fn undo(&mut self) {
253        self.walk.asked = Some(true);
254    }
255    /// Redoes the last undone edit on the inspector's next run.
256    pub fn redo(&mut self) {
257        self.walk.asked = Some(false);
258    }
259    /// Whether a heading is expanded.
260    fn is_open(&self, id: Id) -> bool {
261        self.opened.iter().any(|(open, ..)| *open == id)
262    }
263    /// Expands or collapses a heading.
264    fn flip(&mut self, id: Id, index: usize) {
265        match self.opened.iter().position(|(open, ..)| *open == id) {
266            Some(at) => drop(self.opened.swap_remove(at)),
267            None => self.opened.push((id, self.walk.parent(), index)),
268        }
269    }
270    /// Prepares a run: where the visible rows are, the search, and whether the values are the
271    /// ones the undo history was made with.
272    fn begin<T: Inspect>(&mut self, line: f32, read: [f32; 3], offset: f32, things: &[&mut T]) {
273        let walk = &mut self.walk;
274        (walk.line, walk.names_wide) = (line, (read[0] * self.split.clamp(0.1, 0.9)).round());
275        walk.view = (offset / line).max(0.0) as usize..((offset + read[1]) / line).ceil().max(0.0) as usize;
276        walk.finding.clear();
277        walk.finding.extend(self.search.trim().chars().flat_map(char::to_lowercase));
278        walk.holding = things.len() > 1 || self.start.is_some();
279        // Other values than last time: the history was theirs.
280        let who = things.iter().fold(things.len() as u64, |so_far, thing| fold(so_far, &**thing as *const T as u64));
281        if std::mem::replace(&mut walk.who, who) != who {
282            self.steps.clear();
283            self.undone.clear();
284        }
285        walk.seen.clear();
286        walk.through.clear();
287        walk.asks.clear();
288    }
289    /// Starts a walk through a value: from the first row, nothing entered.
290    fn walk(&mut self, mode: Mode) {
291        let walk = &mut self.walk;
292        (walk.mode, walk.row) = (mode, 0);
293        walk.frames.clear();
294        walk.names.clear();
295    }
296    /// The next list item to look at while counting and describing rows: the next one in view,
297    /// or expanded, after `from`. Skipped items are counted, a row each.
298    fn next_listed(&mut self, len: usize, from: usize, rows: bool) -> Option<usize> {
299        let Inspector { walk, opened, .. } = self;
300        // While searching inside a list that didn't match: single-row items have no names to
301        // match; each item with rows of its own is searched.
302        if !walk.found() {
303            return (!rows && from < len).then_some(from);
304        }
305        let list = walk.parent();
306        let open = opened.iter().filter(|(_, under, at)| *under == list && *at >= from && *at < len).map(|(_, _, at)| *at).min().unwrap_or(len);
307        let ahead = match walk.row {
308            row if row < walk.view.start => from + (walk.view.start - row),
309            row if row < walk.view.end => from,
310            _ => len,
311        };
312        let next = ahead.min(open).min(len);
313        walk.row += next - from;
314        (next < len).then_some(next)
315    }
316    /// Records an undo step. An edit of the same row from the same editor as the last, while
317    /// the pointer holds it or soon after, merges into that one.
318    fn keep(&mut self, step: Step, joins: bool, held: bool) {
319        self.undone.clear();
320        let last = self.steps.last_mut().filter(|last| joins && last.way == step.way && last.focus == step.focus && (held || step.at.saturating_sub(last.at) < ONE_STEP));
321        match last {
322            Some(last) => (last.after, last.at) = (step.after, step.at),
323            None => self.steps.push(step),
324        }
325        if self.steps.len() > STEPS {
326            self.steps.remove(0);
327        }
328    }
329    /// After list rows were removed or moved, expanded ones stay expanded at their new indices.
330    fn reopen(&mut self, way: &[(Id, usize)], change: &Change) {
331        let list = way.last().map_or(0, |(id, _)| *id);
332        let to = |at: usize| match *change {
333            Change::Remove(gone) if at == gone => None,
334            Change::Remove(gone) => Some(at - (at > gone) as usize),
335            Change::Move(from, to) if at == from => Some(to),
336            Change::Move(from, to) if from < to && at > from && at <= to => Some(at - 1),
337            Change::Move(from, to) if to < from && at >= to && at < from => Some(at + 1),
338            _ => Some(at),
339        };
340        self.opened.retain_mut(|(id, under, at)| *under != list || to(*at).map(|now| (*at, *id) = (now, hash((list, now)))).is_some());
341    }
342}
343
344/// A run's walk state, kept to reuse its memory.
345#[derive(Default)]
346struct Walk {
347    mode: Mode,
348    /// Row height, and the name column's width.
349    line: f32,
350    names_wide: f32,
351    /// Rows counted so far; the total, as last counted; the visible ones.
352    row: usize,
353    count: usize,
354    view: Range<usize>,
355    /// The headings being walked, innermost last.
356    frames: Vec<Frame>,
357    /// The search, lower-cased; and the names of headings waiting to show.
358    finding: String,
359    names: String,
360    /// Other values are compared with the first: several are inspected, or the app set initial
361    /// values.
362    holding: bool,
363    /// The visible rows: the first value's hash at each, and the comparison results.
364    seen: ById<(u64, u8)>,
365    /// The headings on the way to the visible rows: for a list, its first and last item on the
366    /// way.
367    through: ById<[usize; 2]>,
368    /// The path a walk goes down, each heading with its index in its list; what it puts there,
369    /// or how it changes a list or map there; and what it found and left there.
370    route: Way,
371    deed: Option<Box<dyn Any>>,
372    change: Option<Change>,
373    acted: Option<(Box<dyn Any>, Box<dyn Any>)>,
374    /// What the user asked during the run, each with its row's path; and an app-requested undo
375    /// (`true`) or redo.
376    asks: Vec<(Way, Ask)>,
377    asked: Option<bool>,
378    /// The row being described: its id and index.
379    here: (Id, usize),
380    /// The path to the row the file dialog was opened for.
381    asking: Option<Way>,
382    /// A map key being typed: for which map, and the text.
383    key: (Id, String),
384    /// A list row being dragged: the list's path, from where, to where.
385    dragged_row: Option<(Way, usize, usize)>,
386    /// The row focus goes to once described: which, which of its boxes, and whether this run or
387    /// retried from the last.
388    refocus: Option<(Id, usize, bool)>,
389    /// Which values were inspected: when others are, the undo history no longer applies.
390    who: u64,
391    /// A row number, formatted.
392    scratch: String,
393}
394
395/// A walk's purpose.
396#[derive(Clone, Copy, Default, PartialEq)]
397enum Mode {
398    /// Counting rows and noting the visible ones.
399    #[default]
400    Count,
401    /// Comparing with the first value at the visible rows, marking differences with this.
402    Hold(u8),
403    /// Describing the visible rows.
404    Draw,
405    /// Going down to one row, to act there.
406    Go,
407}
408
409/// A heading being walked.
410struct Frame {
411    id: Id,
412    /// Its index in its list (`NAMED` for a field).
413    index: usize,
414    /// Everything under it follows expansion: no search, or it or an ancestor matched.
415    found: bool,
416    /// It shows once something under it matches: its name's range in `names`.
417    waiting: Option<[u32; 2]>,
418    /// Its kind, and a list's length.
419    kind: Kind,
420    len: usize,
421}
422
423/// A heading's kind: a struct; a list whose rows are added, removed and moved; a fixed-length
424/// list; a map, whose rows are added and removed.
425#[derive(Clone, Copy, PartialEq)]
426enum Kind {
427    Struct,
428    List,
429    Fixed,
430    Map,
431}
432
433/// A user request on a row during a run, applied to each value once the rows are described.
434enum Ask {
435    /// The first value here was edited, from the first to the second (the third is what the
436    /// others get): whether it may merge into the last step.
437    Changed(Box<dyn Any>, Box<dyn Any>, Box<dyn Any>, bool),
438    /// Every value gets this here: a path the file dialog picked, a list as the first value has
439    /// it.
440    Put(Box<dyn Any>),
441    /// Every value is reset here.
442    Back,
443    /// The list or map here changes.
444    Change(Change),
445}
446
447/// How a list or map changes.
448#[derive(Clone, Debug, PartialEq)]
449enum Change {
450    Add,
451    Remove(usize),
452    Move(usize, usize),
453    AddKey(String),
454    RemoveKey(String),
455}
456
457/// An undoable edit: its row's path, and each value's content there before and after (`None`
458/// where a value lacks the row).
459struct Step {
460    way: Way,
461    before: Vec<Option<Box<dyn Any>>>,
462    after: Vec<Option<Box<dyn Any>>>,
463    /// The focused box, and when it was made.
464    focus: Id,
465    at: Duration,
466}
467
468impl Walk {
469    /// The heading the current rows are under: 0 for the value itself.
470    fn parent(&self) -> Id {
471        self.frames.last().map_or(0, |frame| frame.id)
472    }
473    /// A row's id: its heading, and its name or list index.
474    fn id_of(&self, name: &str, index: usize) -> Id {
475        match index {
476            NAMED => hash((self.parent(), name)),
477            index => hash((self.parent(), index)),
478        }
479    }
480    /// Whether the current rows follow expansion: no search, or under a matching heading.
481    fn found(&self) -> bool {
482        self.frames.last().map_or(self.finding.is_empty(), |frame| frame.found)
483    }
484    /// Whether a name contains the search, case-insensitive.
485    fn matches(&self, name: &str) -> bool {
486        let small = || name.chars().flat_map(char::to_lowercase);
487        let (long, wanted) = (small().count(), self.finding.chars().count());
488        !name.is_empty() && (0..=long.saturating_sub(wanted)).any(|from| small().skip(from).take(wanted).eq(self.finding.chars()))
489    }
490    /// Records a heading waiting to show: its name, or its list index.
491    fn keep_name(&mut self, name: &str, index: usize) -> [u32; 2] {
492        let from = self.names.len() as u32;
493        match index {
494            NAMED => self.names.push_str(name),
495            index => drop(write!(self.names, "{index}")),
496        }
497        [from, self.names.len() as u32]
498    }
499    /// The path to the row being described, or to its heading.
500    fn way(&self, to_row: bool) -> Way {
501        let row = to_row.then_some(self.here);
502        self.frames.iter().map(|frame| (frame.id, frame.index)).chain(row).collect()
503    }
504    /// Records a visible row and its path, for the other values to be compared with.
505    fn note_seen(&mut self, id: Id, index: usize, hashed: u64) {
506        self.seen.insert(id, (hashed, 0));
507        let Walk { frames, through, .. } = self;
508        let (mut under, down) = (0, frames.iter().map(|frame| (frame.id, frame.index)).chain([(id, index)]));
509        for (on, at) in down {
510            let span = through.entry(under).or_insert([usize::MAX, 0]);
511            *span = if at == NAMED { *span } else { [span[0].min(at), span[1].max(at)] };
512            under = on;
513        }
514    }
515    /// Compares another value at a visible row with the first's.
516    fn hold(&mut self, id: Id, hashed: u64, mark: u8) {
517        if let Some(seen) = self.seen.get_mut(&id) {
518            seen.1 |= MET | if seen.0 == hashed { 0 } else { mark };
519        }
520    }
521    /// After comparing a value: a visible row it lacks differs too.
522    fn held(&mut self, mark: u8) {
523        for seen in self.seen.values_mut() {
524            seen.1 = (seen.1 | if seen.1 & MET == 0 { mark } else { 0 }) & !MET;
525        }
526    }
527}
528
529/// The rows of an inspected value, as it lists them: what [`Inspect::fields`] gets.
530pub struct Fields<'a> {
531    ui: &'a mut Ui,
532    ins: &'a mut Inspector,
533}
534
535impl std::fmt::Debug for Fields<'_> {
536    /// The inspector being described into.
537    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
538        f.debug_struct("Fields").field("inspector", &self.ins).finish_non_exhaustive()
539    }
540}
541
542impl Fields<'_> {
543    /// A field: its options (a plain name, or a [`Field`]), and its value, which its row shows
544    /// and edits.
545    pub fn field<'f, T: Inspect>(&mut self, field: impl Into<Field<'f>>, value: &mut T) {
546        self.visit(field.into(), value, NAMED);
547    }
548    /// A list item, at its index.
549    fn item<T: Inspect>(&mut self, index: usize, value: &mut T) {
550        self.visit(Field::new(""), value, index);
551    }
552    fn visit<T: Inspect>(&mut self, field: Field, value: &mut T, index: usize) {
553        match self.ins.walk.mode {
554            Mode::Count | Mode::Draw => self.listed(field, value, index),
555            _ => self.routed(field.name, value, index),
556        }
557    }
558    /// For a list or map: records its kind and length; returns its change, if this walk goes to
559    /// it to change it.
560    fn changes(&mut self, kind: Kind, len: usize) -> Option<Change> {
561        let walk = &mut self.ins.walk;
562        if let Some(frame) = walk.frames.last_mut() {
563            (frame.kind, frame.len) = (kind, len);
564        }
565        (walk.mode == Mode::Go && walk.frames.len() == walk.route.len()).then(|| walk.change.take()).flatten()
566    }
567    /// The next list item to look at, from `from`, of `len` (`rows`: single-row items). Skipped
568    /// items are counted where visible.
569    fn next_item(&mut self, len: usize, from: usize, rows: bool) -> Option<usize> {
570        let walk = &mut self.ins.walk;
571        match walk.mode {
572            Mode::Count | Mode::Draw => self.ins.next_listed(len, from, rows),
573            Mode::Hold(_) => {
574                let span = walk.through.get(&walk.parent()).copied()?;
575                let next = from.max(span[0]);
576                (next <= span[1] && next < len).then_some(next)
577            }
578            Mode::Go => walk.route.get(walk.frames.len()).map(|(_, at)| *at).filter(|at| *at >= from && *at < len),
579        }
580    }
581
582    /// A row while counting and describing: counted where visible, described where in view, and
583    /// entered if an expanded heading (or, while searching, one that didn't match itself).
584    fn listed<T: Inspect>(&mut self, field: Field, value: &mut T, index: usize) {
585        let walk = &mut self.ins.walk;
586        // Most common: a single-row value, no search. Out of view, it is just counted.
587        if T::ROW && walk.finding.is_empty() {
588            walk.row += 1;
589            if walk.view.contains(&(walk.row - 1)) {
590                self.in_view(field, value, index, false);
591            }
592            return;
593        }
594        let found = walk.found();
595        let matched = !found && walk.matches(field.name);
596        if T::ROW && !found && !matched {
597            return;
598        }
599        let id = walk.id_of(field.name, index);
600        let open = !T::ROW && self.ins.is_open(id);
601        if found || matched {
602            self.show_waiting();
603            let walk = &mut self.ins.walk;
604            walk.row += 1;
605            if walk.view.contains(&(walk.row - 1)) {
606                self.in_view(field, value, index, open);
607            }
608        }
609        if !open && (found || matched) {
610            return;
611        }
612        let walk = &mut self.ins.walk;
613        let waiting = (!found && !matched).then(|| walk.keep_name(field.name, index));
614        walk.frames.push(Frame { id, index, found: found || matched, waiting, kind: Kind::Struct, len: 0 });
615        value.fields(self);
616        self.ins.walk.frames.pop();
617    }
618    /// Something under the waiting headings matched: they show, a row each.
619    fn show_waiting(&mut self) {
620        for at in 0..self.ins.walk.frames.len() {
621            let walk = &mut self.ins.walk;
622            let Some(name) = walk.frames[at].waiting.take() else { continue };
623            walk.row += 1;
624            if walk.mode == Mode::Draw && walk.view.contains(&(walk.row - 1)) {
625                self.waiting_heading(at, name);
626            }
627        }
628    }
629    /// A visible row: recorded, or described.
630    fn in_view<T: Inspect>(&mut self, field: Field, value: &mut T, index: usize, open: bool) {
631        let walk = &mut self.ins.walk;
632        let id = walk.id_of(field.name, index);
633        match walk.mode {
634            Mode::Count if walk.holding => walk.note_seen(id, index, value.hashed()),
635            Mode::Draw => self.row(field, value, id, index, open),
636            _ => {}
637        }
638    }
639
640    /// A row while going down to one row (to act there), or while comparing another value with
641    /// the first.
642    fn routed<T: Inspect>(&mut self, name: &str, value: &mut T, index: usize) {
643        let walk = &mut self.ins.walk;
644        let (id, depth) = (walk.id_of(name, index), walk.frames.len());
645        if let Mode::Hold(mark) = walk.mode {
646            walk.hold(id, value.hashed(), mark);
647            if !T::ROW && walk.through.contains_key(&id) {
648                self.go_into(id, index, value);
649            }
650            return;
651        }
652        match walk.route.get(depth) {
653            Some((to, _)) if *to == id && depth + 1 < walk.route.len() => self.go_into(id, index, value),
654            Some((to, _)) if *to == id => self.act(id, index, value),
655            _ => {}
656        }
657    }
658    fn go_into<T: Inspect>(&mut self, id: Id, index: usize, value: &mut T) {
659        self.ins.walk.frames.push(Frame { id, index, found: true, waiting: None, kind: Kind::Struct, len: 0 });
660        value.fields(self);
661        self.ins.walk.frames.pop();
662    }
663    /// At the walk's target row: its content is taken, and the request applied.
664    fn act<T: Inspect>(&mut self, id: Id, index: usize, value: &mut T) {
665        let walk = &mut self.ins.walk;
666        let before = Box::new(value.clone());
667        if let Some(new) = walk.deed.as_deref().and_then(|deed| deed.downcast_ref::<T>()) {
668            *value = new.clone();
669        }
670        if walk.change.is_some() {
671            self.go_into(id, index, value);
672        }
673        self.ins.walk.acted = Some((before, Box::new(value.clone())));
674    }
675
676    /// Describes a row: the name, and the editor.
677    fn row<T: Inspect>(&mut self, field: Field, value: &mut T, id: Id, index: usize, open: bool) {
678        let (t, walk) = (self.ui.theme, &mut self.ins.walk);
679        let marks = walk.seen.get(&id).map_or(0, |seen| seen.1);
680        let (kind, len) = walk.frames.last().map_or((Kind::Fixed, 0), |frame| (frame.kind, frame.len));
681        walk.here = (id, index);
682        // A list row being dragged, and where it would go.
683        let dragged = walk.dragged_row.as_ref().filter(|(way, ..)| way.last().map_or(0, |(list, _)| *list) == walk.parent() && index != NAMED);
684        let fill = match dragged {
685            Some((_, from, _)) if *from == index => t.selected,
686            Some((_, _, to)) if *to == index => t.hover,
687            _ => Color::NONE,
688        };
689        let reach = self.ui.reachable.len();
690        self.ui.row().key(id).h(Length::Px(walk.line)).fill(fill).open();
691        let name = self.name_cell(field, index, !T::ROW, open, marks & CHANGED != 0);
692        if !T::ROW && (name.clicked || name.focused && (!open && self.ui.key(Key::Right, Mods::NONE) || open && self.ui.key(Key::Left, Mods::NONE))) {
693            self.ins.flip(id, index);
694            self.ui.again = true;
695        }
696        if kind == Kind::List && index != NAMED {
697            self.drag_row(&name, index, len);
698        }
699        self.part_cell(field, value, index, marks, kind);
700        self.ui.close();
701        self.row_keys(id, index, kind, len, reach);
702    }
703    /// A row's name, indented by depth: for a heading, its expand toggle.
704    fn name_cell(&mut self, field: Field, index: usize, heads: bool, open: bool, changed: bool) -> Response {
705        let (ui, walk) = (&mut *self.ui, &mut self.ins.walk);
706        let (t, item) = (ui.theme, index != NAMED && walk.frames.last().is_some_and(|frame| frame.kind == Kind::List));
707        let state = if heads { ui.press(ui.next_id()) } else { ui.interact(ui.next_id()) };
708        let cell = ui.row().w(Length::Px(walk.names_wide)).h(Length::Px(walk.line)).pad((6.0 + walk.frames.len() as f32 * STEP_IN, 0.0, 6.0, 0.0)).gap(4.0).clip();
709        match (heads, item || !field.note.is_empty()) {
710            (true, _) => cell.sense().focusable().open(),
711            (false, true) => cell.sense().open(),
712            (false, false) => cell.open(),
713        };
714        if heads {
715            ui.tell(&state, Role::Fold, Some(open), "");
716            ui.el().icon(if open { DOWN } else { RIGHT }, 12.0, t.text_dim).show();
717        }
718        walk.scratch.clear();
719        let _ = if field.name.is_empty() { write!(walk.scratch, "{index}") } else { walk.scratch.write_str(field.name) };
720        ui.el().text(&walk.scratch, t.font, if changed { t.accent } else { t.text }).shrink(1).show();
721        ui.close();
722        if item && (state.hovered || state.pressed) {
723            ui.set_cursor(Cursor::Move);
724        }
725        ui.tooltip(&state, field.note);
726        state
727    }
728    /// A heading shown because something under it matched: its name, expanded.
729    fn waiting_heading(&mut self, at: usize, name: [u32; 2]) {
730        let (ui, walk) = (&mut *self.ui, &mut self.ins.walk);
731        let t = ui.theme;
732        ui.row().key(walk.frames[at].id).h(Length::Px(walk.line)).pad((6.0 + at as f32 * STEP_IN, 0.0, 6.0, 0.0)).gap(4.0).open();
733        ui.el().icon(DOWN, 12.0, t.text_faint).show();
734        ui.el().text(&walk.names[name[0] as usize..name[1] as usize], t.font, t.text_dim).shrink(1).show();
735        ui.close();
736    }
737    /// A row's editor: per its type, disabled if read-only; and the reset and remove buttons.
738    fn part_cell<T: Inspect>(&mut self, field: Field, value: &mut T, index: usize, marks: u8, kind: Kind) {
739        let (line, enabled) = (self.ins.walk.line, self.ui.enabled);
740        self.ui.row().w(Length::Grow(1.0)).h(Length::Px(line)).pad((6.0, 0.0, 4.0, 0.0)).gap(6.0).clip().open();
741        let before = T::ROW.then(|| value.clone());
742        self.ui.set_enabled(enabled && !field.read_only);
743        let mut row = InspectorRow { ui: &mut *self.ui, field, mixed: marks & MIXED != 0, ins: &mut *self.ins };
744        let state = if row.mixed { value.mixed(&mut row) } else { value.part(&mut row) };
745        // A list item is named by its index, formatted only for a listening screen reader.
746        let mut named = String::new();
747        if field.name.is_empty() && self.ui.listening {
748            let _ = write!(named, "{index}");
749        }
750        self.ui.tell_name(&state, if field.name.is_empty() { &named } else { field.name });
751        // An edited single-row value is undone to its old value; a heading edited where the
752        // values differ (a list of another length) is applied to all as in the first.
753        if state.changed {
754            let ask = match before {
755                Some(before) => Ask::Changed(Box::new(before), Box::new(value.clone()), Box::new(value.clone()), !state.clicked),
756                None => Ask::Put(Box::new(value.clone())),
757            };
758            self.ask(true, ask);
759        }
760        let words = self.ins.words;
761        if marks & CHANGED != 0 && self.small_button(BACK, words[0]) {
762            self.ask(true, Ask::Back);
763        }
764        let taken = (kind == Kind::Map || kind == Kind::List && index != NAMED) && self.small_button(CROSS, words[2]);
765        if taken {
766            let change = if kind == Kind::Map { Change::RemoveKey(field.name.into()) } else { Change::Remove(index) };
767            self.ask(false, Ask::Change(change));
768        }
769        self.ui.set_enabled(enabled);
770        self.ui.close();
771    }
772    /// An icon-only button named `name`, at a row's end. Returns whether clicked.
773    fn small_button(&mut self, icon: Icon, name: &str) -> bool {
774        let pressed = self.ui.button_like(Before::Icon(icon), "", None, false);
775        self.ui.tell(&pressed, Role::Button, None, name);
776        pressed.clicked
777    }
778    /// Requests an action at the row being described (`to_row`), or at its heading.
779    fn ask(&mut self, to_row: bool, ask: Ask) {
780        let way = self.ins.walk.way(to_row);
781        self.ins.walk.asks.push((way, ask));
782    }
783    /// A list item grabbed by its name: while dragged, where it would go.
784    fn drag_row(&mut self, name: &Response, index: usize, len: usize) {
785        let Some((gone, _)) = self.ui.drag_delta(name, [0.0; 4]) else { return };
786        let walk = &mut self.ins.walk;
787        let to = (index as f32 + (gone.y / walk.line).round()).clamp(0.0, len.saturating_sub(1) as f32) as usize;
788        if gone.y.abs() >= 4.0 && walk.dragged_row.as_ref().is_none_or(|(_, _, was)| *was != to) {
789            (walk.dragged_row, self.ui.again) = (Some((walk.way(false), index, to)), true);
790        }
791    }
792    /// Keys on a described row: focus moves to it where a row was moved there; and Alt+Up/Down
793    /// moves a focused list row.
794    fn row_keys(&mut self, id: Id, index: usize, kind: Kind, len: usize, reach: usize) {
795        let (ui, walk) = (&mut *self.ui, &mut self.ins.walk);
796        if let Some((_, nth, _)) = walk.refocus.take_if(|(row, ..)| *row == id) {
797            let to = ui.reachable.get(reach + nth).map(|(_, to, _)| *to);
798            to.into_iter().for_each(|to| ui.set_focus(to));
799        }
800        let Some(nth) = ui.reachable[reach..].iter().position(|(_, on, _)| *on == ui.focus).filter(|_| kind == Kind::List && index != NAMED) else { return };
801        let alt = Mods { alt: true, ..Mods::NONE };
802        let to = match (ui.key(Key::Up, alt), ui.key(Key::Down, alt)) {
803            (true, _) if index > 0 => index - 1,
804            (_, true) if index + 1 < len => index + 1,
805            _ => return,
806        };
807        walk.refocus = Some((hash((walk.parent(), to)), nth, true));
808        let way = walk.way(false);
809        walk.asks.push((way, Ask::Change(Change::Move(index, to))));
810    }
811}
812
813impl std::fmt::Debug for InspectorRow<'_> {
814    /// The row's field, and whether the inspected values differ in it.
815    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
816        f.debug_struct("InspectorRow").field("field", &self.field).field("mixed", &self.mixed).finish_non_exhaustive()
817    }
818}
819
820impl InspectorRow<'_> {
821    /// A number of any type, per its field: typed, stepped by Up and Down, clamped to its range
822    /// (with a slider if both ends are set), and its unit after it. (What every number type
823    /// shows.)
824    pub fn number<N: Number>(&mut self, value: &mut N) -> Response {
825        let (ui, field, was) = (&mut *self.ui, self.field, *value);
826        let ranged = field.min.is_finite() && field.max.is_finite();
827        let mut slid = false;
828        if ranged && !self.mixed {
829            let mut at = value.to_f64() as f32;
830            let slider = ui.slider(&mut at, field.min as f32..=field.max as f32);
831            ui.tell_name(&slider, field.name);
832            (*value, slid) = if slider.changed { (N::from_f64(at as f64), true) } else { (*value, false) };
833        }
834        ui.el().w(Length::Px(if ranged { 72.0 } else { 120.0 })).open();
835        let step = N::from_f64(if field.step > 0.0 { field.step } else { 1.0 });
836        let mut state = if self.mixed { ui.entry_box(format_args!("\u{2014}"), ui.locale_in_use().decimal_point, "") } else { ui.number(value, step) };
837        // Where values differ, text typed after the dash applies as soon as it is a number; the
838        // box then shows it as the number of all of them.
839        let typed = self.mixed && state.changed;
840        let number = typed.then(|| ui.entry.1.trim().trim_start_matches('—').trim().parse::<N>().ok()).flatten();
841        if let Some(number) = number {
842            (*value, ui.entry.0) = (number, 0);
843        }
844        ui.close();
845        let at = value.to_f64();
846        if at < field.min || at > field.max {
847            *value = N::from_f64(at.clamp(field.min, field.max));
848        }
849        if !field.unit.is_empty() {
850            ui.note(field.unit);
851        }
852        state.changed = *value != was || slid || number.is_some();
853        state
854    }
855    /// One of `cases`, each named by `names` at its index, picked from a dropdown (with more
856    /// than twelve, a filterable one). What an enum's row shows: `taut::inspect!` writes it.
857    pub fn cases<T: Clone + PartialEq>(&mut self, value: &mut T, cases: &[T], names: &[&str]) -> Response {
858        let mut at = cases.iter().position(|case| case == value).unwrap_or(usize::MAX);
859        let state = if names.len() > 12 { self.ui.combo(&mut at, names) } else { self.ui.select(&mut at, names) };
860        if let Some(case) = cases.get(at).filter(|_| state.changed) {
861            *value = case.clone();
862        }
863        state
864    }
865    /// A "—" box: where the inspected values differ, pressing it sets them all as the first is
866    /// (`changed`), and its row shows their editor from then on.
867    pub fn differs(&mut self) -> Response {
868        let mut state = self.ui.button_like(Before::None, "\u{2014}", None, false);
869        state.changed = state.clicked;
870        state
871    }
872    /// A check box with a dash, where the values differ: pressing it checks them all.
873    fn tick_differs(&mut self, value: &mut bool) -> Response {
874        let ui = &mut *self.ui;
875        let t = ui.theme;
876        let mut state = ui.press(ui.next_id());
877        let edge = if state.hovered { t.text_faint } else { t.line_strong };
878        ui.row().size(16.0, 16.0).fill(t.panel).border(edge, 1.0).radius(4.0).align(Align::Center, Align::Center).sense().focusable().open();
879        ui.el().size(8.0, 2.0).fill(t.text_dim).show();
880        ui.close();
881        ui.tell(&state, Role::CheckBox, None, "");
882        *value |= state.clicked;
883        state.changed = state.clicked;
884        state
885    }
886    /// A path: typed, or picked with the file dialog (a folder, if the field says so).
887    fn path(&mut self, value: &mut PathBuf) -> Response {
888        let mut written = value.to_string_lossy().into_owned();
889        let state = self.ui.text_box(&mut written, "");
890        if state.changed {
891            *value = PathBuf::from(written);
892        }
893        let pick = self.ui.button("\u{2026}");
894        self.ui.tell(&pick, Role::Button, None, self.ins.words[4]);
895        if !pick.clicked {
896            return state;
897        }
898        // The dialog starts at the path, or the working folder.
899        let folder = if self.field.folder { Some(value.as_path()) } else { value.parent() };
900        let from = folder.filter(|folder| folder.is_dir()).map_or(PathBuf::from("."), PathBuf::from);
901        let (field, ins) = (self.field, &mut *self.ins);
902        match field.folder {
903            true => ins.file_dialog.pick_folder(from),
904            false => {
905                ins.file_dialog.only(field.only);
906                ins.file_dialog.pick(from);
907            }
908        }
909        ins.walk.asking = Some(ins.walk.way(true));
910        state
911    }
912    /// What a list heading shows beside its name: its length, and an add button.
913    fn count(&mut self, len: usize, adds: bool) -> Response {
914        let (t, ins) = (self.ui.theme, &mut *self.ins);
915        ins.walk.scratch.clear();
916        let _ = write!(ins.walk.scratch, "{len} {}", ins.words[3]);
917        self.ui.text(&ins.walk.scratch, t.small_font, t.text_dim);
918        if !adds {
919            return Response::default();
920        }
921        let add = self.ui.button_like(Before::Icon(PLUS), "", None, false);
922        self.ui.tell(&add, Role::Button, None, ins.words[1]);
923        if add.clicked {
924            let way = ins.walk.way(true);
925            ins.walk.asks.push((way, Ask::Change(Change::Add)));
926        }
927        Response::default()
928    }
929    /// What a map heading shows: its length, a box for a new key, and an add button (Enter in
930    /// the box too). An existing key (`has`) isn't added again.
931    fn new_key(&mut self, len: usize, has: &dyn Fn(&str) -> bool) -> Response {
932        self.count(len, false);
933        let (ui, ins) = (&mut *self.ui, &mut *self.ins);
934        let (id, word) = (ins.walk.here.0, ins.words[5]);
935        let mut key = if ins.walk.key.0 == id { std::mem::take(&mut ins.walk.key.1) } else { String::new() };
936        let typed = ui.text_box(&mut key, word);
937        let add = ui.button_like(Before::Icon(PLUS), "", None, false);
938        ui.tell(&add, Role::Button, None, ins.words[1]);
939        let adds = (add.clicked || typed.focused && ui.key(Key::Enter, Mods::NONE)) && !key.is_empty() && !has(&key);
940        if adds {
941            let way = ins.walk.way(true);
942            ins.walk.asks.push((way, Ask::Change(Change::AddKey(std::mem::take(&mut key)))));
943        }
944        if ins.walk.key.0 == id || !key.is_empty() {
945            ins.walk.key = (id, key);
946        }
947        Response::default()
948    }
949}
950
951/// Property inspectors: the app's values, viewed and edited in place.
952impl Ui {
953    /// An inspector for `value`: a row per field, name and editor, in two columns with a
954    /// draggable divider; a search box above to filter fields by name; and collapsible headings
955    /// for nested structs, lists and maps. Only visible rows are described. Ctrl+Z undoes while
956    /// focused, Ctrl+Y redoes. `state` keeps its state between runs; `changed` is set when the
957    /// user edits something.
958    pub fn inspect<T: Inspect>(&mut self, state: &mut Inspector, value: &mut T) -> Response {
959        self.inspect_all(state, &mut [value])
960    }
961    /// The same for several values at once (a multi-selection): the first one's rows, with "—"
962    /// where the others differ, and an edit sets all.
963    pub fn inspect_all<T: Inspect>(&mut self, state: &mut Inspector, things: &mut [&mut T]) -> Response {
964        let (line, word) = (self.theme.control_height + 4.0, self.search_word);
965        let mut all = self.column().grow().gap(6.0).sense().open();
966        let reach = self.reachable.len();
967        self.text_box(&mut state.search, word);
968        self.el().key("body").flow(Flow::Stack).grow().open();
969        let rows = self.id("rows");
970        let read = self.rooms.get(&rows).copied().unwrap_or([self.size().w, self.size().h, 0.0]);
971        let offset = self.scrolls.get(&rows).map_or(0.0, |offset| offset[1]);
972        state.begin(line, read, offset, things);
973        self.count_rows(state, things);
974        // A box as tall as all rows, so its scroll bar is right; in it, a spacer for the rows
975        // above the visible ones, then those.
976        let at = self.tree.specs.len() as u32;
977        self.column().key("rows").grow().scroll().open();
978        self.measures.push(Measure { at, within: at, id: rows, read });
979        self.column().h(Length::Px(state.walk.count as f32 * line)).open();
980        self.el().h(Length::Px(state.walk.view.start as f32 * line)).show();
981        state.walk(Mode::Draw);
982        if let Some(first) = things.first_mut() {
983            first.fields(&mut Fields { ui: self, ins: state });
984        }
985        state.walk.refocus = state.walk.refocus.take().filter(|(.., fresh)| *fresh).map(|(row, nth, _)| (row, nth, false));
986        self.close();
987        self.close();
988        self.divider(state, read[0]);
989        self.close();
990        all.changed = self.answer_all(state, things, reach, all.contains_pointer);
991        self.close();
992        all
993    }
994
995    /// Counts the first value's rows, noting the visible ones; and compares the others with it
996    /// there, and with the initial values.
997    fn count_rows<T: Inspect>(&mut self, state: &mut Inspector, things: &mut [&mut T]) {
998        state.walk(Mode::Count);
999        let Some((first, others)) = things.split_first_mut() else { return state.walk.count = 0 };
1000        first.fields(&mut Fields { ui: self, ins: state });
1001        let walk = &mut state.walk;
1002        walk.count = walk.row;
1003        walk.view = walk.view.start.min(walk.count)..walk.view.end.min(walk.count);
1004        for other in others {
1005            state.walk(Mode::Hold(MIXED));
1006            other.fields(&mut Fields { ui: self, ins: state });
1007            state.walk.held(MIXED);
1008        }
1009        let Some(mut start) = state.start.take() else { return };
1010        if let Some(start) = start.downcast_mut::<T>() {
1011            state.walk(Mode::Hold(CHANGED));
1012            start.fields(&mut Fields { ui: self, ins: state });
1013            state.walk.held(CHANGED);
1014        }
1015        state.start = Some(start);
1016    }
1017
1018    /// The draggable divider between names and editors.
1019    fn divider(&mut self, state: &mut Inspector, wide: f32) {
1020        let t = self.theme;
1021        let grip = self.interact(self.id("divider"));
1022        if grip.hovered || grip.pressed {
1023            self.set_cursor(Cursor::ResizeX);
1024        }
1025        if let Some((gone, was)) = self.drag_delta(&grip, [state.split, 0.0, 0.0, 0.0]) {
1026            let split = (was[0] + gone.x / wide.max(1.0)).clamp(0.1, 0.9);
1027            self.again |= split != state.split;
1028            state.split = split;
1029        }
1030        let line = if grip.hovered || grip.pressed { t.accent } else { t.line };
1031        self.row().key("divider").offset(state.walk.names_wide - 3.0, 0.0).w(Length::Px(7.0)).h(Length::Grow(1.0)).align(Align::Center, Align::Spread).sense().open();
1032        self.el().w(Length::Px(1.0)).fill(line).show();
1033        self.close();
1034    }
1035
1036    /// Applies the user's requests of the run to every value: the file dialog's pick, a list
1037    /// row dropped elsewhere, the edits, and an undo or redo (by keys while focused, or nowhere
1038    /// while the pointer is `over` it). Returns whether anything was done.
1039    fn answer_all<T: Inspect>(&mut self, state: &mut Inspector, things: &mut [&mut T], reach: usize, over: bool) -> bool {
1040        let walk = &mut state.walk;
1041        let picked = self.file_dialog(&mut state.file_dialog).map(|path| (walk.asking.take(), path));
1042        if let Some((Some(way), path)) = picked {
1043            walk.asks.push((way, Ask::Put(Box::new(path))));
1044        }
1045        if let Some((way, from, to)) = walk.dragged_row.take_if(|_| !self.input.down[0]).filter(|(_, from, to)| from != to) {
1046            walk.asks.push((way, Ask::Change(Change::Move(from, to))));
1047        }
1048        let mine = self.reachable[reach..].iter().any(|(_, on, _)| *on == self.focus) || self.focus == 0 && over;
1049        let keyed = match mine {
1050            true if self.keys("Ctrl+Z") => Some(true),
1051            true if self.keys("Ctrl+Y") || self.keys("Ctrl+Shift+Z") => Some(false),
1052            _ => None,
1053        };
1054        let back = walk.asked.take().or(keyed);
1055        let done = !walk.asks.is_empty() || back.is_some();
1056        for (way, ask) in std::mem::take(&mut state.walk.asks) {
1057            self.answer(state, things, way, ask);
1058        }
1059        if let Some(back) = back {
1060            self.step_back(state, things, back);
1061        }
1062        // What is shown is what the values hold now: a number box being typed into shows it
1063        // afresh.
1064        if done {
1065            (self.again, self.entry.0) = (true, 0);
1066        }
1067        done
1068    }
1069    /// Applies one row request to every value, and records it as an undo step.
1070    fn answer<T: Inspect>(&mut self, state: &mut Inspector, things: &mut [&mut T], way: Way, ask: Ask) {
1071        let mut step = Step { way, before: Vec::new(), after: Vec::new(), focus: self.focus, at: self.now };
1072        // What each value gets there, from which value on (the first may have its edit
1073        // already).
1074        let (deed, change, from, joins) = match ask {
1075            Ask::Changed(before, after, deed, joins) => {
1076                (step.before, step.after) = (vec![Some(before)], vec![Some(after)]);
1077                (Some(deed), None, 1, joins)
1078            }
1079            Ask::Put(deed) => (Some(deed), None, 0, false),
1080            Ask::Back => (self.as_started::<T>(state, &step.way), None, 0, false),
1081            Ask::Change(change) => (None, Some(change), 0, false),
1082        };
1083        if deed.is_none() && change.is_none() {
1084            return;
1085        }
1086        if let Some(change) = &change {
1087            state.reopen(&step.way, change);
1088        }
1089        (state.walk.mode, state.walk.route, state.walk.deed) = (Mode::Go, std::mem::take(&mut step.way), deed);
1090        for thing in things.iter_mut().skip(from) {
1091            (state.walk.change, state.walk.frames) = (change.clone(), Vec::new());
1092            thing.fields(&mut Fields { ui: self, ins: state });
1093            let (before, after) = state.walk.acted.take().unzip();
1094            step.before.push(before);
1095            step.after.push(after);
1096        }
1097        (step.way, state.walk.deed) = (std::mem::take(&mut state.walk.route), None);
1098        state.keep(step, joins, self.input.down[0]);
1099    }
1100    /// The value at the end of a path in the initial state, if the app set it.
1101    fn as_started<T: Inspect>(&mut self, state: &mut Inspector, way: &[(Id, usize)]) -> Option<Box<dyn Any>> {
1102        let mut start = state.start.take()?;
1103        (state.walk.mode, state.walk.deed, state.walk.change) = (Mode::Go, None, None);
1104        state.walk.route.clear();
1105        state.walk.route.extend_from_slice(way);
1106        if let Some(start) = start.downcast_mut::<T>() {
1107            state.walk.frames.clear();
1108            start.fields(&mut Fields { ui: self, ins: state });
1109        }
1110        state.start = Some(start);
1111        state.walk.acted.take().map(|(before, _)| before)
1112    }
1113    /// Undoes the last step (`back`), or redoes the last undone one: each value gets back what
1114    /// it held before, or after.
1115    fn step_back<T: Inspect>(&mut self, state: &mut Inspector, things: &mut [&mut T], back: bool) {
1116        let Some(mut step) = (if back { state.steps.pop() } else { state.undone.pop() }) else { return };
1117        (state.walk.mode, state.walk.route, state.walk.change) = (Mode::Go, std::mem::take(&mut step.way), None);
1118        for (at, thing) in things.iter_mut().enumerate() {
1119            let kept = if back { &mut step.before } else { &mut step.after };
1120            state.walk.deed = kept.get_mut(at).and_then(Option::take);
1121            state.walk.frames.clear();
1122            thing.fields(&mut Fields { ui: self, ins: state });
1123            let kept = if back { &mut step.before } else { &mut step.after };
1124            kept.get_mut(at).into_iter().for_each(|kept| *kept = state.walk.deed.take());
1125            state.walk.acted = None;
1126        }
1127        step.way = std::mem::take(&mut state.walk.route);
1128        if back { state.undone.push(step) } else { state.steps.push(step) }
1129    }
1130}
1131
1132macro_rules! numbers {
1133    ($($kind:ty)*) => {$(
1134        impl Inspect for $kind {
1135            const ROW: bool = true;
1136            fn part(&mut self, row: &mut InspectorRow) -> Response {
1137                row.number(self)
1138            }
1139            fn mixed(&mut self, row: &mut InspectorRow) -> Response {
1140                row.number(self)
1141            }
1142            fn hashed(&self) -> u64 {
1143                Number::to_f64(*self).to_bits()
1144            }
1145        }
1146    )*};
1147}
1148numbers!(i8 i16 i32 i64 isize u8 u16 u32 u64 usize f32 f64);
1149
1150impl Inspect for bool {
1151    const ROW: bool = true;
1152    fn part(&mut self, row: &mut InspectorRow) -> Response {
1153        row.ui.checkbox(self, "")
1154    }
1155    fn mixed(&mut self, row: &mut InspectorRow) -> Response {
1156        row.tick_differs(self)
1157    }
1158    fn hashed(&self) -> u64 {
1159        *self as u64
1160    }
1161}
1162
1163impl Inspect for String {
1164    const ROW: bool = true;
1165    fn part(&mut self, row: &mut InspectorRow) -> Response {
1166        row.ui.text_box(self, "")
1167    }
1168    /// A box showing "—" until something is typed, which every value then gets.
1169    fn mixed(&mut self, row: &mut InspectorRow) -> Response {
1170        let mut typed = String::new();
1171        let state = row.ui.text_box(&mut typed, "\u{2014}");
1172        if state.changed {
1173            *self = typed;
1174        }
1175        state
1176    }
1177    fn hashed(&self) -> u64 {
1178        hash(self.as_str())
1179    }
1180}
1181
1182impl Inspect for Color {
1183    const ROW: bool = true;
1184    fn part(&mut self, row: &mut InspectorRow) -> Response {
1185        row.ui.color_picker(self)
1186    }
1187    fn hashed(&self) -> u64 {
1188        self.0 as u64
1189    }
1190}
1191
1192impl Inspect for Date {
1193    const ROW: bool = true;
1194    fn part(&mut self, row: &mut InspectorRow) -> Response {
1195        row.ui.date(self)
1196    }
1197    fn hashed(&self) -> u64 {
1198        self.days() as u64
1199    }
1200}
1201
1202impl Inspect for PathBuf {
1203    const ROW: bool = true;
1204    fn part(&mut self, row: &mut InspectorRow) -> Response {
1205        row.path(self)
1206    }
1207    fn hashed(&self) -> u64 {
1208        hash(self.as_os_str())
1209    }
1210}
1211
1212/// A list: a heading showing its length with an add button, and a row per item, removable, and
1213/// movable by dragging its name or with Alt+arrows.
1214impl<T: Inspect + Default> Inspect for Vec<T> {
1215    fn fields(&mut self, fields: &mut Fields) {
1216        match fields.changes(Kind::List, self.len()) {
1217            Some(Change::Add) => self.push(T::default()),
1218            Some(Change::Remove(at)) if at < self.len() => drop(self.remove(at)),
1219            Some(Change::Move(from, to)) if from.max(to) < self.len() => {
1220                let item = self.remove(from);
1221                self.insert(to, item);
1222            }
1223            _ => {}
1224        }
1225        let mut next = 0;
1226        while let Some(at) = fields.next_item(self.len(), next, T::ROW) {
1227            fields.item(at, &mut self[at]);
1228            next = at + 1;
1229        }
1230    }
1231    fn part(&mut self, row: &mut InspectorRow) -> Response {
1232        row.count(self.len(), true)
1233    }
1234    fn hashed(&self) -> u64 {
1235        self.len() as u64
1236    }
1237}
1238
1239/// A fixed-length list: a row per item.
1240impl<T: Inspect, const N: usize> Inspect for [T; N] {
1241    fn fields(&mut self, fields: &mut Fields) {
1242        fields.changes(Kind::Fixed, N);
1243        let mut next = 0;
1244        while let Some(at) = fields.next_item(N, next, T::ROW) {
1245            fields.item(at, &mut self[at]);
1246            next = at + 1;
1247        }
1248    }
1249}
1250
1251/// A map by name: a row per key, in order, removable; and on its heading a box for a new key.
1252impl<T: Inspect + Default> Inspect for BTreeMap<String, T> {
1253    fn fields(&mut self, fields: &mut Fields) {
1254        match fields.changes(Kind::Map, self.len()) {
1255            Some(Change::AddKey(key)) => drop(self.entry(key).or_default()),
1256            Some(Change::RemoveKey(key)) => drop(self.remove(&key)),
1257            _ => {}
1258        }
1259        for (key, value) in self.iter_mut() {
1260            fields.visit(Field::new(key), value, NAMED);
1261        }
1262    }
1263    fn part(&mut self, row: &mut InspectorRow) -> Response {
1264        row.new_key(self.len(), &|key| self.contains_key(key))
1265    }
1266    fn hashed(&self) -> u64 {
1267        self.len() as u64
1268    }
1269}
1270
1271/// Implements [`Inspect`] for a plain app struct, from each field's options; or for a fieldless
1272/// enum, from each variant's name.
1273///
1274/// ```ignore
1275/// taut::inspect!(Lamp { name: "Name", power: Field::new("Power").unit("W"), on: "On", kind: "Kind" });
1276/// taut::inspect!(enum Kind { Point: "A point", Spot: "A spot", Sun: "The sun" });
1277/// ```
1278///
1279/// The struct must be `Clone`, and every named field [`Inspect`]; the enum `Clone` and
1280/// `PartialEq`.
1281#[macro_export]
1282macro_rules! inspect {
1283    (enum $name:ident { $($case:ident: $label:expr),* $(,)? }) => {
1284        impl $crate::Inspect for $name {
1285            const ROW: bool = true;
1286            fn part(&mut self, row: &mut $crate::InspectorRow) -> $crate::Response {
1287                row.cases(self, &[$($name::$case),*], &[$($label),*])
1288            }
1289            fn hashed(&self) -> u64 {
1290                [$($name::$case),*].iter().position(|case| case == self).map_or(u64::MAX, |at| at as u64)
1291            }
1292        }
1293    };
1294    ($name:ident { $($field:ident: $about:expr),* $(,)? }) => {
1295        impl $crate::Inspect for $name {
1296            fn fields(&mut self, fields: &mut $crate::Fields) {
1297                $(fields.field($about, &mut self.$field);)*
1298            }
1299        }
1300    };
1301}