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