Skip to main content

cranpose_app_shell/
surface.rs

1//! Root surfaces: what the shell keeps per window.
2//!
3//! The composition is one tree. Each window the app shows is a root in that
4//! tree: the composition root for the primary window, a node carrying
5//! `Modifier::window_root` for every other. A [`RootSurface`] is the shell's
6//! bookkeeping for one such root: the renderer that draws it, the viewport it
7//! draws into, the pointer that hovers it, the gesture it tracks, the
8//! snapshots a test or a platform reads for it, and the dirt that says whether
9//! it owes the display a frame. A [`SurfaceMut`] borrows one surface together
10//! with the app, which is how a platform delivers a window's events and reads
11//! a window's frame.
12
13use std::{fmt::Debug, rc::Rc};
14
15use cranpose_core::{
16    MemoryApplier, NodeId, NodeMarks, SceneNodeAttachmentScratch,
17    collections::{growth_slack::GrowthSlack, map::HashSet},
18};
19use cranpose_foundation::{
20    PointerButton, PointerButtons, PointerId, PointerSource, RotaryScrollEvent,
21};
22use cranpose_render_common::{NodeUpdate, RenderScene, Renderer};
23use cranpose_ui::{
24    LayoutNode, LayoutTree, MovedSceneNode, PlatformTextInputHandler, SemanticsTree,
25    pointer_icon_session::PointerIconState,
26};
27use cranpose_ui_graphics::{Point, PointerIcon, Size};
28
29use crate::{
30    AppShell, FramePacingMode, FrameRatePreference, FrameSchedule, FrameScheduler,
31    FrameUpdateResult, PlatformFrameDriver, ShellApp, hit_path_tracker::HitPathTracker,
32    shell_frame::DevOverlay, shell_input::extra_pointers::IndependentPointers,
33};
34
35mod text_input_routes;
36pub(crate) use text_input_routes::{TextInputRouter, TextInputRoutes};
37
38/// Names a root surface of the app: the primary window, or a window root
39/// declared with [`Modifier::window_root`](cranpose_ui::Modifier::window_root)
40/// by the id given there.
41#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
42pub enum RootId {
43    /// The composition root, drawn in the app's first window.
44    Primary,
45    /// The node carrying `Modifier::window_root`.
46    Window(NodeId),
47}
48
49/// The shell's bookkeeping for one root.
50///
51/// The primary surface draws the composition root. A window surface draws the
52/// window root node registered under its id, and draws nothing while that
53/// node is not in the tree. Everything here is what an OS owns per window:
54/// the framebuffer, the viewport, the pointer, the cursor image, the soft
55/// keyboard, the frame the window is asked for.
56pub struct RootSurface<R: Renderer> {
57    pub(crate) id: RootId,
58    pub(crate) root: Option<NodeId>,
59    pub(crate) renderer: R,
60    pub(crate) cursor: (f32, f32),
61    pub(crate) viewport: (f32, f32),
62    pub(crate) buffer_size: (u32, u32),
63    pub(crate) layout_tree: Option<LayoutTree>,
64    pub(crate) semantics_tree: Option<SemanticsTree>,
65    /// A layout pass ran since `semantics_tree` was brought up to date, so
66    /// its bounds may be out of date though no node marked its semantics.
67    semantics_moved: bool,
68    // The scene's count of layer moves when the semantics revision last
69    // looked: a layer that moves moves the window bounds of what it holds.
70    seen_layer_moves: u64,
71    pub(crate) modal_focus: Vec<(NodeId, Option<NodeId>)>,
72    // The frames the surface started, counted by `begin_frame`.
73    pub(crate) frames: u64,
74    // The frame count at which a navigation key last moved focus; a held
75    // key's repeats wait for the next frame, so they never queue moves
76    // behind a slow layout. A count, not the frame time: Android draws its
77    // frames with `update_without_frame`, which leaves the time unchanged.
78    pub(crate) key_moved_focus_at: Option<u64>,
79    // Whether a D-pad drives the window, and whether the next update checks
80    // for a focused target with no layout of its own.
81    pub(crate) dpad_navigation: bool,
82    pub(crate) focus_check_due: bool,
83    // The press a click key holds until it comes up.
84    pub(crate) key_press: Option<crate::shell_input::key_activation::KeyPress>,
85    pub(crate) frame_rate_preference: FrameRatePreference,
86    pub(crate) scene_dirty: bool,
87    pub(crate) scene_records: SceneRecords,
88    pub(crate) scoped_layout_scene_nodes: Vec<NodeId>,
89    /// Nodes the layout pass only moved: the scene moves their layers.
90    pub(crate) scoped_moved_scene_nodes: Vec<NodeId>,
91    pub(crate) scoped_draw_nodes: Vec<NodeId>,
92    pub(crate) scoped_layer_property_nodes: Vec<NodeId>,
93    pub(crate) structural_scene_nodes: Vec<NodeId>,
94    pub(crate) scene_updates: Vec<(NodeId, NodeUpdate)>,
95    pub(crate) is_dirty: bool,
96    pub(crate) buttons_pressed: PointerButtons,
97    pub(crate) pointer_source: PointerSource,
98    pub(crate) hit_path_tracker: HitPathTracker,
99    pub(crate) hovered_nodes: Vec<NodeId>,
100    pub(crate) independent_pointers: IndependentPointers,
101    pub(crate) on_rotary_scroll: Option<Rc<dyn Fn(RotaryScrollEvent) -> bool>>,
102    pub(crate) dev_overlay: DevOverlay,
103    pub(crate) inspector: crate::inspector::DeveloperInspector,
104    pub(crate) frame_scheduler: FrameScheduler,
105    pub(crate) pointer_icon: PointerIconState,
106    pub(crate) last_update: FrameUpdateResult,
107    pub(crate) frame_owed: bool,
108    pub(crate) screen_origin: Option<Point>,
109}
110
111impl<R: Renderer> RootSurface<R> {
112    pub(crate) fn new(
113        id: RootId,
114        renderer: R,
115        buffer_size: (u32, u32),
116        viewport: (f32, f32),
117    ) -> Self {
118        Self {
119            id,
120            root: None,
121            renderer,
122            cursor: (0.0, 0.0),
123            viewport,
124            buffer_size,
125            layout_tree: None,
126            semantics_tree: None,
127            semantics_moved: false,
128            seen_layer_moves: 0,
129            modal_focus: Vec::new(),
130            frames: 0,
131            key_moved_focus_at: None,
132            dpad_navigation: false,
133            focus_check_due: false,
134            key_press: None,
135            frame_rate_preference: FrameRatePreference::default(),
136            scene_dirty: true,
137            scene_records: SceneRecords::Owed,
138            scoped_layout_scene_nodes: Vec::new(),
139            scoped_moved_scene_nodes: Vec::new(),
140            scoped_draw_nodes: Vec::new(),
141            scoped_layer_property_nodes: Vec::new(),
142            structural_scene_nodes: Vec::new(),
143            scene_updates: Vec::new(),
144            is_dirty: true,
145            buttons_pressed: PointerButtons::NONE,
146            pointer_source: PointerSource::Unknown,
147            hit_path_tracker: HitPathTracker::new(),
148            hovered_nodes: Vec::new(),
149            independent_pointers: IndependentPointers::default(),
150            on_rotary_scroll: None,
151            dev_overlay: DevOverlay::default(),
152            inspector: crate::inspector::DeveloperInspector::default(),
153            frame_scheduler: FrameScheduler::default(),
154            pointer_icon: PointerIconState::new(),
155            last_update: FrameUpdateResult::default(),
156            frame_owed: false,
157            screen_origin: None,
158        }
159    }
160
161    pub(crate) fn root_node(&self, app: &ShellApp) -> Option<NodeId> {
162        match self.id {
163            RootId::Primary => app.composition.root(),
164            RootId::Window(_) => self.root,
165        }
166    }
167
168    pub(crate) fn owns_nodes_under(&self, window_root: Option<NodeId>) -> bool {
169        match self.id {
170            RootId::Primary => window_root.is_none(),
171            RootId::Window(_) => self.root.is_some() && self.root == window_root,
172        }
173    }
174
175    pub(crate) fn viewport_size(&self) -> Size {
176        Size {
177            width: self.viewport.0,
178            height: self.viewport.1,
179        }
180    }
181
182    pub(crate) fn screen_point_inside(&self, screen: Point) -> Option<Point> {
183        let origin = self.screen_origin?;
184        let local = Point {
185            x: screen.x - origin.x,
186            y: screen.y - origin.y,
187        };
188        (local.x >= 0.0
189            && local.y >= 0.0
190            && local.x <= self.viewport.0
191            && local.y <= self.viewport.1)
192            .then_some(local)
193    }
194
195    pub(crate) fn set_root(&mut self, root: Option<NodeId>) {
196        if self.root == root {
197            return;
198        }
199        self.root = root;
200        self.forget_snapshots();
201        self.invalidate_scene_root(root);
202        self.hit_path_tracker.clear();
203        self.hovered_nodes.clear();
204        self.independent_pointers.clear();
205        self.buttons_pressed = PointerButtons::NONE;
206        self.is_dirty = true;
207    }
208
209    // Takes the dirt of nodes under `root` for a scene that records nothing
210    // yet: `root` alone stands for them, as the update that builds the
211    // scene records the whole tree under it.
212    fn take_whole_scene_dirt(&mut self, root: NodeId) {
213        self.scene_dirty = true;
214        if !self.scoped_layout_scene_nodes.contains(&root) {
215            self.scoped_layout_scene_nodes.push(root);
216        }
217    }
218
219    pub(crate) fn invalidate_scene_root(&mut self, root: Option<NodeId>) {
220        self.scoped_layout_scene_nodes.clear();
221        self.scoped_layout_scene_nodes.extend(root);
222        self.scoped_moved_scene_nodes.clear();
223        self.scoped_draw_nodes.clear();
224        self.scoped_layer_property_nodes.clear();
225        self.structural_scene_nodes.clear();
226        self.scene_updates.clear();
227        self.scene_dirty = true;
228    }
229
230    /// Drops the layout snapshot and marks the semantics tree for an update,
231    /// which keeps what did not change.
232    pub(crate) fn forget_snapshots(&mut self) {
233        self.layout_tree = None;
234        self.semantics_moved = true;
235    }
236
237    // Whether the scene moved a layer since the last call.
238    pub(crate) fn layers_moved_since_look(&mut self) -> bool {
239        let moves = self.renderer.scene().layer_moves();
240        let moved = moves != self.seen_layer_moves;
241        self.seen_layer_moves = moves;
242        moved
243    }
244
245    pub(crate) fn has_active_pointer_gesture(&self) -> bool {
246        (self.buttons_pressed != PointerButtons::NONE
247            && self.hit_path_tracker.has_path(PointerId::PRIMARY))
248            || self.independent_pointers.holds_a_button()
249    }
250
251    pub(crate) fn has_active_primary_gesture(&self) -> bool {
252        self.buttons_pressed.contains(PointerButton::Primary)
253            && self.hit_path_tracker.has_path(PointerId::PRIMARY)
254    }
255
256    // Starts a frame of the surface: counts it, and tells the renderer when
257    // the app held still since the last one, before the frame builds its
258    // scene.
259    pub(crate) fn begin_frame(&mut self) {
260        self.frames += 1;
261        if self.frame_scheduler.take_held_still() {
262            self.renderer.note_held_still();
263        }
264        if self.has_active_pointer_gesture() {
265            self.renderer.note_pointer_held();
266        }
267    }
268
269    pub(crate) fn renderer_warmup_due(&self, app: &ShellApp) -> bool {
270        self.renderer.needs_frame_warmup() && !app.composition.runtime().has_frame_callbacks()
271    }
272
273    pub(crate) fn needs_redraw_in_context(&self, app: &ShellApp) -> bool {
274        app.has_stale_work_in_context()
275            || app.composition.should_recompose()
276            || self.is_dirty
277            || self.scene_dirty
278            || self.renderer_warmup_due(app)
279    }
280
281    pub(crate) fn compute_frame_schedule(
282        &self,
283        app: &ShellApp,
284        surfaces_dirty: bool,
285    ) -> FrameSchedule {
286        let (needs_update, needs_frame) = app.app_context.enter(|| {
287            let needs_frame = self.is_dirty
288                || self.scene_dirty
289                || app.wants_frame_in_context()
290                || self.has_active_pointer_gesture()
291                || self.renderer_warmup_due(app);
292            (app.needs_ui_update_in_context(surfaces_dirty), needs_frame)
293        });
294        FrameSchedule {
295            needs_update,
296            needs_frame,
297            next_deadline: app.next_event_time(),
298        }
299    }
300
301    pub(crate) fn layout_tree_in_context(&mut self, app: &mut ShellApp) -> Option<&LayoutTree> {
302        if self.layout_tree.is_none() {
303            let root = self.root_node(app)?;
304            let mut applier = app.composition.applier_mut();
305            match cranpose_ui::build_layout_tree_from_applier(&mut applier, root) {
306                Ok(layout_tree) => {
307                    self.layout_tree = layout_tree;
308                }
309                Err(err) => {
310                    log::debug!("failed to build layout snapshot: {err}");
311                    return None;
312                }
313            }
314        }
315        self.layout_tree.as_ref()
316    }
317
318    /// The node an open modal takes this surface over with, the root its
319    /// semantics tree would have, found without building the tree.
320    pub(crate) fn top_modal(&self, app: &mut ShellApp) -> Option<NodeId> {
321        let root = self.root_node(app)?;
322        let mut applier = app.composition.applier_mut();
323        cranpose_ui::top_modal_from_applier(&mut applier, root).unwrap_or_else(|err| {
324            log::debug!("failed to find the top modal under root #{root}: {err}");
325            None
326        })
327    }
328
329    pub(crate) fn semantics_tree_in_context(
330        &mut self,
331        app: &mut ShellApp,
332    ) -> Option<&SemanticsTree> {
333        if !app.semantics_enabled && !self.inspector.state.open {
334            return None;
335        }
336        self.semantics_tree_for_input(app)
337    }
338
339    pub(crate) fn semantics_tree_for_input(
340        &mut self,
341        app: &mut ShellApp,
342    ) -> Option<&SemanticsTree> {
343        app.flush_semantics_invalidations();
344        let root = self.root_node(app)?;
345        let semantics_dirty = {
346            let mut applier = app.composition.applier_mut();
347            cranpose_ui::tree_needs_semantics(&mut *applier, root).unwrap_or_else(|err| {
348                log::debug!("failed to check semantics dirty status for root #{root}: {err}");
349                true
350            })
351        };
352        if self.semantics_tree.is_none() || self.semantics_moved || semantics_dirty {
353            let mut applier = app.composition.applier_mut();
354            match cranpose_ui::update_semantics_tree_from_applier(
355                &mut applier,
356                root,
357                &mut self.semantics_tree,
358            ) {
359                Ok(()) => {
360                    #[cfg(debug_assertions)]
361                    crate::semantics_check::assert_matches_rebuild(
362                        &mut applier,
363                        root,
364                        self.semantics_tree.as_ref(),
365                    );
366                    self.semantics_moved = false;
367                    app.semantics_snapshot_revision =
368                        app.semantics_snapshot_revision.wrapping_add(1);
369                }
370                Err(err) => {
371                    log::debug!("failed to build semantics snapshot: {err}");
372                    return None;
373                }
374            }
375        }
376        self.semantics_tree.as_ref()
377    }
378}
379
380// What a surface's scene holds of the surface's tree.
381#[derive(Clone, Copy, PartialEq, Eq)]
382pub(crate) enum SceneRecords {
383    // Nothing yet: its next scene update records the whole tree, so the
384    // dirt of single nodes tells it nothing.
385    Owed,
386    // The records of the tree as the last render left it, which the dirt
387    // of single nodes updates.
388    Held,
389}
390
391#[derive(Clone, Copy)]
392pub(crate) enum SurfaceDirtyLane {
393    Layout,
394    Moved,
395    Draw,
396    LayerProperties,
397    Structural,
398}
399
400#[derive(Default)]
401pub(crate) struct SurfaceRoutingScratch {
402    pub(crate) attached: Vec<Option<NodeId>>,
403    pub(crate) owners: Vec<Option<NodeId>>,
404    pub(crate) seen: HashSet<(usize, NodeId)>,
405    pub(crate) attachment: SceneNodeAttachmentScratch,
406    pub(crate) window_roots: cranpose_ui::WindowRootRoutingScratch,
407    // The nodes a layout lane routing gave the surfaces, while the moved
408    // lane after it is routed.
409    pub(crate) laid_out: NodeMarks,
410    // Each surface's count of layout lane nodes before that routing.
411    pub(crate) laid_out_starts: Vec<usize>,
412    pub(crate) moved: Vec<NodeId>,
413}
414
415impl SurfaceRoutingScratch {
416    // Gives back the room a burst of routed nodes took.
417    pub(crate) fn trim(&mut self) {
418        self.attached.trim_growth_slack();
419        self.owners.trim_growth_slack();
420        self.moved.trim_growth_slack();
421        self.seen.trim_growth_slack();
422    }
423}
424
425fn append_surface_dirty_node(
426    surface: &mut RootSurface<impl Renderer>,
427    surface_index: usize,
428    node: NodeId,
429    lane: SurfaceDirtyLane,
430    seen: &mut HashSet<(usize, NodeId)>,
431) {
432    // The scene update drops repeats of reshaped and moved nodes: the
433    // reshaped ones go into a sorted partial list, the moved ones into its
434    // dirty map. Both lists are taken by the frame that sees them.
435    match lane {
436        SurfaceDirtyLane::Layout => {
437            surface.scene_dirty = true;
438            surface.scoped_layout_scene_nodes.push(node);
439        }
440        SurfaceDirtyLane::Moved => {
441            surface.scene_dirty = true;
442            surface.scoped_moved_scene_nodes.push(node);
443        }
444        SurfaceDirtyLane::Draw => surface.scoped_draw_nodes.push(node),
445        SurfaceDirtyLane::LayerProperties => surface.scoped_layer_property_nodes.push(node),
446        SurfaceDirtyLane::Structural => {
447            if seen.insert((surface_index, node)) {
448                surface.structural_scene_nodes.push(node);
449            }
450        }
451    }
452}
453
454// Routes `nodes` to the surfaces that show them. A lane with no nodes, as
455// in most frames, returns before the routing's prologue.
456#[inline]
457pub(crate) fn route_nodes_by_surface<R: Renderer>(
458    app: &mut ShellApp,
459    surfaces: &mut [RootSurface<R>],
460    nodes: impl IntoIterator<Item = NodeId>,
461    lane: SurfaceDirtyLane,
462    scratch: &mut SurfaceRoutingScratch,
463) {
464    let nodes = nodes.into_iter();
465    if nodes.size_hint().1 == Some(0) {
466        scratch.attached.clear();
467        scratch.owners.clear();
468        return;
469    }
470    route_batch_by_surface(app, surfaces, nodes, lane, scratch);
471}
472
473#[inline(never)]
474fn route_batch_by_surface<R: Renderer>(
475    app: &mut ShellApp,
476    surfaces: &mut [RootSurface<R>],
477    nodes: impl Iterator<Item = NodeId>,
478    lane: SurfaceDirtyLane,
479    scratch: &mut SurfaceRoutingScratch,
480) {
481    let Some(primary_root) = app.composition.root() else {
482        scratch.attached.clear();
483        scratch.owners.clear();
484        return;
485    };
486    let single_window = app.app_context.window_roots().is_empty();
487    let primary = surfaces
488        .iter()
489        .position(|surface| surface.id == RootId::Primary);
490    if single_window && let Some(index) = primary {
491        let surface = &mut surfaces[index];
492        if surface.scene_records == SceneRecords::Owed {
493            scratch.attached.clear();
494            scratch.owners.clear();
495            let mut nodes = nodes;
496            if nodes.next().is_some() {
497                surface.take_whole_scene_dirt(primary_root);
498            }
499            return;
500        }
501    }
502    let mut applier = app.composition.applier_mut();
503    applier.scene_nodes_attached_to_into(
504        nodes,
505        primary_root,
506        &mut scratch.attached,
507        &mut scratch.attachment,
508    );
509    if scratch.attached.is_empty() {
510        scratch.owners.clear();
511        return;
512    }
513    // A clear writes every control byte of the table, even of an empty one.
514    if !scratch.seen.is_empty() {
515        scratch.seen.clear();
516    }
517    if single_window {
518        scratch.owners.clear();
519        if let Some(index) = primary {
520            let surface = &mut surfaces[index];
521            for node in scratch.attached.iter().flatten().copied() {
522                append_surface_dirty_node(surface, index, node, lane, &mut scratch.seen);
523            }
524        }
525        return;
526    }
527    cranpose_ui::nearest_window_roots_into(
528        &mut applier,
529        scratch.attached.iter().flatten().copied(),
530        &mut scratch.owners,
531        &mut scratch.window_roots,
532    );
533    for (node, owner) in scratch.attached.iter().flatten().zip(&scratch.owners) {
534        let node = *node;
535        if let Some(index) = surfaces
536            .iter()
537            .position(|surface| surface.owns_nodes_under(*owner))
538        {
539            let surface = &mut surfaces[index];
540            match surface.scene_records {
541                SceneRecords::Held => {
542                    append_surface_dirty_node(surface, index, node, lane, &mut scratch.seen);
543                }
544                SceneRecords::Owed => surface.take_whole_scene_dirt(owner.unwrap_or(primary_root)),
545            }
546        }
547    }
548}
549
550/// Routes the nodes a layout pass laid out again, `laid_out`, and the nodes
551/// it only moved. A moved node is left out when the scene update of its
552/// surface lays out its placer again: that update places every child of the
553/// placer's layer anew, so the node's own record would be found and settled
554/// there and nowhere else.
555pub(crate) fn route_geometry_scene_nodes<R: Renderer>(
556    app: &mut ShellApp,
557    surfaces: &mut [RootSurface<R>],
558    laid_out: impl IntoIterator<Item = NodeId>,
559    moved: &[MovedSceneNode],
560    scratch: &mut SurfaceRoutingScratch,
561) {
562    if moved.is_empty() {
563        route_nodes_by_surface(app, surfaces, laid_out, SurfaceDirtyLane::Layout, scratch);
564        return;
565    }
566    scratch.laid_out_starts.clear();
567    scratch.laid_out_starts.extend(
568        surfaces
569            .iter()
570            .map(|surface| surface.scoped_layout_scene_nodes.len()),
571    );
572    route_nodes_by_surface(app, surfaces, laid_out, SurfaceDirtyLane::Layout, scratch);
573    let mut routed = std::mem::take(&mut scratch.moved);
574    routed.clear();
575    {
576        let applier = app.composition.applier_mut();
577        scratch.laid_out.reset(&applier);
578        for (surface, &start) in surfaces.iter().zip(&scratch.laid_out_starts) {
579            for &node in &surface.scoped_layout_scene_nodes[start..] {
580                scratch.laid_out.set(&applier, node, 1);
581            }
582        }
583        let marks = &scratch.laid_out;
584        let window_roots = !app.app_context.window_roots().is_empty();
585        // The children one node placed come together: their placer is
586        // looked up once.
587        let mut last_placer = None;
588        for &moved in moved {
589            let placed_again = moved.placer.is_some_and(|placer| match last_placer {
590                Some((last, laid_out)) if last == placer => laid_out,
591                _ => {
592                    let laid_out = marks.get(&applier, placer) != 0;
593                    last_placer = Some((placer, laid_out));
594                    laid_out
595                }
596            });
597            if !placed_again || window_roots && is_window_root(&applier, moved.node) {
598                routed.push(moved.node);
599            }
600        }
601    }
602    route_nodes_by_surface(
603        app,
604        surfaces,
605        routed.iter().copied(),
606        SurfaceDirtyLane::Moved,
607        scratch,
608    );
609    scratch.moved = routed;
610}
611
612/// Whether `node` is a window root, which goes to a surface of its own.
613fn is_window_root(applier: &MemoryApplier, node: NodeId) -> bool {
614    applier.get_ref(node).is_ok_and(|node| {
615        let node: &dyn std::any::Any = node;
616        node.downcast_ref::<LayoutNode>()
617            .is_some_and(LayoutNode::is_window_root)
618    })
619}
620
621/// One surface borrowed together with its shell: the handle a platform
622/// delivers a window's events through and reads a window's frame from.
623///
624/// [`AppShell::surface`] hands one out per root. Every method of [`AppShell`]
625/// that names no root acts on the primary surface through the same code, so
626/// a single-window platform never sees this type.
627pub struct SurfaceMut<'a, R: Renderer> {
628    pub(crate) shell: &'a mut AppShell<R>,
629    pub(crate) index: usize,
630}
631
632impl<'a, R> SurfaceMut<'a, R>
633where
634    R: Renderer,
635    R::Error: Debug,
636{
637    pub(crate) fn new(shell: &'a mut AppShell<R>, index: usize) -> Self {
638        Self { shell, index }
639    }
640
641    /// The whole app, for what a window's event needs beyond its surface:
642    /// the clipboard, the dev options, a debug report.
643    pub fn shell(&mut self) -> &mut AppShell<R> {
644        self.shell
645    }
646
647    pub(crate) fn shell_app(&mut self) -> &mut ShellApp {
648        &mut self.shell.app
649    }
650
651    pub(crate) fn shell_app_ref(&self) -> &ShellApp {
652        &self.shell.app
653    }
654
655    pub(crate) fn surface(&self) -> &RootSurface<R> {
656        &self.shell.surfaces[self.index]
657    }
658
659    pub(crate) fn surface_mut(&mut self) -> &mut RootSurface<R> {
660        &mut self.shell.surfaces[self.index]
661    }
662
663    pub(crate) fn parts(&mut self) -> (&mut ShellApp, &mut RootSurface<R>) {
664        let shell = &mut *self.shell;
665        (&mut shell.app, &mut shell.surfaces[self.index])
666    }
667
668    /// Which root this surface draws.
669    pub fn id(&self) -> RootId {
670        self.surface().id
671    }
672
673    /// The node this surface draws from, when it has one.
674    pub fn root(&self) -> Option<NodeId> {
675        let surface = self.surface();
676        surface.root_node(self.shell_app_ref())
677    }
678
679    /// The renderer that draws this surface.
680    pub fn renderer(&mut self) -> &mut R {
681        &mut self.surface_mut().renderer
682    }
683
684    /// Runs a presentation operation with this surface's app context active.
685    /// Software text rasterization uses the context's font measurement services.
686    pub fn with_renderer<T>(&mut self, block: impl FnOnce(&mut R) -> T) -> T {
687        let (app, surface) = self.parts();
688        app.app_context.enter(|| block(&mut surface.renderer))
689    }
690
691    /// The scene this surface last built.
692    pub fn scene(&self) -> &R::Scene {
693        self.surface().renderer.scene()
694    }
695
696    /// Sets the logical size this surface lays out and draws into.
697    ///
698    /// The primary surface's viewport is the composition root's constraints.
699    /// A window surface's viewport is what its renderer draws into; the
700    /// window root lays out to the size its descriptor reports, which the
701    /// platform keeps equal to this. The next update lays out and renders;
702    /// [`AppShell::set_viewport`] additionally runs that frame at once.
703    pub fn set_viewport(&mut self, width: f32, height: f32) {
704        self.surface_mut().viewport = (width, height);
705        match self.id() {
706            RootId::Primary => self.shell_app().request_forced_layout_pass(),
707            RootId::Window(_) => {
708                if let Some(root) = self.root() {
709                    self.shell_app_ref()
710                        .app_context
711                        .enter(|| cranpose_ui::schedule_measure_repass(root));
712                }
713                self.shell_app().request_layout_pass();
714            }
715        }
716        let root = self.root();
717        self.surface_mut().invalidate_scene_root(root);
718        self.mark_dirty();
719    }
720
721    /// Tells the shell where the window drawing this surface sits on the
722    /// screen, in logical pixels, so pointer events can carry a
723    /// [`screen_position`](cranpose_foundation::PointerEvent::screen_position).
724    /// A platform sets it when the window moves and before it delivers a
725    /// pointer sample; `None` says the platform does not know.
726    pub fn set_screen_origin(&mut self, origin: Option<Point>) {
727        self.surface_mut().screen_origin = origin;
728    }
729
730    /// Where the window drawing this surface sits on the screen, as the
731    /// platform last said.
732    pub fn screen_origin(&self) -> Option<Point> {
733        self.surface().screen_origin
734    }
735
736    /// The logical size this surface draws into.
737    pub fn viewport_size(&self) -> (f32, f32) {
738        self.surface().viewport
739    }
740
741    /// Sets the physical size of this surface's framebuffer.
742    pub fn set_buffer_size(&mut self, width: u32, height: u32) {
743        self.surface_mut().buffer_size = (width, height);
744    }
745
746    /// The physical size of this surface's framebuffer.
747    pub fn buffer_size(&self) -> (u32, u32) {
748        self.surface().buffer_size
749    }
750
751    /// Marks this surface as needing a redraw.
752    pub fn mark_dirty(&mut self) {
753        self.surface_mut().is_dirty = true;
754    }
755
756    /// Whether this surface owes the display a frame: stale pixels, or a
757    /// renderer that has not warmed its swapchain yet. See
758    /// [`AppShell::needs_redraw`].
759    pub fn needs_redraw(&self) -> bool {
760        self.shell_app_ref()
761            .app_context
762            .enter(|| self.surface().needs_redraw_in_context(self.shell_app_ref()))
763    }
764
765    /// Whether a pointer button is held down on a control of this surface,
766    /// whichever button it is.
767    pub fn has_active_pointer_gesture(&self) -> bool {
768        self.surface().has_active_pointer_gesture()
769    }
770
771    /// Whether the primary button is held down on a control of this
772    /// surface. A platform that polls the mouse's primary button compares
773    /// it with this, so a held right button does not look like a lost left
774    /// release.
775    pub fn has_active_primary_gesture(&self) -> bool {
776        self.surface().has_active_primary_gesture()
777    }
778
779    /// What the update and frame produced for this surface the last time
780    /// the app updated.
781    pub fn last_update_result(&self) -> FrameUpdateResult {
782        self.surface().last_update
783    }
784
785    /// Whether an update since the platform last presented this surface
786    /// changed its pixels. An update runs for the whole app, so the update a
787    /// platform ran for one window may have drawn another; this is how the
788    /// other window learns it has a frame to show.
789    pub fn frame_owed(&self) -> bool {
790        self.surface().frame_owed
791    }
792
793    /// [`Self::frame_owed`], cleared: the platform is about to present.
794    pub fn take_frame_owed(&mut self) -> bool {
795        std::mem::take(&mut self.surface_mut().frame_owed)
796    }
797
798    fn compute_frame_schedule(&self) -> FrameSchedule {
799        self.surface()
800            .compute_frame_schedule(self.shell_app_ref(), self.shell.any_surface_dirty())
801    }
802
803    /// The frame this surface asks its platform for, recorded for
804    /// [`Self::frame_scheduler_snapshot`].
805    pub fn frame_schedule(&self) -> FrameSchedule {
806        let schedule = self.compute_frame_schedule();
807        self.surface().frame_scheduler.record(schedule);
808        schedule
809    }
810
811    /// Computes this surface's frame schedule and applies it to `driver`.
812    pub fn schedule_platform_frame<D>(&self, driver: &D) -> FrameSchedule
813    where
814        D: PlatformFrameDriver + ?Sized,
815    {
816        let schedule = self.compute_frame_schedule();
817        self.surface().frame_scheduler.schedule(schedule, driver);
818        schedule
819    }
820
821    /// The schedule this surface last recorded.
822    pub fn frame_scheduler_snapshot(&self) -> FrameSchedule {
823        self.surface().frame_scheduler.snapshot()
824    }
825
826    /// Sets how the platform should vote the display's frame rate for the
827    /// window showing this surface. See [`AppShell::set_frame_rate_preference`].
828    pub fn set_frame_rate_preference(&mut self, preference: FrameRatePreference) {
829        self.surface_mut().frame_rate_preference = preference;
830    }
831
832    /// This surface's display frame-rate preference.
833    pub fn frame_rate_preference(&self) -> FrameRatePreference {
834        self.surface().frame_rate_preference
835    }
836
837    /// Where this surface's dev overlay draws the control for `mode`, in
838    /// logical pixels. See [`AppShell::dev_overlay_control_center`].
839    pub fn dev_overlay_control_center(&self, mode: FramePacingMode) -> Option<(f32, f32)> {
840        self.surface().dev_overlay.control_center(mode)
841    }
842
843    pub(crate) fn dev_overlay_press(&mut self, x: f32, y: f32) -> bool {
844        if !self.shell_app_ref().dev_options.frame_pacing_controls {
845            return false;
846        }
847        let Some(mode) = self.surface().dev_overlay.control_at(x, y) else {
848            return false;
849        };
850        self.shell().set_frame_pacing_mode(mode);
851        true
852    }
853
854    /// Runs `block` with this surface's layout snapshot, built on demand.
855    pub fn with_layout_tree<T>(&mut self, block: impl FnOnce(Option<&LayoutTree>) -> T) -> T {
856        let (app, surface) = self.parts();
857        let _app_context = app.app_context.enter_scope();
858        block(surface.layout_tree_in_context(app))
859    }
860
861    /// Runs `block` with this surface's semantics snapshot, built on demand;
862    /// `None` while semantics are disabled.
863    pub fn with_semantics_tree<T>(&mut self, block: impl FnOnce(Option<&SemanticsTree>) -> T) -> T {
864        let (app, surface) = self.parts();
865        let _app_context = app.app_context.enter_scope();
866        block(surface.semantics_tree_in_context(app))
867    }
868
869    /// The pointer icon the platform has not applied to this surface's
870    /// window yet. See [`AppShell::take_pointer_icon_change`].
871    pub fn take_pointer_icon_change(&self) -> Option<PointerIcon> {
872        self.surface().pointer_icon.take_change()
873    }
874
875    /// Offers this surface's pointer icon to the platform again. See
876    /// [`AppShell::refresh_pointer_icon`].
877    pub fn refresh_pointer_icon(&self) {
878        self.surface().pointer_icon.refresh();
879    }
880
881    /// Installs the platform text input for the window showing this
882    /// surface. Keyboard requests reach the handler of the surface the
883    /// platform last called active, and a hide reaches the handler that
884    /// showed. See [`AppShell::set_platform_text_input`].
885    pub fn set_platform_text_input(&mut self, handler: Rc<dyn PlatformTextInputHandler>) {
886        let id = self.id();
887        let app = self.shell_app();
888        app.text_input_routes.borrow_mut().set_handler(id, handler);
889        app.install_text_input_router();
890    }
891
892    /// Makes this the surface the platform considers focused: the one the
893    /// soft keyboard belongs to. Pointer presses do this on their own.
894    pub fn activate(&mut self) {
895        let id = self.id();
896        self.shell_app()
897            .text_input_routes
898            .borrow_mut()
899            .set_active(id);
900    }
901}
902
903#[expect(clippy::multiple_inherent_impl, reason = "one file per shell concern")]
904impl<R> AppShell<R>
905where
906    R: Renderer,
907    R::Error: Debug,
908{
909    /// Says whether a D-pad drives the primary window, as a TV's remote does.
910    /// A remote acts only through focus, so while `dpad` is set a layout that
911    /// leaves nothing focused gives focus to a target: the one that took the
912    /// place of the target focus left, or the first one. An arrow moves focus
913    /// out of a focused text field, and one that moves focus onto a field
914    /// leaves the software keyboard closed until the center button opens it.
915    pub fn set_dpad_navigation(&mut self, dpad: bool) {
916        let primary = &mut self.surfaces[0];
917        primary.dpad_navigation = dpad;
918        primary.focus_check_due = dpad;
919    }
920
921    // Ends the update at `frame_time` that made `result`: the surfaces are
922    // clean, the recycle pools keep what recent frames asked for, after a
923    // layout the primary window keeps a focused target when it is set to,
924    // and the rest before a trim starts or ends.
925    pub(crate) fn end_update(&mut self, result: FrameUpdateResult, frame_time: Option<u64>) {
926        for surface in &mut self.surfaces {
927            surface.is_dirty = false;
928        }
929        self.app.composition.applier_mut().end_recycle_frame();
930        let primary = &mut self.surfaces[0];
931        if primary.dpad_navigation && (result.structure_changed || primary.focus_check_due) {
932            primary.focus_check_due = false;
933            self.primary().keep_focus();
934        }
935        self.trim_at_rest(result, frame_time);
936    }
937}