use std::any::TypeId;
use std::fmt;
use crcbl_reflect::{
Kind, Range, Reflect, Snapshot, Value, ValueKind, get_path, set_path, set_variant_path,
snapshot_path,
};
use super::{Ui, WidgetKind, typed};
use crate::tree::Response;
pub const INSPECTOR_STEP: f64 = 0.01;
pub const WHOLE_STEP: f64 = 1.0;
pub const AXES: [&str; 3] = ["x", "y", "z"];
#[derive(Clone, Debug, PartialEq)]
pub struct FieldEdit {
pub path: String,
pub before: Value,
pub after: Value,
}
pub const VARIANT_LABEL: &str = "Variant";
#[derive(Clone, Debug, PartialEq)]
pub struct VariantEdit {
pub path: String,
pub before: Snapshot,
pub after: Snapshot,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Inspection {
pub response: Response,
pub edits: Vec<FieldEdit>,
pub switches: Vec<VariantEdit>,
pub hovered: Option<String>,
pub focused: Option<String>,
}
#[derive(Debug, Default)]
struct Report {
edits: Vec<FieldEdit>,
picked: Vec<(String, &'static str)>,
hovered: Option<String>,
focused: Option<String>,
}
impl Report {
fn locate(&mut self, path: &str, response: &Response) {
if response.hovered {
self.hovered = Some(path.to_owned());
}
if response.focused {
self.focused = Some(path.to_owned());
}
}
}
pub type RowBuilder = Box<dyn Fn(&mut Ui, &mut FieldRow<'_>)>;
#[derive(Default)]
pub struct Overrides {
builders: Vec<(TypeId, RowBuilder)>,
}
impl fmt::Debug for Overrides {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Overrides")
.field("types", &self.builders.len())
.finish()
}
}
impl Overrides {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn vectors() -> Self {
let mut overrides = Self::new();
overrides.register::<[f64; 3]>(|ui, field| vector_row(ui, field, false));
overrides.register::<[f32; 3]>(|ui, field| vector_row(ui, field, false));
overrides.register::<glam::DVec3>(|ui, field| vector_row(ui, field, true));
overrides.register::<glam::Vec3>(|ui, field| vector_row(ui, field, true));
overrides
}
pub fn register<T: Reflect>(&mut self, build: impl Fn(&mut Ui, &mut FieldRow<'_>) + 'static) {
let id = TypeId::of::<T>();
let builder: RowBuilder = Box::new(build);
match self.builders.iter_mut().find(|(at, _)| *at == id) {
Some(slot) => slot.1 = builder,
None => self.builders.push((id, builder)),
}
}
#[must_use]
pub fn len(&self) -> usize {
self.builders.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.builders.is_empty()
}
fn of(&self, value: &dyn Reflect) -> Option<&RowBuilder> {
let id = value.as_any().type_id();
self.builders
.iter()
.find(|(at, _)| *at == id)
.map(|(_, builder)| builder)
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct InspectorOptions<'a> {
pub step: f64,
pub overrides: Option<&'a Overrides>,
pub variants: bool,
}
impl InspectorOptions<'_> {
fn float_step(&self) -> f64 {
if self.step.is_finite() && self.step > 0.0 {
self.step
} else {
INSPECTOR_STEP
}
}
}
pub struct FieldRow<'a> {
pub value: &'a mut dyn Reflect,
pub label: &'a str,
pub range: Option<Range>,
pub step: Option<f64>,
path: &'a str,
report: &'a mut Report,
}
impl fmt::Debug for FieldRow<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FieldRow")
.field("type_name", &self.value.type_name())
.field("label", &self.label)
.field("range", &self.range)
.field("step", &self.step)
.field("path", &self.path)
.finish_non_exhaustive()
}
}
impl FieldRow<'_> {
#[must_use]
pub fn path(&self) -> &str {
self.path
}
#[must_use]
pub fn get(&self, at: &str) -> Option<Value> {
get_path(self.value, at).ok()
}
pub fn set(&mut self, at: &str, new: Value) -> bool {
let Ok(before) = get_path(self.value, at) else {
return false;
};
if set_path(self.value, at, &new).is_err() {
return false;
}
let Ok(after) = get_path(self.value, at) else {
return false;
};
if after.identical(&before) {
return false;
}
self.report.edits.push(FieldEdit {
path: joined(self.path, at),
before,
after,
});
true
}
pub fn locate(&mut self, at: &str, response: &Response) {
self.report.locate(&joined(self.path, at), response);
}
}
#[derive(Clone, Copy, Debug)]
struct Row<'a> {
name: &'a str,
label: &'a str,
range: Option<Range>,
step: Option<f64>,
}
fn joined(path: &str, segment: &str) -> String {
match (path.is_empty(), segment.is_empty()) {
(_, true) => path.to_owned(),
(true, false) => segment.to_owned(),
(false, false) => format!("{path}.{segment}"),
}
}
#[track_caller]
fn number_field(
ui: &mut Ui,
before: &Value,
range: Option<Range>,
step: f64,
) -> Option<(Response, Option<Value>)> {
const FIELD: &str = ".inspector-field";
let edited = match *before {
Value::Int(mut number) => {
let (min, max) = range.map_or((i64::MIN, i64::MAX), |range| {
(range.min as i64, range.max as i64)
});
let notch = step.round() as i64;
let response = ui.drag_value(FIELD, &mut number, min..=max, step, notch);
(response, response.changed.then_some(Value::Int(number)))
}
Value::UInt(mut number) => {
let (min, max) = range.map_or((u64::MIN, u64::MAX), |range| {
(range.min as u64, range.max as u64)
});
let notch = step.round() as u64;
let response = ui.drag_value(FIELD, &mut number, min..=max, step, notch);
(response, response.changed.then_some(Value::UInt(number)))
}
Value::Float(mut number) => {
let (min, max) = range.map_or((f64::MIN, f64::MAX), |range| (range.min, range.max));
let response = ui.drag_value(FIELD, &mut number, min..=max, step, step);
(response, response.changed.then_some(Value::Float(number)))
}
Value::Bool(_) | Value::Text(_) => return None,
};
Some(edited)
}
fn vector_row(ui: &mut Ui, field: &mut FieldRow<'_>, named: bool) {
let step = field.step.unwrap_or(INSPECTOR_STEP);
let range = field.range;
let label = field.label;
ui.block(".inspector-row", &[], |ui| {
ui.span(".inspector-label", label, &[]);
for (index, axis) in AXES.iter().enumerate() {
let segment = if named {
(*axis).to_owned()
} else {
index.to_string()
};
let Some(before) = field.get(&segment) else {
continue;
};
let mut new = None;
ui.block_keyed(*axis, ".inspector-axis", &[], |ui| {
ui.span(".inspector-axis-label", *axis, &[]);
if let Some((response, edited)) = number_field(ui, &before, range, step) {
new = edited;
field.locate(&segment, &response);
}
});
if let Some(new) = new {
field.set(&segment, new);
}
}
});
}
impl Ui {
#[track_caller]
pub fn inspector(&mut self, selector: &str, value: &mut dyn Reflect) -> Inspection {
self.inspector_with(selector, value, &InspectorOptions::default())
}
#[track_caller]
pub fn inspector_with(
&mut self,
selector: &str,
value: &mut dyn Reflect,
options: &InspectorOptions<'_>,
) -> Inspection {
let selector = typed("inspector", selector);
let mut report = Report::default();
let mut path = String::new();
let response = self.block(&selector, &[], |ui| {
let root = Row {
name: "",
label: value.type_name(),
range: None,
step: None,
};
let overridden = options
.overrides
.is_some_and(|overrides| overrides.of(value).is_some());
if overridden || matches!(value.kind(), Kind::Leaf(_)) {
ui.inspect_row(value, root, &mut path, options, &mut report);
} else {
ui.inspect_children(value, root, &mut path, options, &mut report);
}
});
self.mark(response.key, WidgetKind::Inspector);
let switches = switch_picked(value, &report.picked);
Inspection {
response,
edits: report.edits,
switches,
hovered: report.hovered,
focused: report.focused,
}
}
fn inspect_children(
&mut self,
value: &mut dyn Reflect,
parent: Row<'_>,
path: &mut String,
options: &InspectorOptions<'_>,
report: &mut Report,
) {
match value.kind() {
Kind::Struct | Kind::Enum => {
let fields = value.fields();
for (index, field) in fields.iter().enumerate() {
let Some(child) = value.field_mut(index) else {
continue;
};
let row = Row {
name: field.name,
label: field.label,
range: field.range,
step: field.step,
};
self.inspect_row(child, row, path, options, report);
}
}
Kind::List { len } => {
for index in 0..len {
let name = index.to_string();
let Some(child) = value.field_mut(index) else {
continue;
};
let row = Row {
name: &name,
label: &name,
range: parent.range,
step: parent.step,
};
self.inspect_row(child, row, path, options, report);
}
}
Kind::Leaf(_) => {}
}
}
fn inspect_row(
&mut self,
child: &mut dyn Reflect,
row: Row<'_>,
path: &mut String,
options: &InspectorOptions<'_>,
report: &mut Report,
) {
let base = path.len();
if !row.name.is_empty() {
if !path.is_empty() {
path.push('.');
}
path.push_str(row.name);
}
if let Some(builder) = options.overrides.and_then(|overrides| overrides.of(child)) {
let mut field = FieldRow {
value: child,
label: row.label,
range: row.range,
step: row.step,
path,
report,
};
builder(self, &mut field);
} else {
match child.kind() {
Kind::Leaf(kind) => self.leaf_row(child, row, kind, path, options, report),
Kind::Struct | Kind::Enum | Kind::List { .. } => {
let title = match child.variant() {
Some(variant) => format!("{}: {variant}", row.label),
None => row.label.to_owned(),
};
self.collapsing_keyed(row.name, ".inspector-group", &title, |ui| {
if options.variants
&& let Some(variant) = ui.variant_select(&*child)
{
report.picked.push((path.clone(), variant));
}
ui.inspect_children(child, row, path, options, report);
});
}
}
}
path.truncate(base);
}
fn variant_select(&mut self, value: &dyn Reflect) -> Option<&'static str> {
let variants = value.variants();
if variants.is_empty() {
return None;
}
let names: Vec<&'static str> = variants.iter().map(|variant| variant.name).collect();
let active = value.variant();
let mut chosen = names
.iter()
.position(|&name| Some(name) == active)
.unwrap_or(names.len());
let mut picked = None;
self.block(".inspector-row", &[], |ui| {
ui.span(".inspector-label", VARIANT_LABEL, &[]);
if ui.select(".inspector-field", &names, &mut chosen).changed {
picked = names.get(chosen).copied();
}
});
picked
}
fn leaf_row(
&mut self,
child: &mut dyn Reflect,
row: Row<'_>,
kind: ValueKind,
path: &str,
options: &InspectorOptions<'_>,
report: &mut Report,
) {
let Some(before) = child.get() else {
return;
};
let float_step = options.float_step();
self.block(".inspector-row", &[], |ui| {
ui.span(".inspector-label", row.label, &[]);
let (response, new) = match kind {
ValueKind::Bool => {
let mut on = matches!(before, Value::Bool(true));
let response = ui.checkbox(".inspector-field", "", &mut on);
let new = response.changed.then_some(Value::Bool(on));
(response, new)
}
ValueKind::Text => {
let mut text = match &before {
Value::Text(text) => text.clone(),
_ => String::new(),
};
let response = ui.text_input(".inspector-field", &mut text);
let new = response.changed.then_some(Value::Text(text));
(response, new)
}
ValueKind::Int | ValueKind::UInt | ValueKind::Float => {
let step = row.step.unwrap_or(match kind {
ValueKind::Float => float_step,
_ => WHOLE_STEP,
});
let Some(edited) = number_field(ui, &before, row.range, step) else {
return;
};
edited
}
};
report.locate(path, &response);
if let Some(new) = new {
write_leaf(child, path, &new, &mut report.edits);
}
});
}
}
fn switch_picked(value: &mut dyn Reflect, picked: &[(String, &'static str)]) -> Vec<VariantEdit> {
let mut switches = Vec::with_capacity(picked.len());
for (path, variant) in picked {
let Ok(before) = snapshot_path(value, path) else {
continue;
};
if set_variant_path(value, path, variant).is_err() {
continue;
}
let Ok(after) = snapshot_path(value, path) else {
continue;
};
switches.push(VariantEdit {
path: path.clone(),
before,
after,
});
}
switches
}
fn write_leaf(leaf: &mut dyn Reflect, path: &str, new: &Value, edits: &mut Vec<FieldEdit>) {
let Some(before) = leaf.get() else {
return;
};
if leaf.set(new).is_err() {
return;
}
let Some(after) = leaf.get() else {
return;
};
if after.identical(&before) {
return;
}
edits.push(FieldEdit {
path: path.to_owned(),
before,
after,
});
}