Skip to main content

native_gui_core/
advanced.rs

1//! Advanced-control substrate.
2//!
3//! The skeleton the advanced-control RFC (`docs/spikes/advanced-control-architecture-rfc.md`)
4//! specifies: the single defaulted base-`Backend` hosting hook, runtime
5//! capability records with engine reporting, per-`Ui` [`OperationId`]
6//! correlation, one-shot default-deny [`DecisionToken`]s with diagnostics
7//! counters, and the feature-gated `property-grid` family (extension trait
8//! plus typed facade and a coalescing `BatchScope`).
9//!
10//! The spike proves the pattern in Mock and on the Win32 lane; the GTK arm is
11//! a typed default for the Linux CI lane, and Cocoa adopts the shapes in its
12//! own rows. StyledText and WebView reuse these contracts when their rows
13//! land — the base `Backend` trait gains nothing beyond `host_advanced_control`.
14
15use 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/// The feature-gated advanced-control families.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
28#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
29pub enum AdvancedFamily {
30    /// Typed property inspection and editing (`property-grid`).
31    PropertyGrid,
32    /// Bounded Scintilla/Lexilla editing (`styled-text`).
33    StyledText,
34    /// System-engine web content (`webview`).
35    WebView,
36}
37
38impl AdvancedFamily {
39    /// Stable lowercase identifier used by capability errors and diagnostics.
40    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/// Native engine backing an advanced family, when one is used.
50///
51/// A version report is required whenever a capability record carries an
52/// engine, so bug reports and diagnostics pages can name the exact provider.
53#[derive(Debug, Clone, PartialEq, Eq)]
54#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
55pub struct EngineInfo {
56    /// Engine or provider name.
57    pub name: String,
58    /// Engine or provider version.
59    pub version: String,
60}
61
62/// Runtime capability record returned by `Backend::host_advanced_control`.
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct AdvancedHostCapabilities {
65    /// The family can be hosted on this lane.
66    pub supported: bool,
67    /// The family runs from the Rust-owned model without a native engine.
68    pub portable: bool,
69    /// Native engine backing the family, when one is used.
70    pub engine: Option<EngineInfo>,
71    /// Policy-decision diagnostics counters for the family.
72    pub decisions: DecisionCounters,
73}
74
75impl AdvancedHostCapabilities {
76    /// The default for lanes that cannot host a family.
77    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/// The outcome of a policy decision (`DecisionToken`).
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum DecisionOutcome {
90    /// The policy request was approved.
91    Allowed,
92    /// The policy request was rejected; `timed_out` distinguishes a timeout
93    /// from an explicit deny and from the default-deny of an undecided token.
94    Denied {
95        /// The decision was produced by a timeout.
96        timed_out: bool,
97    },
98}
99
100/// Per-family diagnostics counters for policy decisions.
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
102pub struct DecisionCounters {
103    /// Policy requests presented to the application.
104    pub requested: u32,
105    /// Requests answered `Allowed`.
106    pub allowed: u32,
107    /// Requests answered `Denied` (explicit or default).
108    pub denied: u32,
109    /// Requests denied by timeout.
110    pub timed_out: u32,
111}
112
113impl DecisionCounters {
114    /// Zeroed counters.
115    pub const fn new() -> Self {
116        Self {
117            requested: 0,
118            allowed: 0,
119            denied: 0,
120            timed_out: 0,
121        }
122    }
123
124    /// Records that a policy request was presented.
125    pub fn record_request(&mut self) {
126        self.requested = self.requested.saturating_add(1);
127    }
128
129    /// Records one resolved outcome.
130    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/// One-shot, default-deny policy decision handle.
145///
146/// The token is produced by a family when it needs an application decision
147/// (navigation, permission, download, validation veto). `decide` consumes the
148/// token, so an answer can be given exactly once; `resolve` of an undecided
149/// token denies, and a timeout resolves to `Denied { timed_out: true }`.
150/// Dropping the token without deciding can never allow the request — the
151/// token owns no state that could turn into `Allowed` afterwards.
152#[derive(Debug, Clone, Copy, PartialEq, Eq)]
153pub struct DecisionToken {
154    id: OperationId,
155}
156
157impl DecisionToken {
158    /// Creates a pending token correlated with `id`.
159    pub const fn new(id: OperationId) -> Self {
160        Self { id }
161    }
162
163    /// The correlated operation id.
164    pub const fn id(&self) -> OperationId {
165        self.id
166    }
167
168    /// Resolves the decision explicitly (consumes the token).
169    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    /// Resolves the decision on timeout (consumes the token).
178    pub fn timeout(self) -> DecisionOutcome {
179        DecisionOutcome::Denied { timed_out: true }
180    }
181
182    /// Resolves an undecided token: default deny (consumes the token).
183    pub fn resolve(self) -> DecisionOutcome {
184        DecisionOutcome::Denied { timed_out: false }
185    }
186}
187
188/// Opaque correlation id for asynchronous family operations.
189///
190/// Allocated by [`Ui`] (monotonic per instance) so two backends in one
191/// process cannot collide; apps never mint ids.
192#[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    /// Allocates the next operation id and marks it pending.
204    #[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    /// Whether the operation is still pending (allocated and not completed).
213    pub fn operation_pending(&self, id: OperationId) -> bool {
214        self.pending_operations.contains(&id)
215    }
216
217    /// Cancels a pending operation; reports `false` for unknown or already
218    /// finished ids (best-effort cancellation §7).
219    pub fn cancel_operation(&mut self, id: OperationId) -> bool {
220        self.pending_operations.remove(&id)
221    }
222
223    /// Marks an operation completed; reports `false` for stale ids, which
224    /// callers ignore instead of erroring.
225    pub fn complete_operation(&mut self, id: OperationId) -> bool {
226        self.pending_operations.remove(&id)
227    }
228
229    /// Calls the base hosting hook on the backend.
230    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/// Runtime capability record for the `property-grid` family.
240#[cfg(feature = "property-grid")]
241#[derive(Debug, Clone, PartialEq, Eq)]
242pub struct PropertyGridCapabilities {
243    /// The family can be hosted on this lane.
244    pub supported: bool,
245    /// The family runs from the Rust-owned model without a native engine.
246    pub portable: bool,
247    /// Native engine backing the family, when one is used.
248    pub engine: Option<EngineInfo>,
249    /// Native per-row editors are available (manifest group P3).
250    pub native_editors: bool,
251    /// Row virtualization is available (manifest group P10).
252    pub virtualization: bool,
253}
254
255/// Feature-gated backend contract for the PropertyGrid family.
256///
257/// Methods mirror the RFC: capability reporting, model binding, value
258/// application for one node, and a coalesced refresh. Operation ids are
259/// allocated by the [`Ui`] facade, so backend methods do not mint them.
260#[cfg(feature = "property-grid")]
261pub trait PropertyGridBackend: Backend {
262    /// Reports runtime capabilities for this lane.
263    fn property_grid_capabilities(&self) -> PropertyGridCapabilities;
264    /// Binds a Rust-owned model to a hosted control (host must be known).
265    fn bind_property_model(&mut self, host: WidgetId, model: &PropertyModel) -> GuiResult<()>;
266    /// Applies the bound model's current value for `id` to the native control.
267    fn set_property_value(
268        &mut self,
269        host: WidgetId,
270        id: PropertyId,
271        value: &PropertyValue,
272    ) -> GuiResult<()>;
273    /// Performs one coalesced refresh of the hosted control.
274    fn refresh_property_grid(&mut self, host: WidgetId) -> GuiResult<()>;
275}
276
277#[cfg(feature = "property-grid")]
278impl<B: Backend + PropertyGridBackend> Ui<B> {
279    /// Reports the backend's PropertyGrid capabilities.
280    pub fn property_grid_capabilities(&self) -> PropertyGridCapabilities {
281        self.backend().property_grid_capabilities()
282    }
283
284    /// Binds a Rust-owned model to a hosted control and returns the
285    /// correlation id of the binding operation.
286    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    /// Forwards one node's value to the backend (immediate mode).
299    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    /// Opens a coalescing batch scope.
309    ///
310    /// Queued mutations apply to the bound model on commit, one backend call
311    /// per distinct node plus one refresh per affected host.
312    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/// A coalescing mutation scope for the PropertyGrid family.
324#[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    /// Queues a value mutation; repeated mutations of the same node coalesce
336    /// to the last queued value while the first-seen order is preserved.
337    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    /// Total queued mutations (including coalesced repeats).
353    pub fn mutations(&self) -> usize {
354        self.mutations
355    }
356
357    /// Distinct nodes that will be applied on commit.
358    pub fn distinct_nodes(&self) -> usize {
359        self.entries.len()
360    }
361
362    /// Applies the coalesced final values and refreshes each affected host
363    /// exactly once.
364    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/// What one batch commit actually did.
388#[cfg(feature = "property-grid")]
389#[derive(Debug, Clone, Copy, PartialEq, Eq)]
390pub struct BatchReport {
391    /// Total queued mutations, including coalesced repeats.
392    pub mutations: usize,
393    /// Distinct nodes applied to the backend.
394    pub applied_nodes: usize,
395    /// Hosts refreshed once each.
396    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}