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