use std::fmt;
#[cfg(feature = "property-grid")]
use crate::error::GuiError;
use crate::error::GuiResult;
use crate::ui::{Backend, Ui};
use crate::WidgetId;
#[cfg(feature = "property-grid")]
use crate::properties::{PropertyId, PropertyModel, PropertyValue};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AdvancedFamily {
PropertyGrid,
StyledText,
WebView,
}
impl AdvancedFamily {
pub const fn as_str(self) -> &'static str {
match self {
Self::PropertyGrid => "property_grid",
Self::StyledText => "styled_text",
Self::WebView => "webview",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EngineInfo {
pub name: String,
pub version: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AdvancedHostCapabilities {
pub supported: bool,
pub portable: bool,
pub engine: Option<EngineInfo>,
pub decisions: DecisionCounters,
}
impl AdvancedHostCapabilities {
pub const fn unsupported() -> Self {
Self {
supported: false,
portable: false,
engine: None,
decisions: DecisionCounters::new(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DecisionOutcome {
Allowed,
Denied {
timed_out: bool,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct DecisionCounters {
pub requested: u32,
pub allowed: u32,
pub denied: u32,
pub timed_out: u32,
}
impl DecisionCounters {
pub const fn new() -> Self {
Self {
requested: 0,
allowed: 0,
denied: 0,
timed_out: 0,
}
}
pub fn record_request(&mut self) {
self.requested = self.requested.saturating_add(1);
}
pub fn record(&mut self, outcome: DecisionOutcome) {
match outcome {
DecisionOutcome::Allowed => self.allowed = self.allowed.saturating_add(1),
DecisionOutcome::Denied { timed_out: false } => {
self.denied = self.denied.saturating_add(1);
}
DecisionOutcome::Denied { timed_out: true } => {
self.denied = self.denied.saturating_add(1);
self.timed_out = self.timed_out.saturating_add(1);
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DecisionToken {
id: OperationId,
}
impl DecisionToken {
pub const fn new(id: OperationId) -> Self {
Self { id }
}
pub const fn id(&self) -> OperationId {
self.id
}
pub fn decide(self, allowed: bool) -> DecisionOutcome {
if allowed {
DecisionOutcome::Allowed
} else {
DecisionOutcome::Denied { timed_out: false }
}
}
pub fn timeout(self) -> DecisionOutcome {
DecisionOutcome::Denied { timed_out: true }
}
pub fn resolve(self) -> DecisionOutcome {
DecisionOutcome::Denied { timed_out: false }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OperationId(pub u64);
impl fmt::Display for OperationId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl<B: Backend> Ui<B> {
#[cfg(any(feature = "property-grid", feature = "webview"))]
pub(crate) fn allocate_operation_id(&mut self) -> OperationId {
let id = OperationId(self.next_operation_id);
self.next_operation_id = self.next_operation_id.saturating_add(1);
self.pending_operations.insert(id);
id
}
pub fn operation_pending(&self, id: OperationId) -> bool {
self.pending_operations.contains(&id)
}
pub fn cancel_operation(&mut self, id: OperationId) -> bool {
self.pending_operations.remove(&id)
}
pub fn complete_operation(&mut self, id: OperationId) -> bool {
self.pending_operations.remove(&id)
}
pub fn host_advanced_control(
&mut self,
host: WidgetId,
family: AdvancedFamily,
) -> GuiResult<AdvancedHostCapabilities> {
self.backend_mut().host_advanced_control(host, family)
}
}
#[cfg(feature = "property-grid")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PropertyGridCapabilities {
pub supported: bool,
pub portable: bool,
pub engine: Option<EngineInfo>,
pub native_editors: bool,
pub virtualization: bool,
}
#[cfg(feature = "property-grid")]
pub trait PropertyGridBackend: Backend {
fn property_grid_capabilities(&self) -> PropertyGridCapabilities;
fn bind_property_model(&mut self, host: WidgetId, model: &PropertyModel) -> GuiResult<()>;
fn set_property_value(
&mut self,
host: WidgetId,
id: PropertyId,
value: &PropertyValue,
) -> GuiResult<()>;
fn refresh_property_grid(&mut self, host: WidgetId) -> GuiResult<()>;
}
#[cfg(feature = "property-grid")]
impl<B: Backend + PropertyGridBackend> Ui<B> {
pub fn property_grid_capabilities(&self) -> PropertyGridCapabilities {
self.backend().property_grid_capabilities()
}
pub fn bind_property_model(
&mut self,
host: WidgetId,
model: &PropertyModel,
) -> GuiResult<OperationId> {
if self.widget(host).is_none() {
return Err(GuiError::WidgetNotFound(host.0));
}
self.backend_mut().bind_property_model(host, model)?;
Ok(self.allocate_operation_id())
}
pub fn set_property_value(
&mut self,
host: WidgetId,
id: PropertyId,
value: &PropertyValue,
) -> GuiResult<()> {
self.backend_mut().set_property_value(host, id, value)
}
pub fn begin_batch(&mut self) -> BatchScope<'_, B> {
BatchScope {
ui: self,
mutations: 0,
entries: Vec::new(),
index: std::collections::HashMap::new(),
hosts: Vec::new(),
}
}
}
#[cfg(feature = "property-grid")]
pub struct BatchScope<'a, B: Backend + PropertyGridBackend> {
ui: &'a mut Ui<B>,
mutations: usize,
entries: Vec<(WidgetId, PropertyId, PropertyValue)>,
index: std::collections::HashMap<(u64, u64), usize>,
hosts: Vec<WidgetId>,
}
#[cfg(feature = "property-grid")]
impl<'a, B: Backend + PropertyGridBackend> BatchScope<'a, B> {
pub fn set_property_value(&mut self, host: WidgetId, id: PropertyId, value: PropertyValue) {
self.mutations = self.mutations.saturating_add(1);
let key = (host.0, id.0);
match self.index.get(&key) {
Some(&position) => self.entries[position].2 = value,
None => {
self.index.insert(key, self.entries.len());
if !self.hosts.contains(&host) {
self.hosts.push(host);
}
self.entries.push((host, id, value));
}
}
}
pub fn mutations(&self) -> usize {
self.mutations
}
pub fn distinct_nodes(&self) -> usize {
self.entries.len()
}
pub fn commit(self) -> GuiResult<BatchReport> {
let BatchScope {
ui,
mutations,
entries,
hosts,
..
} = self;
let applied_nodes = entries.len();
for (host, id, value) in entries {
ui.backend_mut().set_property_value(host, id, &value)?;
}
for host in &hosts {
ui.backend_mut().refresh_property_grid(*host)?;
}
Ok(BatchReport {
mutations,
applied_nodes,
refreshed_hosts: hosts.len(),
})
}
}
#[cfg(feature = "property-grid")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BatchReport {
pub mutations: usize,
pub applied_nodes: usize,
pub refreshed_hosts: usize,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn decision_token_defaults_to_deny() {
let token = DecisionToken::new(OperationId(7));
assert_eq!(token.id(), OperationId(7));
assert_eq!(
token.resolve(),
DecisionOutcome::Denied { timed_out: false },
"an undecided token denies"
);
let token = DecisionToken::new(OperationId(8));
assert_eq!(token.decide(true), DecisionOutcome::Allowed);
let token = DecisionToken::new(OperationId(9));
assert_eq!(
token.decide(false),
DecisionOutcome::Denied { timed_out: false }
);
let token = DecisionToken::new(OperationId(10));
assert_eq!(token.timeout(), DecisionOutcome::Denied { timed_out: true });
}
#[test]
fn decision_counters_record_outcomes() {
let mut counters = DecisionCounters::default();
counters.record_request();
counters.record(DecisionOutcome::Allowed);
assert_eq!(counters.requested, 1);
assert_eq!(counters.allowed, 1);
counters.record_request();
counters.record(DecisionOutcome::Denied { timed_out: false });
assert_eq!(counters.denied, 1);
assert_eq!(counters.timed_out, 0);
counters.record(DecisionOutcome::Denied { timed_out: true });
assert_eq!(counters.denied, 2);
assert_eq!(counters.timed_out, 1);
}
#[test]
fn advanced_family_identifiers_are_stable() {
assert_eq!(AdvancedFamily::PropertyGrid.as_str(), "property_grid");
assert_eq!(AdvancedFamily::StyledText.as_str(), "styled_text");
assert_eq!(AdvancedFamily::WebView.as_str(), "webview");
}
#[test]
fn unsupported_host_capabilities_default_to_none() {
let caps = AdvancedHostCapabilities::unsupported();
assert!(!caps.supported);
assert!(!caps.portable);
assert!(caps.engine.is_none());
assert_eq!(caps.decisions, DecisionCounters::new());
}
#[cfg(feature = "property-grid")]
mod property_grid {
use super::*;
use crate::properties::{PropertyEditor, PropertyValue};
use crate::test_support::MockBackend;
use crate::{Ui, WidgetKind};
fn ui_with_window() -> (Ui<MockBackend>, WidgetId) {
let mut ui = Ui::new(MockBackend::default());
let window = ui
.create(WidgetKind::Window, Some("Advanced spike"))
.expect("window creates");
ui.show(window).expect("window shows");
(ui, window)
}
fn sample_model() -> (PropertyModel, PropertyId, PropertyId, PropertyId) {
let mut model = PropertyModel::new();
let width = model
.add_property(
None,
"Width",
PropertyEditor::Numeric,
PropertyValue::Int(10),
)
.unwrap();
let height = model
.add_property(
None,
"Height",
PropertyEditor::Numeric,
PropertyValue::Int(20),
)
.unwrap();
let name = model
.add_property(
None,
"Name",
PropertyEditor::Text,
PropertyValue::Text("x".to_owned()),
)
.unwrap();
(model, width, height, name)
}
#[test]
fn hosting_supports_property_grid_and_rejects_unknown_hosts() {
let (mut ui, window) = ui_with_window();
let caps = ui
.host_advanced_control(window, AdvancedFamily::PropertyGrid)
.expect("hosts property grid");
assert!(caps.supported);
assert!(caps.portable);
assert!(caps.engine.is_none());
ui.host_advanced_control(window, AdvancedFamily::PropertyGrid)
.expect("hosting is idempotent");
assert_eq!(ui.backend().advanced_hosts.len(), 1);
let unknown = ui.host_advanced_control(WidgetId(9999), AdvancedFamily::PropertyGrid);
assert!(matches!(unknown, Err(GuiError::WidgetNotFound(_))));
let styled = ui.host_advanced_control(window, AdvancedFamily::StyledText);
assert!(matches!(styled, Err(GuiError::UnsupportedCapability(_))));
}
#[test]
fn capabilities_report_portable_mock_and_engine_override() {
let (mut ui, window) = ui_with_window();
let caps = ui.property_grid_capabilities();
assert!(caps.supported);
assert!(caps.portable);
assert!(caps.engine.is_none(), "the Mock tier is engine-free");
assert!(!caps.native_editors);
assert!(!caps.virtualization);
ui.backend_mut().advanced_engine = Some(EngineInfo {
name: "MockGrid".to_owned(),
version: "1.0".to_owned(),
});
let caps = ui.property_grid_capabilities();
assert_eq!(
caps.engine.as_ref().map(|engine| engine.name.as_str()),
Some("MockGrid"),
"engine records are reported verbatim"
);
let host_caps = ui
.host_advanced_control(window, AdvancedFamily::PropertyGrid)
.expect("hosts with engine");
assert!(host_caps.engine.is_some());
}
#[test]
fn operations_allocate_cancel_and_ignore_stale_ids() {
let (mut ui, window) = ui_with_window();
let (model, _, _, _) = sample_model();
let first = ui.bind_property_model(window, &model).expect("first bind");
let second = ui.bind_property_model(window, &model).expect("second bind");
assert_ne!(first, second, "ids are unique per Ui");
assert!(ui.operation_pending(first));
assert!(ui.cancel_operation(second));
assert!(!ui.cancel_operation(second), "cancellation is one-shot");
assert!(ui.complete_operation(first));
assert!(
!ui.complete_operation(first),
"stale completions answer false"
);
assert!(!ui.operation_pending(first));
}
#[test]
fn binding_unknown_hosts_and_unbound_values_fail_typed() {
let (mut ui, _window) = ui_with_window();
let (model, width, _, _) = sample_model();
let unknown = ui.bind_property_model(WidgetId(999), &model);
assert!(matches!(unknown, Err(GuiError::WidgetNotFound(_))));
let unbound = ui.set_property_value(WidgetId(999), width, &PropertyValue::Int(1));
assert!(matches!(unbound, Err(GuiError::UnsupportedCapability(_))));
}
#[test]
fn batch_coalesces_mutations_and_commits_final_state() {
let (mut ui, window) = ui_with_window();
let (model, width, height, name) = sample_model();
ui.bind_property_model(window, &model).expect("bind");
let mut scope = ui.begin_batch();
for round in 0..6 {
scope.set_property_value(window, width, PropertyValue::Int(10 + round));
scope.set_property_value(window, height, PropertyValue::Int(round));
}
scope.set_property_value(window, name, PropertyValue::Text("final".to_owned()));
assert_eq!(scope.mutations(), 13);
assert_eq!(scope.distinct_nodes(), 3);
let report = scope.commit().expect("batch commits");
assert_eq!(
report,
BatchReport {
mutations: 13,
applied_nodes: 3,
refreshed_hosts: 1
}
);
assert_eq!(
ui.backend().property_grid_applied.len(),
3,
"one call per node"
);
assert_eq!(
ui.backend().property_grid_refreshes.get(&window).copied(),
Some(1),
"one refresh per host"
);
let stored = ui
.backend()
.property_grid_models
.get(&window)
.expect("model bound");
assert_eq!(stored.value(width), Some(&PropertyValue::Int(15)));
assert_eq!(stored.value(height), Some(&PropertyValue::Int(5)));
assert_eq!(
stored.value(name),
Some(&PropertyValue::Text("final".to_owned())),
"final state after coalescing is observable"
);
}
}
}