Skip to main content

noonoo_engine/
lib.rs

1//! # noonoo-engine
2//!
3//! Orchestration: the crate that gives you a *working* page — the equivalent of
4//! the replaced engine's `BaseDocument` / `HtmlDocument`, but assembled from the
5//! small crates instead of a monolith.
6//!
7//! An [`Engine`] owns a [`noonoo_dom::Document`], the [`Stylesheet`]s parsed out
8//! of the document, and (once the `resolve` feature is on) the layout caches
9//! that keep it presentable. Each of those abilities is a different crate
10//! underneath, and — crucially — the parse and style-ingest steps are **ours**:
11//! [`noonoo_html`] and [`noonoo_css`], not a borrowed parser.
12//!
13//! ## The `Send` question
14//!
15//! The replaced engine's `Document` was `!Send`, which blocked running a page
16//! off the UI thread and forced consumers into a texture-overlay workaround for
17//! sub-documents. Noonoo's tree owns no `Rc`/`RefCell` and promises nothing
18//! unsafe, so an engine is `Send` whenever its payload is.
19
20#![forbid(unsafe_code)]
21#![warn(missing_docs)]
22
23use noonoo_css::Stylesheet;
24use noonoo_dom::{Change, Changes, Document, NodeData, NodeId};
25use noonoo_style::{Cascade, Interaction, Styles, Viewport};
26
27mod fonts;
28mod resources;
29
30pub use fonts::{FontData, LoadedFont};
31mod sheets;
32
33/// A page: a DOM document, its stylesheets, and (later) its resolved layout.
34pub struct Engine {
35    dom: Document,
36    stylesheets: Vec<Stylesheet>,
37    /// The `<style>` elements the stylesheets came from, in order.
38    style_elements: Vec<NodeId>,
39    /// The stylesheets prepared for [`Engine::restyle`], once it has run.
40    cascade: Option<Cascade>,
41    /// Whether the host prefers a dark colour scheme (see
42    /// [`Engine::set_prefers_dark`]).
43    prefers_dark: bool,
44    /// Subresources: the loader, what was asked of it, and what arrived.
45    resources: resources::Resources,
46}
47
48impl Default for Engine {
49    fn default() -> Self {
50        Self::new()
51    }
52}
53
54impl Engine {
55    /// Create an empty engine with a fresh document.
56    pub fn new() -> Self {
57        Self {
58            dom: Document::new(),
59            stylesheets: Vec::new(),
60            style_elements: Vec::new(),
61            cascade: None,
62            prefers_dark: false,
63            resources: resources::Resources::default(),
64        }
65    }
66
67    /// Parse `html` into a fresh engine, collecting its stylesheets.
68    pub fn from_html(html: &str) -> Self {
69        let mut engine = Self {
70            dom: noonoo_html::parse(html),
71            ..Self::new()
72        };
73        engine.refresh_stylesheets();
74        engine
75    }
76
77    /// Borrow the underlying DOM document.
78    pub fn dom(&self) -> &Document {
79        &self.dom
80    }
81
82    /// Mutably borrow the underlying DOM document.
83    pub fn dom_mut(&mut self) -> &mut Document {
84        &mut self.dom
85    }
86
87    /// The stylesheets collected from the document's `<style>` elements.
88    pub fn stylesheets(&self) -> &[Stylesheet] {
89        &self.stylesheets
90    }
91
92    /// Re-scan the document's `<style>` elements for stylesheets.
93    pub fn refresh_stylesheets(&mut self) {
94        (self.style_elements, self.stylesheets) = self.collect_stylesheets();
95        self.cascade = None;
96    }
97
98    /// The `<style>` elements and loaded `<link>` sheets, in document order
99    /// (so cascade order is document order however the loads arrived), with
100    /// the element ids they came from.
101    fn collect_stylesheets(&self) -> (Vec<NodeId>, Vec<Stylesheet>) {
102        let elements = style_elements(&self.dom);
103        let mut sheets = Vec::new();
104        for &id in &elements {
105            if is_style(&self.dom, id) {
106                let text = self.dom.text_content(id);
107                if text.trim().is_empty() {
108                    continue;
109                }
110                let text = match &self.resources.base_url {
111                    Some(base) => sheets::absolutize_urls(&text, base),
112                    None => text,
113                };
114                if let Ok(sheet) = Stylesheet::parse(&text) {
115                    sheets.push(sheet);
116                }
117            } else {
118                sheets.extend(self.resources.sheets.for_link(id));
119            }
120        }
121        (elements, sheets)
122    }
123
124    /// Bring `styles` up to date with the document, its stylesheets,
125    /// `viewport` and `interaction`, restyling only what changed since the
126    /// last call. Returns how many times an element was styled.
127    ///
128    /// Start from [`Styles::default`]: the first call computes everything.
129    /// After that, edits made through [`Document::mutate`] restyle only the
130    /// subtrees they can reach, and a hover, focus or press moving restyles
131    /// the nodes it moved between. An edit to a `<style>` element, a new
132    /// viewport, or raw writes through [`Document::tree_mut`] restyle
133    /// everything, and so does any edit but to text while a rule uses
134    /// `:has()`.
135    pub fn restyle(
136        &mut self,
137        styles: &mut Styles,
138        viewport: noonoo_geometry::Size,
139        interaction: Interaction,
140    ) -> usize {
141        let changes = self.dom.take_changes();
142        if self.touches_stylesheets(&changes) {
143            self.refresh_stylesheets();
144        }
145        let viewport = Viewport {
146            width: viewport.width,
147            height: viewport.height,
148        };
149        match &self.cascade {
150            Some(cascade) if cascade.viewport() == viewport => {
151                cascade.restyle(styles, &self.dom, interaction, &changes)
152            }
153            _ => {
154                let cascade =
155                    Cascade::with_preferences(&self.stylesheets, viewport, self.prefers_dark);
156                *styles = cascade.compute(&self.dom, interaction);
157                self.cascade = Some(cascade);
158                self.dom.elements().len()
159            }
160        }
161    }
162
163    /// Whether `changes` may have changed what the `<style>` elements say:
164    /// text inside one changed, or one was added or removed.
165    fn touches_stylesheets(&self, changes: &Changes) -> bool {
166        if changes.overflowed() {
167            return true;
168        }
169        let in_style = |node: NodeId| {
170            std::iter::once(node)
171                .chain(self.dom.tree().ancestors(node))
172                .any(|id| is_style(&self.dom, id))
173        };
174        let mut moved = false;
175        for change in changes.iter() {
176            match *change {
177                // `collect_stylesheets` reads no attributes.
178                Change::Attributes(_) => {}
179                Change::Text(node) if in_style(node) => return true,
180                Change::Text(_) => {}
181                Change::Children(node) if in_style(node) => return true,
182                Change::Children(_) => moved = true,
183            }
184        }
185        moved && style_elements(&self.dom) != self.style_elements
186    }
187
188    /// The `@font-face` descriptors collected from the stylesheets, in source
189    /// order.
190    ///
191    /// A host loads each `src` (`noonoo-net` covers `file:` and `data:`),
192    /// parses the bytes with `noonoo-ttf`'s `Font`, and registers the face
193    /// with a `FontSet`; see the `noonoo` CLI's `--paint` for the pattern.
194    pub fn font_faces(&self) -> Vec<noonoo_css::FontFace> {
195        self.stylesheets
196            .iter()
197            .flat_map(|sheet| sheet.font_faces())
198            .collect()
199    }
200
201    /// Compute every element's style: cascade the collected stylesheets over the
202    /// user-agent sheet and any inline `style` attributes.
203    ///
204    /// Viewport-relative units resolve against
205    /// [`noonoo_style::Viewport::DEFAULT`]; [`Engine::compute_styles_for`] uses a
206    /// real viewport instead.
207    pub fn compute_styles(&self) -> noonoo_style::Styles {
208        noonoo_style::compute(&self.dom, &self.stylesheets)
209    }
210
211    /// Compute every element's style against `viewport`, so `vw`/`vh` and
212    /// `calc(100vw - 2rem)` resolve correctly.
213    pub fn compute_styles_for(&self, viewport: noonoo_geometry::Size) -> noonoo_style::Styles {
214        self.compute_styles_in(viewport, noonoo_style::Interaction::default())
215    }
216
217    /// Compute every element's style against `viewport` and the interactive
218    /// state, so `:hover`/`:focus`/`:active` style the elements they name.
219    pub fn compute_styles_in(
220        &self,
221        viewport: noonoo_geometry::Size,
222        interaction: noonoo_style::Interaction,
223    ) -> noonoo_style::Styles {
224        Cascade::with_preferences(
225            &self.stylesheets,
226            Viewport {
227                width: viewport.width,
228                height: viewport.height,
229            },
230            self.prefers_dark,
231        )
232        .compute(&self.dom, interaction)
233    }
234
235    /// Lay the document out for a viewport, using the given text shaper.
236    pub fn layout(
237        &self,
238        viewport: noonoo_geometry::Size,
239        shaper: &dyn noonoo_layout::Shaper,
240    ) -> noonoo_layout::LayoutTree {
241        let styles = self.compute_styles_for(viewport);
242        noonoo_layout::layout_with_images(&self.dom, &styles, viewport, shaper, self.images())
243    }
244
245    /// Whether the host prefers a dark colour scheme (default: light). It
246    /// decides `light-dark()` for an element whose `color-scheme` lists both
247    /// `light` and `dark` (a page that sets no `color-scheme` stays light),
248    /// and `@media (prefers-color-scheme)`. Takes effect at the next
249    /// restyle.
250    pub fn set_prefers_dark(&mut self, prefers_dark: bool) {
251        self.prefers_dark = prefers_dark;
252        self.cascade = None;
253    }
254
255    /// The canvas background for `styles`: the root element's background
256    /// colour or, when the root has neither a colour nor a background image,
257    /// the body's (CSS Backgrounds 3, section 2.11.2). `None` when neither
258    /// paints.
259    pub fn canvas(&self, styles: &noonoo_style::Styles) -> Option<noonoo_paint::Canvas> {
260        let root = *self.dom.get_elements_by_tag_name("html").first()?;
261        let painted = |node: NodeId| {
262            let color = styles.get(node)?.background_color;
263            (color.a > 0).then_some(noonoo_paint::Canvas {
264                color,
265                source: node,
266            })
267        };
268        // The body's background propagates only when the root has neither a
269        // colour nor an image; a root image paints as the root's own.
270        let root_style = styles.get(root)?;
271        let root_image =
272            root_style.background_image.is_some() || root_style.background_url.is_some();
273        painted(root).or_else(|| {
274            if root_image {
275                return None;
276            }
277            let body = self
278                .dom
279                .tree()
280                .children(root)
281                .iter()
282                .copied()
283                .find(|&child| self.dom.element(child).is_some_and(|e| e.name == "body"))?;
284            painted(body)
285        })
286    }
287
288    /// Lay out and paint the document, returning the render command stream.
289    pub fn paint(
290        &self,
291        viewport: noonoo_geometry::Size,
292        shaper: &dyn noonoo_layout::Shaper,
293    ) -> noonoo_paint::CommandList {
294        self.paint_with(viewport, shaper, &noonoo_paint::TextRuns)
295    }
296
297    /// Lay out and paint the document, drawing text with `glyphs`.
298    ///
299    /// Use this with a font-backed shaper and matching glyph renderer to render
300    /// vector text (see `noonoo-ttf`'s `FontShaper` + `OutlineGlyphs`).
301    pub fn paint_with(
302        &self,
303        viewport: noonoo_geometry::Size,
304        shaper: &dyn noonoo_layout::Shaper,
305        glyphs: &dyn noonoo_paint::Glyphs,
306    ) -> noonoo_paint::CommandList {
307        let styles = self.compute_styles_for(viewport);
308        let layout =
309            noonoo_layout::layout_with_images(&self.dom, &styles, viewport, shaper, self.images());
310        noonoo_paint::paint_canvas(&styles, &layout, glyphs, self.canvas(&styles))
311    }
312
313    /// Consume the engine and return its document.
314    pub fn into_dom(self) -> Document {
315        self.dom
316    }
317}
318
319/// Collect and parse the `<style>` elements in a document.
320///
321/// A `<style>` whose text is empty or fails to parse is skipped; a page with a
322/// broken stylesheet still yields its DOM.
323/// The document's `<style>` elements, and the stylesheets parsed from them.
324/// The `<style>` and `<link>` elements, in document order.
325fn style_elements(dom: &Document) -> Vec<NodeId> {
326    dom.elements()
327        .into_iter()
328        .filter(|&id| {
329            matches!(dom.node(id), Some(NodeData::Element(e)) if e.name == "style" || e.name == "link")
330        })
331        .collect()
332}
333
334fn is_style(dom: &Document, id: NodeId) -> bool {
335    matches!(dom.node(id), Some(NodeData::Element(element)) if element.name == "style")
336}
337
338/// The version of this crate, taken from the workspace.
339pub const VERSION: &str = env!("CARGO_PKG_VERSION");
340
341#[cfg(test)]
342mod tests {
343    use super::*;
344
345    #[test]
346    fn new_engine_has_a_document_root() {
347        let engine = Engine::new();
348        let root = engine.dom().root();
349        assert!(engine.dom().tree().contains(root));
350        assert!(engine.stylesheets().is_empty());
351    }
352
353    #[test]
354    fn from_html_parses_the_tree() {
355        let engine = Engine::from_html("<div id=\"box\"><span>hi</span></div>");
356        let box_id = engine.dom().get_element_by_id("box").unwrap();
357        assert_eq!(engine.dom().element(box_id).unwrap().name, "div");
358    }
359
360    #[test]
361    fn collects_style_sheets() {
362        let engine = Engine::from_html("<style>body { color: red; margin: 0 }</style><p>hi</p>");
363        assert_eq!(engine.stylesheets().len(), 1);
364        assert_eq!(engine.stylesheets()[0].rules.len(), 1);
365    }
366
367    #[test]
368    fn collects_font_face_descriptors() {
369        let engine = Engine::from_html(
370            "<style>@font-face { font-family: A; src: url(a.ttf); font-weight: bold }</style>
371             <style>@font-face { font-family: B; src: url(b.ttf) url(b.woff) }</style>",
372        );
373        let faces = engine.font_faces();
374        assert_eq!(faces.len(), 2);
375        assert_eq!(faces[0].family, "A");
376        assert_eq!(faces[0].weight, 700);
377        assert_eq!(faces[1].src, vec!["b.ttf".to_owned(), "b.woff".to_owned()]);
378    }
379
380    #[test]
381    fn skips_empty_and_broken_stylesheets() {
382        let engine = Engine::from_html(
383            "<style></style><style>a { color: red</style><style>b { color: blue }</style>",
384        );
385        // The empty one is dropped, the unclosed one fails to parse, the valid one stays.
386        assert_eq!(engine.stylesheets().len(), 1);
387    }
388
389    #[test]
390    fn computes_styles_for_a_page() {
391        let engine = Engine::from_html(
392            "<style>p { display: flex; color: red; margin: 5px }</style><p>x</p>",
393        );
394        let styles = engine.compute_styles();
395        let p = engine.dom().get_elements_by_tag_name("p")[0];
396        let style = styles.get(p).unwrap();
397        assert_eq!(style.display, noonoo_style::Display::Flex);
398        assert_eq!(style.color, noonoo_css::Color::rgb(255, 0, 0));
399        assert_eq!(style.margin.top, noonoo_style::Dimension::Px(5.0));
400    }
401
402    #[test]
403    fn lays_out_a_page() {
404        let engine = Engine::from_html(
405            "<style>body { margin: 0 } #a { height: 40px }</style><div id=\"a\"></div>",
406        );
407        let tree = engine.layout(
408            noonoo_geometry::Size::new(300.0, 200.0),
409            &noonoo_layout::MetricShaper,
410        );
411        let a = engine.dom().get_element_by_id("a").unwrap();
412        let box_ = tree.get(a).unwrap();
413        assert_eq!(box_.rect.width, 300.0);
414        assert_eq!(box_.rect.height, 40.0);
415    }
416
417    #[test]
418    fn paints_a_page() {
419        let engine = Engine::from_html(
420            "<style>#a { background-color: #102030 }</style><div id=\"a\">hi</div>",
421        );
422        let list = engine.paint(
423            noonoo_geometry::Size::new(200.0, 100.0),
424            &noonoo_layout::MetricShaper,
425        );
426        assert!(!list.is_empty());
427    }
428}
429
430#[cfg(doctest)]
431#[doc = include_str!("../README.md")]
432pub struct ReadmeDoctests;