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