native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//! Advanced-control substrate.
//!
//! The skeleton the advanced-control RFC (`docs/spikes/advanced-control-architecture-rfc.md`)
//! specifies: the single defaulted base-`Backend` hosting hook, runtime
//! capability records with engine reporting, per-`Ui` [`OperationId`]
//! correlation, one-shot default-deny [`DecisionToken`]s with diagnostics
//! counters, and the feature-gated `property-grid` family (extension trait
//! plus typed facade and a coalescing `BatchScope`).
//!
//! The spike proves the pattern in Mock and on the Win32 lane; the GTK arm is
//! a typed default for the Linux CI lane, and Cocoa adopts the shapes in its
//! own rows. StyledText and WebView reuse these contracts when their rows
//! land — the base `Backend` trait gains nothing beyond `host_advanced_control`.

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};

/// The feature-gated advanced-control families.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AdvancedFamily {
    /// Typed property inspection and editing (`property-grid`).
    PropertyGrid,
    /// Bounded Scintilla/Lexilla editing (`styled-text`).
    StyledText,
    /// System-engine web content (`webview`).
    WebView,
}

impl AdvancedFamily {
    /// Stable lowercase identifier used by capability errors and diagnostics.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::PropertyGrid => "property_grid",
            Self::StyledText => "styled_text",
            Self::WebView => "webview",
        }
    }
}

/// Native engine backing an advanced family, when one is used.
///
/// A version report is required whenever a capability record carries an
/// engine, so bug reports and diagnostics pages can name the exact provider.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EngineInfo {
    /// Engine or provider name.
    pub name: String,
    /// Engine or provider version.
    pub version: String,
}

/// Runtime capability record returned by `Backend::host_advanced_control`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AdvancedHostCapabilities {
    /// The family can be hosted on this lane.
    pub supported: bool,
    /// The family runs from the Rust-owned model without a native engine.
    pub portable: bool,
    /// Native engine backing the family, when one is used.
    pub engine: Option<EngineInfo>,
    /// Policy-decision diagnostics counters for the family.
    pub decisions: DecisionCounters,
}

impl AdvancedHostCapabilities {
    /// The default for lanes that cannot host a family.
    pub const fn unsupported() -> Self {
        Self {
            supported: false,
            portable: false,
            engine: None,
            decisions: DecisionCounters::new(),
        }
    }
}

/// The outcome of a policy decision (`DecisionToken`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DecisionOutcome {
    /// The policy request was approved.
    Allowed,
    /// The policy request was rejected; `timed_out` distinguishes a timeout
    /// from an explicit deny and from the default-deny of an undecided token.
    Denied {
        /// The decision was produced by a timeout.
        timed_out: bool,
    },
}

/// Per-family diagnostics counters for policy decisions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct DecisionCounters {
    /// Policy requests presented to the application.
    pub requested: u32,
    /// Requests answered `Allowed`.
    pub allowed: u32,
    /// Requests answered `Denied` (explicit or default).
    pub denied: u32,
    /// Requests denied by timeout.
    pub timed_out: u32,
}

impl DecisionCounters {
    /// Zeroed counters.
    pub const fn new() -> Self {
        Self {
            requested: 0,
            allowed: 0,
            denied: 0,
            timed_out: 0,
        }
    }

    /// Records that a policy request was presented.
    pub fn record_request(&mut self) {
        self.requested = self.requested.saturating_add(1);
    }

    /// Records one resolved outcome.
    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);
            }
        }
    }
}

/// One-shot, default-deny policy decision handle.
///
/// The token is produced by a family when it needs an application decision
/// (navigation, permission, download, validation veto). `decide` consumes the
/// token, so an answer can be given exactly once; `resolve` of an undecided
/// token denies, and a timeout resolves to `Denied { timed_out: true }`.
/// Dropping the token without deciding can never allow the request — the
/// token owns no state that could turn into `Allowed` afterwards.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DecisionToken {
    id: OperationId,
}

impl DecisionToken {
    /// Creates a pending token correlated with `id`.
    pub const fn new(id: OperationId) -> Self {
        Self { id }
    }

    /// The correlated operation id.
    pub const fn id(&self) -> OperationId {
        self.id
    }

    /// Resolves the decision explicitly (consumes the token).
    pub fn decide(self, allowed: bool) -> DecisionOutcome {
        if allowed {
            DecisionOutcome::Allowed
        } else {
            DecisionOutcome::Denied { timed_out: false }
        }
    }

    /// Resolves the decision on timeout (consumes the token).
    pub fn timeout(self) -> DecisionOutcome {
        DecisionOutcome::Denied { timed_out: true }
    }

    /// Resolves an undecided token: default deny (consumes the token).
    pub fn resolve(self) -> DecisionOutcome {
        DecisionOutcome::Denied { timed_out: false }
    }
}

/// Opaque correlation id for asynchronous family operations.
///
/// Allocated by [`Ui`] (monotonic per instance) so two backends in one
/// process cannot collide; apps never mint ids.
#[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> {
    /// Allocates the next operation id and marks it pending.
    #[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
    }

    /// Whether the operation is still pending (allocated and not completed).
    pub fn operation_pending(&self, id: OperationId) -> bool {
        self.pending_operations.contains(&id)
    }

    /// Cancels a pending operation; reports `false` for unknown or already
    /// finished ids (best-effort cancellation §7).
    pub fn cancel_operation(&mut self, id: OperationId) -> bool {
        self.pending_operations.remove(&id)
    }

    /// Marks an operation completed; reports `false` for stale ids, which
    /// callers ignore instead of erroring.
    pub fn complete_operation(&mut self, id: OperationId) -> bool {
        self.pending_operations.remove(&id)
    }

    /// Calls the base hosting hook on the backend.
    pub fn host_advanced_control(
        &mut self,
        host: WidgetId,
        family: AdvancedFamily,
    ) -> GuiResult<AdvancedHostCapabilities> {
        self.backend_mut().host_advanced_control(host, family)
    }
}

/// Runtime capability record for the `property-grid` family.
#[cfg(feature = "property-grid")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PropertyGridCapabilities {
    /// The family can be hosted on this lane.
    pub supported: bool,
    /// The family runs from the Rust-owned model without a native engine.
    pub portable: bool,
    /// Native engine backing the family, when one is used.
    pub engine: Option<EngineInfo>,
    /// Native per-row editors are available (manifest group P3).
    pub native_editors: bool,
    /// Row virtualization is available (manifest group P10).
    pub virtualization: bool,
}

/// Feature-gated backend contract for the PropertyGrid family.
///
/// Methods mirror the RFC: capability reporting, model binding, value
/// application for one node, and a coalesced refresh. Operation ids are
/// allocated by the [`Ui`] facade, so backend methods do not mint them.
#[cfg(feature = "property-grid")]
pub trait PropertyGridBackend: Backend {
    /// Reports runtime capabilities for this lane.
    fn property_grid_capabilities(&self) -> PropertyGridCapabilities;
    /// Binds a Rust-owned model to a hosted control (host must be known).
    fn bind_property_model(&mut self, host: WidgetId, model: &PropertyModel) -> GuiResult<()>;
    /// Applies the bound model's current value for `id` to the native control.
    fn set_property_value(
        &mut self,
        host: WidgetId,
        id: PropertyId,
        value: &PropertyValue,
    ) -> GuiResult<()>;
    /// Performs one coalesced refresh of the hosted control.
    fn refresh_property_grid(&mut self, host: WidgetId) -> GuiResult<()>;
}

#[cfg(feature = "property-grid")]
impl<B: Backend + PropertyGridBackend> Ui<B> {
    /// Reports the backend's PropertyGrid capabilities.
    pub fn property_grid_capabilities(&self) -> PropertyGridCapabilities {
        self.backend().property_grid_capabilities()
    }

    /// Binds a Rust-owned model to a hosted control and returns the
    /// correlation id of the binding operation.
    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())
    }

    /// Forwards one node's value to the backend (immediate mode).
    pub fn set_property_value(
        &mut self,
        host: WidgetId,
        id: PropertyId,
        value: &PropertyValue,
    ) -> GuiResult<()> {
        self.backend_mut().set_property_value(host, id, value)
    }

    /// Opens a coalescing batch scope.
    ///
    /// Queued mutations apply to the bound model on commit, one backend call
    /// per distinct node plus one refresh per affected host.
    pub fn begin_batch(&mut self) -> BatchScope<'_, B> {
        BatchScope {
            ui: self,
            mutations: 0,
            entries: Vec::new(),
            index: std::collections::HashMap::new(),
            hosts: Vec::new(),
        }
    }
}

/// A coalescing mutation scope for the PropertyGrid family.
#[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> {
    /// Queues a value mutation; repeated mutations of the same node coalesce
    /// to the last queued value while the first-seen order is preserved.
    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));
            }
        }
    }

    /// Total queued mutations (including coalesced repeats).
    pub fn mutations(&self) -> usize {
        self.mutations
    }

    /// Distinct nodes that will be applied on commit.
    pub fn distinct_nodes(&self) -> usize {
        self.entries.len()
    }

    /// Applies the coalesced final values and refreshes each affected host
    /// exactly once.
    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(),
        })
    }
}

/// What one batch commit actually did.
#[cfg(feature = "property-grid")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BatchReport {
    /// Total queued mutations, including coalesced repeats.
    pub mutations: usize,
    /// Distinct nodes applied to the backend.
    pub applied_nodes: usize,
    /// Hosts refreshed once each.
    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"
            );
        }
    }
}