use std::collections::HashMap;
use crate::error::{GuiError, GuiResult};
use crate::events::UiEvent;
use crate::pickers::{ColorDialogData, Rgba};
use crate::properties::{
ChangeToken, ProjectionMode, PropertyEvent, PropertyId, PropertyModel, PropertyValue,
};
use crate::ui::{Backend, Ui};
use crate::widgets::{Color, ContainerDirection, WidgetKind};
use crate::WidgetId;
pub const DEFAULT_PROPERTY_LABEL_WIDTH: u32 = 140;
const NESTED_INDENT: f32 = 16.0;
const MIN_ROW_HEIGHT: i32 = 26;
const CATEGORY_GAP: i32 = 6;
const CATEGORY_PADDING: i32 = 8;
const CATEGORY_CAPTION_BAND: i32 = 24;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PropertyEditorWidget {
TextInput,
Checkbox,
ComboBox,
MultiSelect,
DatePicker,
ColorDialog,
}
impl PropertyEditorWidget {
pub fn for_value(value: &PropertyValue) -> Self {
match value {
PropertyValue::Bool(_) => Self::Checkbox,
PropertyValue::Enum { .. } => Self::ComboBox,
PropertyValue::Flags { .. } => Self::MultiSelect,
PropertyValue::Date(_) => Self::DatePicker,
PropertyValue::Color(_) => Self::ColorDialog,
PropertyValue::Text(_)
| PropertyValue::Path(_)
| PropertyValue::Int(_)
| PropertyValue::Uint(_)
| PropertyValue::Float(_)
| PropertyValue::Aggregate(_) => Self::TextInput,
}
}
pub const fn widget_kind(self) -> WidgetKind {
match self {
Self::TextInput => WidgetKind::TextInput,
Self::Checkbox => WidgetKind::Checkbox,
Self::ComboBox => WidgetKind::ComboBox,
Self::MultiSelect => WidgetKind::MultiSelect,
Self::DatePicker => WidgetKind::DatePicker,
Self::ColorDialog => WidgetKind::ColorDialog,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PropertyGridFeatures {
pub native_editors: bool,
pub virtualization: bool,
pub user_collapsible_categories: bool,
pub veto: bool,
}
pub const PROPERTY_GRID_FEATURES: PropertyGridFeatures = PropertyGridFeatures {
native_editors: true,
virtualization: false,
user_collapsible_categories: false,
veto: true,
};
fn editor_min_height(value: &PropertyValue) -> i32 {
match value {
PropertyValue::Flags { options, .. } => (options.len().clamp(1, 6) * 22 + 6) as i32,
_ => 0,
}
}
pub fn format_property_value(value: &PropertyValue) -> String {
match value {
PropertyValue::Text(text) | PropertyValue::Path(text) | PropertyValue::Date(text) => {
text.clone()
}
PropertyValue::Bool(flag) => flag.to_string(),
PropertyValue::Int(number) => number.to_string(),
PropertyValue::Uint(number) => number.to_string(),
PropertyValue::Float(number) => number.to_string(),
PropertyValue::Enum { selected, options } => {
options.get(*selected).cloned().unwrap_or_default()
}
PropertyValue::Flags { selected, options } => selected
.iter()
.filter_map(|index| options.get(*index).cloned())
.collect::<Vec<_>>()
.join(", "),
PropertyValue::Color(color) => format!("#{:02X}{:02X}{:02X}", color.r, color.g, color.b),
PropertyValue::Aggregate(parts) => parts
.iter()
.map(format_property_value)
.collect::<Vec<_>>()
.join(", "),
}
}
pub fn parse_property_text(current: &PropertyValue, text: &str) -> Result<PropertyValue, String> {
let trimmed = text.trim();
match current {
PropertyValue::Text(_) => Ok(PropertyValue::Text(text.to_owned())),
PropertyValue::Path(_) => Ok(PropertyValue::Path(text.to_owned())),
PropertyValue::Date(_) => Ok(PropertyValue::Date(trimmed.to_owned())),
PropertyValue::Int(_) => trimmed
.parse::<i64>()
.map(PropertyValue::Int)
.map_err(|_| format!("'{trimmed}' is not a whole number")),
PropertyValue::Uint(_) => trimmed
.parse::<u64>()
.map(PropertyValue::Uint)
.map_err(|_| format!("'{trimmed}' is not a non-negative whole number")),
PropertyValue::Float(_) => match trimmed.parse::<f64>() {
Ok(number) if number.is_finite() => Ok(PropertyValue::Float(number)),
_ => Err(format!("'{trimmed}' is not a number")),
},
PropertyValue::Bool(_) => match trimmed.to_ascii_lowercase().as_str() {
"true" | "yes" | "on" | "1" => Ok(PropertyValue::Bool(true)),
"false" | "no" | "off" | "0" => Ok(PropertyValue::Bool(false)),
_ => Err(format!("'{trimmed}' is not true or false")),
},
PropertyValue::Color(_) => parse_hex_color(trimmed)
.map(PropertyValue::Color)
.ok_or_else(|| format!("'{trimmed}' is not a #RRGGBB color")),
PropertyValue::Enum { options, .. } => options
.iter()
.position(|option| option == trimmed)
.map(|selected| PropertyValue::Enum {
selected,
options: options.clone(),
})
.ok_or_else(|| format!("'{trimmed}' is not one of the options")),
PropertyValue::Flags { options, .. } => {
let mut selected = Vec::new();
for part in trimmed.split(',').map(str::trim).filter(|p| !p.is_empty()) {
let index = options
.iter()
.position(|option| option == part)
.ok_or_else(|| format!("'{part}' is not one of the options"))?;
selected.push(index);
}
selected.sort_unstable();
selected.dedup();
Ok(PropertyValue::Flags {
selected,
options: options.clone(),
})
}
PropertyValue::Aggregate(parts) => {
let pieces: Vec<&str> = text.split(',').collect();
if pieces.len() != parts.len() {
return Err(format!(
"expected {} comma-separated values, found {}",
parts.len(),
pieces.len()
));
}
parts
.iter()
.zip(pieces)
.map(|(part, piece)| parse_property_text(part, piece))
.collect::<Result<Vec<_>, _>>()
.map(PropertyValue::Aggregate)
}
}
}
fn parse_hex_color(text: &str) -> Option<Color> {
let hex = text.strip_prefix('#').unwrap_or(text);
if hex.len() != 6 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
return None;
}
let channel = |range: std::ops::Range<usize>| u8::from_str_radix(&hex[range], 16).ok();
Some(Color::rgb(channel(0..2)?, channel(2..4)?, channel(4..6)?))
}
#[derive(Debug, Clone)]
struct RowWidgets {
frame: WidgetId,
label: Option<WidgetId>,
editor: Option<(WidgetId, PropertyEditorWidget)>,
}
#[derive(Debug, Clone, PartialEq)]
struct RowShape {
id: PropertyId,
depth: usize,
category: bool,
label: String,
editor: Option<PropertyEditorWidget>,
options: Vec<String>,
}
#[derive(Debug, Clone)]
struct GridState {
model: PropertyModel,
mode: ProjectionMode,
label_width: u32,
veto: bool,
rows: HashMap<PropertyId, RowWidgets>,
top_level: Vec<WidgetId>,
shape: Vec<RowShape>,
}
#[derive(Debug, Default)]
pub(crate) struct PropertyGridRegistry {
grids: HashMap<WidgetId, GridState>,
editors: HashMap<WidgetId, (WidgetId, PropertyId)>,
}
impl PropertyGridRegistry {
pub(crate) fn forget(&mut self, widget_id: WidgetId) {
if self.grids.remove(&widget_id).is_some() {
self.editors.retain(|_, (grid, _)| *grid != widget_id);
}
self.editors.remove(&widget_id);
}
pub(crate) fn is_empty(&self) -> bool {
self.grids.is_empty()
}
}
fn shape_of(model: &PropertyModel, mode: ProjectionMode) -> Vec<RowShape> {
model
.rows(mode)
.into_iter()
.map(|row| RowShape {
id: row.id,
depth: row.depth,
category: row.category,
label: row.label.to_owned(),
editor: row.value.map(PropertyEditorWidget::for_value),
options: match row.value {
Some(PropertyValue::Enum { options, .. })
| Some(PropertyValue::Flags { options, .. }) => options.clone(),
_ => Vec::new(),
},
})
.collect()
}
fn is_text_editor(state: &GridState, id: PropertyId) -> bool {
state
.rows
.get(&id)
.and_then(|row| row.editor)
.is_some_and(|(_, kind)| kind == PropertyEditorWidget::TextInput)
}
fn to_rgba(color: Color) -> Rgba {
Rgba::rgb(color.r, color.g, color.b)
}
impl<B: Backend> Ui<B> {
pub fn create_property_grid(&mut self, model: PropertyModel) -> GuiResult<WidgetId> {
model.validate()?;
let host = self.create(WidgetKind::Container, None)?;
let built = (|| -> GuiResult<()> {
self.set_container_direction(host, ContainerDirection::Vertical)?;
self.set_container_gap(host, 6)?;
self.set_container_padding(host, 8)?;
let _ = self.set_accessible_name(host, "Properties");
Ok(())
})();
if let Err(error) = built {
let _ = self.remove(host);
return Err(error);
}
let mut state = GridState {
model,
mode: ProjectionMode::Categorized,
label_width: DEFAULT_PROPERTY_LABEL_WIDTH,
veto: false,
rows: HashMap::new(),
top_level: Vec::new(),
shape: Vec::new(),
};
state.model.clear_events();
if let Err(error) = self.build_property_rows(host, &mut state) {
let _ = self.remove(host);
return Err(error);
}
self.property_grids.grids.insert(host, state);
Ok(host)
}
pub fn property_grid_model(&self, grid: WidgetId) -> GuiResult<&PropertyModel> {
self.property_grids
.grids
.get(&grid)
.map(|state| &state.model)
.ok_or(GuiError::WidgetNotFound(grid.0))
}
pub fn set_property_grid_model(
&mut self,
grid: WidgetId,
model: PropertyModel,
) -> GuiResult<()> {
model.validate()?;
self.with_grid(grid, |ui, state| {
state.model = model;
state.model.clear_events();
ui.build_property_rows(grid, state)
})
}
pub fn update_property_grid<R>(
&mut self,
grid: WidgetId,
edit: impl FnOnce(&mut PropertyModel) -> R,
) -> GuiResult<R> {
self.with_grid(grid, |ui, state| {
let result = edit(&mut state.model);
state.model.clear_events();
ui.sync_property_rows(grid, state)?;
Ok(result)
})
}
pub fn set_property_grid_value(
&mut self,
grid: WidgetId,
id: PropertyId,
value: PropertyValue,
) -> GuiResult<()> {
self.with_grid(grid, |ui, state| {
state.model.set_value(id, value)?;
state.model.clear_events();
ui.refresh_property_editor(state, id)
})
}
pub fn set_property_grid_projection(
&mut self,
grid: WidgetId,
mode: ProjectionMode,
) -> GuiResult<()> {
self.with_grid(grid, |ui, state| {
if state.mode == mode {
return Ok(());
}
state.mode = mode;
ui.build_property_rows(grid, state)
})
}
pub fn property_grid_projection(&self, grid: WidgetId) -> GuiResult<ProjectionMode> {
self.property_grids
.grids
.get(&grid)
.map(|state| state.mode)
.ok_or(GuiError::WidgetNotFound(grid.0))
}
pub fn set_property_expanded(
&mut self,
grid: WidgetId,
id: PropertyId,
expanded: bool,
) -> GuiResult<()> {
self.update_property_grid(grid, |model| model.set_expanded(id, expanded))?
.map_err(GuiError::from)
}
pub fn set_property_grid_label_width(&mut self, grid: WidgetId, width: u32) -> GuiResult<()> {
if width == 0 {
return Err(GuiError::InvalidLayoutGeometry);
}
self.with_grid(grid, |ui, state| {
state.label_width = width;
let labels: Vec<WidgetId> = state.rows.values().filter_map(|row| row.label).collect();
for label in labels {
ui.apply_property_label_width(label, width)?;
}
Ok(())
})
}
pub fn property_grid_label_width(&self, grid: WidgetId) -> GuiResult<u32> {
self.property_grids
.grids
.get(&grid)
.map(|state| state.label_width)
.ok_or(GuiError::WidgetNotFound(grid.0))
}
pub fn set_property_grid_veto(&mut self, grid: WidgetId, enabled: bool) -> GuiResult<()> {
self.with_grid(grid, |ui, state| {
state.veto = enabled;
if !enabled {
if let Some(pending) = state.model.pending_change().cloned() {
state.model.resolve_change(pending.token)?;
ui.emit_property_events(grid, state)?;
}
}
Ok(())
})
}
pub fn resolve_property_change(
&mut self,
grid: WidgetId,
token: ChangeToken,
accept: bool,
) -> GuiResult<()> {
self.with_grid(grid, |ui, state| {
if accept {
state.model.commit_change(token)?;
} else {
state.model.deny_change(token)?;
}
ui.emit_property_events(grid, state)
})
}
pub fn property_grid_editor(
&self,
grid: WidgetId,
id: PropertyId,
) -> GuiResult<Option<WidgetId>> {
let state = self
.property_grids
.grids
.get(&grid)
.ok_or(GuiError::WidgetNotFound(grid.0))?;
Ok(state
.rows
.get(&id)
.and_then(|row| row.editor.map(|(editor, _)| editor)))
}
pub fn property_grid_row(&self, grid: WidgetId, id: PropertyId) -> GuiResult<Option<WidgetId>> {
let state = self
.property_grids
.grids
.get(&grid)
.ok_or(GuiError::WidgetNotFound(grid.0))?;
Ok(state.rows.get(&id).map(|row| row.frame))
}
pub fn is_property_grid(&self, widget_id: WidgetId) -> bool {
self.property_grids.grids.contains_key(&widget_id)
}
pub fn select_property(&mut self, grid: WidgetId, id: Option<PropertyId>) -> GuiResult<()> {
self.with_grid(grid, |ui, state| {
state.model.set_selected(id)?;
state.model.clear_events();
if let Some(editor) = id
.and_then(|id| state.rows.get(&id))
.and_then(|row| row.editor.map(|(editor, _)| editor))
{
ui.focus(editor)?;
}
Ok(())
})
}
fn with_grid<R>(
&mut self,
grid: WidgetId,
run: impl FnOnce(&mut Self, &mut GridState) -> GuiResult<R>,
) -> GuiResult<R> {
let mut state = self
.property_grids
.grids
.remove(&grid)
.ok_or(GuiError::WidgetNotFound(grid.0))?;
let result = run(self, &mut state);
if self.widget(grid).is_some() {
self.property_grids.grids.insert(grid, state);
}
result
}
fn apply_property_label_width(&mut self, label: WidgetId, width: u32) -> GuiResult<()> {
let mut style = self.layout_style(label)?;
style.size.width = crate::layout::Dimension::Length(width as f32);
style.flex_shrink = 0.0;
self.set_layout_style(label, style)
}
fn sync_property_rows(&mut self, grid: WidgetId, state: &mut GridState) -> GuiResult<()> {
if shape_of(&state.model, state.mode) != state.shape {
return self.build_property_rows(grid, state);
}
let ids: Vec<PropertyId> = state.rows.keys().copied().collect();
for id in ids {
self.refresh_property_editor(state, id)?;
}
Ok(())
}
fn build_property_rows(&mut self, grid: WidgetId, state: &mut GridState) -> GuiResult<()> {
for widget in std::mem::take(&mut state.top_level) {
if self.widget(widget).is_some() {
self.remove(widget)?;
}
}
for row in state.rows.values() {
if let Some((editor, _)) = row.editor {
self.property_grids.editors.remove(&editor);
}
}
state.rows.clear();
state.shape = shape_of(&state.model, state.mode);
let mut open: Vec<(usize, WidgetId)> = Vec::new();
let mut categories: Vec<WidgetId> = Vec::new();
let mut children: HashMap<WidgetId, Vec<WidgetId>> = HashMap::new();
let mut min_heights: HashMap<WidgetId, i32> = HashMap::new();
let shape = state.shape.clone();
for row in &shape {
while open.last().is_some_and(|(depth, _)| *depth >= row.depth) {
open.pop();
}
let (parent, base_depth) = open
.last()
.map(|(depth, frame)| (*frame, depth + 1))
.unwrap_or((grid, 0));
let frame = if row.category {
let frame = self.create(WidgetKind::GroupBox, Some(&row.label))?;
self.attach(parent, frame)?;
self.set_container_direction(frame, ContainerDirection::Vertical)?;
self.set_container_gap(frame, CATEGORY_GAP)?;
self.set_container_padding(frame, CATEGORY_PADDING)?;
open.push((row.depth, frame));
categories.push(frame);
state.rows.insert(
row.id,
RowWidgets {
frame,
label: None,
editor: None,
},
);
frame
} else {
let (frame, row_height) = self.build_property_row(grid, state, row, parent)?;
min_heights.insert(frame, row_height);
let indent = row.depth.saturating_sub(base_depth) as f32 * NESTED_INDENT;
if indent > 0.0 {
let mut style = self.layout_style(frame)?;
style.margin.left = crate::layout::LengthPercentageAuto::Length(indent);
self.set_layout_style(frame, style)?;
}
frame
};
if parent == grid {
state.top_level.push(frame);
} else {
children.entry(parent).or_default().push(frame);
}
}
for frame in categories.into_iter().rev() {
let rows = children.get(&frame).map(Vec::as_slice).unwrap_or(&[]);
let content: i32 = rows
.iter()
.map(|child| min_heights.get(child).copied().unwrap_or(MIN_ROW_HEIGHT))
.sum::<i32>()
+ CATEGORY_GAP * (rows.len().saturating_sub(1) as i32);
let height = content + 2 * CATEGORY_PADDING + CATEGORY_CAPTION_BAND;
min_heights.insert(frame, height);
self.set_min_size(frame, 0, height)?;
}
Ok(())
}
fn build_property_row(
&mut self,
grid: WidgetId,
state: &mut GridState,
row: &RowShape,
parent: WidgetId,
) -> GuiResult<(WidgetId, i32)> {
let node = state
.model
.get(row.id)
.ok_or(GuiError::WidgetNotFound(row.id.0))?
.clone();
let value = node
.value
.clone()
.ok_or_else(|| GuiError::Backend(format!("property {} has no value", row.id)))?;
let kind = PropertyEditorWidget::for_value(&value);
let frame = self.create(WidgetKind::Container, None)?;
self.attach(parent, frame)?;
self.set_container_direction(frame, ContainerDirection::Horizontal)?;
self.set_container_gap(frame, 8)?;
let mut style = self.layout_style(frame)?;
style.align_items = Some(crate::layout::AlignItems::Center);
self.set_layout_style(frame, style)?;
let label = self.create(WidgetKind::Label, Some(&node.label))?;
self.attach(frame, label)?;
self.apply_property_label_width(label, state.label_width)?;
let editor = match kind {
PropertyEditorWidget::TextInput => {
self.create(WidgetKind::TextInput, Some(&format_property_value(&value)))?
}
PropertyEditorWidget::Checkbox => self.create(WidgetKind::Checkbox, Some(""))?,
PropertyEditorWidget::ComboBox => match &value {
PropertyValue::Enum { options, .. } => self.create_combo_box(options)?,
_ => unreachable!("combo editors hold enum values"),
},
PropertyEditorWidget::MultiSelect => match &value {
PropertyValue::Flags { options, .. } => {
self.create(WidgetKind::MultiSelect, Some(&options.join("|")))?
}
_ => unreachable!("multi-select editors hold flag values"),
},
PropertyEditorWidget::DatePicker => self.create(WidgetKind::DatePicker, None)?,
PropertyEditorWidget::ColorDialog => self.create(
WidgetKind::ColorDialog,
Some(&format_property_value(&value)),
)?,
};
self.attach(frame, editor)?;
self.set_flex_grow(editor, 1.0)?;
let _ = self.set_accessible_name(editor, &node.label);
let list_height = editor_min_height(&value);
let editor_height = if list_height > 0 {
let mut style = self.layout_style(editor)?;
style.size.height = crate::layout::Dimension::Length(list_height as f32);
self.set_layout_style(editor, style)?;
list_height
} else {
self.backend()
.natural_size(editor)
.map_or(0, |(_, height)| height)
};
let label_height = self
.backend()
.natural_size(label)
.map_or(0, |(_, height)| height);
let row_height = MIN_ROW_HEIGHT.max(editor_height).max(label_height);
self.set_min_size(frame, 0, row_height)?;
state.rows.insert(
row.id,
RowWidgets {
frame,
label: Some(label),
editor: Some((editor, kind)),
},
);
self.property_grids.editors.insert(editor, (grid, row.id));
self.refresh_property_editor(state, row.id)?;
Ok((frame, row_height))
}
fn refresh_property_editor(&mut self, state: &GridState, id: PropertyId) -> GuiResult<()> {
let Some(RowWidgets {
editor: Some((editor, kind)),
..
}) = state.rows.get(&id).cloned()
else {
return Ok(());
};
let Some(node) = state.model.get(id) else {
return Ok(());
};
let Some(value) = node.value.clone() else {
return Ok(());
};
let editable = node.enabled && !node.read_only;
let tooltip = node.validation.clone();
let Some(spec) = self.widget(editor).cloned() else {
return Ok(());
};
match (kind, &value) {
(PropertyEditorWidget::Checkbox, PropertyValue::Bool(checked)) => {
if spec.checked != Some(*checked) {
self.set_checked(editor, *checked)?;
}
}
(PropertyEditorWidget::ComboBox, PropertyValue::Enum { selected, .. }) => {
if spec.selected_index != Some(*selected) {
self.set_selected_index(editor, *selected)?;
}
}
(PropertyEditorWidget::MultiSelect, PropertyValue::Flags { selected, .. }) => {
if spec.selected_indices != *selected {
self.set_selected_indices(editor, selected)?;
}
}
(PropertyEditorWidget::DatePicker, PropertyValue::Date(date)) => {
if spec.date_value.as_deref() != Some(date.as_str()) {
self.set_date_value(editor, date)?;
}
}
(PropertyEditorWidget::ColorDialog, PropertyValue::Color(color)) => {
let text = format_property_value(&value);
if spec.text.as_deref() != Some(text.as_str()) {
self.set_text(editor, &text)?;
}
let rgba = to_rgba(*color);
if spec.color_dialog_data.as_ref().map(|data| data.initial) != Some(rgba) {
let mut data = spec
.color_dialog_data
.clone()
.unwrap_or_else(|| ColorDialogData::new(rgba));
data.initial = rgba;
let _ = self.set_color_dialog_data(editor, data);
}
}
_ => {
let text = format_property_value(&value);
if spec.text.as_deref() != Some(text.as_str()) {
self.set_text(editor, &text)?;
}
}
}
if spec.enabled.unwrap_or(true) != editable {
self.set_enabled(editor, editable)?;
}
let _ = self.set_tooltip(editor, tooltip.as_deref().unwrap_or(""));
Ok(())
}
pub(crate) fn observe_property_grid_event(&mut self, event: &UiEvent) {
if self.property_grids.is_empty() {
return;
}
let editor = match event {
UiEvent::Toggled { widget_id, .. }
| UiEvent::SelectionChanged { widget_id, .. }
| UiEvent::MultiSelectionChanged { widget_id, .. }
| UiEvent::TextSubmitted { widget_id, .. }
| UiEvent::DateChanged { widget_id, .. }
| UiEvent::ColorSelected { widget_id, .. }
| UiEvent::FocusChanged { widget_id, .. }
| UiEvent::KeyDown { widget_id, .. } => *widget_id,
_ => return,
};
let Some(&(grid, id)) = self.property_grids.editors.get(&editor) else {
return;
};
let _ = self.with_grid(grid, |ui, state| {
ui.handle_property_editor_event(grid, state, id, editor, event)
});
}
fn handle_property_editor_event(
&mut self,
grid: WidgetId,
state: &mut GridState,
id: PropertyId,
editor: WidgetId,
event: &UiEvent,
) -> GuiResult<()> {
let Some(current) = state.model.value(id).cloned() else {
return Ok(());
};
let proposal: Result<PropertyValue, String> = match (event, ¤t) {
(UiEvent::FocusChanged { focused: true, .. }, _) => {
if state.model.selected() != Some(id) {
state.model.set_selected(Some(id))?;
self.emit_property_events(grid, state)?;
}
return Ok(());
}
(UiEvent::KeyDown { key, .. }, _) if is_text_editor(state, id) => {
match key.as_str() {
"Escape" => return self.refresh_property_editor(state, id),
"Enter" | "Return" => {}
_ => return Ok(()),
}
let text = self
.widget(editor)
.and_then(|spec| spec.text.clone())
.unwrap_or_default();
parse_property_text(¤t, &text)
}
(UiEvent::FocusChanged { focused: false, .. }, _) => {
if !is_text_editor(state, id) {
return Ok(());
}
let text = self
.widget(editor)
.and_then(|spec| spec.text.clone())
.unwrap_or_default();
parse_property_text(¤t, &text)
}
(UiEvent::TextSubmitted { text, .. }, _) => parse_property_text(¤t, text),
(UiEvent::Toggled { checked, .. }, PropertyValue::Bool(_)) => {
Ok(PropertyValue::Bool(*checked))
}
(
UiEvent::SelectionChanged {
index: Some(index), ..
},
PropertyValue::Enum { options, .. },
) => Ok(PropertyValue::Enum {
selected: *index,
options: options.clone(),
}),
(
UiEvent::MultiSelectionChanged { indices, .. },
PropertyValue::Flags { options, .. },
) => {
let mut selected = indices.clone();
selected.sort_unstable();
selected.dedup();
Ok(PropertyValue::Flags {
selected,
options: options.clone(),
})
}
(UiEvent::DateChanged { iso_date, .. }, PropertyValue::Date(_)) => {
Ok(PropertyValue::Date(iso_date.clone()))
}
(
UiEvent::ColorSelected {
color: Some(color), ..
},
PropertyValue::Color(_),
) => Ok(PropertyValue::Color(Color::rgb(color.r, color.g, color.b))),
_ => return Ok(()),
};
let proposed = match proposal {
Ok(value) => value,
Err(reason) => {
self.reject_property_edit(grid, state, id, reason)?;
return Ok(());
}
};
if proposed == current {
return self.refresh_property_editor(state, id);
}
let token = match state.model.request_change(id, proposed) {
Ok(token) => token,
Err(error) => {
state.model.clear_events();
self.reject_property_edit(grid, state, id, error.to_string())?;
return Ok(());
}
};
if !state.veto {
state.model.commit_change(token)?;
}
self.emit_property_events(grid, state)
}
fn reject_property_edit(
&mut self,
grid: WidgetId,
state: &mut GridState,
id: PropertyId,
reason: String,
) -> GuiResult<()> {
self.refresh_property_editor(state, id)?;
self.queue_event(UiEvent::PropertyEditRejected {
widget_id: grid,
property: id,
reason,
});
Ok(())
}
fn emit_property_events(&mut self, grid: WidgetId, state: &mut GridState) -> GuiResult<()> {
for event in state.model.drain_events() {
match event {
PropertyEvent::Changing {
token,
id,
proposed,
..
} => {
if state.veto {
self.queue_event(UiEvent::PropertyChanging {
widget_id: grid,
property: id,
token,
proposed,
});
}
}
PropertyEvent::Changed {
id,
previous,
current,
} => {
self.refresh_property_editor(state, id)?;
self.queue_event(UiEvent::PropertyChanged {
widget_id: grid,
property: id,
previous,
value: current,
});
}
PropertyEvent::ChangeDenied { id, reason, .. } => {
self.refresh_property_editor(state, id)?;
self.queue_event(UiEvent::PropertyEditRejected {
widget_id: grid,
property: id,
reason: reason.as_str().to_owned(),
});
}
PropertyEvent::SelectionChanged { current, .. } => {
self.queue_event(UiEvent::PropertySelected {
widget_id: grid,
property: current,
});
}
_ => {}
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::properties::{PropertyEditor, PropertyModel};
use crate::test_support::MockBackend;
struct Fixture {
ui: Ui<MockBackend>,
grid: WidgetId,
title: PropertyId,
visible: PropertyId,
tint: PropertyId,
width: PropertyId,
opacity: PropertyId,
align: PropertyId,
borders: PropertyId,
due: PropertyId,
locked: PropertyId,
layout: PropertyId,
}
fn fixture() -> Fixture {
let mut model = PropertyModel::new();
let appearance = model.add_category(None, "Appearance").unwrap();
let title = model
.add_property(
Some(appearance),
"Title",
PropertyEditor::Text,
PropertyValue::Text("Untitled".into()),
)
.unwrap();
let visible = model
.add_property(
Some(appearance),
"Visible",
PropertyEditor::Checkbox,
PropertyValue::Bool(true),
)
.unwrap();
let tint = model
.add_property(
Some(appearance),
"Tint",
PropertyEditor::Color,
PropertyValue::Color(Color::rgb(0x41, 0x69, 0xE1)),
)
.unwrap();
let layout = model.add_category(None, "Layout").unwrap();
let width = model
.add_property(
Some(layout),
"Width",
PropertyEditor::Numeric,
PropertyValue::Int(320),
)
.unwrap();
let opacity = model
.add_property(
Some(layout),
"Opacity",
PropertyEditor::Numeric,
PropertyValue::Float(0.5),
)
.unwrap();
let align = model
.add_property(
Some(layout),
"Align",
PropertyEditor::Choice,
PropertyValue::Enum {
selected: 0,
options: vec!["Start".into(), "Center".into(), "End".into()],
},
)
.unwrap();
let borders = model
.add_property(
Some(layout),
"Borders",
PropertyEditor::Choice,
PropertyValue::Flags {
selected: vec![0],
options: vec!["Top".into(), "Bottom".into()],
},
)
.unwrap();
let due = model
.add_property(
Some(layout),
"Due",
PropertyEditor::Date,
PropertyValue::Date("2026-12-04".into()),
)
.unwrap();
let locked = model
.add_property(
Some(layout),
"Id",
PropertyEditor::Text,
PropertyValue::Text("node-7".into()),
)
.unwrap();
model.set_read_only(locked, true).unwrap();
let mut ui = Ui::new(MockBackend::default());
let window = ui.create(WidgetKind::Window, Some("Grid")).unwrap();
let grid = ui.create_property_grid(model).unwrap();
ui.attach(window, grid).unwrap();
Fixture {
ui,
grid,
title,
visible,
tint,
width,
opacity,
align,
borders,
due,
locked,
layout,
}
}
fn editor(f: &Fixture, id: PropertyId) -> WidgetId {
f.ui.property_grid_editor(f.grid, id).unwrap().unwrap()
}
fn user(f: &mut Fixture, event: UiEvent) -> Vec<UiEvent> {
f.ui.backend_mut().push_event(event);
let mut events = Vec::new();
while let Some(event) = f.ui.poll_event().unwrap() {
events.push(event);
}
events
}
fn grid_events(events: &[UiEvent]) -> Vec<UiEvent> {
events
.iter()
.filter(|event| {
matches!(
event,
UiEvent::PropertyChanged { .. }
| UiEvent::PropertyChanging { .. }
| UiEvent::PropertyEditRejected { .. }
| UiEvent::PropertySelected { .. }
)
})
.cloned()
.collect()
}
#[test]
fn builds_one_native_editor_per_property_inside_category_frames() {
let f = fixture();
let kinds = [
(f.title, WidgetKind::TextInput),
(f.visible, WidgetKind::Checkbox),
(f.tint, WidgetKind::ColorDialog),
(f.width, WidgetKind::TextInput),
(f.opacity, WidgetKind::TextInput),
(f.align, WidgetKind::ComboBox),
(f.borders, WidgetKind::MultiSelect),
(f.due, WidgetKind::DatePicker),
];
for (id, kind) in kinds {
let spec = f.ui.widget(editor(&f, id)).unwrap();
assert_eq!(spec.kind, kind, "editor kind for {id}");
}
let frame = f.ui.property_grid_row(f.grid, f.layout).unwrap().unwrap();
assert_eq!(f.ui.widget(frame).unwrap().kind, WidgetKind::GroupBox);
assert_eq!(f.ui.widget(frame).unwrap().text.as_deref(), Some("Layout"));
assert_eq!(f.ui.text(editor(&f, f.width)).unwrap(), "320");
assert_eq!(f.ui.text(editor(&f, f.tint)).unwrap(), "#4169E1");
assert!(f.ui.is_checked(editor(&f, f.visible)).unwrap());
assert_eq!(
f.ui.widget(editor(&f, f.borders)).unwrap().selected_indices,
vec![0]
);
assert_eq!(
f.ui.widget(editor(&f, f.due))
.unwrap()
.date_value
.as_deref(),
Some("2026-12-04")
);
let locked = f.ui.widget(editor(&f, f.locked)).unwrap();
assert_eq!(
locked.enabled,
Some(false),
"read-only rows are not editable"
);
assert!(f.ui.is_property_grid(f.grid));
}
#[test]
fn user_edits_become_property_changed_events() {
let mut f = fixture();
let check = editor(&f, f.visible);
let events = user(
&mut f,
UiEvent::Toggled {
widget_id: check,
checked: false,
},
);
assert_eq!(
grid_events(&events),
vec![UiEvent::PropertyChanged {
widget_id: f.grid,
property: f.visible,
previous: PropertyValue::Bool(true),
value: PropertyValue::Bool(false),
}]
);
let model = f.ui.property_grid_model(f.grid).unwrap();
assert_eq!(model.value(f.visible), Some(&PropertyValue::Bool(false)));
assert!(model.is_modified(f.visible));
let combo = editor(&f, f.align);
let events = user(
&mut f,
UiEvent::SelectionChanged {
widget_id: combo,
selected: Some("End".into()),
index: Some(2),
},
);
assert!(matches!(
grid_events(&events).as_slice(),
[UiEvent::PropertyChanged {
value: PropertyValue::Enum { selected: 2, .. },
..
}]
));
let list = editor(&f, f.borders);
let events = user(
&mut f,
UiEvent::MultiSelectionChanged {
widget_id: list,
indices: vec![1, 0],
},
);
assert!(matches!(
grid_events(&events).as_slice(),
[UiEvent::PropertyChanged { value: PropertyValue::Flags { selected, .. }, .. }]
if selected == &vec![0, 1]
));
let date = editor(&f, f.due);
let events = user(
&mut f,
UiEvent::DateChanged {
widget_id: date,
iso_date: "2027-01-15".into(),
},
);
assert!(matches!(
grid_events(&events).as_slice(),
[UiEvent::PropertyChanged { value: PropertyValue::Date(date), .. }] if date == "2027-01-15"
));
let color = editor(&f, f.tint);
let events = user(
&mut f,
UiEvent::ColorSelected {
widget_id: color,
color: Some(Rgba::rgb(255, 0, 0)),
},
);
assert!(matches!(
grid_events(&events).as_slice(),
[UiEvent::PropertyChanged { value: PropertyValue::Color(c), .. }] if *c == Color::rgb(255, 0, 0)
));
assert_eq!(f.ui.text(color).unwrap(), "#FF0000");
let events = user(
&mut f,
UiEvent::ColorSelected {
widget_id: color,
color: None,
},
);
assert!(grid_events(&events).is_empty());
}
#[test]
fn text_editors_parse_on_submit_and_on_focus_loss() {
let mut f = fixture();
let width = editor(&f, f.width);
let events = user(
&mut f,
UiEvent::TextSubmitted {
widget_id: width,
text: "wide".into(),
},
);
assert!(matches!(
grid_events(&events).as_slice(),
[UiEvent::PropertyEditRejected { property, .. }] if *property == f.width
));
assert_eq!(f.ui.text(width).unwrap(), "320", "editor restored");
assert_eq!(
f.ui.property_grid_model(f.grid).unwrap().value(f.width),
Some(&PropertyValue::Int(320))
);
let events = user(
&mut f,
UiEvent::TextSubmitted {
widget_id: width,
text: " 480 ".into(),
},
);
assert!(matches!(
grid_events(&events).as_slice(),
[UiEvent::PropertyChanged {
value: PropertyValue::Int(480),
..
}]
));
assert_eq!(
f.ui.text(width).unwrap(),
"480",
"editor shows the stored form"
);
let opacity = editor(&f, f.opacity);
user(
&mut f,
UiEvent::TextChanged {
widget_id: opacity,
text: "0.75".into(),
},
);
let events = user(
&mut f,
UiEvent::FocusChanged {
widget_id: opacity,
focused: false,
},
);
assert!(matches!(
grid_events(&events).as_slice(),
[UiEvent::PropertyChanged { value: PropertyValue::Float(v), .. }] if *v == 0.75
));
let events = user(
&mut f,
UiEvent::FocusChanged {
widget_id: opacity,
focused: false,
},
);
assert!(grid_events(&events).is_empty());
}
#[test]
fn enter_commits_and_escape_restores_text_editors() {
let mut f = fixture();
let title = editor(&f, f.title);
user(
&mut f,
UiEvent::TextChanged {
widget_id: title,
text: "Draft".into(),
},
);
let escape = UiEvent::KeyDown {
widget_id: title,
key: "Escape".into(),
ctrl: false,
shift: false,
alt: false,
};
assert!(grid_events(&user(&mut f, escape)).is_empty());
assert_eq!(f.ui.text(title).unwrap(), "Untitled");
user(
&mut f,
UiEvent::TextChanged {
widget_id: title,
text: "Report".into(),
},
);
let enter = UiEvent::KeyDown {
widget_id: title,
key: "Enter".into(),
ctrl: false,
shift: false,
alt: false,
};
assert!(matches!(
grid_events(&user(&mut f, enter)).as_slice(),
[UiEvent::PropertyChanged { value: PropertyValue::Text(t), .. }] if t == "Report"
));
}
#[test]
fn echoes_of_the_stored_value_are_silent() {
let mut f = fixture();
let check = editor(&f, f.visible);
let events = user(
&mut f,
UiEvent::Toggled {
widget_id: check,
checked: true,
},
);
assert!(grid_events(&events).is_empty());
assert!(!f
.ui
.property_grid_model(f.grid)
.unwrap()
.is_modified(f.visible));
}
#[test]
fn read_only_rows_reject_edits_that_reach_them() {
let mut f = fixture();
let locked = editor(&f, f.locked);
let events = user(
&mut f,
UiEvent::TextSubmitted {
widget_id: locked,
text: "other".into(),
},
);
assert!(matches!(
grid_events(&events).as_slice(),
[UiEvent::PropertyEditRejected { property, .. }] if *property == f.locked
));
assert_eq!(f.ui.text(locked).unwrap(), "node-7");
}
#[test]
fn veto_mode_waits_for_the_application() {
let mut f = fixture();
f.ui.set_property_grid_veto(f.grid, true).unwrap();
let title = editor(&f, f.title);
let events = user(
&mut f,
UiEvent::TextSubmitted {
widget_id: title,
text: "Draft".into(),
},
);
let token = match grid_events(&events).as_slice() {
[UiEvent::PropertyChanging {
token, proposed, ..
}] => {
assert_eq!(proposed, &PropertyValue::Text("Draft".into()));
*token
}
other => panic!("expected one PropertyChanging, got {other:?}"),
};
assert_eq!(
f.ui.property_grid_model(f.grid).unwrap().value(f.title),
Some(&PropertyValue::Text("Untitled".into()))
);
f.ui.resolve_property_change(f.grid, token, true).unwrap();
let events: Vec<_> = std::iter::from_fn(|| f.ui.poll_event().unwrap()).collect();
assert!(matches!(
grid_events(&events).as_slice(),
[UiEvent::PropertyChanged { value: PropertyValue::Text(t), .. }] if t == "Draft"
));
assert!(
f.ui.resolve_property_change(f.grid, token, true).is_err(),
"tokens are one-shot"
);
let events = user(
&mut f,
UiEvent::TextSubmitted {
widget_id: title,
text: "Final".into(),
},
);
let Some(UiEvent::PropertyChanging { token, .. }) = grid_events(&events).pop() else {
panic!("expected a staged change");
};
f.ui.resolve_property_change(f.grid, token, false).unwrap();
let events: Vec<_> = std::iter::from_fn(|| f.ui.poll_event().unwrap()).collect();
assert!(matches!(
grid_events(&events).as_slice(),
[UiEvent::PropertyEditRejected { reason, .. }] if reason == "vetoed"
));
assert_eq!(
f.ui.text(title).unwrap(),
"Draft",
"editor shows the stored value"
);
}
#[test]
fn programmatic_updates_are_silent_and_refresh_editors_in_place() {
let mut f = fixture();
let width = editor(&f, f.width);
f.ui.set_property_grid_value(f.grid, f.width, PropertyValue::Int(99))
.unwrap();
assert_eq!(f.ui.text(width).unwrap(), "99");
f.ui.update_property_grid(f.grid, |model| {
model
.set_value(f.visible, PropertyValue::Bool(false))
.unwrap();
model.set_enabled(f.title, false).unwrap();
})
.unwrap();
assert_eq!(
editor(&f, f.width),
width,
"value-only updates keep widgets"
);
assert!(!f.ui.is_checked(editor(&f, f.visible)).unwrap());
assert_eq!(
f.ui.widget(editor(&f, f.title)).unwrap().enabled,
Some(false)
);
let events: Vec<_> = std::iter::from_fn(|| f.ui.poll_event().unwrap()).collect();
assert!(grid_events(&events).is_empty());
assert!(f
.ui
.set_property_grid_value(f.grid, f.locked, PropertyValue::Text("x".into()))
.is_err());
}
#[test]
fn structure_changes_rebuild_rows() {
let mut f = fixture();
let layout = f.layout;
let added =
f.ui.update_property_grid(f.grid, |model| {
model.add_property(
Some(layout),
"Height",
PropertyEditor::Numeric,
PropertyValue::Uint(200),
)
})
.unwrap()
.unwrap();
assert_eq!(f.ui.text(editor(&f, added)).unwrap(), "200");
f.ui.set_property_expanded(f.grid, f.layout, false).unwrap();
assert!(f
.ui
.property_grid_editor(f.grid, f.width)
.unwrap()
.is_none());
assert!(f.ui.property_grid_row(f.grid, f.layout).unwrap().is_some());
f.ui.set_property_expanded(f.grid, f.layout, true).unwrap();
assert!(f
.ui
.property_grid_editor(f.grid, f.width)
.unwrap()
.is_some());
let before = f.ui.widget_count();
f.ui.set_property_grid_projection(f.grid, ProjectionMode::CategoryFree)
.unwrap();
assert!(f.ui.property_grid_row(f.grid, f.layout).unwrap().is_none());
assert_eq!(
f.ui.widget_count(),
before - 2,
"two category frames dropped"
);
assert_eq!(
f.ui.property_grid_projection(f.grid).unwrap(),
ProjectionMode::CategoryFree
);
f.ui.set_property_grid_projection(f.grid, ProjectionMode::Categorized)
.unwrap();
assert_eq!(f.ui.widget_count(), before);
}
#[test]
fn focus_selects_and_label_width_applies() {
let mut f = fixture();
let title = editor(&f, f.title);
let events = user(
&mut f,
UiEvent::FocusChanged {
widget_id: title,
focused: true,
},
);
assert_eq!(
grid_events(&events),
vec![UiEvent::PropertySelected {
widget_id: f.grid,
property: Some(f.title),
}]
);
f.ui.set_property_grid_label_width(f.grid, 200).unwrap();
assert_eq!(f.ui.property_grid_label_width(f.grid).unwrap(), 200);
let label = f.ui.property_grids.grids[&f.grid].rows[&f.title]
.label
.unwrap();
assert_eq!(
f.ui.layout_style(label).unwrap().size.width,
crate::layout::Dimension::Length(200.0)
);
assert!(f.ui.set_property_grid_label_width(f.grid, 0).is_err());
}
#[test]
fn removing_the_grid_forgets_its_editors() {
let mut f = fixture();
let check = editor(&f, f.visible);
f.ui.remove(f.grid).unwrap();
assert!(!f.ui.is_property_grid(f.grid));
assert!(f.ui.property_grid_model(f.grid).is_err());
f.ui.backend_mut().push_event(UiEvent::Toggled {
widget_id: check,
checked: false,
});
while f.ui.poll_event().unwrap().is_some() {}
}
#[test]
fn a_model_with_only_an_empty_category_builds() {
let mut ui = Ui::new(MockBackend::default());
let mut model = PropertyModel::new();
model.add_category(None, "Empty").unwrap();
assert!(ui.create_property_grid(model).is_ok());
}
#[test]
fn text_round_trips_for_every_value_type() {
let values = [
PropertyValue::Text("a b".into()),
PropertyValue::Int(-5),
PropertyValue::Uint(7),
PropertyValue::Float(1.25),
PropertyValue::Bool(true),
PropertyValue::Color(Color::rgb(1, 2, 255)),
PropertyValue::Path("/tmp/x".into()),
PropertyValue::Date("2026-01-02".into()),
PropertyValue::Enum {
selected: 1,
options: vec!["a".into(), "b".into()],
},
PropertyValue::Flags {
selected: vec![0, 2],
options: vec!["x".into(), "y".into(), "z".into()],
},
PropertyValue::Aggregate(vec![PropertyValue::Int(3), PropertyValue::Float(4.5)]),
];
for value in values {
let text = format_property_value(&value);
assert_eq!(
parse_property_text(&value, &text),
Ok(value.clone()),
"{text}"
);
}
assert!(parse_property_text(&PropertyValue::Uint(1), "-1").is_err());
assert!(parse_property_text(&PropertyValue::Float(1.0), "inf").is_err());
assert!(parse_property_text(&PropertyValue::Color(Color::rgb(0, 0, 0)), "#12345").is_err());
assert!(parse_property_text(
&PropertyValue::Aggregate(vec![PropertyValue::Int(1)]),
"1, 2"
)
.is_err());
}
}