Skip to main content

noonoo_shell/
lib.rs

1//! # noonoo-shell
2//!
3//! The **document host**: several documents in one window, with input routed to
4//! the right one and their paint output composited (see `docs/SHELL.md`).
5//!
6//! Where the engine it replaces had *one root document plus single-slot
7//! overlays* — so pages became blitted bitmaps with no scroll/hover/focus — this
8//! host treats every document as first-class: each has its own DOM, styles,
9//! layout, and paint output, placed at a rectangle in the window. A pointer or
10//! key event is routed to the owning document at the right coordinates, and the
11//! composition seam returns one command stream per layer.
12//!
13//! Interactive state is host state: [`Host::hover`] tracks the hovered node,
14//! [`Host::press`]/[`Host::release`] the pressed one, and [`Host::set_focus`]
15//! keyboard focus. [`Host::layout`] feeds that state into the cascade, so
16//! `:hover`/`:active`/`:focus` style the elements they name.
17//!
18//! The host model is dependency-free and testable headless. The actual window
19//! and GPU surface (`window`/`gpu`) are a borrowed backend behind features. The
20//! accessibility tree is **owned** (`a11y`, on by default): [`Host::a11y`]
21//! composes each layer's tree under one window root, with bounds offset and ids
22//! renumbered, so a platform bridge (see `integrations/noonoo-accesskit`) can
23//! pass it straight to AT-SPI/UiKit/WinRT.
24
25#![forbid(unsafe_code)]
26#![warn(missing_docs)]
27
28use noonoo_dom::NodeId;
29use noonoo_engine::Engine;
30use noonoo_events::{Event, EventListener, dispatch};
31use noonoo_geometry::{Point, Rect, Size};
32use noonoo_layout::{LayoutTree, Shaper};
33use noonoo_paint::{CommandList, Glyphs, TextRuns};
34use noonoo_style::{Cursor, Interaction, Styles};
35
36/// A document's trust context.
37///
38/// Bound to a document when it is admitted to the host and never derived from
39/// content. Internal schemes are reachable only from a trusted origin
40/// ([`navigation_allowed`]).
41#[derive(Clone, PartialEq, Eq, Debug)]
42pub enum Origin {
43    /// Trusted host UI (the chrome document).
44    Chrome,
45    /// Untrusted content (a page).
46    Content,
47    /// A host-defined trusted origin.
48    Custom(String),
49}
50
51impl Origin {
52    /// Whether this origin may reach internal command schemes.
53    pub fn is_trusted(&self) -> bool {
54        !matches!(self, Origin::Content)
55    }
56}
57
58/// Whether `target_scheme` may be navigated to from `origin`.
59pub fn navigation_allowed(origin: &Origin, target_scheme: &str) -> bool {
60    match target_scheme {
61        "shell" | "noonoo" | "exo" => origin.is_trusted(),
62        _ => true,
63    }
64}
65
66/// A layer's role.
67#[derive(Clone, Copy, PartialEq, Eq, Debug)]
68pub enum LayerKind {
69    /// The chrome document.
70    Chrome,
71    /// A content document.
72    Content,
73}
74
75/// A sub-document's placement: anchored to a host node in a parent layer.
76#[derive(Clone, Copy, PartialEq, Eq, Debug)]
77pub struct Anchor {
78    /// The index of the parent layer.
79    pub parent: usize,
80    /// The host node in the parent document.
81    pub host: NodeId,
82}
83
84/// One document placed in the window.
85pub struct Layer {
86    /// The document's trust context.
87    pub origin: Origin,
88    /// The layer's role.
89    pub kind: LayerKind,
90    /// Where the document sits in the window (computed from the parent for
91    /// sub-documents, fixed otherwise).
92    pub rect: Rect,
93    anchor: Option<Anchor>,
94    engine: Engine,
95    styles: Styles,
96    layout: LayoutTree,
97    commands: CommandList,
98    scroll: Point,
99}
100
101impl Layer {
102    /// The document.
103    pub fn engine(&self) -> &Engine {
104        &self.engine
105    }
106
107    /// The document, to change in place. The change shows after the next
108    /// [`Host::layout`].
109    pub fn engine_mut(&mut self) -> &mut Engine {
110        &mut self.engine
111    }
112
113    /// The computed styles (populated by [`Host::layout`]).
114    pub fn styles(&self) -> &Styles {
115        &self.styles
116    }
117
118    /// The box tree (populated by [`Host::layout`]).
119    pub fn layout(&self) -> &LayoutTree {
120        &self.layout
121    }
122
123    /// The layer's paint commands (populated by [`Host::layout`]).
124    pub fn commands(&self) -> &CommandList {
125        &self.commands
126    }
127
128    /// The sub-document anchor, if this layer is a sub-document.
129    pub fn anchor(&self) -> Option<Anchor> {
130        self.anchor
131    }
132
133    /// The layer's current scroll offset.
134    pub fn scroll(&self) -> Point {
135        self.scroll
136    }
137
138    /// The maximum vertical scroll for this layer (content height minus the
139    /// viewport height, floored at zero).
140    pub fn max_scroll_y(&self) -> f32 {
141        (self.layout.content_height() - self.rect.height).max(0.0)
142    }
143
144    /// This layer's accessibility tree, with bounds in the layer's own
145    /// coordinates and `focus` marked on the source node.
146    #[cfg(feature = "a11y")]
147    pub fn a11y(&self, focus: Option<NodeId>) -> noonoo_a11y::A11yTree {
148        noonoo_a11y::build_in(self.engine.dom(), self.styles(), Some(self.layout()), focus)
149    }
150}
151
152/// A window hosting several documents.
153pub struct Host {
154    /// The window size.
155    pub viewport: Size,
156    layers: Vec<Layer>,
157    focus: Option<(usize, NodeId)>,
158    hovered: Option<(usize, NodeId)>,
159    active: Option<(usize, NodeId)>,
160    /// How text runs are painted: plain `DrawText` by default, glyph
161    /// outlines once a font-backed renderer is set.
162    glyphs: Box<dyn Glyphs + Send + Sync>,
163}
164
165impl Host {
166    /// An empty host for a window of `viewport`.
167    pub fn new(viewport: Size) -> Self {
168        Self {
169            viewport,
170            layers: Vec::new(),
171            focus: None,
172            hovered: None,
173            active: None,
174            glyphs: Box::new(TextRuns),
175        }
176    }
177
178    /// Paint text with `glyphs` from the next layout on: e.g. `noonoo-ttf`'s
179    /// `OutlineGlyphs`, so a GPU window receives glyph outlines. The default,
180    /// `TextRuns`, emits `DrawText` commands.
181    pub fn set_glyphs(&mut self, glyphs: Box<dyn Glyphs + Send + Sync>) {
182        self.glyphs = glyphs;
183    }
184
185    /// Admit the chrome document, placed at `rect`.
186    pub fn add_chrome(&mut self, engine: Engine, rect: Rect) -> usize {
187        self.push(LayerKind::Chrome, Origin::Chrome, engine, rect)
188    }
189
190    /// Admit a content document, placed at `rect`.
191    pub fn add_content(&mut self, engine: Engine, rect: Rect) -> usize {
192        self.push(LayerKind::Content, Origin::Content, engine, rect)
193    }
194
195    fn push(&mut self, kind: LayerKind, origin: Origin, engine: Engine, rect: Rect) -> usize {
196        let index = self.layers.len();
197        self.layers.push(Layer {
198            origin,
199            kind,
200            rect,
201            anchor: None,
202            engine,
203            styles: Styles::default(),
204            layout: LayoutTree::default(),
205            commands: CommandList::default(),
206            scroll: Point::ZERO,
207        });
208        index
209    }
210
211    /// Attach `engine` as a sub-document of the host node `host` in `parent`.
212    ///
213    /// The parent sizes the sub-document: its rectangle is the host node's
214    /// content box, computed on the next [`Host::layout`]. Sub-documents are
215    /// first-class layers, so routing, hit-testing, and composition apply to
216    /// them unchanged.
217    pub fn add_sub_document(&mut self, parent: usize, host: NodeId, engine: Engine) -> usize {
218        let index = self.layers.len();
219        self.layers.push(Layer {
220            origin: Origin::Content,
221            kind: LayerKind::Content,
222            rect: Rect::default(),
223            anchor: Some(Anchor { parent, host }),
224            engine,
225            styles: Styles::default(),
226            layout: LayoutTree::default(),
227            commands: CommandList::default(),
228            scroll: Point::ZERO,
229        });
230        index
231    }
232
233    /// Every layer, in admission order (later layers paint on top).
234    pub fn layers(&self) -> &[Layer] {
235        &self.layers
236    }
237
238    /// Every layer, mutably — for a host adjusting rectangles on resize.
239    pub fn layers_mut(&mut self) -> &mut [Layer] {
240        &mut self.layers
241    }
242
243    /// The layer at `index`.
244    pub fn layer(&self, index: usize) -> Option<&Layer> {
245        self.layers.get(index)
246    }
247
248    /// Compute styles, layout, and paint commands for every layer.
249    ///
250    /// A sub-document's rectangle is taken from its host node's content box in
251    /// the (already laid-out) parent, so the parent sizes it; the sub-document
252    /// is then laid out and painted with its own styles.
253    pub fn layout(&mut self, shaper: &dyn Shaper) {
254        for index in 0..self.layers.len() {
255            if let Some(anchor) = self.layers[index].anchor {
256                let rect = {
257                    let parent = &self.layers[anchor.parent];
258                    let content = parent
259                        .layout
260                        .get(anchor.host)
261                        .map(|box_| box_.content_box())
262                        .unwrap_or_default();
263                    Rect::new(
264                        parent.rect.x + content.x,
265                        parent.rect.y + content.y,
266                        content.width,
267                        content.height,
268                    )
269                };
270                self.layers[index].rect = rect;
271            }
272
273            let interaction = self.interaction_for(index);
274            let layer = &mut self.layers[index];
275            let styles = layer
276                .engine
277                .compute_styles_in(layer.rect.size(), interaction);
278            let mut layout = noonoo_layout::layout_with_images(
279                layer.engine.dom(),
280                &styles,
281                layer.rect.size(),
282                shaper,
283                layer.engine.images(),
284            );
285            // Preserve what the user scrolled across a re-layout.
286            layout.inherit_scroll(&layer.layout);
287            let commands = noonoo_paint::paint_with(&styles, &layout, self.glyphs.as_ref());
288            layer.styles = styles;
289            layer.layout = layout;
290            layer.commands = commands;
291        }
292    }
293
294    /// Take in each layer's finished loads (see
295    /// [`Engine::poll_resources`]); true when an image arrived, so the next
296    /// [`Host::layout`] changes what's drawn.
297    pub fn poll_resources(&mut self) -> bool {
298        let mut changed = false;
299        for layer in &mut self.layers {
300            changed |= layer.engine.poll_resources();
301        }
302        changed
303    }
304
305    /// The topmost layer whose rectangle contains `point`.
306    pub fn route(&self, point: Point) -> Option<usize> {
307        self.layers
308            .iter()
309            .rposition(|layer| layer.rect.contains(point))
310    }
311
312    /// The topmost layer and node under `point`.
313    pub fn hit(&self, point: Point) -> Option<(usize, NodeId)> {
314        let index = self.route(point)?;
315        let layer = &self.layers[index];
316        let local = local_point(layer.rect, point);
317        let node = layer.layout.hit_test(local)?;
318        Some((index, node))
319    }
320
321    /// The topmost layer and *element* under `point`: a hit on text resolves
322    /// to the element containing it, which is what `:hover`, `:active`,
323    /// focus and `cursor` apply to.
324    pub fn element_hit(&self, point: Point) -> Option<(usize, NodeId)> {
325        let (index, mut node) = self.hit(point)?;
326        let dom = self.layers[index].engine().dom();
327        while dom.element(node).is_none() {
328            node = dom.tree().parent(node)?;
329        }
330        Some((index, node))
331    }
332
333    /// The layer that last received a pointer event.
334    pub fn focus(&self) -> Option<(usize, NodeId)> {
335        self.focus
336    }
337
338    /// Set focus to a specific layer and node.
339    pub fn set_focus(&mut self, layer: usize, node: NodeId) {
340        self.focus = Some((layer, node));
341    }
342
343    /// Update the hovered node from a hit test at `point`.
344    ///
345    /// Returns whether it changed — a caller re-layouts to restyle, which is
346    /// when `:hover` takes effect.
347    pub fn hover(&mut self, point: Point) -> bool {
348        let hit = self.element_hit(point);
349        if hit != self.hovered {
350            self.hovered = hit;
351            true
352        } else {
353            false
354        }
355    }
356
357    /// The hovered `(layer, node)`, if any.
358    pub fn hovered(&self) -> Option<(usize, NodeId)> {
359        self.hovered
360    }
361
362    /// Mark the node under `point` as pressed (`:active`).
363    pub fn press(&mut self, point: Point) {
364        self.active = self.element_hit(point);
365    }
366
367    /// Release the press (`:active` ends).
368    pub fn release(&mut self) {
369        self.active = None;
370    }
371
372    /// The pressed `(layer, node)`, if any.
373    pub fn active(&self) -> Option<(usize, NodeId)> {
374        self.active
375    }
376
377    /// The computed `cursor` of the node under `point` (`Auto` when nothing
378    /// is there). Call after a layout, so the styles are fresh.
379    pub fn cursor_at(&self, point: Point) -> Cursor {
380        match self.element_hit(point) {
381            Some((index, node)) => self.layers[index]
382                .styles
383                .get(node)
384                .map(|style| style.cursor.clone())
385                .unwrap_or(Cursor::Auto),
386            None => Cursor::Auto,
387        }
388    }
389
390    /// The interactive state of one layer: only nodes *in* it count.
391    fn interaction_for(&self, index: usize) -> Interaction {
392        let on_layer = |state: Option<(usize, NodeId)>| {
393            state
394                .filter(|(layer, _)| *layer == index)
395                .map(|(_, node)| node)
396        };
397        Interaction {
398            hovered: on_layer(self.hovered),
399            focused: on_layer(self.focus),
400            active: on_layer(self.active),
401        }
402    }
403
404    /// Route a pointer event to the layer under `point`, updating focus.
405    ///
406    /// Returns the `(layer, node)` the event was delivered to, if any.
407    pub fn dispatch_pointer(
408        &mut self,
409        point: Point,
410        event: &Event,
411        listener: &impl EventListener,
412    ) -> Option<(usize, NodeId)> {
413        let (index, node) = self.element_hit(point)?;
414        self.focus = Some((index, node));
415        dispatch(
416            self.layers[index].engine().dom().tree(),
417            node,
418            event,
419            listener,
420        );
421        Some((index, node))
422    }
423
424    /// Route a key event to the focused node (or the focused layer's root).
425    pub fn dispatch_key(&mut self, event: &Event, listener: &impl EventListener) -> bool {
426        let Some((index, node)) = self.focus else {
427            return false;
428        };
429        let layer = &self.layers[index];
430        dispatch(layer.engine().dom().tree(), node, event, listener);
431        true
432    }
433
434    /// Re-run paint for one layer against its current layout, after a scroll.
435    fn repaint(&mut self, index: usize) {
436        let layer = &mut self.layers[index];
437        layer.commands =
438            noonoo_paint::paint_with(&layer.styles, &layer.layout, self.glyphs.as_ref());
439    }
440
441    /// Apply a wheel (scroll) delta at `point`, chaining outward.
442    ///
443    /// Inside a layer, the innermost scroll container under `point` scrolls
444    /// first; what it cannot consume goes to the next container outward, then to
445    /// the layer's own viewport, then — for a sub-document — to its parent.
446    ///
447    /// Returns `(layer, consumed)` pairs along the layer-level chain, innermost
448    /// first. Per-container consumption is visible through
449    /// [`Layer::layout`]/[`LayoutTree::scroll_offset`].
450    pub fn wheel(&mut self, point: Point, delta_y: f32) -> Vec<(usize, f32)> {
451        let mut chain = Vec::new();
452        let Some(mut index) = self.route(point) else {
453            return chain;
454        };
455        let mut leftover = delta_y;
456        loop {
457            // Scroll containers inside this layer first.
458            let local = local_point(self.layers[index].rect, point);
459            let (boxes, remaining) = self.layers[index].layout.scroll_at(local, leftover);
460            if !boxes.is_empty() {
461                self.repaint(index);
462                leftover = remaining;
463            }
464
465            // Then the layer's own viewport scroll.
466            let layer = &mut self.layers[index];
467            let max = layer.max_scroll_y();
468            let before = layer.scroll.y;
469            let after = (before + leftover).clamp(0.0, max);
470            let consumed = after - before;
471            layer.scroll.y = after;
472            if consumed != 0.0 {
473                chain.push((index, consumed));
474            }
475            leftover -= consumed;
476            if leftover.abs() < 1e-4 {
477                break;
478            }
479            match layer.anchor {
480                Some(anchor) => index = anchor.parent,
481                None => break,
482            }
483        }
484        chain
485    }
486
487    /// The window's accessibility tree: every layer under one `window` root.
488    ///
489    /// Bounds are translated by each layer's position (minus its scroll), and
490    /// nodes are renumbered so ids are unique across the window. The focused
491    /// node, if any, is marked and reported as [`noonoo_a11y::A11yTree::focus`].
492    #[cfg(feature = "a11y")]
493    pub fn a11y(&self) -> noonoo_a11y::A11yTree {
494        let mut trees = Vec::with_capacity(self.layers.len());
495        for (index, layer) in self.layers.iter().enumerate() {
496            let focused = match self.focus {
497                Some((layer_index, node)) if layer_index == index => Some(node),
498                _ => None,
499            };
500            let tree = layer.a11y(focused);
501            let offset = Point::new(layer.rect.x - layer.scroll.x, layer.rect.y - layer.scroll.y);
502            trees.push((tree, offset));
503        }
504        let layers: Vec<(&noonoo_a11y::A11yTree, Point)> =
505            trees.iter().map(|(tree, offset)| (tree, *offset)).collect();
506        noonoo_a11y::compose("", &layers)
507    }
508}
509
510fn local_point(rect: Rect, point: Point) -> Point {
511    Point::new(point.x - rect.x, point.y - rect.y)
512}
513
514/// The version of this crate, taken from the workspace.
515pub const VERSION: &str = env!("CARGO_PKG_VERSION");
516
517#[cfg(test)]
518mod tests {
519    use super::*;
520    use noonoo_layout::MetricShaper;
521    use noonoo_paint::Color;
522    use std::cell::RefCell;
523    use std::rc::Rc;
524
525    fn engine(html: &str, css: &str) -> Engine {
526        // Without the UA's `body` margin, a snippet starts at the origin.
527        Engine::from_html(&format!("<style>body {{ margin: 0 }} {css}</style>{html}"))
528    }
529
530    fn host() -> Host {
531        let mut host = Host::new(Size::new(400.0, 300.0));
532        host.add_chrome(
533            engine(
534                r#"<div id="bar">chrome</div>"#,
535                "#bar { height: 24px; background-color: #222222 }",
536            ),
537            Rect::new(0.0, 0.0, 400.0, 24.0),
538        );
539        host.add_content(
540            engine(
541                r#"<div id="page">content</div>"#,
542                "#page { height: 100px; background-color: #ffffff }",
543            ),
544            Rect::new(0.0, 24.0, 400.0, 276.0),
545        );
546        host.layout(&MetricShaper);
547        host
548    }
549
550    /// A layer's images load through its engine's loader; polling reports
551    /// the arrival, and the next layout draws them.
552    #[test]
553    fn layers_draw_the_images_their_engines_loaded() {
554        let dir = std::env::temp_dir().join("noonoo-shell-images");
555        std::fs::create_dir_all(&dir).unwrap();
556        let mut png = b"\x89PNG\r\n\x1a\n".to_vec();
557        png.extend(13u32.to_be_bytes());
558        png.extend(b"IHDR");
559        png.extend(40u32.to_be_bytes());
560        png.extend(30u32.to_be_bytes());
561        png.extend([8, 6, 0, 0, 0]);
562        std::fs::write(dir.join("a.png"), png).unwrap();
563        let mut host = host();
564        assert!(!host.poll_resources());
565        let mut page = engine(r#"<img src="a.png">"#, "");
566        page.set_base_url(format!("{}/index.html", dir.display()));
567        page.set_loader(noonoo_net::FileLoader);
568        page.load_resources();
569        let layer = host.add_content(page, Rect::new(0.0, 24.0, 400.0, 276.0));
570        assert!(host.poll_resources());
571        assert!(!host.poll_resources());
572        host.layout(&MetricShaper);
573        let drawn = host.layers()[layer]
574            .commands()
575            .commands()
576            .iter()
577            .filter(|c| matches!(c, noonoo_paint::Command::DrawImage { .. }))
578            .count();
579        assert_eq!(drawn, 1);
580    }
581
582    /// An embedder patches a layer's document (super-surfer's address bar,
583    /// tabs, progress) and the next layout paints the change.
584    #[test]
585    fn a_layers_document_can_be_changed_in_place() {
586        let mut host = host();
587        let engine = host.layers_mut()[0].engine_mut();
588        let bar = engine.dom().get_element_by_id("bar").unwrap();
589        let text = engine.dom().tree().children(bar)[0];
590        engine.dom_mut().mutate().set_text(text, "patched").unwrap();
591        host.layout(&MetricShaper);
592        let painted = host.layers()[0].commands().commands().iter().any(|command| {
593            matches!(command, noonoo_paint::Command::DrawText { text, .. } if text == "patched")
594        });
595        assert!(painted);
596    }
597
598    #[test]
599    fn routes_by_region() {
600        let host = host();
601        assert_eq!(host.route(Point::new(10.0, 10.0)), Some(0));
602        assert_eq!(host.route(Point::new(10.0, 50.0)), Some(1));
603        assert_eq!(host.route(Point::new(10.0, 999.0)), None);
604    }
605
606    #[test]
607    fn hit_tests_to_the_right_document_and_node() {
608        let host = host();
609        let (layer, node) = host.hit(Point::new(10.0, 50.0)).unwrap();
610        assert_eq!(layer, 1);
611        assert_eq!(
612            host.layer(1)
613                .unwrap()
614                .engine()
615                .dom()
616                .element(node)
617                .unwrap()
618                .name,
619            "div"
620        );
621    }
622
623    #[test]
624    fn pointer_sets_focus_and_dispatches() {
625        let mut host = host();
626        let seen: Rc<RefCell<Vec<NodeId>>> = Rc::new(RefCell::new(Vec::new()));
627        let listener = {
628            let seen = seen.clone();
629            noonoo_events::FnListener(
630                move |node: NodeId, _e: &Event, _p: noonoo_events::EventPhase| {
631                    seen.borrow_mut().push(node);
632                    noonoo_events::Propagation::Continue
633                },
634            )
635        };
636        let routed = host.dispatch_pointer(
637            Point::new(10.0, 50.0),
638            &Event::Click(noonoo_events::PointerEvent {
639                x: 10.0,
640                y: 50.0,
641                button: noonoo_events::MouseButton::Primary,
642                state: noonoo_events::ElementState::Released,
643                modifiers: noonoo_events::Modifiers::default(),
644            }),
645            &listener,
646        );
647        let (layer, _node) = routed.unwrap();
648        assert_eq!(layer, 1);
649        assert_eq!(host.focus().unwrap().0, 1);
650        assert!(!seen.borrow().is_empty());
651
652        // A key event goes to the focused layer.
653        assert!(host.dispatch_key(&Event::Input { value: "a".into() }, &listener));
654    }
655
656    #[test]
657    fn composes_one_command_stream_per_layer() {
658        let host = host();
659        assert_eq!(host.layers().len(), 2);
660        assert!(!host.layer(0).unwrap().commands().is_empty());
661        assert!(!host.layer(1).unwrap().commands().is_empty());
662    }
663
664    #[test]
665    fn sub_document_is_sized_by_its_host_node() {
666        let mut host = Host::new(Size::new(400.0, 300.0));
667        let parent = host.add_chrome(
668            engine(
669                r#"<div id="slot"></div>"#,
670                "#slot { width: 200px; height: 100px }",
671            ),
672            Rect::new(0.0, 0.0, 400.0, 300.0),
673        );
674        let slot = host
675            .layer(parent)
676            .unwrap()
677            .engine()
678            .dom()
679            .get_element_by_id("slot")
680            .unwrap();
681        let sub = engine(
682            r#"<p id="emb">embedded</p>"#,
683            "p { margin: 0; height: 40px; background-color: #eeeeee }",
684        );
685        let sub_index = host.add_sub_document(parent, slot, sub);
686        host.layout(&MetricShaper);
687
688        // The parent's host node (200×100) sized the sub-document.
689        assert_eq!(
690            host.layer(sub_index).unwrap().rect,
691            Rect::new(0.0, 0.0, 200.0, 100.0)
692        );
693        // Inside the sub-document, routing and hit-testing select it.
694        assert_eq!(host.route(Point::new(10.0, 10.0)), Some(sub_index));
695        let (layer, node) = host.hit(Point::new(10.0, 10.0)).unwrap();
696        assert_eq!(layer, sub_index);
697        // The deepest node is the text run inside the sub-document's <p>.
698        assert_eq!(
699            host.layer(sub_index)
700                .unwrap()
701                .engine()
702                .dom()
703                .node(node)
704                .and_then(|data| data.as_text()),
705            Some("embedded")
706        );
707        // It composed its own command stream.
708        assert!(!host.layer(sub_index).unwrap().commands().is_empty());
709    }
710
711    #[test]
712    fn pointing_at_text_hovers_and_presses_its_element() {
713        let mut host = Host::new(Size::new(400.0, 300.0));
714        host.add_content(
715            engine(
716                "<p>hello</p>",
717                "body { margin: 0 } p { margin: 0; cursor: pointer }
718                 p:hover { background: red }",
719            ),
720            Rect::new(0.0, 0.0, 400.0, 300.0),
721        );
722        host.layout(&MetricShaper);
723        // The point is on the text "hello", not just its paragraph.
724        let point = Point::new(2.0, 2.0);
725        let (_, deepest) = host.hit(point).unwrap();
726        let dom = host.layer(0).unwrap().engine().dom();
727        assert!(dom.element(deepest).is_none(), "the hit is the text node");
728
729        assert_eq!(host.cursor_at(point), Cursor::Pointer);
730        host.hover(point);
731        host.press(point);
732        let p = host.hovered().unwrap().1;
733        let dom = host.layer(0).unwrap().engine().dom();
734        assert_eq!(dom.element(p).unwrap().name, "p");
735        assert_eq!(host.active().unwrap().1, p);
736        host.layout(&MetricShaper);
737        assert_eq!(
738            host.layer(0)
739                .unwrap()
740                .styles()
741                .get(p)
742                .unwrap()
743                .background_color,
744            Color::rgb(255, 0, 0)
745        );
746    }
747
748    #[test]
749    fn hover_and_active_restyle_on_the_next_layout() {
750        let mut host = Host::new(Size::new(400.0, 300.0));
751        host.add_content(
752            engine(
753                r#"<button id="b">hi</button>"#,
754                "button { cursor: pointer; background: white }
755                 button:hover { background: red }
756                 button:active { background: green }
757                 button:focus { outline: 1px }",
758            ),
759            Rect::new(0.0, 0.0, 400.0, 300.0),
760        );
761        host.layout(&MetricShaper);
762        let point = Point::new(10.0, 10.0);
763
764        // Nothing hovered: white, but `cursor: pointer` is unconditional.
765        assert!(host.hovered().is_none());
766        assert_eq!(host.cursor_at(point), Cursor::Pointer);
767
768        // Hover restyles on the next layout and lights up the cursor.
769        assert!(host.hover(point), "the first hover is a change");
770        host.layout(&MetricShaper);
771        let b = host.hovered().unwrap().1;
772        assert_eq!(
773            host.layer(0)
774                .unwrap()
775                .styles()
776                .get(b)
777                .unwrap()
778                .background_color,
779            Color::rgb(255, 0, 0)
780        );
781        assert_eq!(host.cursor_at(point), Cursor::Pointer);
782        // Hovering the same point again is not a change.
783        assert!(!host.hover(point));
784
785        // Pressing goes active; releasing returns to the hover colour.
786        host.press(point);
787        host.layout(&MetricShaper);
788        assert_eq!(
789            host.layer(0)
790                .unwrap()
791                .styles()
792                .get(b)
793                .unwrap()
794                .background_color,
795            Color::rgb(0, 128, 0)
796        );
797        host.release();
798        host.layout(&MetricShaper);
799        assert_eq!(
800            host.layer(0)
801                .unwrap()
802                .styles()
803                .get(b)
804                .unwrap()
805                .background_color,
806            Color::rgb(255, 0, 0)
807        );
808    }
809
810    #[test]
811    fn hover_does_not_leak_across_layers() {
812        let mut host = Host::new(Size::new(400.0, 300.0));
813        host.add_chrome(
814            engine("<div id=\"c\">x</div>", "div:hover { color: red }"),
815            Rect::new(0.0, 0.0, 400.0, 50.0),
816        );
817        host.add_content(
818            engine("<div id=\"d\">y</div>", "div { color: black }"),
819            Rect::new(0.0, 50.0, 400.0, 250.0),
820        );
821        host.layout(&MetricShaper);
822
823        // Hovering the content layer must not style the chrome's div.
824        assert!(host.hover(Point::new(10.0, 60.0)));
825        host.layout(&MetricShaper);
826        let c = host
827            .layer(0)
828            .unwrap()
829            .engine()
830            .dom()
831            .get_element_by_id("c")
832            .unwrap();
833        assert_eq!(
834            host.layer(0).unwrap().styles().get(c).unwrap().color,
835            Color::BLACK
836        );
837    }
838
839    #[test]
840    fn wheel_chains_from_a_sub_document_to_its_parent() {
841        let mut host = Host::new(Size::new(400.0, 200.0));
842        let parent = host.add_chrome(
843            engine(
844                r#"<div id="slot"></div><div id="tail"></div>"#,
845                "#slot { width: 200px; height: 100px } #tail { height: 400px }",
846            ),
847            Rect::new(0.0, 0.0, 400.0, 200.0),
848        );
849        let slot = host
850            .layer(parent)
851            .unwrap()
852            .engine()
853            .dom()
854            .get_element_by_id("slot")
855            .unwrap();
856        let sub = engine(r#"<div id="long"></div>"#, "#long { height: 300px }");
857        let sub_index = host.add_sub_document(parent, slot, sub);
858        host.layout(&MetricShaper);
859
860        // Sub viewport 100 over 300 content → 200; parent 200 over 500 → 300.
861        assert_eq!(host.layer(sub_index).unwrap().max_scroll_y(), 200.0);
862        assert_eq!(host.layer(parent).unwrap().max_scroll_y(), 300.0);
863
864        // 250 down: the sub-document takes 200, the parent takes the rest.
865        let chain = host.wheel(Point::new(10.0, 10.0), 250.0);
866        assert_eq!(chain, vec![(sub_index, 200.0), (parent, 50.0)]);
867        assert_eq!(host.layer(sub_index).unwrap().scroll().y, 200.0);
868        assert_eq!(host.layer(parent).unwrap().scroll().y, 50.0);
869    }
870
871    #[test]
872    fn wheel_does_not_chain_while_the_sub_document_can_scroll() {
873        let mut host = Host::new(Size::new(400.0, 200.0));
874        let parent = host.add_chrome(
875            engine(
876                r#"<div id="slot"></div>"#,
877                "#slot { width: 200px; height: 100px }",
878            ),
879            Rect::new(0.0, 0.0, 400.0, 200.0),
880        );
881        let slot = host
882            .layer(parent)
883            .unwrap()
884            .engine()
885            .dom()
886            .get_element_by_id("slot")
887            .unwrap();
888        let sub = engine(r#"<div id="long"></div>"#, "#long { height: 300px }");
889        let sub_index = host.add_sub_document(parent, slot, sub);
890        host.layout(&MetricShaper);
891
892        let chain = host.wheel(Point::new(10.0, 10.0), 50.0);
893        assert_eq!(chain, vec![(sub_index, 50.0)]);
894        assert_eq!(host.layer(parent).unwrap().scroll().y, 0.0);
895    }
896
897    /// A `Glyphs` that marks each run with a green square, standing in for
898    /// a font-backed renderer.
899    struct MarkGlyphs;
900
901    impl noonoo_paint::Glyphs for MarkGlyphs {
902        fn draw(
903            &self,
904            _text: &str,
905            (x, y): (f32, f32),
906            _font_size: f32,
907            _color: Color,
908            _request: noonoo_paint::FontRequest,
909            out: &mut noonoo_paint::CommandList,
910        ) {
911            out.0.push(noonoo_paint::Command::FillRect {
912                rect: Rect::new(x, y, 1.0, 1.0),
913                color: Color::rgb(0, 255, 0),
914                radius: (0.0, 0.0, 0.0, 0.0),
915            });
916        }
917    }
918
919    fn marks(host: &Host, index: usize) -> (usize, usize) {
920        let commands = host.layer(index).unwrap().commands().commands();
921        let marks = commands
922            .iter()
923            .filter(|c| {
924                matches!(c, noonoo_paint::Command::FillRect { color, .. } if *color == Color::rgb(0, 255, 0))
925            })
926            .count();
927        let runs = commands
928            .iter()
929            .filter(|c| matches!(c, noonoo_paint::Command::DrawText { .. }))
930            .count();
931        (marks, runs)
932    }
933
934    /// Text paints through the host's `Glyphs`, on layout and on the repaint
935    /// after a scroll, so a window gets glyph outlines instead of text runs
936    /// a GPU backend can't draw.
937    #[test]
938    fn text_paints_through_the_hosts_glyphs() {
939        let mut host = Host::new(Size::new(400.0, 300.0));
940        host.set_glyphs(Box::new(MarkGlyphs));
941        let index = host.add_content(
942            engine(
943                r#"<div id="list"><p>one</p><div id="tall"></div></div>"#,
944                "#list { height: 50px; overflow-y: auto } #tall { height: 200px }",
945            ),
946            Rect::new(0.0, 0.0, 400.0, 300.0),
947        );
948        host.layout(&MetricShaper);
949        assert_eq!(marks(&host, index), (1, 0));
950
951        host.wheel(Point::new(10.0, 10.0), 100.0);
952        assert_eq!(
953            marks(&host, index),
954            (1, 0),
955            "the scroll repaint keeps the glyphs"
956        );
957    }
958
959    #[test]
960    fn wheel_scrolls_an_inner_container_before_the_layer() {
961        let mut host = Host::new(Size::new(400.0, 300.0));
962        let index = host.add_content(
963            engine(
964                r#"<div id="list"><div id="tall"></div></div><div id="tail"></div>"#,
965                "#list { width: 200px; height: 50px; overflow-y: auto } \
966                 #tall { height: 200px } #tail { height: 600px }",
967            ),
968            Rect::new(0.0, 0.0, 400.0, 300.0),
969        );
970        host.layout(&MetricShaper);
971        let list = host
972            .layer(index)
973            .unwrap()
974            .engine()
975            .dom()
976            .get_element_by_id("list")
977            .unwrap();
978        assert_eq!(host.layer(index).unwrap().layout().scroll_max(list), 150.0);
979
980        // A wheel over the list scrolls the list, not the layer.
981        host.wheel(Point::new(10.0, 10.0), 100.0);
982        assert_eq!(
983            host.layer(index).unwrap().layout().scroll_offset(list),
984            100.0
985        );
986        assert_eq!(host.layer(index).unwrap().scroll().y, 0.0);
987    }
988
989    #[test]
990    fn wheel_chains_from_a_container_to_the_layer() {
991        let mut host = Host::new(Size::new(400.0, 300.0));
992        let index = host.add_content(
993            engine(
994                r#"<div id="list"><div id="tall"></div></div><div id="tail"></div>"#,
995                "#list { width: 200px; height: 50px; overflow-y: auto } \
996                 #tall { height: 200px } #tail { height: 600px }",
997            ),
998            Rect::new(0.0, 0.0, 400.0, 300.0),
999        );
1000        host.layout(&MetricShaper);
1001        let list = host
1002            .layer(index)
1003            .unwrap()
1004            .engine()
1005            .dom()
1006            .get_element_by_id("list")
1007            .unwrap();
1008
1009        // 200 down: the list takes 150 (its whole range), the layer the rest.
1010        let chain = host.wheel(Point::new(10.0, 10.0), 200.0);
1011        assert_eq!(
1012            host.layer(index).unwrap().layout().scroll_offset(list),
1013            150.0
1014        );
1015        assert_eq!(host.layer(index).unwrap().scroll().y, 50.0);
1016        assert_eq!(chain, vec![(index, 50.0)]);
1017    }
1018
1019    #[cfg(feature = "a11y")]
1020    #[test]
1021    fn a11y_composes_layers_with_bounds_and_focus() {
1022        let mut host = host();
1023        let node = host
1024            .layer(1)
1025            .unwrap()
1026            .engine()
1027            .dom()
1028            .get_element_by_id("page")
1029            .unwrap();
1030        host.set_focus(1, node);
1031
1032        let tree = host.a11y();
1033        assert_eq!(tree.root.role, noonoo_a11y::Role::Window);
1034        assert_eq!(tree.root.children.len(), 2);
1035
1036        let focused = tree.focus.unwrap();
1037        let node = tree.find_by_id(focused).unwrap();
1038        assert_eq!(
1039            node.node,
1040            Some(
1041                host.layer(1)
1042                    .unwrap()
1043                    .engine()
1044                    .dom()
1045                    .get_element_by_id("page")
1046                    .unwrap()
1047            )
1048        );
1049        assert_eq!(node.layer, Some(1));
1050        assert_eq!(node.role, noonoo_a11y::Role::Generic);
1051        assert!(node.bounds.unwrap().y >= 24.0);
1052    }
1053
1054    #[test]
1055    fn origin_gates_internal_schemes() {
1056        assert!(navigation_allowed(&Origin::Chrome, "shell"));
1057        assert!(!navigation_allowed(&Origin::Content, "shell"));
1058        assert!(navigation_allowed(&Origin::Content, "https"));
1059        assert!(navigation_allowed(&Origin::Custom("app".into()), "exo"));
1060    }
1061}