Skip to main content

nadir_debug/
inspector.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The inspector: the world's entities, filtered, and the components of the
16//! one selected, each field edited through `Reflect`; a component added or
17//! removed by its name, the entity despawned, or saved as a prefab
18//! (`debug-tools.md`, "Tools"; roadmap M7.4, ADR-0062).
19
20use std::fmt::{self, Write as _};
21
22use nadir_codec::json::{self, Value};
23use nadir_codec::{Limits, prefab};
24use nadir_core::log::warn;
25use nadir_core::{Color, Key};
26use nadir_ecs::{Entity, World};
27use nadir_scene::{Reflect, ReflectContext, ReflectKind, Registration, TypeRegistry};
28
29use crate::Ui;
30use crate::id::Id;
31
32/// The entities a page of the list shows.
33const PAGE: usize = 16;
34
35/// How much a drag changes a number, for each UI unit the pointer moves.
36const DRAG_PER_UNIT: f32 = 0.1;
37
38/// The longest name a saved prefab may have, in bytes.
39const MAX_PREFAB_NAME: usize = 64;
40
41/// What the inspector asks of its caller, this frame.
42#[non_exhaustive]
43#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
44pub struct InspectorResponse {
45    /// "Save as prefab" was clicked, on an entity alive, with a name a
46    /// prefab may have: the caller writes [`Inspector::prefab`] into
47    /// `<name>.jsonc`, the name [`Inspector::prefab_name`].
48    pub save_prefab: bool,
49}
50
51/// A text field's edit, kept from frame to frame until it is applied, on
52/// Enter or a press elsewhere, or dropped, on Escape or when the field is
53/// not drawn in a frame: the window closed or collapsed, say, which takes
54/// the keyboard from it.
55struct TextEdit {
56    key: Id,
57    text: String,
58    /// The UI's frame its field was last drawn in.
59    frame: u64,
60}
61
62/// The inspector's window: a list of the world's entities, a page at a
63/// time, filtered by their numbers and the names of their components, and
64/// the components of the one clicked, which [`Inspector::show`] edits
65/// through their [`Reflect`] impls. It finds the component types in the
66/// world's [`TypeRegistry`], a resource.
67///
68/// - **The list:** each entity as its slot and generation, `3v1`, then the
69///   names of its registered components. The filter keeps the entities
70///   that match each of its words, ignoring case: a word matches an
71///   entity's number, or the name of a component it has.
72/// - **Editing:** a struct's fields are rows, a struct inside one a tree
73///   node; a list's elements and an object's members (a value reflected
74///   whole, such as a sprite) are rows under a node; a boolean is a
75///   checkbox; a float a drag; a whole number, a string or an asset's path a
76///   text field, applied on Enter or a press elsewhere, dropped on Escape;
77///   a `Color` a color edit, as is a string that writes a color among the
78///   members of a value reflected whole; an enum's variant a combo; a pair
79///   of numbers a row of two. A change is applied to the component at once, through
80///   [`Reflect::apply_value`]; one it refuses is not set, and the note
81///   says why, as the log does in full.
82/// - **Changes of structure** go through the world's commands, and so show
83///   after the next tick or frame: "Despawn", "Add" (a component of a type
84///   it lacks, made from the JSONC typed beside it, `{}` at first: `0` for
85///   a number's newtype, `[0, 0]` for a position's, `"Down"` for an enum;
86///   one the type refuses is not added, and the note says why), and each
87///   component's "Remove".
88/// - **Save as prefab:** with a name the prefab reader takes, lowercase
89///   letters, digits and `_`, it asks the caller to write
90///   [`Inspector::prefab`].
91///
92/// A frame with no component open allocates nothing once its buffers have
93/// grown; an open one builds its values ([`Reflect::to_value`]) each frame.
94pub struct Inspector {
95    filter: String,
96    page: usize,
97    selected: Option<Entity>,
98    /// Every entity alive, then those the filter keeps: made each frame.
99    entities: Vec<Entity>,
100    /// The types the selected entity lacks, for the combo that adds one.
101    lacking: Vec<&'static str>,
102    /// Which of them the combo shows.
103    add: usize,
104    /// The data "Add" makes it from, as JSONC.
105    add_data: String,
106    prefab_name: String,
107    note: String,
108    edit: Option<TextEdit>,
109    /// A value's text, for a field not being edited; an entity's number,
110    /// for the filter.
111    scratch: String,
112}
113
114impl Default for Inspector {
115    fn default() -> Self {
116        Self::new()
117    }
118}
119
120impl Inspector {
121    /// An inspector with nothing selected and no filter.
122    pub fn new() -> Self {
123        Self {
124            filter: String::new(),
125            page: 0,
126            selected: None,
127            entities: Vec::new(),
128            lacking: Vec::new(),
129            add: 0,
130            add_data: String::from("{}"),
131            prefab_name: String::new(),
132            note: String::new(),
133            edit: None,
134            scratch: String::new(),
135        }
136    }
137
138    /// The entity whose components it shows, if one was clicked; it may
139    /// have been despawned since.
140    pub fn selected(&self) -> Option<Entity> {
141        self.selected
142    }
143
144    /// Shows `entity`'s components, or none. An edit not yet applied is
145    /// dropped.
146    pub fn select(&mut self, entity: Option<Entity>) {
147        if entity != self.selected {
148            self.edit = None;
149        }
150        self.selected = entity;
151    }
152
153    /// The name typed for a prefab, which "Save as prefab" saves the
154    /// selected entity as.
155    pub fn prefab_name(&self) -> &str {
156        &self.prefab_name
157    }
158
159    /// Shows `note` under the selected entity's buttons, until the next:
160    /// where a prefab was written, say, or why not.
161    pub fn set_note(&mut self, note: impl fmt::Display) {
162        set_note(&mut self.note, note);
163    }
164
165    /// Fills a window with the entity list and the selected entity's
166    /// components, from the world's [`TypeRegistry`]. `cx` reads and
167    /// writes the values: one that can write and read asset handles, and
168    /// that has the resources the game's components need, such as the
169    /// facade's `loading_context`. Its errors and warnings name the
170    /// component and the field, under `cx`'s source.
171    ///
172    /// # Panics
173    ///
174    /// If a registered type is not registered with `world`, or its
175    /// components or the registry are borrowed mutably elsewhere.
176    pub fn show(
177        &mut self,
178        world: &World,
179        ui: &mut Ui<'_>,
180        cx: &mut ReflectContext<'_>,
181    ) -> InspectorResponse {
182        let mut response = InspectorResponse::default();
183        let frame = ui.frame_number();
184        // An edit whose field was not drawn in the frame before has lost the
185        // keyboard: the window was closed or collapsed meanwhile.
186        if self
187            .edit
188            .as_ref()
189            .is_some_and(|edit| edit.frame + 1 < frame)
190        {
191            self.edit = None;
192        }
193        if !world.contains_resource::<TypeRegistry>() {
194            ui.label("The world has no type registry.");
195            return response;
196        }
197        let registry = world.resource::<TypeRegistry>();
198        self.list(world, &registry, ui);
199        ui.separator();
200        self.entity(world, &registry, ui, cx, &mut response);
201        // A field not drawn this frame has let go of the keyboard.
202        if self.edit.as_ref().is_some_and(|edit| edit.frame != frame) {
203            self.edit = None;
204        }
205        response
206    }
207
208    /// The selected entity as the prefab [`Inspector::prefab_name`], as
209    /// JSONC text: a comment line, then `{"name": ..., "components":
210    /// {...}}`, each component of a type in the world's [`TypeRegistry`]
211    /// that it has, in the registry's order, as [`Reflect::to_value`]
212    /// writes it with `cx`, but those whose names `leave_out` lists. `None`
213    /// if no entity alive is selected, or the world has no registry.
214    ///
215    /// `cx` writes the values: one that writes asset handles as their
216    /// paths, and has the resources the game's components need, such as
217    /// the facade's `reflect_context`.
218    pub fn prefab(
219        &self,
220        world: &World,
221        leave_out: &[&str],
222        cx: &mut ReflectContext<'_>,
223    ) -> Option<String> {
224        let entity = self.selected.filter(|&entity| world.is_alive(entity))?;
225        if !world.contains_resource::<TypeRegistry>() {
226            return None;
227        }
228        let registry = world.resource::<TypeRegistry>();
229        let mut components = Vec::new();
230        for registration in registry.iter() {
231            let name = registration.name();
232            if leave_out.contains(&name) {
233                continue;
234            }
235            registration.inspect(world, entity, &mut |component| {
236                let value = cx.key(name, |cx| component.to_value(cx));
237                components.push((name.to_string(), value));
238            });
239        }
240        let prefab = Value::Object(vec![
241            ("name".to_string(), Value::String(self.prefab_name.clone())),
242            ("components".to_string(), Value::Object(components)),
243        ]);
244        Some(format!(
245            "// The prefab `{}`, saved by the inspector from entity {}.\n{}\n",
246            self.prefab_name,
247            Number(entity),
248            json::to_string_pretty(&prefab)
249        ))
250    }
251
252    /// The filter, the count, a page of entities and the page's buttons.
253    fn list(&mut self, world: &World, registry: &TypeRegistry, ui: &mut Ui<'_>) {
254        if ui.text_input("Filter", &mut self.filter).changed {
255            self.page = 0;
256        }
257        world.entities_into(&mut self.entities);
258        let alive = self.entities.len();
259        if self.filter.trim().is_empty() {
260            ui.label(format_args!("{alive} entities"));
261        } else {
262            let (filter, scratch) = (&self.filter, &mut self.scratch);
263            self.entities
264                .retain(|&entity| matches(world, registry, entity, filter, scratch));
265            ui.label(format_args!("{} of {alive} entities", self.entities.len()));
266        }
267        let shown = self.entities.len();
268        let pages = shown.div_ceil(PAGE).max(1);
269        self.page = self.page.min(pages - 1);
270        let start = self.page * PAGE;
271        let end = (start + PAGE).min(shown);
272        let mut clicked = None;
273        for &entity in &self.entities[start..end] {
274            let row = Row {
275                world,
276                registry,
277                entity,
278                selected: self.selected == Some(entity),
279            };
280            if ui.button(format_args!("{row}##{}", Number(entity))).clicked {
281                clicked = Some(entity);
282            }
283        }
284        if pages > 1 {
285            let page = &mut self.page;
286            ui.horizontal(|ui| {
287                if ui.button("<##previous").clicked {
288                    *page = page.saturating_sub(1);
289                }
290                if ui.button(">##next").clicked {
291                    *page = (*page + 1).min(pages - 1);
292                }
293                ui.label(format_args!("{}-{end} of {shown}", start + 1));
294            });
295        }
296        if clicked.is_some() {
297            self.select(clicked);
298        }
299    }
300
301    /// The selected entity: its buttons, the note, and its components.
302    fn entity(
303        &mut self,
304        world: &World,
305        registry: &TypeRegistry,
306        ui: &mut Ui<'_>,
307        cx: &mut ReflectContext<'_>,
308        response: &mut InspectorResponse,
309    ) {
310        let Some(entity) = self.selected else {
311            ui.label("Click an entity to inspect it.");
312            return;
313        };
314        if !world.is_alive(entity) {
315            ui.label(format_args!(
316                "Entity {} is gone: click another.",
317                Number(entity)
318            ));
319            return;
320        }
321        ui.horizontal(|ui| {
322            ui.label(format_args!("Entity {}", Number(entity)));
323            if ui.button("Despawn").clicked {
324                world.commands().despawn(entity);
325                set_note(
326                    &mut self.note,
327                    format_args!("Despawned {}.", Number(entity)),
328                );
329            }
330        });
331        ui.horizontal(|ui| {
332            ui.text_input("##prefab", &mut self.prefab_name);
333            if ui.button("Save as prefab").clicked {
334                if is_prefab_name(&self.prefab_name) {
335                    response.save_prefab = true;
336                } else {
337                    set_note(
338                        &mut self.note,
339                        "Name the prefab first: lowercase letters, digits and _.",
340                    );
341                }
342            }
343        });
344        self.lacking.clear();
345        for registration in registry.iter() {
346            if !has(world, registration, entity) {
347                self.lacking.push(registration.name());
348            }
349        }
350        if !self.lacking.is_empty() {
351            self.add = self.add.min(self.lacking.len() - 1);
352            let (add, data, lacking, note) = (
353                &mut self.add,
354                &mut self.add_data,
355                &self.lacking,
356                &mut self.note,
357            );
358            ui.horizontal(|ui| {
359                ui.combo("##add", add, lacking);
360                ui.text_input("##data", data);
361                if ui.button("Add").clicked
362                    && let Some(registration) =
363                        lacking.get(*add).and_then(|name| registry.get(name))
364                {
365                    add_component(world, registration, entity, data, cx, note);
366                }
367            });
368        }
369        if !self.note.is_empty() {
370            ui.label(&self.note);
371        }
372        // In a scope of their own, so that a component named as one of the
373        // inspector's own widgets ("Filter", "Add") has an identity of its
374        // own, as two widgets of one text in two scopes do.
375        let (edit, scratch, note) = (&mut self.edit, &mut self.scratch, &mut self.note);
376        ui.with_id("nadir::components", |ui| {
377            for registration in registry.iter() {
378                let name = registration.name();
379                let key = Id::ROOT.with((entity.index(), entity.generation().get(), name));
380                let mut remove = false;
381                let mut editor = Editor {
382                    cx: &mut *cx,
383                    edit: &mut *edit,
384                    scratch: &mut *scratch,
385                    note: &mut *note,
386                };
387                registration.inspect_mut(world, entity, &mut |component| {
388                    ui.tree_node(name, |ui| {
389                        remove = ui.button("Remove").clicked;
390                        editor.within(Step::Key(name), |editor| {
391                            edit_component(ui, component, key, editor);
392                        });
393                    });
394                });
395                if remove {
396                    registration.remove(&mut world.commands(), entity);
397                    set_note(note, format_args!("Removed {name}."));
398                }
399            }
400        });
401    }
402}
403
404/// Gives `entity` a component of `registration`'s type, made from `data`,
405/// JSONC, or an empty object if it is blank, through the world's commands;
406/// or says in `note` why not.
407fn add_component(
408    world: &World,
409    registration: &Registration,
410    entity: Entity,
411    data: &str,
412    cx: &mut ReflectContext<'_>,
413    note: &mut String,
414) {
415    let name = registration.name();
416    let value = if data.trim().is_empty() {
417        Value::Object(Vec::new())
418    } else {
419        match json::parse(data, Limits::default()) {
420            Ok(value) => value,
421            Err(error) => {
422                refuse(note, format_args!("{name} is not added: its data: {error}"));
423                return;
424            }
425        }
426    };
427    let added = cx.key(name, |cx| {
428        registration.insert(&mut world.commands(), entity, &value, cx)
429    });
430    match added {
431        Ok(()) => set_note(note, format_args!("Added {name}.")),
432        Err(error) => refuse(note, format_args!("{name} is not added: {error}")),
433    }
434}
435
436/// Whether `entity` has a component of `registration`'s type.
437fn has(world: &World, registration: &Registration, entity: Entity) -> bool {
438    registration.inspect(world, entity, &mut |_| {})
439}
440
441/// Whether `entity` matches each word of `filter`: its number, or the name
442/// of a component it has, holds the word, ignoring case. `scratch` holds
443/// its number.
444fn matches(
445    world: &World,
446    registry: &TypeRegistry,
447    entity: Entity,
448    filter: &str,
449    scratch: &mut String,
450) -> bool {
451    scratch.clear();
452    let _ = write!(scratch, "{}", Number(entity));
453    filter.split_whitespace().all(|word| {
454        contains_ignoring_case(scratch, word)
455            || registry.iter().any(|registration| {
456                contains_ignoring_case(registration.name(), word)
457                    && has(world, registration, entity)
458            })
459    })
460}
461
462/// Whether `text` holds `word`, ignoring the case of ASCII letters.
463fn contains_ignoring_case(text: &str, word: &str) -> bool {
464    word.is_empty()
465        || text
466            .as_bytes()
467            .windows(word.len())
468            .any(|part| part.eq_ignore_ascii_case(word.as_bytes()))
469}
470
471/// Whether `name` may name a saved prefab, and its file: a name the prefab
472/// reader and the cook take ([`prefab::is_name`]: lowercase ASCII letters,
473/// digits and `_`), of at most [`MAX_PREFAB_NAME`] bytes.
474fn is_prefab_name(name: &str) -> bool {
475    name.len() <= MAX_PREFAB_NAME && prefab::is_name(name)
476}
477
478fn set_note(note: &mut String, text: impl fmt::Display) {
479    note.clear();
480    let _ = write!(note, "{text}");
481}
482
483/// Says in `note` why something was not done, and logs it: a window cuts a
484/// long note at its edge, and the log keeps it whole.
485fn refuse(note: &mut String, text: impl fmt::Display) {
486    set_note(note, text);
487    warn!("{note}");
488}
489
490/// An entity as the list shows it: `3v1`, its slot and its generation.
491struct Number(Entity);
492
493impl fmt::Display for Number {
494    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
495        write!(f, "{}v{}", self.0.index(), self.0.generation())
496    }
497}
498
499/// A row of the list: a mark if it is selected, its number, then the names
500/// of its registered components.
501struct Row<'a> {
502    world: &'a World,
503    registry: &'a TypeRegistry,
504    entity: Entity,
505    selected: bool,
506}
507
508impl fmt::Display for Row<'_> {
509    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
510        let mark = if self.selected { '>' } else { ' ' };
511        write!(f, "{mark} {}", Number(self.entity))?;
512        for registration in self.registry.iter() {
513            if has(self.world, registration, self.entity) {
514                write!(f, " {}", registration.name())?;
515            }
516        }
517        Ok(())
518    }
519}
520
521/// What a row of an editor shows before or after its control.
522#[derive(Clone, Copy, Hash)]
523enum Label<'a> {
524    Name(&'a str),
525    Index(usize),
526}
527
528impl fmt::Display for Label<'_> {
529    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
530        match self {
531            Label::Name(name) => f.write_str(name),
532            Label::Index(index) => write!(f, "{index}"),
533        }
534    }
535}
536
537/// One step of the context's path, to the field at hand.
538enum Step<'a> {
539    Field(&'static str),
540    Key(&'a str),
541    Index(usize),
542}
543
544/// What editing a component's values needs besides the UI and the values.
545struct Editor<'e, 'c> {
546    cx: &'e mut ReflectContext<'c>,
547    edit: &'e mut Option<TextEdit>,
548    scratch: &'e mut String,
549    note: &'e mut String,
550}
551
552impl Editor<'_, '_> {
553    /// Runs `f` with the context's path a step further: errors and
554    /// warnings then name the field.
555    fn within<R>(&mut self, step: Step<'_>, f: impl FnOnce(&mut Editor<'_, '_>) -> R) -> R {
556        let Editor {
557            cx,
558            edit,
559            scratch,
560            note,
561        } = self;
562        let run = |cx: &mut ReflectContext<'_>| {
563            f(&mut Editor {
564                cx,
565                edit,
566                scratch,
567                note,
568            })
569        };
570        match step {
571            Step::Field(name) => cx.field(name, run),
572            Step::Key(key) => cx.key(key, run),
573            Step::Index(index) => cx.index(index, run),
574        }
575    }
576
577    /// Sets `value` to `new`, or says in the note why not.
578    fn apply(&mut self, value: &mut dyn Reflect, new: &Value) {
579        if let Err(error) = value.apply_value(new, self.cx) {
580            refuse(self.note, format_args!("Not set: {error}"));
581        }
582    }
583}
584
585/// A component's rows, inside its node: a struct's fields; a value
586/// reflected whole as an object, such as a sprite, its members; anything
587/// else, one row.
588fn edit_component(
589    ui: &mut Ui<'_>,
590    component: &mut dyn Reflect,
591    key: Id,
592    editor: &mut Editor<'_, '_>,
593) {
594    match component.kind() {
595        ReflectKind::Struct => edit_fields(ui, component, key, editor),
596        ReflectKind::Primitive | ReflectKind::Handle => {
597            let current = component.to_value(editor.cx);
598            let new = match &current {
599                Value::Object(members) => edit_members(ui, members, key, Strings::Guess, editor),
600                _ => edit_json(
601                    ui,
602                    Label::Name("value"),
603                    &current,
604                    key,
605                    strings(component),
606                    editor,
607                ),
608            };
609            if let Some(new) = new {
610                editor.apply(component, &new);
611            }
612        }
613        ReflectKind::Enum | ReflectKind::List | ReflectKind::Option => {
614            edit_value(ui, Label::Name("value"), component, key, editor);
615        }
616    }
617}
618
619/// A struct's fields, a row each, or a line saying it has none.
620fn edit_fields(ui: &mut Ui<'_>, value: &mut dyn Reflect, key: Id, editor: &mut Editor<'_, '_>) {
621    let fields = value.fields();
622    if fields.is_empty() {
623        ui.label("A tag: no fields.");
624        return;
625    }
626    for (index, info) in fields.iter().enumerate() {
627        let Some(field) = value.field_mut(index) else {
628            continue;
629        };
630        editor.within(Step::Field(info.name), |editor| {
631            edit_value(
632                ui,
633                Label::Name(info.name),
634                field,
635                key.with(info.name),
636                editor,
637            );
638        });
639    }
640}
641
642/// The row, or the node, of a reflected value.
643fn edit_value(
644    ui: &mut Ui<'_>,
645    label: Label<'_>,
646    value: &mut dyn Reflect,
647    key: Id,
648    editor: &mut Editor<'_, '_>,
649) {
650    match value.kind() {
651        ReflectKind::Struct => {
652            ui.tree_node(label, |ui| edit_fields(ui, value, key, editor));
653        }
654        ReflectKind::List => {
655            let len = (0..)
656                .take_while(|&index| value.field(index).is_some())
657                .count();
658            ui.tree_node(format_args!("{label} [{len}]##{label}"), |ui| {
659                for index in 0..len {
660                    let Some(element) = value.field_mut(index) else {
661                        break;
662                    };
663                    editor.within(Step::Index(index), |editor| {
664                        edit_value(ui, Label::Index(index), element, key.with(index), editor);
665                    });
666                }
667            });
668        }
669        ReflectKind::Option => match value.field_mut(0) {
670            Some(inner) => edit_value(ui, label, inner, key, editor),
671            None => ui.label(format_args!("{label}: none")),
672        },
673        ReflectKind::Enum => {
674            let variants = value.variants();
675            let current = value.to_value(editor.cx);
676            let new = if variants.is_empty() {
677                // An enum written by hand, which lists none: its name typed.
678                edit_json(ui, label, &current, key, Strings::Text, editor)
679            } else {
680                let mut picked = current
681                    .as_str()
682                    .and_then(|name| variants.iter().position(|variant| *variant == name))
683                    .unwrap_or(variants.len());
684                let changed = ui.combo(label, &mut picked, variants).changed;
685                variants
686                    .get(picked)
687                    .filter(|_| changed)
688                    .map(|variant| Value::String((*variant).to_string()))
689            };
690            if let Some(new) = new {
691                editor.apply(value, &new);
692            }
693        }
694        ReflectKind::Primitive | ReflectKind::Handle => {
695            let current = value.to_value(editor.cx);
696            if let Some(new) = edit_json(ui, label, &current, key, strings(value), editor) {
697                editor.apply(value, &new);
698            }
699        }
700    }
701}
702
703/// How the strings of a value's data are edited.
704#[derive(Clone, Copy, PartialEq, Eq)]
705enum Strings {
706    /// As text: a `String`'s, an asset path's, a newtype's around one.
707    Text,
708    /// As a color, when they write one: a `Color`'s.
709    Color,
710    /// As a whole number: a `u64`'s or a `usize`'s, which data writes as
711    /// digits past an `i64`.
712    Number,
713    /// As a color when they write one, else as text: the members of a value
714    /// reflected whole, such as a sprite's, whose types its data does not
715    /// say.
716    Guess,
717}
718
719/// How the strings of `value`'s own data are edited, by its type's name;
720/// those of an object in it are guessed at.
721fn strings(value: &dyn Reflect) -> Strings {
722    match value.type_name() {
723        "Color" => Strings::Color,
724        "u64" | "usize" => Strings::Number,
725        _ => Strings::Text,
726    }
727}
728
729/// The row, or the node, of `value`, part of a reflected value's data. If
730/// it changed: for an object, the member that changed, in an object, which
731/// applying sets alone; otherwise the whole new value.
732fn edit_json(
733    ui: &mut Ui<'_>,
734    label: Label<'_>,
735    value: &Value,
736    key: Id,
737    strings: Strings,
738    editor: &mut Editor<'_, '_>,
739) -> Option<Value> {
740    match value {
741        Value::Null => {
742            ui.label(format_args!("{label}: null"));
743            None
744        }
745        &Value::Bool(on) => {
746            let mut on = on;
747            ui.checkbox(label, &mut on)
748                .changed
749                .then_some(Value::Bool(on))
750        }
751        &Value::Float(number) => {
752            // Drawn and dragged as an `f32`: an `f64` is cut to one only
753            // when it is dragged.
754            let mut drawn = number as f32;
755            ui.drag_f32(label, &mut drawn, DRAG_PER_UNIT)
756                .changed
757                .then(|| Value::Float(f64::from(drawn)))
758        }
759        &Value::Int(number) => text_field(ui, label, key, number, editor, whole_number),
760        Value::String(text) => {
761            let color = match strings {
762                Strings::Color | Strings::Guess => color_of(text),
763                Strings::Text | Strings::Number => None,
764            };
765            match color {
766                Some(mut color) => ui
767                    .color_edit(label, &mut color)
768                    .changed
769                    .then(|| color.to_value(editor.cx)),
770                None if strings == Strings::Number => {
771                    text_field(ui, label, key, text, editor, whole_number)
772                }
773                None => text_field(ui, label, key, text, editor, |text| {
774                    Ok(Value::String(text.to_string()))
775                }),
776            }
777        }
778        Value::Array(items) => edit_array(ui, label, items, key, strings, editor),
779        Value::Object(members) => {
780            let mut new = None;
781            ui.tree_node(label, |ui| {
782                new = edit_members(ui, members, key, Strings::Guess, editor)
783            });
784            new
785        }
786    }
787}
788
789/// An object's members, a row each: the member that changed, in an object.
790fn edit_members(
791    ui: &mut Ui<'_>,
792    members: &[(String, Value)],
793    key: Id,
794    strings: Strings,
795    editor: &mut Editor<'_, '_>,
796) -> Option<Value> {
797    let mut new = None;
798    for (name, member) in members {
799        let key = key.with(name.as_str());
800        if let Some(changed) = edit_json(ui, Label::Name(name), member, key, strings, editor) {
801            new = Some(Value::Object(vec![(name.clone(), changed)]));
802        }
803    }
804    new
805}
806
807/// A list's elements: up to four numbers in one row, as a position's two,
808/// the label after the last, in a scope of the label's, as the numbers
809/// before the last have none; others a row each under a node. The whole
810/// new list, if one changed, as a list is applied whole.
811fn edit_array(
812    ui: &mut Ui<'_>,
813    label: Label<'_>,
814    items: &[Value],
815    key: Id,
816    strings: Strings,
817    editor: &mut Editor<'_, '_>,
818) -> Option<Value> {
819    let numbers = (1..=4).contains(&items.len())
820        && items
821            .iter()
822            .all(|item| matches!(item, Value::Int(_) | Value::Float(_)));
823    let mut changed = None;
824    if numbers {
825        ui.with_id(label, |ui| {
826            ui.horizontal(|ui| {
827                for (index, item) in items.iter().enumerate() {
828                    let shown = if index + 1 == items.len() {
829                        label
830                    } else {
831                        Label::Name("")
832                    };
833                    ui.with_id(index, |ui| {
834                        let key = key.with(index);
835                        if let Some(new) = edit_json(ui, shown, item, key, strings, editor) {
836                            changed = Some((index, new));
837                        }
838                    });
839                }
840            });
841        });
842    } else {
843        ui.tree_node(format_args!("{label} [{}]##{label}", items.len()), |ui| {
844            for (index, item) in items.iter().enumerate() {
845                let shown = Label::Index(index);
846                if let Some(new) = edit_json(ui, shown, item, key.with(index), strings, editor) {
847                    changed = Some((index, new));
848                }
849            }
850        });
851    }
852    let (index, new) = changed?;
853    let mut items = items.to_vec();
854    merge(&mut items[index], new);
855    Some(Value::Array(items))
856}
857
858/// Applies `change`, from [`edit_json`], to `target`: an object's members
859/// one by one, anything else whole.
860fn merge(target: &mut Value, change: Value) {
861    match (target, change) {
862        (Value::Object(members), Value::Object(changes)) => {
863            for (name, change) in changes {
864                match members.iter_mut().find(|(member, _)| *member == name) {
865                    Some((_, member)) => merge(member, change),
866                    None => members.push((name, change)),
867                }
868            }
869        }
870        (target, change) => *target = change,
871    }
872}
873
874/// A text field of `current`, or of the edit typed into it, which `parse`
875/// makes a value of on Enter or a press elsewhere; Escape drops it. The
876/// value, if one was made; a text `parse` refuses is dropped, and the note
877/// says why.
878fn text_field(
879    ui: &mut Ui<'_>,
880    label: Label<'_>,
881    key: Id,
882    current: impl fmt::Display,
883    editor: &mut Editor<'_, '_>,
884    parse: impl FnOnce(&str) -> Result<Value, String>,
885) -> Option<Value> {
886    let frame = ui.frame_number();
887    let response = match editor.edit.as_mut().filter(|edit| edit.key == key) {
888        Some(edit) => {
889            edit.frame = frame;
890            ui.text_input(label, &mut edit.text)
891        }
892        None => {
893            editor.scratch.clear();
894            let _ = write!(editor.scratch, "{current}");
895            let response = ui.text_input(label, editor.scratch);
896            if response.changed {
897                *editor.edit = Some(TextEdit {
898                    key,
899                    text: editor.scratch.clone(),
900                    frame,
901                });
902            }
903            response
904        }
905    };
906    if !(response.submitted || response.lost_focus) {
907        return None;
908    }
909    let escaped = response.lost_focus && ui.key_pressed(Key::Escape);
910    let edit = editor.edit.take_if(|edit| edit.key == key)?;
911    if escaped {
912        return None;
913    }
914    match parse(&edit.text) {
915        Ok(value) => Some(value),
916        Err(why) => {
917            refuse(editor.note, format_args!("Not set: {why}"));
918            None
919        }
920    }
921}
922
923/// A whole number typed: an integer, or digits past an `i64`, as data
924/// writes a `u64` that large.
925fn whole_number(text: &str) -> Result<Value, String> {
926    let text = text.trim();
927    if let Ok(number) = text.parse::<i64>() {
928        return Ok(Value::Int(number));
929    }
930    if !text.is_empty() && text.bytes().all(|byte| byte.is_ascii_digit()) {
931        return Ok(Value::String(text.to_string()));
932    }
933    Err(format!("`{text}` is not a whole number"))
934}
935
936/// The color `text` writes, if it is one as data writes them: `#rrggbb` or
937/// `#rrggbbaa`.
938fn color_of(text: &str) -> Option<Color> {
939    let digits = text.strip_prefix('#')?;
940    let hex = matches!(digits.len(), 6 | 8) && digits.bytes().all(|byte| byte.is_ascii_hexdigit());
941    hex.then(|| Color::from_hex(digits).ok()).flatten()
942}
943
944#[cfg(test)]
945mod tests {
946    use super::*;
947
948    #[test]
949    fn a_word_matches_ignoring_case_and_an_empty_one_always() {
950        assert!(contains_ignoring_case("Transform", "trans"));
951        assert!(contains_ignoring_case("Transform", "FORM"));
952        assert!(contains_ignoring_case("3v1", ""));
953        assert!(!contains_ignoring_case("3v1", "3v12"));
954        assert!(!contains_ignoring_case("Sprite", "sprites"));
955    }
956
957    #[test]
958    fn a_prefab_s_name_is_lowercase_letters_digits_and_underscores() {
959        assert!(is_prefab_name("slime_2_big"));
960        for bad in [
961            "",
962            "Slime",
963            "en/slime",
964            "slime.kbj",
965            "../up",
966            "a b",
967            "é",
968            "slime-big",
969        ] {
970            assert!(!is_prefab_name(bad), "{bad:?}");
971        }
972        assert!(is_prefab_name(&"a".repeat(MAX_PREFAB_NAME)));
973        assert!(!is_prefab_name(&"a".repeat(MAX_PREFAB_NAME + 1)));
974    }
975
976    #[test]
977    fn whole_numbers_and_colors_read_as_data_writes_them() {
978        assert_eq!(whole_number(" -12 "), Ok(Value::Int(-12)));
979        assert_eq!(
980            whole_number("18446744073709551615"),
981            Ok(Value::String("18446744073709551615".to_string()))
982        );
983        assert!(whole_number("1.5").is_err() && whole_number("").is_err());
984        assert_eq!(color_of("#ff8000"), Some(Color::rgb(255, 128, 0)));
985        assert_eq!(color_of("#ff800080"), Some(Color::rgba(255, 128, 0, 128)));
986        for not in [
987            "ff8000",
988            "#ff80",
989            "#ff800",
990            "#gg8000",
991            "##ff8000",
992            "#ff8000ff00",
993        ] {
994            assert_eq!(color_of(not), None, "{not:?}");
995        }
996    }
997
998    #[test]
999    fn a_change_merges_into_an_object_by_member_and_replaces_the_rest() {
1000        let object = |members: &[(&str, Value)]| {
1001            Value::Object(
1002                members
1003                    .iter()
1004                    .map(|(name, value)| ((*name).to_string(), value.clone()))
1005                    .collect(),
1006            )
1007        };
1008        let mut target = object(&[
1009            ("shape", object(&[("radius", Value::Float(6.0))])),
1010            ("layer", Value::Int(1)),
1011        ]);
1012        let change = object(&[("shape", object(&[("radius", Value::Float(7.0))]))]);
1013        merge(&mut target, change);
1014        let expected = object(&[
1015            ("shape", object(&[("radius", Value::Float(7.0))])),
1016            ("layer", Value::Int(1)),
1017        ]);
1018        assert_eq!(target, expected);
1019        merge(&mut target, Value::Int(3));
1020        assert_eq!(target, Value::Int(3));
1021    }
1022}