incular-runtime 0.1.1

Application runtime and scheduling foundations for Incular
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
use crate::TransientPresentationResolution;
use crate::application_shell::ApplicationShellService;
use crate::application_types::ApplicationLifecycle;
use crate::application_types::{RestorableWindowMetadata, WindowError, WindowRestorationId};
use crate::context::BuildContext;
use crate::environment::{
    BuildScope, BuildScopeGuard, EnvironmentFields, InitialBuildDependencies, ReactiveQueue,
};
use crate::file_dialogs::{FileDialogBridge, FileDialogService};
use crate::frame::Runtime;
use crate::global_shortcuts::GlobalShortcutBridge;
use crate::profiling::{FrameRecord, GpuSample, RenderFrameMetrics};
use crate::restoration;
use crate::tasks::{self, TaskScope};
use crate::window_commands::{
    DisplayCatalog, NativeWindowCommand, WindowCommandBridge, WindowHandle,
};
use incular_accessibility::AccessibilityDiagnostics;
use incular_config::{Constraints, ContentSensitivity, RuntimeEnvironment, WindowSizePolicy};
use incular_core::{RestorationKey, RestorationScope, Size};
use incular_platform::{
    PlatformCapabilities, PlatformOperationError, WindowId, WindowLifecycle, WindowMetrics,
    WindowObservedState, WindowOptions, WindowRequestedState,
};
use incular_widgets::Widget;
use std::{
    cell::{Cell, RefCell},
    collections::{HashSet, VecDeque},
    rc::{Rc, Weak},
    sync::{Arc, RwLock},
};

/// Debug-facing, native-free state of one retained application window.
#[derive(Clone, Debug, PartialEq)]
pub struct WindowDiagnostics {
    pub id: WindowId,
    pub title: String,
    pub logical_size: incular_core::Size,
    pub physical_size: incular_platform::PhysicalSize,
    pub scale_factor: f64,
    pub visible: bool,
    pub native_focused: bool,
    pub lifecycle: WindowLifecycle,
    /// Application-wide runtime lifecycle inherited from the native adapter.
    /// This is intentionally separate from the window-local visibility/focus
    /// lifecycle above.
    pub application_lifecycle: ApplicationLifecycle,
    pub frame_requested: bool,
    pub requested_frames: u64,
    pub presented_frames: u64,
    pub skipped_frames: u64,
    pub input_events: u64,
    pub surface_generation: u64,
    /// Effective retained-tree capture policy at the last diagnostics read.
    pub content_sensitivity: ContentSensitivity,
    pub elements: usize,
    pub render_objects: usize,
    pub semantics: usize,
    /// Adapter health for this window only. It contains no native IDs or text
    /// values, and remains zero when no desktop accessibility adapter exists.
    pub accessibility: AccessibilityDiagnostics,
    /// Native backend capabilities currently published for this window.
    pub capabilities: PlatformCapabilities,
    /// Most recent native operation failure, if any. The stable error category
    /// is suitable for diagnostics; no native error object is retained.
    pub last_platform_error: Option<PlatformOperationError>,
    /// Last application-requested mutable native state.
    pub requested_state: WindowRequestedState,
    /// State most recently observed from the native backend. Unknown fields are
    /// `None` rather than copied from requested state.
    pub observed_state: WindowObservedState,
    /// Resolved native-vs-overlay presentation for every currently visible
    /// semantic transient in this window.
    pub transient_presentations: Vec<TransientPresentationResolution>,
}

/// Aggregate lifecycle and stale-command diagnostics for an application.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ApplicationDiagnostics {
    pub windows_created: u64,
    pub windows_closed: u64,
    pub active_windows: usize,
    pub stale_window_commands: u64,
    pub pending_native_requests: usize,
    pub pending_file_dialog_requests: usize,
}

pub(crate) struct WindowRecord {
    pub(crate) runtime: Runtime,
    pub(crate) scope: TaskScope,
    pub(crate) last_frame: FrameRecord,
    pub(crate) render_metrics: RenderFrameMetrics,
    pub(crate) gpu_sample: Option<GpuSample>,
    pub(crate) options: WindowOptions,
    pub(crate) lifecycle: WindowLifecycle,
    pub(crate) metrics: WindowMetrics,
    pub(crate) native_focused: bool,
    pub(crate) requested_frames: u64,
    pub(crate) presented_frames: u64,
    pub(crate) skipped_frames: u64,
    pub(crate) input_events: u64,
    pub(crate) surface_generation: u64,
    pub(crate) accessibility: AccessibilityDiagnostics,
    pub(crate) last_content_sensitivity: Option<ContentSensitivity>,
    pub(crate) content_sizing: ContentSizeCoordinator,
    pub(crate) restoration: Option<RestorableWindowMetadata>,
    pub(crate) _restoration_scope_lease: Option<restoration::ScopeLease>,
    pub(crate) capabilities: Arc<RwLock<PlatformCapabilities>>,
    pub(crate) last_platform_error: Option<PlatformOperationError>,
    pub(crate) requested_state: WindowRequestedState,
    pub(crate) observed_state: Arc<RwLock<WindowObservedState>>,
    pub(crate) transient_presentations: Arc<RwLock<Vec<TransientPresentationResolution>>>,
}

/// Window-local negotiation state for content-driven native sizing.
///
/// The retained root layout produces a logical target, while the native host
/// remains asynchronous. Paint-only overflow (including transient overlays,
/// shadows, and filters) is deliberately excluded. Remembering the outstanding target prevents redraws from
/// flooding the event loop with identical resize requests before metrics catch
/// up.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct ContentSizeCoordinator {
    pending: Option<Size>,
}

impl ContentSizeCoordinator {
    pub(crate) fn layout_constraints(
        options: &WindowOptions,
        viewport_constraints: Constraints,
    ) -> Constraints {
        if options.size_policy != WindowSizePolicy::Content {
            return viewport_constraints;
        }
        let minimum = content_minimum(options);
        let (maximum_width, maximum_height) = options
            .maximum_logical_size
            .map_or((f32::INFINITY, f32::INFINITY), |maximum| {
                (maximum.width, maximum.height)
            });
        Constraints::new(
            minimum.width,
            maximum_width.max(minimum.width),
            minimum.height,
            maximum_height.max(minimum.height),
        )
    }

    pub(crate) fn reconcile(
        &mut self,
        options: &WindowOptions,
        metrics: WindowMetrics,
        root_layout_size: Option<Size>,
    ) -> Option<Size> {
        if options.size_policy != WindowSizePolicy::Content {
            self.pending = None;
            return None;
        }

        let minimum = content_minimum(options);
        let extent = root_layout_size.unwrap_or(Size::ZERO);
        let mut target = Size::new(
            minimum.width.max(extent.width),
            minimum.height.max(extent.height),
        );
        if let Some(maximum) = options.maximum_logical_size {
            target.width = target.width.min(maximum.width);
            target.height = target.height.min(maximum.height);
        }
        target = snap_outward_to_physical_pixels(target, metrics.scale_factor);
        if let Some(maximum) = options.maximum_logical_size {
            target.width = target.width.min(maximum.width);
            target.height = target.height.min(maximum.height);
        }

        let current = metrics.logical_size();
        if equivalent_logical_size(target, current, metrics.scale_factor) {
            self.pending = None;
            return None;
        }
        if self
            .pending
            .is_some_and(|pending| equivalent_logical_size(pending, target, metrics.scale_factor))
        {
            return None;
        }
        self.pending = Some(target);
        Some(target)
    }

    pub(crate) fn reset(&mut self) {
        self.pending = None;
    }
}

fn content_minimum(options: &WindowOptions) -> Size {
    let declared = options.minimum_logical_size.unwrap_or(Size::ZERO);
    Size::new(
        options.initial_logical_size.width.max(declared.width),
        options.initial_logical_size.height.max(declared.height),
    )
}

fn snap_outward_to_physical_pixels(size: Size, scale_factor: f64) -> Size {
    let scale = if scale_factor.is_finite() && scale_factor > 0.0 {
        scale_factor as f32
    } else {
        1.0
    };
    Size::new(
        (size.width * scale).ceil() / scale,
        (size.height * scale).ceil() / scale,
    )
}

fn equivalent_logical_size(left: Size, right: Size, scale_factor: f64) -> bool {
    let scale = if scale_factor.is_finite() && scale_factor > 0.0 {
        scale_factor as f32
    } else {
        1.0
    };
    let tolerance = 0.5 / scale + f32::EPSILON;
    (left.width - right.width).abs() <= tolerance && (left.height - right.height).abs() <= tolerance
}

pub(crate) struct WindowSlot {
    pub(crate) generation: u32,
    pub(crate) reserved: bool,
    pub(crate) retired: bool,
    pub(crate) record: Option<WindowRecord>,
}

#[derive(Default)]
pub(crate) struct WindowRegistry {
    pub(crate) slots: Vec<WindowSlot>,
    pub(crate) windows_created: u64,
    pub(crate) windows_closed: u64,
    pub(crate) stale_window_commands: u64,
}

impl WindowRegistry {
    pub(crate) fn reserve(&mut self) -> WindowId {
        if let Some((index, slot)) = self
            .slots
            .iter_mut()
            .enumerate()
            .find(|(_, slot)| !slot.retired && !slot.reserved && slot.record.is_none())
        {
            slot.reserved = true;
            return WindowId::from_parts(
                u32::try_from(index).expect("window index was validated on insertion"),
                slot.generation,
            );
        }
        let index = u32::try_from(self.slots.len()).expect("window identity space exhausted");
        self.slots.push(WindowSlot {
            generation: 0,
            reserved: true,
            retired: false,
            record: None,
        });
        WindowId::from_parts(index, 0)
    }

    pub(crate) fn insert(&mut self, id: WindowId, record: WindowRecord) {
        let slot = &mut self.slots[id.index() as usize];
        debug_assert!(slot.reserved && slot.generation == id.generation());
        slot.record = Some(record);
        self.windows_created += 1;
    }

    pub(crate) fn take(&mut self, id: WindowId) -> Option<WindowRecord> {
        self.slots
            .get_mut(id.index() as usize)
            .filter(|slot| slot.reserved && slot.generation == id.generation())?
            .record
            .take()
    }

    pub(crate) fn restore(&mut self, id: WindowId, record: WindowRecord) {
        let slot = &mut self.slots[id.index() as usize];
        debug_assert!(slot.reserved && slot.generation == id.generation());
        debug_assert!(slot.record.is_none());
        slot.record = Some(record);
    }

    pub(crate) fn close(&mut self, id: WindowId) -> Option<WindowRecord> {
        let slot = self
            .slots
            .get_mut(id.index() as usize)
            .filter(|slot| slot.reserved && slot.generation == id.generation())?;
        let record = slot.record.take()?;
        slot.reserved = false;
        if let Some(next_generation) = slot.generation.checked_add(1) {
            slot.generation = next_generation;
        } else {
            slot.retired = true;
        }
        self.windows_closed += 1;
        Some(record)
    }

    pub(crate) fn ids(&self) -> Vec<WindowId> {
        self.slots
            .iter()
            .enumerate()
            .filter_map(|(index, slot)| {
                slot.record.as_ref().map(|_| {
                    WindowId::from_parts(
                        u32::try_from(index).expect("window index was validated on insertion"),
                        slot.generation,
                    )
                })
            })
            .collect()
    }

    pub(crate) fn contains(&self, id: WindowId) -> bool {
        self.slots.get(id.index() as usize).is_some_and(|slot| {
            slot.reserved && slot.generation == id.generation() && slot.record.is_some()
        })
    }

    #[cfg_attr(not(feature = "devtools"), allow(dead_code))]
    pub(crate) fn get(&self, id: WindowId) -> Option<&WindowRecord> {
        self.slots
            .get(id.index() as usize)
            .filter(|slot| slot.reserved && slot.generation == id.generation())?
            .record
            .as_ref()
    }

    pub(crate) fn visible_count(&self) -> usize {
        self.slots
            .iter()
            .filter_map(|slot| slot.record.as_ref())
            .filter(|record| record.options.visible)
            .count()
    }
}

#[derive(Clone)]
pub(crate) struct WindowManager {
    pub(crate) registry: Weak<RefCell<WindowRegistry>>,
    pub(crate) scheduler: Rc<RefCell<tasks::TaskScheduler>>,
    pub(crate) bridge: Arc<WindowCommandBridge>,
    pub(crate) file_dialog_bridge: Arc<FileDialogBridge>,
    pub(crate) global_shortcut_bridge: Arc<GlobalShortcutBridge>,
    pub(crate) application_shell: ApplicationShellService,
    pub(crate) native_commands: Rc<RefCell<VecDeque<NativeWindowCommand>>>,
    pub(crate) restoration: Option<restoration::RestorationManager>,
    pub(crate) application_capabilities: Arc<RwLock<PlatformCapabilities>>,
    pub(crate) displays: Arc<RwLock<DisplayCatalog>>,
    pub(crate) application_lifecycle: Rc<Cell<ApplicationLifecycle>>,
}

impl WindowManager {
    pub(crate) fn open_window(
        &self,
        options: WindowOptions,
        root: Widget,
    ) -> Result<WindowHandle, WindowError> {
        self.open_window_inner(options, root, None)
    }

    pub(crate) fn open_window_inner(
        &self,
        mut options: WindowOptions,
        root: Widget,
        restoration: Option<RestorableWindowMetadata>,
    ) -> Result<WindowHandle, WindowError> {
        self.apply_restored_window_options(&mut options, restoration.as_ref());
        options.validate()?;
        let registry = self
            .registry
            .upgrade()
            .ok_or(WindowError::ApplicationStopped)?;
        let restoration_lease = self.acquire_restoration_scope(restoration.as_ref())?;
        let id = registry.borrow_mut().reserve();
        let scope = tasks::TaskScheduler::spawner(&self.scheduler).scope();
        scope.bind_window(id);
        let mut runtime = Runtime::with_window(
            root,
            self.scheduler.clone(),
            Some(id),
            scope,
            Some(self.clone()),
        )?;
        runtime.lifecycle = self.application_lifecycle.get();
        runtime.update_window_metrics(initial_metrics(&options));
        Ok(self.install_window(id, runtime, options, restoration, restoration_lease))
    }

    pub(crate) fn open_window_with(
        &self,
        options: WindowOptions,
        build: impl FnMut(&mut BuildContext) -> Widget + 'static,
    ) -> Result<WindowHandle, WindowError> {
        self.open_window_with_inner(options, build, None)
    }

    pub(crate) fn open_restorable_window_with(
        &self,
        restoration_id: WindowRestorationId,
        kind: impl Into<String>,
        options: WindowOptions,
        build: impl FnMut(&mut BuildContext) -> Widget + 'static,
    ) -> Result<WindowHandle, WindowError> {
        self.open_window_with_inner(
            options,
            build,
            Some(RestorableWindowMetadata::new(restoration_id, kind)?),
        )
    }

    pub(crate) fn open_window_with_inner(
        &self,
        mut options: WindowOptions,
        build: impl FnMut(&mut BuildContext) -> Widget + 'static,
        restoration: Option<RestorableWindowMetadata>,
    ) -> Result<WindowHandle, WindowError> {
        self.apply_restored_window_options(&mut options, restoration.as_ref());
        options.validate()?;
        let registry = self
            .registry
            .upgrade()
            .ok_or(WindowError::ApplicationStopped)?;
        let restoration_scope = self.restoration_scope(restoration.as_ref());
        let restoration_lease = self.acquire_restoration_scope(restoration.as_ref())?;
        let id = registry.borrow_mut().reserve();
        let spawner = tasks::TaskScheduler::spawner_for(&self.scheduler, id);
        let window_scope = spawner.scope();
        window_scope.bind_window(id);
        let root_scope = window_scope.child();
        let metrics = initial_metrics(&options);
        let initial_environment = RuntimeEnvironment {
            viewport: metrics.logical_size(),
            physical_width: metrics.physical_size.width,
            physical_height: metrics.physical_size.height,
            scale_factor: metrics.scale_factor,
            ..RuntimeEnvironment::default()
        };
        let environment = Rc::new(RefCell::new(initial_environment));
        let environment_dependencies = Rc::new(Cell::new(EnvironmentFields::empty()));
        let build = Rc::new(RefCell::new(build));
        let reactive = ReactiveQueue::new();
        let initial_dependencies = Rc::new(RefCell::new(InitialBuildDependencies::default()));
        let mut build_context = BuildContext::new(
            spawner.clone(),
            root_scope.clone(),
            environment.clone(),
            environment_dependencies.clone(),
            Some(self.clone()),
            restoration_scope.clone(),
        );
        let initial = {
            let _build_scope = BuildScopeGuard::enter(BuildScope {
                root: reactive.borrow().root,
                element: None,
                queue: Rc::downgrade(&reactive),
                initial_dependencies: Some(initial_dependencies.clone()),
                spawner: spawner.clone(),
                owner_scope: root_scope.clone(),
            });
            incular_core::hot_reload::call_with(&mut *build.borrow_mut(), &mut build_context)
        };
        let mut runtime = Runtime::with_window_and_reactive(
            initial,
            self.scheduler.clone(),
            Some(id),
            window_scope.clone(),
            Some(self.clone()),
            reactive,
        )?;
        runtime.environment = environment;
        runtime.environment_dependencies = environment_dependencies;
        let root = runtime.tree().root().expect("new runtime has root");
        root_scope.bind_owner(root);
        runtime.install_initial_dependencies(root, initial_dependencies);
        let closure = build.clone();
        let builder_spawner = spawner.clone();
        let builder_scope = root_scope.clone();
        let builder_environment = runtime.environment.clone();
        let builder_dependencies = runtime.environment_dependencies.clone();
        let builder_manager = self.clone();
        runtime.register_builder_without_rebuild(root, move || {
            let mut context = BuildContext::new(
                builder_spawner.clone(),
                builder_scope.clone(),
                builder_environment.clone(),
                builder_dependencies.clone(),
                Some(builder_manager.clone()),
                restoration_scope.clone(),
            );
            // The retained root builder is the hot-patch entry point: every
            // rebuild resolves the application's newest build function.
            incular_core::hot_reload::call_with(&mut *closure.borrow_mut(), &mut context)
        })?;
        runtime.application_root = Some(root);
        runtime.owner_scopes.insert(root, root_scope);
        // A native application adapter owns the transition out of `Starting`.
        // Do not guess foreground/activity state while constructing a retained
        // root before the OS event loop has attached.
        runtime.lifecycle = self.application_lifecycle.get();
        Ok(self.install_window(id, runtime, options, restoration, restoration_lease))
    }

    pub(crate) fn adopt_runtime(&self, mut runtime: Runtime) -> WindowId {
        let registry = self
            .registry
            .upgrade()
            .expect("application owns its registry");
        let id = registry.borrow_mut().reserve();
        runtime.window_id = Some(id);
        runtime.window_manager = Some(self.clone());
        runtime.window_scope.bind_window(id);
        for scope in runtime.owner_scopes.values() {
            scope.bind_window(id);
        }
        self.install_window(id, runtime, WindowOptions::default(), None, None)
            .id()
    }

    fn install_window(
        &self,
        id: WindowId,
        runtime: Runtime,
        options: WindowOptions,
        restoration: Option<RestorableWindowMetadata>,
        restoration_lease: Option<restoration::ScopeLease>,
    ) -> WindowHandle {
        let registry = self
            .registry
            .upgrade()
            .expect("application owns its registry");
        let window_scope = runtime.window_scope.clone();
        let metrics = initial_metrics(&options);
        let capabilities = Arc::new(RwLock::new(
            *self
                .application_capabilities
                .read()
                .expect("application capability snapshot lock"),
        ));
        let observed_state = Arc::new(RwLock::new(WindowObservedState::default()));
        let transient_presentations = Arc::new(RwLock::new(Vec::new()));
        let requested_state = options
            .requested_state()
            .expect("WindowOptions were validated before requested-state construction");
        registry.borrow_mut().insert(
            id,
            WindowRecord {
                runtime,
                scope: window_scope,
                last_frame: FrameRecord::default(),
                render_metrics: RenderFrameMetrics::default(),
                gpu_sample: None,
                lifecycle: if options.visible {
                    WindowLifecycle::Visible
                } else {
                    WindowLifecycle::Hidden
                },
                metrics,
                options: options.clone(),
                native_focused: false,
                requested_frames: 0,
                presented_frames: 0,
                skipped_frames: 0,
                input_events: 0,
                surface_generation: 1,
                accessibility: AccessibilityDiagnostics::default(),
                last_content_sensitivity: None,
                content_sizing: ContentSizeCoordinator::default(),
                restoration,
                _restoration_scope_lease: restoration_lease,
                capabilities: capabilities.clone(),
                last_platform_error: None,
                requested_state,
                observed_state: observed_state.clone(),
                transient_presentations: transient_presentations.clone(),
            },
        );
        self.sync_restorable_windows(true);
        self.native_commands
            .borrow_mut()
            .push_back(NativeWindowCommand::Create {
                window_id: id,
                options,
            });
        WindowHandle {
            id,
            bridge: self.bridge.clone(),
            file_dialogs: FileDialogService::new(
                id,
                self.file_dialog_bridge.clone(),
                capabilities.clone(),
            ),
            capabilities,
            observed_state,
            displays: self.displays.clone(),
            transient_presentations,
        }
    }

    pub(crate) fn handle(&self, id: WindowId) -> Option<WindowHandle> {
        let registry = self.registry.upgrade()?;
        let (capabilities, observed_state, transient_presentations) = {
            let registry = registry.borrow();
            let record = registry.get(id)?;
            (
                record.capabilities.clone(),
                record.observed_state.clone(),
                record.transient_presentations.clone(),
            )
        };
        Some(WindowHandle {
            id,
            bridge: self.bridge.clone(),
            file_dialogs: FileDialogService::new(
                id,
                self.file_dialog_bridge.clone(),
                capabilities.clone(),
            ),
            capabilities,
            observed_state,
            displays: self.displays.clone(),
            transient_presentations,
        })
    }

    pub(crate) fn send_window_operation(
        &self,
        id: WindowId,
        operation: incular_platform::WindowOperation,
    ) -> bool {
        self.bridge
            .send(incular_platform::WindowCommand::new(id, operation))
            .is_ok()
    }

    pub(crate) fn restoration_scope(
        &self,
        restoration: Option<&RestorableWindowMetadata>,
    ) -> Option<RestorationScope> {
        self.restoration.as_ref().map(|manager| {
            let root = manager.scope();
            restoration.map_or_else(
                || manager.application_scope(),
                |metadata| {
                    root.child_unchecked(RestorationKey::new("window").expect("static key"))
                        .child_unchecked(metadata.id.0.clone())
                },
            )
        })
    }

    pub(crate) fn acquire_restoration_scope(
        &self,
        restoration: Option<&RestorableWindowMetadata>,
    ) -> Result<Option<restoration::ScopeLease>, WindowError> {
        let Some(metadata) = restoration else {
            return Ok(None);
        };
        let Some(manager) = &self.restoration else {
            return Ok(None);
        };
        let path = [
            RestorationKey::new("window").expect("static key"),
            metadata.id.0.clone(),
        ];
        manager
            .acquire_scope(&path)
            .map(Some)
            .map_err(WindowError::Restoration)
    }

    pub(crate) fn apply_restored_window_options(
        &self,
        options: &mut WindowOptions,
        restoration: Option<&RestorableWindowMetadata>,
    ) {
        let Some(metadata) = restoration else {
            return;
        };
        let Some(manager) = &self.restoration else {
            return;
        };
        let Some(saved) = manager
            .windows()
            .into_iter()
            .find(|saved| saved.restoration_id == metadata.id.as_key().as_str())
        else {
            return;
        };
        if saved.kind != metadata.kind {
            return;
        }
        let saved_size = incular_core::Size::new(saved.logical_width, saved.logical_height);
        if saved_size.width.is_finite()
            && saved_size.height.is_finite()
            && saved_size.width > 0.0
            && saved_size.height > 0.0
        {
            let minimum = options
                .minimum_logical_size
                .unwrap_or(incular_core::Size::ZERO);
            let maximum = options.maximum_logical_size;
            options.initial_logical_size = incular_core::Size::new(
                saved_size
                    .width
                    .clamp(minimum.width, maximum.map_or(f32::MAX, |size| size.width)),
                saved_size
                    .height
                    .clamp(minimum.height, maximum.map_or(f32::MAX, |size| size.height)),
            );
        }
        options.maximized = saved.maximized;
        options.fullscreen = saved
            .fullscreen
            .then_some(incular_platform::Fullscreen::Borderless);
        manager.note_restored_window();
    }

    pub(crate) fn sync_restorable_windows(&self, retain_unopened: bool) {
        let Some(manager) = &self.restoration else {
            return;
        };
        let Some(registry) = self.registry.upgrade() else {
            return;
        };
        let active_windows = registry
            .borrow()
            .slots
            .iter()
            .filter_map(|slot| slot.record.as_ref())
            .filter_map(|record| {
                let metadata = record.restoration.as_ref()?;
                // Content-driven expansion is derived presentation state.
                // Persist the stable application baseline instead; transient
                // overlays are a separate surface concern and never contribute
                // to top-level content sizing. Explicit SetLogicalSize updates
                // the baseline before synchronization reaches this point.
                let logical = if record.options.size_policy == WindowSizePolicy::Content {
                    record.options.initial_logical_size
                } else {
                    record.metrics.logical_size()
                };
                Some(restoration::RestoredWindow {
                    restoration_id: metadata.id.as_key().as_str().to_owned(),
                    kind: metadata.kind.clone(),
                    logical_width: logical.width,
                    logical_height: logical.height,
                    maximized: record.options.maximized,
                    fullscreen: record.options.fullscreen.is_some(),
                })
            })
            .collect::<Vec<_>>();
        let windows = if retain_unopened {
            let active_ids = active_windows
                .iter()
                .map(|window| window.restoration_id.clone())
                .collect::<HashSet<_>>();
            manager
                .windows()
                .into_iter()
                .filter(|window| !active_ids.contains(&window.restoration_id))
                .chain(active_windows)
                .collect()
        } else {
            active_windows
        };
        manager.replace_windows(windows);
    }
}

pub(crate) fn initial_metrics(options: &WindowOptions) -> WindowMetrics {
    WindowMetrics::new(
        incular_platform::PhysicalSize::new(
            options.initial_logical_size.width.ceil() as u32,
            options.initial_logical_size.height.ceil() as u32,
        ),
        incular_config::ApplicationDefaults::DEFAULT.scale_factor,
    )
}