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    scratch.seen.clear();
577    if single_window {
578        scratch.owners.clear();
579        if let Some(index) = primary {
580            let surface = &mut surfaces[index];
581            for node in scratch.attached.iter().flatten().copied() {
582                append_surface_dirty_node(surface, index, node, lane, &mut scratch.seen);
583            }
584        }
585        return;
586    }
587    cranpose_ui::nearest_window_roots_into(
588        &mut applier,
589        scratch.attached.iter().flatten().copied(),
590        &mut scratch.owners,
591        &mut scratch.window_roots,
592    );
593    for (node, owner) in scratch.attached.iter().flatten().zip(&scratch.owners) {
594        let node = *node;
595        if let Some(index) = surfaces
596            .iter()
597            .position(|surface| surface.owns_nodes_under(*owner))
598        {
599            let surface = &mut surfaces[index];
600            match surface.scene_records {
601                SceneRecords::Held => {
602                    append_surface_dirty_node(surface, index, node, lane, &mut scratch.seen);
603                }
604                SceneRecords::Owed => surface.take_whole_scene_dirt(owner.unwrap_or(primary_root)),
605            }
606        }
607    }
608}
609
610/// Routes the nodes a layout pass laid out again, `laid_out`, and the nodes
611/// it only moved. A moved node is left out when the scene update of its
612/// surface lays out its placer again: that update places every child of the
613/// placer's layer anew, so the node's own record would be found and settled
614/// there and nowhere else.
615pub(crate) fn route_geometry_scene_nodes<R: Renderer>(
616    app: &mut ShellApp,
617    surfaces: &mut [RootSurface<R>],
618    laid_out: impl IntoIterator<Item = NodeId>,
619    moved: &[MovedSceneNode],
620    scratch: &mut SurfaceRoutingScratch,
621) {
622    if moved.is_empty() {
623        route_nodes_by_surface(app, surfaces, laid_out, SurfaceDirtyLane::Layout, scratch);
624        return;
625    }
626    scratch.laid_out_starts.clear();
627    scratch.laid_out_starts.extend(
628        surfaces
629            .iter()
630            .map(|surface| surface.scoped_layout_scene_nodes.len()),
631    );
632    route_nodes_by_surface(app, surfaces, laid_out, SurfaceDirtyLane::Layout, scratch);
633    let mut routed = std::mem::take(&mut scratch.moved);
634    routed.clear();
635    {
636        let applier = app.composition.applier_mut();
637        scratch.laid_out.reset(&applier);
638        for (surface, &start) in surfaces.iter().zip(&scratch.laid_out_starts) {
639            for &node in &surface.scoped_layout_scene_nodes[start..] {
640                scratch.laid_out.set(&applier, node, 1);
641            }
642        }
643        let marks = &scratch.laid_out;
644        let window_roots = !app.app_context.window_roots().is_empty();
645        // The children one node placed come together: their placer is
646        // looked up once.
647        let mut last_placer = None;
648        for &moved in moved {
649            let placed_again = moved.placer.is_some_and(|placer| match last_placer {
650                Some((last, laid_out)) if last == placer => laid_out,
651                _ => {
652                    let laid_out = marks.get(&applier, placer) != 0;
653                    last_placer = Some((placer, laid_out));
654                    laid_out
655                }
656            });
657            if !placed_again || window_roots && is_window_root(&applier, moved.node) {
658                routed.push(moved.node);
659            }
660        }
661    }
662    route_nodes_by_surface(
663        app,
664        surfaces,
665        routed.iter().copied(),
666        SurfaceDirtyLane::Moved,
667        scratch,
668    );
669    scratch.moved = routed;
670}
671
672/// Whether `node` is a window root, which goes to a surface of its own.
673fn is_window_root(applier: &MemoryApplier, node: NodeId) -> bool {
674    applier.get_ref(node).is_ok_and(|node| {
675        let node: &dyn std::any::Any = node;
676        node.downcast_ref::<LayoutNode>()
677            .is_some_and(LayoutNode::is_window_root)
678    })
679}
680
681/// One surface borrowed together with its shell: the handle a platform
682/// delivers a window's events through and reads a window's frame from.
683///
684/// [`AppShell::surface`] hands one out per root. Every method of [`AppShell`]
685/// that names no root acts on the primary surface through the same code, so
686/// a single-window platform never sees this type.
687pub struct SurfaceMut<'a, R: Renderer> {
688    pub(crate) shell: &'a mut AppShell<R>,
689    pub(crate) index: usize,
690}
691
692impl<'a, R> SurfaceMut<'a, R>
693where
694    R: Renderer,
695    R::Error: Debug,
696{
697    pub(crate) fn new(shell: &'a mut AppShell<R>, index: usize) -> Self {
698        Self { shell, index }
699    }
700
701    /// The whole app, for what a window's event needs beyond its surface:
702    /// the clipboard, the dev options, a debug report.
703    pub fn shell(&mut self) -> &mut AppShell<R> {
704        self.shell
705    }
706
707    pub(crate) fn shell_app(&mut self) -> &mut ShellApp {
708        &mut self.shell.app
709    }
710
711    pub(crate) fn shell_app_ref(&self) -> &ShellApp {
712        &self.shell.app
713    }
714
715    pub(crate) fn surface(&self) -> &RootSurface<R> {
716        &self.shell.surfaces[self.index]
717    }
718
719    pub(crate) fn surface_mut(&mut self) -> &mut RootSurface<R> {
720        &mut self.shell.surfaces[self.index]
721    }
722
723    pub(crate) fn parts(&mut self) -> (&mut ShellApp, &mut RootSurface<R>) {
724        let shell = &mut *self.shell;
725        (&mut shell.app, &mut shell.surfaces[self.index])
726    }
727
728    /// Which root this surface draws.
729    pub fn id(&self) -> RootId {
730        self.surface().id
731    }
732
733    /// The node this surface draws from, when it has one.
734    pub fn root(&self) -> Option<NodeId> {
735        let surface = self.surface();
736        surface.root_node(self.shell_app_ref())
737    }
738
739    /// The renderer that draws this surface.
740    pub fn renderer(&mut self) -> &mut R {
741        &mut self.surface_mut().renderer
742    }
743
744    /// Runs a presentation operation with this surface's app context active.
745    /// Software text rasterization uses the context's font measurement services.
746    pub fn with_renderer<T>(&mut self, block: impl FnOnce(&mut R) -> T) -> T {
747        let (app, surface) = self.parts();
748        app.app_context.enter(|| block(&mut surface.renderer))
749    }
750
751    /// The scene this surface last built.
752    pub fn scene(&self) -> &R::Scene {
753        self.surface().renderer.scene()
754    }
755
756    /// Sets the logical size this surface lays out and draws into.
757    ///
758    /// The primary surface's viewport is the composition root's constraints.
759    /// A window surface's viewport is what its renderer draws into; the
760    /// window root lays out to the size its descriptor reports, which the
761    /// platform keeps equal to this. The next update lays out and renders;
762    /// [`AppShell::set_viewport`] additionally runs that frame at once.
763    pub fn set_viewport(&mut self, width: f32, height: f32) {
764        self.surface_mut().viewport = (width, height);
765        match self.id() {
766            RootId::Primary => self.shell_app().request_forced_layout_pass(),
767            RootId::Window(_) => {
768                if let Some(root) = self.root() {
769                    self.shell_app_ref()
770                        .app_context
771                        .enter(|| cranpose_ui::schedule_measure_repass(root));
772                }
773                self.shell_app().request_layout_pass();
774            }
775        }
776        let root = self.root();
777        self.surface_mut().invalidate_scene_root(root);
778        self.mark_dirty();
779    }
780
781    /// Tells the shell where the window drawing this surface sits on the
782    /// screen, in logical pixels, so pointer events can carry a
783    /// [`screen_position`](cranpose_foundation::PointerEvent::screen_position).
784    /// A platform sets it when the window moves and before it delivers a
785    /// pointer sample; `None` says the platform does not know.
786    pub fn set_screen_origin(&mut self, origin: Option<Point>) {
787        self.surface_mut().screen_origin = origin;
788    }
789
790    /// Where the window drawing this surface sits on the screen, as the
791    /// platform last said.
792    pub fn screen_origin(&self) -> Option<Point> {
793        self.surface().screen_origin
794    }
795
796    /// The logical size this surface draws into.
797    pub fn viewport_size(&self) -> (f32, f32) {
798        self.surface().viewport
799    }
800
801    /// Sets the physical size of this surface's framebuffer.
802    pub fn set_buffer_size(&mut self, width: u32, height: u32) {
803        self.surface_mut().buffer_size = (width, height);
804    }
805
806    /// The physical size of this surface's framebuffer.
807    pub fn buffer_size(&self) -> (u32, u32) {
808        self.surface().buffer_size
809    }
810
811    /// Marks this surface as needing a redraw.
812    pub fn mark_dirty(&mut self) {
813        self.surface_mut().is_dirty = true;
814    }
815
816    /// Whether this surface owes the display a frame: stale pixels, or a
817    /// renderer that has not warmed its swapchain yet. See
818    /// [`AppShell::needs_redraw`].
819    pub fn needs_redraw(&self) -> bool {
820        self.shell_app_ref()
821            .app_context
822            .enter(|| self.surface().needs_redraw_in_context(self.shell_app_ref()))
823    }
824
825    /// Whether a pointer button is held down on a control of this surface,
826    /// whichever button it is.
827    pub fn has_active_pointer_gesture(&self) -> bool {
828        self.surface().has_active_pointer_gesture()
829    }
830
831    /// Whether the primary button is held down on a control of this
832    /// surface. A platform that polls the mouse's primary button compares
833    /// it with this, so a held right button does not look like a lost left
834    /// release.
835    pub fn has_active_primary_gesture(&self) -> bool {
836        self.surface().has_active_primary_gesture()
837    }
838
839    /// What the update and frame produced for this surface the last time
840    /// the app updated.
841    pub fn last_update_result(&self) -> FrameUpdateResult {
842        self.surface().last_update
843    }
844
845    /// Whether an update since the platform last presented this surface
846    /// changed its pixels. An update runs for the whole app, so the update a
847    /// platform ran for one window may have drawn another; this is how the
848    /// other window learns it has a frame to show.
849    pub fn frame_owed(&self) -> bool {
850        self.surface().frame_owed
851    }
852
853    /// [`Self::frame_owed`], cleared: the platform is about to present.
854    pub fn take_frame_owed(&mut self) -> bool {
855        std::mem::take(&mut self.surface_mut().frame_owed)
856    }
857
858    fn compute_frame_schedule(&self) -> FrameSchedule {
859        self.surface()
860            .compute_frame_schedule(self.shell_app_ref(), self.shell.any_surface_dirty())
861    }
862
863    /// The frame this surface asks its platform for, recorded for
864    /// [`Self::frame_scheduler_snapshot`].
865    pub fn frame_schedule(&self) -> FrameSchedule {
866        let schedule = self.compute_frame_schedule();
867        self.surface().frame_scheduler.record(schedule);
868        schedule
869    }
870
871    /// Computes this surface's frame schedule and applies it to `driver`.
872    pub fn schedule_platform_frame<D>(&self, driver: &D) -> FrameSchedule
873    where
874        D: PlatformFrameDriver + ?Sized,
875    {
876        let schedule = self.compute_frame_schedule();
877        self.surface().frame_scheduler.schedule(schedule, driver);
878        schedule
879    }
880
881    /// The schedule this surface last recorded.
882    pub fn frame_scheduler_snapshot(&self) -> FrameSchedule {
883        self.surface().frame_scheduler.snapshot()
884    }
885
886    /// Sets how the platform should vote the display's frame rate for the
887    /// window showing this surface. See [`AppShell::set_frame_rate_preference`].
888    pub fn set_frame_rate_preference(&mut self, preference: FrameRatePreference) {
889        self.surface_mut().frame_rate_preference = preference;
890    }
891
892    /// This surface's display frame-rate preference.
893    pub fn frame_rate_preference(&self) -> FrameRatePreference {
894        self.surface().frame_rate_preference
895    }
896
897    /// Where this surface's dev overlay draws the control for `mode`, in
898    /// logical pixels. See [`AppShell::dev_overlay_control_center`].
899    pub fn dev_overlay_control_center(&self, mode: FramePacingMode) -> Option<(f32, f32)> {
900        self.surface().dev_overlay.control_center(mode)
901    }
902
903    pub(crate) fn dev_overlay_press(&mut self, x: f32, y: f32) -> bool {
904        if !self.shell_app_ref().dev_options.frame_pacing_controls {
905            return false;
906        }
907        let Some(mode) = self.surface().dev_overlay.control_at(x, y) else {
908            return false;
909        };
910        self.shell().set_frame_pacing_mode(mode);
911        true
912    }
913
914    /// Runs `block` with this surface's layout snapshot, built on demand.
915    pub fn with_layout_tree<T>(&mut self, block: impl FnOnce(Option<&LayoutTree>) -> T) -> T {
916        let (app, surface) = self.parts();
917        let _app_context = app.app_context.enter_scope();
918        block(surface.layout_tree_in_context(app))
919    }
920
921    /// Runs `block` with this surface's semantics snapshot, built on demand;
922    /// `None` while semantics are disabled.
923    pub fn with_semantics_tree<T>(&mut self, block: impl FnOnce(Option<&SemanticsTree>) -> T) -> T {
924        let (app, surface) = self.parts();
925        let _app_context = app.app_context.enter_scope();
926        block(surface.semantics_tree_in_context(app))
927    }
928
929    /// The pointer icon the platform has not applied to this surface's
930    /// window yet. See [`AppShell::take_pointer_icon_change`].
931    pub fn take_pointer_icon_change(&self) -> Option<PointerIcon> {
932        self.surface().pointer_icon.take_change()
933    }
934
935    /// Offers this surface's pointer icon to the platform again. See
936    /// [`AppShell::refresh_pointer_icon`].
937    pub fn refresh_pointer_icon(&self) {
938        self.surface().pointer_icon.refresh();
939    }
940
941    /// Installs the platform text input for the window showing this
942    /// surface. Keyboard requests reach the handler of the surface the
943    /// platform last called active, and a hide reaches the handler that
944    /// showed. See [`AppShell::set_platform_text_input`].
945    pub fn set_platform_text_input(&mut self, handler: Rc<dyn PlatformTextInputHandler>) {
946        let id = self.id();
947        let app = self.shell_app();
948        app.text_input_routes.borrow_mut().set_handler(id, handler);
949        app.install_text_input_router();
950    }
951
952    /// Makes this the surface the platform considers focused: the one the
953    /// soft keyboard belongs to. Pointer presses do this on their own.
954    pub fn activate(&mut self) {
955        let id = self.id();
956        self.shell_app()
957            .text_input_routes
958            .borrow_mut()
959            .set_active(id);
960    }
961}
962
963#[expect(clippy::multiple_inherent_impl, reason = "one file per shell concern")]
964impl<R> AppShell<R>
965where
966    R: Renderer,
967    R::Error: Debug,
968{
969    /// Says whether a D-pad drives the primary window, as a TV's remote does.
970    /// A remote acts only through focus, so while `dpad` is set a layout that
971    /// leaves nothing focused gives focus to a target: the one that took the
972    /// place of the target focus left, or the first one. An arrow moves focus
973    /// out of a focused text field, and one that moves focus onto a field
974    /// leaves the software keyboard closed until the center button opens it.
975    pub fn set_dpad_navigation(&mut self, dpad: bool) {
976        let primary = &mut self.surfaces[0];
977        primary.dpad_navigation = dpad;
978        primary.focus_check_due = dpad;
979    }
980
981    // Ends the update at `frame_time` that made `result`: the surfaces are
982    // clean, after a layout the primary window keeps a focused target when
983    // it is set to, and the rest before a trim starts or ends.
984    pub(crate) fn end_update(&mut self, result: FrameUpdateResult, frame_time: Option<u64>) {
985        for surface in &mut self.surfaces {
986            surface.is_dirty = false;
987        }
988        let primary = &mut self.surfaces[0];
989        if primary.dpad_navigation && (result.structure_changed || primary.focus_check_due) {
990            primary.focus_check_due = false;
991            self.primary().keep_focus();
992        }
993        self.trim_at_rest(result, frame_time);
994    }
995}