Skip to main content

layout_api/
lib.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! This module contains traits in script used generically in the rest of Servo.
6//! The traits are here instead of in script so that these modules won't have
7//! to depend on script.
8
9#![deny(unsafe_code)]
10
11mod accessibility;
12mod container_timing_record;
13mod largest_contentful_paint_candidate;
14mod layout_damage;
15mod layout_dom;
16mod layout_element;
17mod layout_node;
18mod pseudo_element_chain;
19mod writing_mode_ext;
20
21use std::any::Any;
22use std::rc::Rc;
23use std::sync::Arc;
24use std::sync::atomic::AtomicIsize;
25use std::thread::JoinHandle;
26use std::time::Duration;
27
28pub use accessibility::{
29    ACCESSKIT_ROLE_TO_ARIA_ROLE, ARIA_ROLE_TO_ACCESSKIT_ROLE, AccessibilityDamage,
30    SUPPORTED_ARIA_ROLES,
31};
32use accesskit::{Action, ActionData, ActionRequest};
33use app_units::Au;
34use background_hang_monitor_api::BackgroundHangMonitorRegister;
35use bitflags::bitflags;
36pub use container_timing_record::ContainerTimingRecord;
37use embedder_traits::{Cursor, ScriptToEmbedderChan, Theme, UntrustedNodeAddress, ViewportDetails};
38use euclid::{Point2D, Rect};
39use fonts::{FontContext, WebFontDocumentContext, WebFontSetDifference};
40pub use largest_contentful_paint_candidate::LCPCandidate;
41pub use layout_damage::LayoutDamage;
42pub use layout_dom::{
43    DangerousStyleElementOf, DangerousStyleNodeOf, LayoutDomTypeBundle, LayoutElementOf,
44    LayoutNodeOf,
45};
46pub use layout_element::{DangerousStyleElement, LayoutElement};
47pub use layout_node::{DangerousStyleNode, LayoutNode};
48use libc::c_void;
49use malloc_size_of::{MallocSizeOf as MallocSizeOfTrait, MallocSizeOfOps, malloc_size_of_is_0};
50use malloc_size_of_derive::MallocSizeOf;
51use net_traits::image_cache::{ImageCache, ImageCacheFactory, PendingImageId};
52use net_traits::request::InternalRequest;
53use paint_api::CrossProcessPaintApi;
54use paint_api::display_list::PaintTimingInfo;
55use parking_lot::RwLock;
56use pixels::{RasterImage, Repeat};
57use profile_traits::mem::Report;
58use profile_traits::time;
59pub use pseudo_element_chain::PseudoElementChain;
60use rustc_hash::{FxHashMap, FxHashSet};
61use script_traits::{InitialScriptState, Painter, ScriptThreadMessage};
62use serde::{Deserialize, Serialize};
63use servo_arc::Arc as ServoArc;
64use servo_base::Epoch;
65use servo_base::generic_channel::GenericSender;
66use servo_base::id::{BrowsingContextId, PipelineId, WebViewId};
67use servo_base::text::{RangeAny, Utf32CodeUnits, Utf32CodeUnitsOrNodeOffset};
68use servo_url::{ImmutableOrigin, ServoUrl};
69use style::Atom;
70use style::animation::DocumentAnimationSet;
71use style::attr::AttrValue;
72use style::context::QuirksMode;
73use style::data::ElementDataWrapper;
74use style::device::Device;
75use style::dom::OpaqueNode;
76use style::invalidation::element::restyle_hints::RestyleHint;
77use style::logical_geometry::WritingMode;
78use style::properties::style_structs::Font;
79use style::properties::{ComputedValues, PropertyId};
80use style::selector_parser::{PseudoElement, RestyleDamage, Snapshot};
81use style::stylesheets::{DocumentStyleSheet, Stylesheet};
82use style::stylist::Stylist;
83#[cfg(debug_assertions)]
84use style::thread_state::{self, ThreadState};
85use style::values::computed::Overflow;
86use style_traits::CSSPixel;
87use uuid::Uuid;
88use webrender_api::units::{DeviceIntSize, LayoutPoint, LayoutVector2D};
89use webrender_api::{ExternalScrollId, ImageKey};
90
91pub use crate::writing_mode_ext::WritingModeExt;
92
93pub trait GenericLayoutDataTrait: Any + MallocSizeOfTrait + Send + Sync + 'static {
94    fn as_any(&self) -> &dyn Any;
95
96    /// Returns whether `new_range` was successfully set on an existing text run
97    fn set_text_run_selection(
98        &self,
99        new_range: Option<RangeAny<Utf32CodeUnits>>,
100        new_paints_caret: bool,
101    ) -> bool;
102
103    /// Set whether or not this node is selected when it is an element. Returns `true`
104    /// if anything changed that requires a new display list.
105    fn set_element_selection(&self, selected: bool) -> bool;
106
107    /// Get the text rendered by this node, if it is a `CharacterData` node and produces
108    /// a `TextRun` in the box tree.
109    fn rendered_text(&self, range: RangeAny<Utf32CodeUnits>) -> Option<String>;
110}
111
112pub trait LayoutDataTrait: GenericLayoutDataTrait + Default {}
113pub type GenericLayoutData = dyn GenericLayoutDataTrait;
114
115#[derive(Default, MallocSizeOf)]
116pub struct StyleData {
117    /// Data that the style system associates with a node. When the
118    /// style system is being used standalone, this is all that hangs
119    /// off the node. This must be first to permit the various
120    /// transmutations between ElementData and PersistentLayoutData.
121    pub element_data: ElementDataWrapper,
122
123    /// Information needed during parallel traversals.
124    pub parallel: DomParallelInfo,
125}
126
127/// Information that we need stored in each DOM node.
128#[derive(Default, MallocSizeOf)]
129pub struct DomParallelInfo {
130    /// The number of children remaining to process during bottom-up traversal.
131    pub children_to_process: AtomicIsize,
132}
133
134#[derive(Clone, Copy, Debug, Eq, PartialEq)]
135pub enum LayoutNodeType {
136    Element(LayoutElementType),
137    Text,
138}
139
140#[derive(Clone, Copy, Debug, Eq, PartialEq)]
141pub enum LayoutElementType {
142    Element,
143    HTMLBodyElement,
144    HTMLButtonElement,
145    HTMLBRElement,
146    HTMLCanvasElement,
147    HTMLHtmlElement,
148    HTMLIFrameElement,
149    HTMLImageElement,
150    HTMLInputElement,
151    HTMLMediaElement,
152    HTMLMeterElement,
153    HTMLObjectElement,
154    HTMLOptGroupElement,
155    HTMLOptionElement,
156    HTMLParagraphElement,
157    HTMLPreElement,
158    HTMLProgressElement,
159    HTMLSelectElement,
160    HTMLTableCellElement,
161    HTMLTableColElement,
162    HTMLTableElement,
163    HTMLTableRowElement,
164    HTMLTableSectionElement,
165    HTMLTextAreaElement,
166    SVGImageElement,
167    SVGSVGElement,
168}
169
170pub struct HTMLCanvasData {
171    pub image_key: Option<ImageKey>,
172    pub width: u32,
173    pub height: u32,
174}
175
176pub struct SVGElementData<'dom> {
177    /// The SVG's XML source represented as a base64 encoded `data:` url.
178    pub source: Option<Result<ServoUrl, ()>>,
179    pub view_box_ratio: Option<f32>,
180    pub width: Option<&'dom AttrValue>,
181    pub height: Option<&'dom AttrValue>,
182    pub svg_id: Uuid,
183}
184
185/// The address of a node known to be valid. These are sent from script to layout.
186#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
187pub struct TrustedNodeAddress(pub *const c_void);
188
189#[expect(unsafe_code)]
190unsafe impl Send for TrustedNodeAddress {}
191
192/// Whether the pending image needs to be fetched or is waiting on an existing fetch.
193#[derive(Debug)]
194pub enum PendingImageState {
195    Unrequested(ServoUrl),
196    PendingResponse,
197}
198
199/// The destination in layout where an image is needed.
200#[derive(Debug, MallocSizeOf)]
201pub enum LayoutImageDestination {
202    BoxTreeConstruction,
203    DisplayListBuilding,
204}
205
206/// The data associated with an image that is not yet present in the image cache.
207/// Used by the script thread to hold on to DOM elements that need to be repainted
208/// when an image fetch is complete.
209#[derive(Debug)]
210pub struct PendingImage {
211    pub state: PendingImageState,
212    pub node: UntrustedNodeAddress,
213    pub id: PendingImageId,
214    pub origin: ImmutableOrigin,
215    pub destination: LayoutImageDestination,
216    pub is_internal_request: InternalRequest,
217}
218
219/// A data structure to track vector image that are fully loaded (i.e has a parsed SVG
220/// tree) but not yet rasterized to the size needed by layout. The rasterization is
221/// happening in the image cache.
222#[derive(Debug)]
223pub struct PendingRasterizationImage {
224    pub node: UntrustedNodeAddress,
225    pub id: PendingImageId,
226    pub size: DeviceIntSize,
227}
228
229#[derive(Clone, Copy, Debug, MallocSizeOf)]
230pub struct MediaFrame {
231    pub image_key: webrender_api::ImageKey,
232    pub width: i32,
233    pub height: i32,
234}
235
236pub struct MediaMetadata {
237    pub width: u32,
238    pub height: u32,
239}
240
241pub struct HTMLMediaData {
242    pub current_frame: Option<MediaFrame>,
243    pub metadata: Option<MediaMetadata>,
244    pub poster_or_src_url: Option<ServoUrl>,
245}
246
247#[derive(Debug)]
248pub struct AccessibilityActionRequest {
249    pub action: Action,
250    pub target: OpaqueNode,
251    pub data: Option<ActionData>,
252}
253
254pub struct LayoutConfig {
255    pub id: PipelineId,
256    pub webview_id: WebViewId,
257    pub url: ServoUrl,
258    pub is_iframe: bool,
259    pub script_chan: GenericSender<ScriptThreadMessage>,
260    pub image_cache: Arc<dyn ImageCache>,
261    pub font_context: Arc<FontContext>,
262    pub time_profiler_chan: time::ProfilerChan,
263    pub paint_api: CrossProcessPaintApi,
264    pub viewport_details: ViewportDetails,
265    pub user_stylesheets: Rc<Vec<DocumentStyleSheet>>,
266    pub theme: Theme,
267    pub embedder_chan: ScriptToEmbedderChan,
268    /// Document-scoped key for hashing the inputs of CSS `random()` functions.
269    /// This random value is 128 bits, as required for the key of the SipHash-1-3
270    /// keyed hash function (see [`style::device::Device::document_random_hasher()`]).
271    pub document_random_hasher_key: (u64, u64),
272}
273
274bitflags! {
275    #[derive(Copy, Clone)]
276    pub struct HitTestFlags: u8 {
277        /// Whether to populate [`HitTestResult::dom_position_for_selection`]
278        const IncludeDomPosition = 0b0000_0001;
279    }
280}
281
282pub trait LayoutFactory: Send + Sync {
283    fn create(&self, config: LayoutConfig) -> Box<dyn Layout>;
284}
285
286pub trait Layout {
287    /// Get a reference to this Layout's Stylo `Device` used to handle media queries and
288    /// resolve font metrics.
289    fn device(&self) -> &Device;
290
291    /// Set the theme on this [`Layout`]'s [`Device`]. The caller should also trigger a
292    /// new layout when this happens, though it can happen later. Returns `true` if the
293    /// [`Theme`] actually changed or `false` otherwise.
294    fn set_theme(&mut self, theme: Theme) -> bool;
295
296    /// Set the [`ViewportDetails`] on this [`Layout`]'s [`Device`]. The caller should also
297    /// trigger a new layout when this happens, though it can happen later. Returns `true`
298    /// if the [`ViewportDetails`] actually changed or `false` otherwise.
299    fn set_viewport_details(&mut self, viewport_details: ViewportDetails) -> bool;
300
301    /// Add a stylesheet to this Layout's `Stylist`.
302    ///
303    /// The second stylesheet is the insertion point (if it exists, the sheet needs to be
304    /// inserted before it).
305    fn add_stylesheet(
306        &mut self,
307        stylesheet: ServoArc<Stylesheet>,
308        before_stylesheet: Option<ServoArc<Stylesheet>>,
309    );
310
311    /// Inform the layout that its ScriptThread is about to exit.
312    fn exit_now(&mut self);
313
314    /// Requests that layout measure its memory usage. The resulting reports are sent back
315    /// via the supplied channel.
316    fn collect_reports(&self, reports: &mut Vec<Report>, ops: &mut MallocSizeOfOps);
317
318    /// Sets quirks mode for the document, causing the quirks mode stylesheet to be used.
319    fn set_quirks_mode(&mut self, quirks_mode: QuirksMode);
320
321    /// Removes a stylesheet from the Layout.
322    fn remove_stylesheet(&mut self, stylesheet: ServoArc<Stylesheet>);
323
324    /// Removes an image from the Layout image resolver cache.
325    fn remove_cached_image(&mut self, image_url: &ServoUrl);
326
327    /// Requests a reflow.
328    fn reflow(&mut self, reflow_request: ReflowRequest) -> Option<ReflowResult>;
329
330    /// Do not request a reflow, but ensure that any previous reflow completes building a stacking
331    /// context tree so that it is ready to query the final size of any elements in script.
332    fn ensure_stacking_context_tree(&self, viewport_details: ViewportDetails);
333
334    /// Tells layout that script has added some paint worklet modules.
335    fn register_paint_worklet_modules(
336        &mut self,
337        name: Atom,
338        properties: Vec<Atom>,
339        painter: Box<dyn Painter>,
340    );
341
342    /// Set the scroll states of this layout after a `Paint` scroll.
343    fn set_scroll_offsets_from_renderer(
344        &mut self,
345        scroll_states: &FxHashMap<ExternalScrollId, LayoutVector2D>,
346    );
347
348    /// Get the scroll offset of the given scroll node with id of [`ExternalScrollId`] or `None` if it does
349    /// not exist in the tree.
350    fn scroll_offset(&self, id: ExternalScrollId) -> Option<LayoutVector2D>;
351
352    /// Returns true if this layout needs to produce a new display list for rendering updates.
353    fn needs_new_display_list(&self) -> bool;
354
355    /// Marks that this layout needs to produce a new display list for rendering updates.
356    fn set_needs_new_display_list(&self);
357
358    /// Returns the [`NodeRenderingType`] for this node and pseudo. This is used to determine
359    /// if a node is being rendered, delegating its rendering, or not being rendered at all.
360    fn node_rendering_type(
361        &self,
362        node: TrustedNodeAddress,
363        pseudo: Option<PseudoElement>,
364    ) -> NodeRenderingType;
365
366    fn query_containing_block(&self, node: TrustedNodeAddress) -> Option<UntrustedNodeAddress>;
367    fn query_containing_block_is_descendant(
368        &self,
369        root: TrustedNodeAddress,
370        possible_descendant: TrustedNodeAddress,
371    ) -> bool;
372    fn query_padding(&self, node: TrustedNodeAddress) -> Option<PhysicalSides<Au>>;
373    fn query_box_area(
374        &self,
375        node: TrustedNodeAddress,
376        area: BoxAreaType,
377        exclude_transform_and_inline: bool,
378    ) -> Option<Rect<Au, CSSPixel>>;
379    fn query_box_areas(&self, node: TrustedNodeAddress, area: BoxAreaType) -> CSSPixelRectVec;
380    fn query_client_rect(&self, node: TrustedNodeAddress) -> Rect<i32, CSSPixel>;
381    fn query_current_css_zoom(&self, node: TrustedNodeAddress) -> f32;
382    fn query_element_inner_outer_text(&self, node: TrustedNodeAddress) -> String;
383    fn query_offset_parent(&self, node: TrustedNodeAddress) -> OffsetParentResponse;
384    /// Query the scroll container for the given node. If node is `None`, the scroll container for
385    /// the viewport is returned.
386    fn query_scroll_container(
387        &self,
388        node: Option<TrustedNodeAddress>,
389        flags: ScrollContainerQueryFlags,
390    ) -> Option<ScrollContainerResponse>;
391    fn query_resolved_style(
392        &self,
393        node: TrustedNodeAddress,
394        pseudo: Option<PseudoElement>,
395        property_id: PropertyId,
396        animations: DocumentAnimationSet,
397        animation_timeline_value: f64,
398    ) -> String;
399
400    fn query_accesskit_node(&self, node: TrustedNodeAddress) -> Option<accesskit::Node>;
401
402    fn query_resolved_font_style(
403        &self,
404        node: TrustedNodeAddress,
405        value: &str,
406        animations: DocumentAnimationSet,
407        animation_timeline_value: f64,
408    ) -> Option<ServoArc<Font>>;
409    fn query_scrolling_area(&self, node: Option<TrustedNodeAddress>) -> Rect<i32, CSSPixel>;
410    /// Find the closest character offset of the point within descendants of the given
411    /// node, if it has text content. This works even if the point is outside of all of
412    /// the layout boxes of the node.
413    fn query_text_index(
414        &self,
415        node: TrustedNodeAddress,
416        point_in_viewport: Point2D<Au, CSSPixel>,
417    ) -> Option<(OpaqueNode, Utf32CodeUnits)>;
418    /// Find the text segment of the given [`SegmentGranularity`] at the given `offset` in the
419    /// given node. Returns `None` when `node` is not a text node or due to any other failure.
420    fn query_text_segment(
421        &self,
422        node: TrustedNodeAddress,
423        offset: Utf32CodeUnitsOrNodeOffset,
424        granularity: SegmentGranularity,
425    ) -> Option<(
426        (OpaqueNode, Utf32CodeUnitsOrNodeOffset),
427        (OpaqueNode, Utf32CodeUnitsOrNodeOffset),
428    )>;
429    fn hit_test(&self, flags: HitTestFlags, point: LayoutPoint) -> HitTestResult;
430    fn query_effective_overflow(&self, node: TrustedNodeAddress) -> Option<AxesOverflow>;
431    fn stylist_mut(&mut self) -> &mut Stylist;
432
433    /// Set whether the accessibility tree should be constructed for this Layout.
434    /// This should be called by the embedder when accessibility is requested by the user.
435    fn set_accessibility_active(&self, enabled: bool, epoch: Epoch);
436
437    /// Returns whether accessibility is active for this Layout.
438    fn accessibility_active(&self) -> bool;
439
440    /// Whether the accessibility tree must be updated. This is true when accessibility is
441    /// activated, and at least one of the following conditions is met:
442    /// - the accessibility tree has not yet been built after activating accessibility;
443    /// - set_force_accessibility_update_if_active() has been called since the accessibility tree
444    ///   was last updated (for example, if a scroll occurred, or the focused element changed);
445    /// - there are pending actions from assistive technology.
446    ///
447    /// Checked in can_skip_reflow_request_entirely(), as a pending accessibility tree update
448    /// should force a reflow, and during reflow to determine whether to update the
449    /// accessibility tree.
450    fn needs_accessibility_update(&self) -> bool;
451
452    /// If accessibility is active, force an accessibility update on the next reflow.
453    /// See [Self::needs_accessibility_update()].
454    fn set_force_accessibility_update_if_active(&self);
455
456    /// Handle an accessibility action.
457    fn handle_accessibility_action(&self, action_request: ActionRequest);
458
459    fn font_context(&self) -> &Arc<FontContext>;
460}
461
462/// The granularity of the text boundaries to find.
463#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
464pub enum SegmentGranularity {
465    /// A Unicode word boundary.
466    Word,
467    /// A hard line break. If no hard line break is found, this is the entire
468    /// containing inline formatting context's text.
469    HardLineBreak,
470}
471
472/// This trait is part of `layout_api` because it depends on both `script_traits`
473/// and also `LayoutFactory` from this crate. If it was in `script_traits` there would be a
474/// circular dependency.
475pub trait ScriptThreadFactory {
476    /// Create a `ScriptThread`.
477    fn create(
478        state: InitialScriptState,
479        layout_factory: Arc<dyn LayoutFactory>,
480        image_cache_factory: Arc<dyn ImageCacheFactory>,
481        background_hang_monitor_register: Box<dyn BackgroundHangMonitorRegister>,
482    ) -> JoinHandle<()>;
483}
484
485/// Type of the area of CSS box for query.
486/// See <https://www.w3.org/TR/css-box-3/#box-model>.
487#[derive(Copy, Clone)]
488pub enum BoxAreaType {
489    Content,
490    Padding,
491    Border,
492}
493
494pub type CSSPixelRectVec = Vec<Rect<Au, CSSPixel>>;
495
496/// Whether or not this node is being rendered or delegates rendering according
497/// to the HTML standard.
498#[derive(Copy, Clone)]
499pub enum NodeRenderingType {
500    /// <https://html.spec.whatwg.org/multipage/#being-rendered>
501    Rendered,
502    /// <https://html.spec.whatwg.org/multipage/#delegating-its-rendering-to-its-children>
503    DelegatesRendering,
504    /// If neither of the other two cases are true, this is. The node is effectively not
505    /// taking part in the final layout of the page.
506    NotRendered,
507}
508
509pub type PhysicalSides<U> = euclid::SideOffsets2D<U, CSSPixel>;
510
511#[derive(Clone, Default)]
512pub struct OffsetParentResponse {
513    pub node_address: Option<UntrustedNodeAddress>,
514    pub rect: Rect<Au, CSSPixel>,
515}
516
517bitflags! {
518    #[derive(PartialEq)]
519    pub struct ScrollContainerQueryFlags: u8 {
520        /// Whether or not this query is for the purposes of a `scrollParent` layout query.
521        const ForScrollParent = 1 << 0;
522        /// Whether or not to consider the original element's scroll box for the return value.
523        const Inclusive = 1 << 1;
524    }
525}
526
527#[derive(Clone, Copy, Debug, MallocSizeOf)]
528pub struct AxesOverflow {
529    pub x: Overflow,
530    pub y: Overflow,
531}
532
533impl Default for AxesOverflow {
534    fn default() -> Self {
535        Self {
536            x: Overflow::Visible,
537            y: Overflow::Visible,
538        }
539    }
540}
541
542impl From<&ComputedValues> for AxesOverflow {
543    fn from(style: &ComputedValues) -> Self {
544        Self {
545            x: style.slow_clone_overflow_x(),
546            y: style.slow_clone_overflow_y(),
547        }
548    }
549}
550
551impl AxesOverflow {
552    pub fn to_scrollable(&self) -> Self {
553        Self {
554            x: self.x.to_scrollable(),
555            y: self.y.to_scrollable(),
556        }
557    }
558
559    /// Whether or not the `overflow` value establishes a scroll container.
560    pub fn establishes_scroll_container(&self) -> bool {
561        // Checking one axis suffices, because the computed value ensures that
562        // either both axes are scrollable, or none is scrollable.
563        self.x.is_scrollable()
564    }
565}
566
567#[derive(Clone)]
568pub enum ScrollContainerResponse {
569    Viewport(AxesOverflow, WritingMode),
570    Element(UntrustedNodeAddress, AxesOverflow, WritingMode),
571}
572
573#[derive(Debug, PartialEq)]
574pub enum QueryMsg {
575    BoxArea,
576    BoxAreas,
577    ClientRectQuery,
578    CurrentCSSZoomQuery,
579    EffectiveOverflow,
580    ElementInnerOuterTextQuery,
581    ElementsFromPoint,
582    InnerWindowDimensionsQuery,
583    NodesFromPointQuery,
584    OffsetParentQuery,
585    ScrollParentQuery,
586    ResolvedFontStyleQuery,
587    /// A style query, with an optional [`PropertyId`], used to limit the phases
588    /// of layout run before the query.
589    ResolvedStyleQuery(PropertyId),
590    ScrollingAreaOrOffsetQuery,
591    StyleQuery,
592    TextIndexOrSegmentQuery,
593    PaddingQuery,
594    FlushForUpdateTheRenderingQuery,
595    AccessKitNodeQuery,
596}
597
598/// The goal of a reflow request.
599///
600/// Please do not add any other types of reflows. In general, all reflow should
601/// go through the *update the rendering* step of the HTML specification. Exceptions
602/// should have careful review.
603#[derive(Debug, PartialEq)]
604pub enum ReflowGoal {
605    /// A reflow has been requesting by the *update the rendering* step of the HTML
606    /// event loop. This nominally driven by the display's VSync.
607    UpdateTheRendering,
608
609    /// Script has done a layout query and this reflow ensurs that layout is up-to-date
610    /// with the latest changes to the DOM.
611    LayoutQuery(QueryMsg),
612
613    /// Tells layout about a single new scrolling offset from the script. The rest will
614    /// remain untouched. Layout will forward whether the element is scrolled through
615    /// [ReflowResult].
616    UpdateScrollNode(ExternalScrollId, LayoutVector2D),
617}
618
619#[derive(Clone, Debug, MallocSizeOf)]
620pub struct IFrameSize {
621    pub browsing_context_id: BrowsingContextId,
622    pub pipeline_id: PipelineId,
623    pub viewport_details: ViewportDetails,
624}
625
626pub type IFrameSizes = FxHashMap<BrowsingContextId, IFrameSize>;
627
628bitflags! {
629    /// Conditions which cause a [`Document`] to need to be restyled during reflow, which
630    /// might cause the rest of layout to happen as well.
631    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
632    pub struct RestyleReason: u16 {
633        const StylesheetsChanged = 1 << 0;
634        const DOMChanged = 1 << 1;
635        const PendingRestyles = 1 << 2;
636        const HighlightedDOMNodeChanged = 1 << 3;
637        const ThemeChanged = 1 << 4;
638        const ViewportChanged = 1 << 5;
639        const PaintWorkletLoaded = 1 << 6;
640    }
641}
642
643malloc_size_of_is_0!(RestyleReason);
644
645impl RestyleReason {
646    pub fn needs_restyle(&self) -> bool {
647        !self.is_empty()
648    }
649}
650
651/// Information derived from a layout pass that needs to be returned to the script thread.
652#[derive(Default)]
653pub struct ReflowResult {
654    /// The phases that were run during this reflow.
655    pub reflow_phases_run: ReflowPhasesRun,
656    pub reflow_statistics: ReflowStatistics,
657    /// The list of images that were encountered that are in progress.
658    pub pending_images: Vec<PendingImage>,
659    /// The list of vector images that were encountered that still need to be rasterized.
660    pub pending_rasterization_images: Vec<PendingRasterizationImage>,
661    /// The list of `SVGSVGElement`s encountered in the DOM that need to be serialized.
662    /// This is needed to support inline SVGs as the serialization needs to happen on
663    /// the script thread.
664    pub pending_svg_elements_for_serialization: Vec<UntrustedNodeAddress>,
665    /// The list of iframes in this layout and their sizes, used in order
666    /// to communicate them with the Constellation and also the `Window`
667    /// element of their content pages. Returning None if incremental reflow
668    /// finished before reaching this stage of the layout. I.e., no update
669    /// required.
670    pub iframe_sizes: Option<IFrameSizes>,
671    /// Enumerates web fonts that were added or removed as part of restyling.
672    pub changed_web_fonts: WebFontSetDifference,
673    /// The LCP candidate during this layout pass, if any.
674    pub lcp_candidate: Option<LCPCandidate>,
675    /// Actions which have been requested by assistive technology, if any.
676    pub pending_accessibility_actions: Vec<AccessibilityActionRequest>,
677    /// The containers whose painted area grew during this layout pass, if any.
678    pub container_timing_records: Vec<ContainerTimingRecord>,
679}
680
681bitflags! {
682    /// The phases of reflow that were run when processing a reflow in layout.
683    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
684    pub struct ReflowPhasesRun: u8 {
685        const RanLayout = 1 << 0;
686        const BuiltStackingContextTree = 1 << 2;
687        const BuiltDisplayList = 1 << 3;
688        const UpdatedScrollNodeOffset = 1 << 4;
689        /// Image data for a WebRender image key has been updated, without necessarily
690        /// updating style or layout. This is used when updating canvas contents and
691        /// progressing to a new animated image frame.
692        const UpdatedImageData = 1 << 5;
693        const UpdatedAccessibilityTree = 1 << 6;
694    }
695}
696
697impl ReflowPhasesRun {
698    pub fn needs_frame(&self) -> bool {
699        self.intersects(
700            Self::BuiltDisplayList | Self::UpdatedScrollNodeOffset | Self::UpdatedImageData,
701        )
702    }
703}
704
705#[derive(Debug, Default)]
706pub struct ReflowStatistics {
707    /// A count of the number of fragments that have been completely rebuilt.
708    pub rebuilt_fragment_count: u32,
709    /// A count of the number of fragments that are reused, but have had their style change.
710    pub restyle_fragment_count: u32,
711    /// A count of the number of fragments that are reused, but may have had some descendant
712    /// fragment change.
713    pub only_descendants_changed_count: u32,
714    /// A count of the number of accessibility nodes which were checked for changes based on their
715    /// corresponding DOM nodes (whether the check resulted in changes or not).
716    pub nodes_updated_from_dom: u32,
717    /// A count of the number of accessibility nodes which were checked for changes based on data
718    /// already in the accessibility tree (whether the check resulted in changes or not).
719    pub nodes_updated_from_tree: u32,
720    /// A count of the number of accessibility nodes which had their bounds recomputed from layout
721    /// geometry (whether the recomputation resulted in changes or not).
722    pub nodes_updated_bounds: u32,
723    /// A count of the number of accessibility nodes actually serialized to the TreeUpdate.
724    pub nodes_in_tree_update: u32,
725}
726
727/// Information needed for a script-initiated reflow that requires a restyle
728/// and reconstruction of box and fragment trees.
729#[derive(Debug)]
730pub struct ReflowRequestRestyle {
731    /// Whether or not (and for what reasons) restyle needs to happen.
732    pub reason: RestyleReason,
733    /// The dirty root from which to restyle.
734    pub dirty_root: Option<TrustedNodeAddress>,
735    /// Whether the document's stylesheets have changed since the last script reflow.
736    pub stylesheets_changed: bool,
737    /// Restyle snapshot map.
738    pub pending_restyles: Vec<(TrustedNodeAddress, PendingRestyle)>,
739}
740
741/// Information needed for a script-initiated reflow that requires the accessibility tree to be
742/// updated.
743#[derive(Debug)]
744pub struct ReflowRequestAccessibility {
745    /// Damage to the accessibility tree from DOM mutations.
746    pub damage: Vec<(TrustedNodeAddress, AccessibilityDamage)>,
747    /// The document's focused element at the time of the reflow, if any.
748    pub focused_element: Option<OpaqueNode>,
749    /// Nodes which were removed from the DOM tree since the last reflow, which were rooted in
750    /// [`AccessibilityData`]. Only set if [`pref::expensive_accessibility_test_assertions_enabled`]
751    /// is set.
752    pub rooted_nodes_for_integrity_check: Option<FxHashSet<OpaqueNode>>,
753}
754
755/// Information needed for a script-initiated reflow.
756#[derive(Debug)]
757pub struct ReflowRequest {
758    /// The document node.
759    pub document: TrustedNodeAddress,
760    /// The current layout [`Epoch`] managed by the script thread.
761    pub epoch: Epoch,
762    /// If a restyle is necessary, all of the information needed to do that restyle.
763    pub restyle: Option<ReflowRequestRestyle>,
764    /// The current [`ViewportDetails`] to use for this reflow.
765    pub viewport_details: ViewportDetails,
766    /// The goal of this reflow.
767    pub reflow_goal: ReflowGoal,
768    /// The current window origin
769    pub origin: ImmutableOrigin,
770    /// The current animation timeline value.
771    pub animation_timeline_value: f64,
772    /// The set of animations for this document.
773    pub animations: DocumentAnimationSet,
774    /// An [`AnimatingImages`] struct used to track images that are animating.
775    pub animating_images: Arc<RwLock<AnimatingImages>>,
776    /// The node highlighted by the devtools, if any
777    pub highlighted_dom_node: Option<OpaqueNode>,
778    /// Whether or not this document has system focus and is the focused frame
779    /// in the frame tree.
780    pub frame_focused: bool,
781    /// Whether LCP computation should be halted for this reflow.
782    /// From <https://www.w3.org/TR/largest-contentful-paint/#limitations>:
783    /// > The LargestContentfulPaint ... algorithm halts ... inputs.
784    pub halt_lcp: bool,
785    /// Whether the document's browsing context is paint-timing eligible.
786    /// <https://www.w3.org/TR/paint-timing/#paint-timing-eligible>
787    pub paint_timing_eligible: bool,
788    /// The [`PaintTimingInfo`] for this reflow.
789    /// <https://www.w3.org/TR/paint-timing/#paint-timing-info>
790    pub paint_timing_info: PaintTimingInfo,
791    /// The current font context.
792    pub document_context: WebFontDocumentContext,
793    /// If an accessibility tree update is necessary, all the information needed to do the update.
794    pub accessibility: Option<ReflowRequestAccessibility>,
795}
796
797impl ReflowRequest {
798    pub fn stylesheets_changed(&self) -> bool {
799        self.restyle
800            .as_ref()
801            .is_some_and(|restyle| restyle.stylesheets_changed)
802    }
803}
804
805/// A pending restyle.
806#[derive(Debug, Default, MallocSizeOf)]
807pub struct PendingRestyle {
808    /// If this element had a state or attribute change since the last restyle, track
809    /// the original condition of the element.
810    pub snapshot: Option<Snapshot>,
811
812    /// Any explicit restyles hints that have been accumulated for this element.
813    pub hint: RestyleHint,
814
815    /// Any explicit restyles damage that have been accumulated for this element.
816    pub damage: RestyleDamage,
817}
818
819/// The type of fragment that a scroll root is created for.
820///
821/// This can only ever grow to maximum 4 entries. That's because we cram the value of this enum
822/// into the lower 2 bits of the `OpaqueNodeId`, which otherwise contains a 32-bit-aligned
823/// or 64-bit-aligned heap address depending on the machine.
824#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
825pub enum FragmentType {
826    /// A StackingContext for the fragment body itself.
827    FragmentBody,
828    /// A StackingContext created to contain ::before pseudo-element content.
829    BeforePseudoContent,
830    /// A StackingContext created to contain ::after pseudo-element content.
831    AfterPseudoContent,
832}
833
834impl From<Option<PseudoElement>> for FragmentType {
835    fn from(value: Option<PseudoElement>) -> Self {
836        match value {
837            Some(PseudoElement::After) => FragmentType::AfterPseudoContent,
838            Some(PseudoElement::Before) => FragmentType::BeforePseudoContent,
839            _ => FragmentType::FragmentBody,
840        }
841    }
842}
843
844pub fn combine_id_with_fragment_type(id: usize, fragment_type: FragmentType) -> u64 {
845    debug_assert_eq!(id & (fragment_type as usize), 0);
846    (id as u64) | (fragment_type as u64)
847}
848
849pub fn node_id_from_scroll_id(id: usize) -> usize {
850    id & !3
851}
852
853#[derive(Clone, Debug, MallocSizeOf)]
854pub struct ImageAnimationState {
855    #[conditional_malloc_size_of]
856    pub image: Arc<RasterImage>,
857    pub active_frame: usize,
858    frame_start_time: f64,
859
860    /// The number of loops that have fully completed in this [`ImageAnimationState`].
861    /// If this is greater than or equal to the maximum number of loops in the
862    /// [`RasterImage`], then the animation has ended. If it is `None`, then the image
863    /// will loop infinitely.
864    pub completed_loops: Option<u32>,
865}
866
867impl ImageAnimationState {
868    pub fn new(image: Arc<RasterImage>, last_update_time: f64) -> Self {
869        let completd_loops = match &image.loop_count {
870            None => unreachable!("Loop count of an animated Image should never be None"),
871            Some(repeat) if Repeat::Infinite == *repeat => None,
872            _ => Some(0),
873        };
874
875        Self {
876            image,
877            active_frame: 0,
878            frame_start_time: last_update_time,
879            completed_loops: completd_loops,
880        }
881    }
882
883    pub fn image_key(&self) -> Option<ImageKey> {
884        self.image.id
885    }
886
887    pub fn duration_to_next_frame(&self, now: f64) -> Option<Duration> {
888        if self.is_finished() {
889            return None;
890        }
891        let frame_delay = self
892            .image
893            .frames
894            .get(self.active_frame)
895            .expect("Image frame should always be valid")
896            .delay
897            .unwrap_or_default();
898
899        let time_since_frame_start = (now - self.frame_start_time).max(0.0) * 1000.0;
900        let time_since_frame_start = Duration::from_secs_f64(time_since_frame_start);
901        Some(frame_delay - time_since_frame_start.min(frame_delay))
902    }
903
904    /// check whether image active frame need to be updated given current time,
905    /// return true if there are image that need to be updated.
906    /// false otherwise.
907    pub fn update_frame_for_animation_timeline_value(&mut self, now: f64) -> bool {
908        if self.image.frames.len() <= 1 || self.is_finished() {
909            return false;
910        }
911        let time_interval_since_last_update = now - self.frame_start_time;
912        let mut remain_time_interval = time_interval_since_last_update -
913            self.image
914                .frames
915                .get(self.active_frame)
916                .unwrap()
917                .delay()
918                .unwrap()
919                .as_secs_f64();
920        let mut next_active_frame_id = self.active_frame;
921
922        let frame_count = self.image.frames.len();
923        while remain_time_interval > 0.0 {
924            next_active_frame_id = (next_active_frame_id + 1) % frame_count;
925
926            // If the next active frame is 0, this means the animation is about to loop.
927            if next_active_frame_id == 0 {
928                self.advance_completed_loops();
929
930                // If we have just finished the animation, advance to the final frame if
931                // necessary and stop walking through frames.
932                if self.is_finished() {
933                    if self.active_frame == frame_count - 1 {
934                        return false;
935                    }
936                    self.active_frame = frame_count - 1;
937                    self.frame_start_time = now;
938                    return true;
939                }
940            }
941
942            remain_time_interval -= self
943                .image
944                .frames
945                .get(next_active_frame_id)
946                .unwrap()
947                .delay()
948                .unwrap()
949                .as_secs_f64();
950        }
951        if self.active_frame == next_active_frame_id {
952            return false;
953        }
954        self.active_frame = next_active_frame_id;
955        self.frame_start_time = now;
956        true
957    }
958
959    /// Whether or not this animation has finished looping and has reached its final frame.
960    fn is_finished(&self) -> bool {
961        let Some(Repeat::Finite(maximum_loops)) = self.image.loop_count.as_ref() else {
962            return false;
963        };
964        self.completed_loops
965            .is_some_and(|completed_loops| completed_loops >= maximum_loops.get())
966    }
967
968    /// If this animation has a finite number of loops, advance the count of completed loops.
969    fn advance_completed_loops(&mut self) {
970        if let Some(completed_loops) = self.completed_loops.as_mut() {
971            *completed_loops += 1;
972        }
973    }
974}
975
976/// The result of a hit test query.
977#[derive(Debug, Default)]
978pub struct HitTestResult {
979    pub items: Vec<HitTestResultItem>,
980    pub dom_position_for_selection: Option<(OpaqueNode, Utf32CodeUnitsOrNodeOffset)>,
981}
982
983/// Describe an item that matched a hit-test query.
984#[derive(Debug)]
985pub struct HitTestResultItem {
986    /// An [`OpaqueNode`] that contains a pointer to the node hit by
987    /// this hit test result.
988    pub node: OpaqueNode,
989    /// The [`Point2D`] of the original query point relative to the
990    /// node fragment rectangle.
991    pub point_in_target: Point2D<f32, CSSPixel>,
992    /// The [`Cursor`] that's defined on the item that is hit by this
993    /// hit test result.
994    pub cursor: Cursor,
995}
996
997#[derive(Debug, Default, MallocSizeOf)]
998pub struct AnimatingImages {
999    /// A map from the [`OpaqueNode`] to the state of an animating image. This is used
1000    /// to update frames in script and to track newly animating nodes.
1001    pub node_to_state_map: FxHashMap<OpaqueNode, ImageAnimationState>,
1002    /// Whether or not this map has changed during a layout. This is used by script to
1003    /// trigger future animation updates.
1004    pub dirty: bool,
1005}
1006
1007impl AnimatingImages {
1008    pub fn maybe_insert_or_update(
1009        &mut self,
1010        node: OpaqueNode,
1011        image: Arc<RasterImage>,
1012        current_timeline_value: f64,
1013    ) {
1014        let entry = self.node_to_state_map.entry(node).or_insert_with(|| {
1015            self.dirty = true;
1016            ImageAnimationState::new(image.clone(), current_timeline_value)
1017        });
1018
1019        // If the entry exists, but it is for a different image id, replace it as the image
1020        // has changed during this layout.
1021        if entry.image.id != image.id {
1022            self.dirty = true;
1023            *entry = ImageAnimationState::new(image.clone(), current_timeline_value);
1024        }
1025    }
1026
1027    pub fn remove(&mut self, node: OpaqueNode) {
1028        if self.node_to_state_map.remove(&node).is_some() {
1029            self.dirty = true;
1030        }
1031    }
1032
1033    /// Clear the dirty bit on this [`AnimatingImages`] and return the previous value.
1034    pub fn clear_dirty(&mut self) -> bool {
1035        std::mem::take(&mut self.dirty)
1036    }
1037
1038    pub fn is_empty(&self) -> bool {
1039        self.node_to_state_map.is_empty()
1040    }
1041}
1042
1043struct ThreadStateRestorer;
1044
1045impl ThreadStateRestorer {
1046    fn new() -> Self {
1047        #[cfg(debug_assertions)]
1048        {
1049            thread_state::exit(ThreadState::SCRIPT);
1050            thread_state::enter(ThreadState::LAYOUT);
1051        }
1052        Self
1053    }
1054}
1055
1056impl Drop for ThreadStateRestorer {
1057    fn drop(&mut self) {
1058        #[cfg(debug_assertions)]
1059        {
1060            thread_state::exit(ThreadState::LAYOUT);
1061            thread_state::enter(ThreadState::SCRIPT);
1062        }
1063    }
1064}
1065
1066/// Set up the thread-local state to reflect that layout code is about to run,
1067/// then call the provided function.
1068/// This must be used when running code that will interact with the DOM tree
1069/// through types like `ServoLayoutNode`, `ServoLayoutElement`, and `LayoutDom`,
1070/// which have rules about how they must be used from layout worker threads.
1071pub fn with_layout_state<R>(f: impl FnOnce() -> R) -> R {
1072    let _guard = ThreadStateRestorer::new();
1073    f()
1074}
1075
1076#[cfg(test)]
1077mod test {
1078    use std::num::NonZeroU32;
1079    use std::sync::Arc;
1080    use std::time::Duration;
1081
1082    use pixels::{CorsStatus, ImageFrame, ImageMetadata, PixelFormat, RasterImage, Repeat};
1083
1084    use crate::ImageAnimationState;
1085
1086    #[test]
1087    fn test_animated_image_update() {
1088        let image_frames: Vec<ImageFrame> = std::iter::repeat_with(|| ImageFrame {
1089            delay: Some(Duration::from_millis(100)),
1090            byte_range: 0..1,
1091            width: 100,
1092            height: 100,
1093        })
1094        .take(10)
1095        .collect();
1096        let image = RasterImage {
1097            metadata: ImageMetadata {
1098                width: 100,
1099                height: 100,
1100            },
1101            format: PixelFormat::BGRA8,
1102            id: None,
1103            bytes: Arc::new(vec![1]),
1104            frames: image_frames,
1105            cors_status: CorsStatus::Unsafe,
1106            load_time: None,
1107            loop_count: Some(Repeat::Infinite),
1108            is_opaque: false,
1109        };
1110        let mut image_animation_state = ImageAnimationState::new(Arc::new(image), 0.0);
1111
1112        assert_eq!(image_animation_state.active_frame, 0);
1113        assert_eq!(image_animation_state.frame_start_time, 0.0);
1114        assert_eq!(
1115            image_animation_state.update_frame_for_animation_timeline_value(0.101),
1116            true
1117        );
1118        assert_eq!(image_animation_state.active_frame, 1);
1119        assert_eq!(image_animation_state.frame_start_time, 0.101);
1120        assert_eq!(
1121            image_animation_state.update_frame_for_animation_timeline_value(0.116),
1122            false
1123        );
1124        assert_eq!(image_animation_state.active_frame, 1);
1125        assert_eq!(image_animation_state.frame_start_time, 0.101);
1126    }
1127
1128    #[test]
1129    fn test_finite_image_repeat() {
1130        let image_frames: Vec<ImageFrame> = std::iter::repeat_with(|| ImageFrame {
1131            delay: Some(Duration::from_millis(100)),
1132            byte_range: 0..1,
1133            width: 100,
1134            height: 100,
1135        })
1136        .take(2)
1137        .collect();
1138        let image = RasterImage {
1139            metadata: ImageMetadata {
1140                width: 100,
1141                height: 100,
1142            },
1143            format: PixelFormat::BGRA8,
1144            id: None,
1145            bytes: Arc::new(vec![1]),
1146            frames: image_frames,
1147            cors_status: CorsStatus::Unsafe,
1148            load_time: None,
1149            loop_count: Some(Repeat::Finite(NonZeroU32::new(1).unwrap())),
1150            is_opaque: false,
1151        };
1152        let mut image_animation_state = ImageAnimationState::new(Arc::new(image), 0.0);
1153
1154        assert_eq!(image_animation_state.active_frame, 0);
1155        assert_eq!(image_animation_state.frame_start_time, 0.0);
1156        assert_eq!(
1157            image_animation_state.update_frame_for_animation_timeline_value(0.101),
1158            true
1159        );
1160        assert_eq!(image_animation_state.active_frame, 1);
1161        assert_eq!(image_animation_state.frame_start_time, 0.101);
1162        assert_eq!(
1163            image_animation_state.update_frame_for_animation_timeline_value(0.202),
1164            false
1165        );
1166        assert_eq!(
1167            image_animation_state.update_frame_for_animation_timeline_value(0.303),
1168            false
1169        );
1170
1171        assert_eq!(image_animation_state.active_frame, 1);
1172    }
1173}