1use std::fmt;
16
17#[cfg(feature = "property-grid")]
18use crate::error::GuiError;
19use crate::error::GuiResult;
20use crate::ui::{Backend, Ui};
21use crate::WidgetId;
22
23#[cfg(feature = "property-grid")]
24use crate::properties::{PropertyId, PropertyModel, PropertyValue};
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
28#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
29pub enum AdvancedFamily {
30 PropertyGrid,
32 StyledText,
34 WebView,
36}
37
38impl AdvancedFamily {
39 pub const fn as_str(self) -> &'static str {
41 match self {
42 Self::PropertyGrid => "property_grid",
43 Self::StyledText => "styled_text",
44 Self::WebView => "webview",
45 }
46 }
47}
48
49#[derive(Debug, Clone, PartialEq, Eq)]
54#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
55pub struct EngineInfo {
56 pub name: String,
58 pub version: String,
60}
61
62#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct AdvancedHostCapabilities {
65 pub supported: bool,
67 pub portable: bool,
69 pub engine: Option<EngineInfo>,
71 pub decisions: DecisionCounters,
73}
74
75impl AdvancedHostCapabilities {
76 pub const fn unsupported() -> Self {
78 Self {
79 supported: false,
80 portable: false,
81 engine: None,
82 decisions: DecisionCounters::new(),
83 }
84 }
85}
86
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum DecisionOutcome {
90 Allowed,
92 Denied {
95 timed_out: bool,
97 },
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
102pub struct DecisionCounters {
103 pub requested: u32,
105 pub allowed: u32,
107 pub denied: u32,
109 pub timed_out: u32,
111}
112
113impl DecisionCounters {
114 pub const fn new() -> Self {
116 Self {
117 requested: 0,
118 allowed: 0,
119 denied: 0,
120 timed_out: 0,
121 }
122 }
123
124 pub fn record_request(&mut self) {
126 self.requested = self.requested.saturating_add(1);
127 }
128
129 pub fn record(&mut self, outcome: DecisionOutcome) {
131 match outcome {
132 DecisionOutcome::Allowed => self.allowed = self.allowed.saturating_add(1),
133 DecisionOutcome::Denied { timed_out: false } => {
134 self.denied = self.denied.saturating_add(1);
135 }
136 DecisionOutcome::Denied { timed_out: true } => {
137 self.denied = self.denied.saturating_add(1);
138 self.timed_out = self.timed_out.saturating_add(1);
139 }
140 }
141 }
142}
143
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
153pub struct DecisionToken {
154 id: OperationId,
155}
156
157impl DecisionToken {
158 pub const fn new(id: OperationId) -> Self {
160 Self { id }
161 }
162
163 pub const fn id(&self) -> OperationId {
165 self.id
166 }
167
168 pub fn decide(self, allowed: bool) -> DecisionOutcome {
170 if allowed {
171 DecisionOutcome::Allowed
172 } else {
173 DecisionOutcome::Denied { timed_out: false }
174 }
175 }
176
177 pub fn timeout(self) -> DecisionOutcome {
179 DecisionOutcome::Denied { timed_out: true }
180 }
181
182 pub fn resolve(self) -> DecisionOutcome {
184 DecisionOutcome::Denied { timed_out: false }
185 }
186}
187
188#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
193#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
194pub struct OperationId(pub u64);
195
196impl fmt::Display for OperationId {
197 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198 write!(f, "{}", self.0)
199 }
200}
201
202impl<B: Backend> Ui<B> {
203 #[cfg(any(feature = "property-grid", feature = "webview"))]
205 pub(crate) fn allocate_operation_id(&mut self) -> OperationId {
206 let id = OperationId(self.next_operation_id);
207 self.next_operation_id = self.next_operation_id.saturating_add(1);
208 self.pending_operations.insert(id);
209 id
210 }
211
212 pub fn operation_pending(&self, id: OperationId) -> bool {
214 self.pending_operations.contains(&id)
215 }
216
217 pub fn cancel_operation(&mut self, id: OperationId) -> bool {
220 self.pending_operations.remove(&id)
221 }
222
223 pub fn complete_operation(&mut self, id: OperationId) -> bool {
226 self.pending_operations.remove(&id)
227 }
228
229 pub fn host_advanced_control(
231 &mut self,
232 host: WidgetId,
233 family: AdvancedFamily,
234 ) -> GuiResult<AdvancedHostCapabilities> {
235 self.backend_mut().host_advanced_control(host, family)
236 }
237}
238
239#[cfg(feature = "property-grid")]
241#[derive(Debug, Clone, PartialEq, Eq)]
242pub struct PropertyGridCapabilities {
243 pub supported: bool,
245 pub portable: bool,
247 pub engine: Option<EngineInfo>,
249 pub native_editors: bool,
251 pub virtualization: bool,
253}
254
255#[cfg(feature = "property-grid")]
261pub trait PropertyGridBackend: Backend {
262 fn property_grid_capabilities(&self) -> PropertyGridCapabilities;
264 fn bind_property_model(&mut self, host: WidgetId, model: &PropertyModel) -> GuiResult<()>;
266 fn set_property_value(
268 &mut self,
269 host: WidgetId,
270 id: PropertyId,
271 value: &PropertyValue,
272 ) -> GuiResult<()>;
273 fn refresh_property_grid(&mut self, host: WidgetId) -> GuiResult<()>;
275}
276
277#[cfg(feature = "property-grid")]
278impl<B: Backend + PropertyGridBackend> Ui<B> {
279 pub fn property_grid_capabilities(&self) -> PropertyGridCapabilities {
281 self.backend().property_grid_capabilities()
282 }
283
284 pub fn bind_property_model(
287 &mut self,
288 host: WidgetId,
289 model: &PropertyModel,
290 ) -> GuiResult<OperationId> {
291 if self.widget(host).is_none() {
292 return Err(GuiError::WidgetNotFound(host.0));
293 }
294 self.backend_mut().bind_property_model(host, model)?;
295 Ok(self.allocate_operation_id())
296 }
297
298 pub fn set_property_value(
300 &mut self,
301 host: WidgetId,
302 id: PropertyId,
303 value: &PropertyValue,
304 ) -> GuiResult<()> {
305 self.backend_mut().set_property_value(host, id, value)
306 }
307
308 pub fn begin_batch(&mut self) -> BatchScope<'_, B> {
313 BatchScope {
314 ui: self,
315 mutations: 0,
316 entries: Vec::new(),
317 index: std::collections::HashMap::new(),
318 hosts: Vec::new(),
319 }
320 }
321}
322
323#[cfg(feature = "property-grid")]
325pub struct BatchScope<'a, B: Backend + PropertyGridBackend> {
326 ui: &'a mut Ui<B>,
327 mutations: usize,
328 entries: Vec<(WidgetId, PropertyId, PropertyValue)>,
329 index: std::collections::HashMap<(u64, u64), usize>,
330 hosts: Vec<WidgetId>,
331}
332
333#[cfg(feature = "property-grid")]
334impl<'a, B: Backend + PropertyGridBackend> BatchScope<'a, B> {
335 pub fn set_property_value(&mut self, host: WidgetId, id: PropertyId, value: PropertyValue) {
338 self.mutations = self.mutations.saturating_add(1);
339 let key = (host.0, id.0);
340 match self.index.get(&key) {
341 Some(&position) => self.entries[position].2 = value,
342 None => {
343 self.index.insert(key, self.entries.len());
344 if !self.hosts.contains(&host) {
345 self.hosts.push(host);
346 }
347 self.entries.push((host, id, value));
348 }
349 }
350 }
351
352 pub fn mutations(&self) -> usize {
354 self.mutations
355 }
356
357 pub fn distinct_nodes(&self) -> usize {
359 self.entries.len()
360 }
361
362 pub fn commit(self) -> GuiResult<BatchReport> {
365 let BatchScope {
366 ui,
367 mutations,
368 entries,
369 hosts,
370 ..
371 } = self;
372 let applied_nodes = entries.len();
373 for (host, id, value) in entries {
374 ui.backend_mut().set_property_value(host, id, &value)?;
375 }
376 for host in &hosts {
377 ui.backend_mut().refresh_property_grid(*host)?;
378 }
379 Ok(BatchReport {
380 mutations,
381 applied_nodes,
382 refreshed_hosts: hosts.len(),
383 })
384 }
385}
386
387#[cfg(feature = "property-grid")]
389#[derive(Debug, Clone, Copy, PartialEq, Eq)]
390pub struct BatchReport {
391 pub mutations: usize,
393 pub applied_nodes: usize,
395 pub refreshed_hosts: usize,
397}
398
399#[cfg(test)]
400mod tests {
401 use super::*;
402
403 #[test]
404 fn decision_token_defaults_to_deny() {
405 let token = DecisionToken::new(OperationId(7));
406 assert_eq!(token.id(), OperationId(7));
407 assert_eq!(
408 token.resolve(),
409 DecisionOutcome::Denied { timed_out: false },
410 "an undecided token denies"
411 );
412
413 let token = DecisionToken::new(OperationId(8));
414 assert_eq!(token.decide(true), DecisionOutcome::Allowed);
415
416 let token = DecisionToken::new(OperationId(9));
417 assert_eq!(
418 token.decide(false),
419 DecisionOutcome::Denied { timed_out: false }
420 );
421
422 let token = DecisionToken::new(OperationId(10));
423 assert_eq!(token.timeout(), DecisionOutcome::Denied { timed_out: true });
424 }
425
426 #[test]
427 fn decision_counters_record_outcomes() {
428 let mut counters = DecisionCounters::default();
429 counters.record_request();
430 counters.record(DecisionOutcome::Allowed);
431 assert_eq!(counters.requested, 1);
432 assert_eq!(counters.allowed, 1);
433 counters.record_request();
434 counters.record(DecisionOutcome::Denied { timed_out: false });
435 assert_eq!(counters.denied, 1);
436 assert_eq!(counters.timed_out, 0);
437 counters.record(DecisionOutcome::Denied { timed_out: true });
438 assert_eq!(counters.denied, 2);
439 assert_eq!(counters.timed_out, 1);
440 }
441
442 #[test]
443 fn advanced_family_identifiers_are_stable() {
444 assert_eq!(AdvancedFamily::PropertyGrid.as_str(), "property_grid");
445 assert_eq!(AdvancedFamily::StyledText.as_str(), "styled_text");
446 assert_eq!(AdvancedFamily::WebView.as_str(), "webview");
447 }
448
449 #[test]
450 fn unsupported_host_capabilities_default_to_none() {
451 let caps = AdvancedHostCapabilities::unsupported();
452 assert!(!caps.supported);
453 assert!(!caps.portable);
454 assert!(caps.engine.is_none());
455 assert_eq!(caps.decisions, DecisionCounters::new());
456 }
457
458 #[cfg(feature = "property-grid")]
459 mod property_grid {
460 use super::*;
461 use crate::properties::{PropertyEditor, PropertyValue};
462 use crate::test_support::MockBackend;
463 use crate::{Ui, WidgetKind};
464
465 fn ui_with_window() -> (Ui<MockBackend>, WidgetId) {
466 let mut ui = Ui::new(MockBackend::default());
467 let window = ui
468 .create(WidgetKind::Window, Some("Advanced spike"))
469 .expect("window creates");
470 ui.show(window).expect("window shows");
471 (ui, window)
472 }
473
474 fn sample_model() -> (PropertyModel, PropertyId, PropertyId, PropertyId) {
475 let mut model = PropertyModel::new();
476 let width = model
477 .add_property(
478 None,
479 "Width",
480 PropertyEditor::Numeric,
481 PropertyValue::Int(10),
482 )
483 .unwrap();
484 let height = model
485 .add_property(
486 None,
487 "Height",
488 PropertyEditor::Numeric,
489 PropertyValue::Int(20),
490 )
491 .unwrap();
492 let name = model
493 .add_property(
494 None,
495 "Name",
496 PropertyEditor::Text,
497 PropertyValue::Text("x".to_owned()),
498 )
499 .unwrap();
500 (model, width, height, name)
501 }
502
503 #[test]
504 fn hosting_supports_property_grid_and_rejects_unknown_hosts() {
505 let (mut ui, window) = ui_with_window();
506 let caps = ui
507 .host_advanced_control(window, AdvancedFamily::PropertyGrid)
508 .expect("hosts property grid");
509 assert!(caps.supported);
510 assert!(caps.portable);
511 assert!(caps.engine.is_none());
512
513 ui.host_advanced_control(window, AdvancedFamily::PropertyGrid)
514 .expect("hosting is idempotent");
515 assert_eq!(ui.backend().advanced_hosts.len(), 1);
516
517 let unknown = ui.host_advanced_control(WidgetId(9999), AdvancedFamily::PropertyGrid);
518 assert!(matches!(unknown, Err(GuiError::WidgetNotFound(_))));
519
520 let styled = ui.host_advanced_control(window, AdvancedFamily::StyledText);
521 assert!(matches!(styled, Err(GuiError::UnsupportedCapability(_))));
522 }
523
524 #[test]
525 fn capabilities_report_portable_mock_and_engine_override() {
526 let (mut ui, window) = ui_with_window();
527 let caps = ui.property_grid_capabilities();
528 assert!(caps.supported);
529 assert!(caps.portable);
530 assert!(caps.engine.is_none(), "the Mock tier is engine-free");
531 assert!(!caps.native_editors);
532 assert!(!caps.virtualization);
533
534 ui.backend_mut().advanced_engine = Some(EngineInfo {
535 name: "MockGrid".to_owned(),
536 version: "1.0".to_owned(),
537 });
538 let caps = ui.property_grid_capabilities();
539 assert_eq!(
540 caps.engine.as_ref().map(|engine| engine.name.as_str()),
541 Some("MockGrid"),
542 "engine records are reported verbatim"
543 );
544
545 let host_caps = ui
546 .host_advanced_control(window, AdvancedFamily::PropertyGrid)
547 .expect("hosts with engine");
548 assert!(host_caps.engine.is_some());
549 }
550
551 #[test]
552 fn operations_allocate_cancel_and_ignore_stale_ids() {
553 let (mut ui, window) = ui_with_window();
554 let (model, _, _, _) = sample_model();
555 let first = ui.bind_property_model(window, &model).expect("first bind");
556 let second = ui.bind_property_model(window, &model).expect("second bind");
557 assert_ne!(first, second, "ids are unique per Ui");
558 assert!(ui.operation_pending(first));
559 assert!(ui.cancel_operation(second));
560 assert!(!ui.cancel_operation(second), "cancellation is one-shot");
561 assert!(ui.complete_operation(first));
562 assert!(
563 !ui.complete_operation(first),
564 "stale completions answer false"
565 );
566 assert!(!ui.operation_pending(first));
567 }
568
569 #[test]
570 fn binding_unknown_hosts_and_unbound_values_fail_typed() {
571 let (mut ui, _window) = ui_with_window();
572 let (model, width, _, _) = sample_model();
573 let unknown = ui.bind_property_model(WidgetId(999), &model);
574 assert!(matches!(unknown, Err(GuiError::WidgetNotFound(_))));
575
576 let unbound = ui.set_property_value(WidgetId(999), width, &PropertyValue::Int(1));
577 assert!(matches!(unbound, Err(GuiError::UnsupportedCapability(_))));
578 }
579
580 #[test]
581 fn batch_coalesces_mutations_and_commits_final_state() {
582 let (mut ui, window) = ui_with_window();
583 let (model, width, height, name) = sample_model();
584 ui.bind_property_model(window, &model).expect("bind");
585
586 let mut scope = ui.begin_batch();
587 for round in 0..6 {
588 scope.set_property_value(window, width, PropertyValue::Int(10 + round));
589 scope.set_property_value(window, height, PropertyValue::Int(round));
590 }
591 scope.set_property_value(window, name, PropertyValue::Text("final".to_owned()));
592 assert_eq!(scope.mutations(), 13);
593 assert_eq!(scope.distinct_nodes(), 3);
594
595 let report = scope.commit().expect("batch commits");
596 assert_eq!(
597 report,
598 BatchReport {
599 mutations: 13,
600 applied_nodes: 3,
601 refreshed_hosts: 1
602 }
603 );
604 assert_eq!(
605 ui.backend().property_grid_applied.len(),
606 3,
607 "one call per node"
608 );
609 assert_eq!(
610 ui.backend().property_grid_refreshes.get(&window).copied(),
611 Some(1),
612 "one refresh per host"
613 );
614
615 let stored = ui
616 .backend()
617 .property_grid_models
618 .get(&window)
619 .expect("model bound");
620 assert_eq!(stored.value(width), Some(&PropertyValue::Int(15)));
621 assert_eq!(stored.value(height), Some(&PropertyValue::Int(5)));
622 assert_eq!(
623 stored.value(name),
624 Some(&PropertyValue::Text("final".to_owned())),
625 "final state after coalescing is observable"
626 );
627 }
628 }
629}