Skip to main content

layout/
layout_impl.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#![expect(unsafe_code)]
6
7use std::cell::{Cell, OnceCell, RefCell};
8use std::collections::HashMap;
9use std::fmt::Debug;
10use std::rc::Rc;
11use std::sync::{Arc, LazyLock};
12
13use accesskit::{ActionRequest, Node};
14use app_units::Au;
15use bitflags::bitflags;
16use embedder_traits::{
17    EmbedderMsg, ScriptToEmbedderChan, Theme, UntrustedNodeAddress, ViewportDetails,
18};
19use encoding_rs::ISO_8859_8;
20use euclid::{Point2D, Rect, Scale, Size2D};
21use fonts::{FontContext, FontContextWebFontMethods};
22use fonts_traits::{StylesheetWebFontLoadFinishedCallback, WebFontSetDifference};
23use icu_locale_core::subtags::Language;
24use layout_api::{
25    AccessibilityActionRequest, AccessibilityDamage, AxesOverflow, BoxAreaType, CSSPixelRectVec,
26    ContainerTimingRecord, DangerousStyleNode, HitTestFlags, HitTestResult, IFrameSizes, Layout,
27    LayoutConfig, LayoutDamage, LayoutElement, LayoutFactory, LayoutNode, NodeRenderingType,
28    OffsetParentResponse, PhysicalSides, QueryMsg, ReflowGoal, ReflowPhasesRun, ReflowRequest,
29    ReflowRequestAccessibility, ReflowRequestRestyle, ReflowResult, ReflowStatistics,
30    ScrollContainerQueryFlags, ScrollContainerResponse, SegmentGranularity, TrustedNodeAddress,
31    with_layout_state,
32};
33use log::{debug, warn};
34use malloc_size_of::{MallocConditionalSizeOf, MallocSizeOf, MallocSizeOfOps};
35use net_traits::image_cache::ImageCache;
36use paint_api::CrossProcessPaintApi;
37use paint_api::display_list::{AxesScrollSensitivity, PaintDisplayListInfo, ScrollType};
38use parking_lot::{Mutex, RwLock};
39use profile_traits::mem::{Report, ReportKind};
40use profile_traits::time::{
41    self as profile_time, TimerMetadata, TimerMetadataFrameType, TimerMetadataReflowType,
42};
43use profile_traits::{path, time_profile};
44use rustc_hash::FxHashMap;
45use script::HTML_INPUT_TYPE_SUBMIT_DEFAULT_VALUE;
46use script::layout_dom::{
47    ServoDangerousStyleDocument, ServoDangerousStyleElement, ServoLayoutElement, ServoLayoutNode,
48};
49use script_traits::{DrawAPaintImageResult, PaintWorkletError, Painter, ScriptThreadMessage};
50use servo_arc::Arc as ServoArc;
51use servo_base::Epoch;
52use servo_base::id::{PipelineId, WebViewId};
53use servo_base::text::{Utf32CodeUnits, Utf32CodeUnitsOrNodeOffset};
54use servo_config::opts::{self, DiagnosticsLogging, DiagnosticsLoggingOption};
55use servo_config::pref;
56use servo_url::ServoUrl;
57use style::animation::DocumentAnimationSet;
58use style::context::{
59    QuirksMode, RegisteredSpeculativePainter, RegisteredSpeculativePainters, SharedStyleContext,
60};
61use style::device::Device;
62use style::device::servo::{FontMetricsProvider, MediaData};
63use style::dom::{OpaqueNode, ShowSubtreeDataAndPrimaryValues, TDocument, TElement, TNode};
64use style::font_metrics::FontMetrics;
65use style::global_style_data::GLOBAL_STYLE_DATA;
66use style::invalidation::element::restyle_hints::RestyleHint;
67use style::invalidation::stylesheets::StylesheetInvalidationSet;
68use style::media_queries::{MediaList, MediaType};
69use style::properties::style_structs::Font;
70use style::properties::{ComputedValues, LonghandId, NonCustomPropertyId, PropertyId, ShorthandId};
71use style::queries::values::PrefersColorScheme;
72use style::selector_parser::{PseudoElement, SnapshotMap};
73use style::servo::media_features::PointerCapabilities;
74use style::shared_lock::{SharedRwLock, StylesheetGuards};
75use style::stylesheets::{DocumentStyleSheet, Origin, Stylesheet};
76use style::stylist::Stylist;
77use style::traversal::DomTraversal;
78use style::traversal_flags::TraversalFlags;
79use style::values::computed::font::GenericFontFamily;
80use style::values::computed::{CSSPixelLength, FontSize, Length, NonNegativeLength};
81use style::values::specified::font::{KeywordInfo, QueryFontMetricsFlags};
82use style::{Zero, driver};
83use style_traits::{CSSPixel, SpeculativePainter};
84use stylo_atoms::Atom;
85use url::Url;
86use webrender_api::ExternalScrollId;
87use webrender_api::units::{DevicePixel, LayoutVector2D};
88
89use crate::accessibility::{AccessibilityContext, AccessibilityDamageMap, AccessibilityTree};
90use crate::context::{CachedImageOrError, ImageResolver, LayoutContext};
91use crate::display_list::{DisplayListBuilder, HitTest, PaintTimingHandler, StackingContextTree};
92use crate::dom::NodeExt;
93use crate::query::{
94    BoxAreaInclusion, find_character_offset_in_fragment_descendants, get_the_text_steps,
95    process_box_area_request, process_box_areas_request, process_client_rect_request,
96    process_containing_block_descendant_query, process_containing_block_query,
97    process_current_css_zoom_query, process_effective_overflow_query,
98    process_node_scroll_area_request, process_offset_parent_query, process_padding_request,
99    process_resolved_font_style_query, process_resolved_style_request,
100    process_scroll_container_query,
101};
102use crate::selection::PositionInInlineFormattingContext;
103use crate::traversal::{RecalcStyle, compute_damage_and_rebuild_box_tree};
104use crate::{BoxTree, FragmentTree};
105
106// This mutex is necessary due to syncronisation issues between two different types of thread-local storage
107// which manifest themselves when the layout thread tries to layout iframes in parallel with the main page
108//
109// See: https://github.com/servo/servo/pull/29792
110// And: https://gist.github.com/mukilan/ed57eb61b83237a05fbf6360ec5e33b0
111static STYLE_THREAD_POOL: Mutex<&LazyLock<style::global_style_data::StyleThreadPool>> =
112    Mutex::new(&style::global_style_data::STYLE_THREAD_POOL);
113
114/// A CSS file to style the user agent stylesheet.
115static USER_AGENT_CSS: &[u8] = include_bytes!("./stylesheets/user-agent.css");
116
117/// A CSS file to style the user agent stylesheet in HTML documents.
118static HTML_MODE_CSS: &[u8] = include_bytes!("./stylesheets/html-mode.css");
119
120/// A CSS file to style the Servo browser.
121static SERVO_CSS: &[u8] = include_bytes!("./stylesheets/servo.css");
122
123/// A CSS file to style the presentational hints.
124static PRESENTATIONAL_HINTS_CSS: &[u8] = include_bytes!("./stylesheets/presentational-hints.css");
125
126/// A CSS file to style the quirks mode.
127static QUIRKS_MODE_CSS: &[u8] = include_bytes!("./stylesheets/quirks-mode.css");
128
129/// A CSS file to style documents that use the ISO-8859-8 encoding.
130static ISO_8859_8_CSS: &[u8] = include_bytes!("./stylesheets/iso-8859-8.css");
131
132/// Information needed by layout.
133pub struct LayoutThread {
134    /// The ID of the pipeline that we belong to.
135    id: PipelineId,
136
137    /// The webview that contains the pipeline we belong to.
138    webview_id: WebViewId,
139
140    /// The URL of the pipeline that we belong to.
141    url: ServoUrl,
142
143    /// Performs CSS selector matching and style resolution.
144    stylist: Stylist,
145
146    /// Is the current reflow of an iframe, as opposed to a root window?
147    is_iframe: bool,
148
149    /// The channel on which messages can be sent to the time profiler.
150    time_profiler_chan: profile_time::ProfilerChan,
151
152    /// The channel to send messages to the Embedder.
153    embedder_chan: ScriptToEmbedderChan,
154
155    /// Reference to the script thread image cache.
156    image_cache: Arc<dyn ImageCache>,
157
158    /// A FontContext to be used during layout.
159    font_context: Arc<FontContext>,
160
161    /// Whether or not user agent stylesheets have been added to the Stylist or not.
162    have_added_user_agent_stylesheets: bool,
163
164    // A vector of parsed `DocumentStyleSheet`s representing the corresponding `UserStyleSheet`s
165    // associated with the `WebView` to which this `Layout` belongs. The `DocumentStylesheet`s might
166    // be shared with `Layout`s in the same `ScriptThread`.
167    user_stylesheets: Rc<Vec<DocumentStyleSheet>>,
168
169    /// Whether or not this [`LayoutImpl`]'s [`Device`] has changed since the last restyle.
170    /// If it has, a restyle is pending.
171    device_has_changed: bool,
172
173    /// Is this the first reflow in this LayoutThread?
174    have_ever_generated_display_list: Cell<bool>,
175
176    /// Whether the last display list we sent was effectively empty.
177    last_display_list_was_empty: Cell<bool>,
178
179    /// Whether a new display list is necessary due to changes to layout or stacking
180    /// contexts. This is set to true every time layout changes, even when a display list
181    /// isn't requested for this layout, such as for layout queries. The next time a
182    /// layout requests a display list, it is produced unconditionally, even when the
183    /// layout trees remain the same.
184    need_new_display_list: Cell<bool>,
185
186    /// Whether or not cumulative containing blocks offsets have been set into the
187    /// [`FragmentTree`]. This typically happens during [`StackingContextTree`]
188    /// construction, but if a layout query needs these value beforehand, they are
189    /// eagerly calculated.
190    need_containing_block_calculation: Cell<bool>,
191
192    /// Whether or not the existing stacking context tree is dirty and needs to be
193    /// rebuilt. This happens after a relayout or overflow update. The reason that we
194    /// don't simply clear the stacking context tree when it becomes dirty is that we need
195    /// to preserve scroll offsets from the old tree to the new one.
196    need_new_stacking_context_tree: Cell<bool>,
197
198    /// The box tree.
199    box_tree: RefCell<Option<Arc<BoxTree>>>,
200
201    /// The fragment tree.
202    fragment_tree: RefCell<Option<Rc<FragmentTree>>>,
203
204    /// The [`StackingContextTree`] cached from previous layouts.
205    stacking_context_tree: RefCell<Option<StackingContextTree>>,
206
207    // A cache that maps image resources specified in CSS (e.g as the `url()` value
208    // for `background-image` or `content` properties) to either the final resolved
209    // image data, or an error if the image cache failed to load/decode the image.
210    resolved_images_cache: Arc<RwLock<HashMap<ServoUrl, CachedImageOrError>>>,
211
212    /// The executors for paint worklets.
213    registered_painters: RegisteredPaintersImpl,
214
215    /// Cross-process access to the `Paint` API.
216    paint_api: CrossProcessPaintApi,
217
218    /// Debug options, copied from configuration to this `LayoutThread` in order
219    /// to avoid having to constantly access the thread-safe global options.
220    debug: DiagnosticsLogging,
221
222    /// Tracks the node that was highlighted by the devtools during the last reflow.
223    ///
224    /// If this changed, then we need to create a new display list.
225    previously_highlighted_dom_node: Cell<Option<OpaqueNode>>,
226
227    /// Handler for all Paint Timings
228    paint_timing_handler: RefCell<Option<PaintTimingHandler>>,
229
230    /// The Container Timing records produced by the display list build of the reflow
231    /// currently in progress, waiting to be handed to script on the [`ReflowResult`].
232    /// Paint receives only their [`servo_base::id::ContainerTimingID`]s, via the display
233    /// list, and hands them back once it knows the frame's real paint time.
234    pending_container_timing_records: RefCell<Vec<ContainerTimingRecord>>,
235
236    /// Whether accessibility is active for this Layout.
237    accessibility_active: Cell<bool>,
238
239    /// Layout's internal representation of its accessibility tree.
240    /// This is `None` if accessibility is not active.
241    accessibility_tree: RefCell<Option<AccessibilityTree>>,
242
243    /// See [Layout::force_accessibility_update()].
244    force_accessibility_update_if_active: Cell<bool>,
245
246    /// Accessibility action requests which have arrived from assistive technology since the last
247    /// reflow, in chronological order.
248    /// This will be `None` unless [`Self::accessibility_active`] is true.
249    /// During reflow, these actions are drained and sent to the accessibility tree.
250    /// A reflow will be forced if this vec is non-empty.
251    pending_accessibility_actions: RefCell<Vec<ActionRequest>>,
252
253    /// A callback to run whenever a web font from a `@font-face` rule finishes loading.
254    web_font_finished_loading_callback: StylesheetWebFontLoadFinishedCallback,
255}
256
257pub struct LayoutFactoryImpl();
258
259impl LayoutFactory for LayoutFactoryImpl {
260    fn create(&self, config: LayoutConfig) -> Box<dyn Layout> {
261        Box::new(LayoutThread::new(config))
262    }
263}
264
265impl Drop for LayoutThread {
266    fn drop(&mut self) {
267        let (keys, instance_keys) = self
268            .font_context
269            .collect_unused_webrender_resources(true /* all */);
270        self.paint_api
271            .remove_unused_font_resources(self.webview_id.into(), keys, instance_keys)
272    }
273}
274
275impl Layout for LayoutThread {
276    fn device(&self) -> &Device {
277        self.stylist.device()
278    }
279
280    fn set_theme(&mut self, theme: Theme) -> bool {
281        let theme: PrefersColorScheme = theme.into();
282        let device = self.stylist.device_mut();
283        if theme == device.color_scheme() {
284            return false;
285        }
286
287        device.set_color_scheme(theme);
288        self.device_has_changed = true;
289        true
290    }
291
292    fn set_viewport_details(&mut self, viewport_details: ViewportDetails) -> bool {
293        let device = self.stylist.device_mut();
294        let device_pixel_ratio = Scale::new(viewport_details.hidpi_scale_factor.get());
295        let device_size = viewport_details.device_size.cast_unit();
296        if device.viewport_size() == viewport_details.size &&
297            device.device_pixel_ratio() == device_pixel_ratio &&
298            device.device_size() == device_size
299        {
300            return false;
301        }
302
303        device.set_viewport_size(viewport_details.size);
304        device.set_device_pixel_ratio(device_pixel_ratio);
305        device.set_device_size(device_size);
306        self.device_has_changed = true;
307        true
308    }
309
310    #[servo_tracing::instrument(skip_all)]
311    fn add_stylesheet(
312        &mut self,
313        stylesheet: ServoArc<Stylesheet>,
314        before_stylesheet: Option<ServoArc<Stylesheet>>,
315    ) {
316        let guard = stylesheet.shared_lock.read();
317        let stylesheet = DocumentStyleSheet(stylesheet.clone());
318
319        match before_stylesheet {
320            Some(insertion_point) => self.stylist.insert_stylesheet_before(
321                stylesheet,
322                DocumentStyleSheet(insertion_point),
323                &guard,
324            ),
325            None => self.stylist.append_stylesheet(stylesheet, &guard),
326        }
327    }
328
329    #[servo_tracing::instrument(skip_all)]
330    fn remove_stylesheet(&mut self, stylesheet: ServoArc<Stylesheet>) {
331        let guard = stylesheet.shared_lock.read();
332        let stylesheet = DocumentStyleSheet(stylesheet.clone());
333        self.stylist.remove_stylesheet(stylesheet, &guard);
334    }
335
336    #[servo_tracing::instrument(skip_all)]
337    fn remove_cached_image(&mut self, url: &ServoUrl) {
338        let mut resolved_images_cache = self.resolved_images_cache.write();
339        resolved_images_cache.remove(url);
340    }
341
342    fn node_rendering_type(
343        &self,
344        node: TrustedNodeAddress,
345        pseudo: Option<PseudoElement>,
346    ) -> NodeRenderingType {
347        with_layout_state(|| {
348            let node = unsafe { ServoLayoutNode::new(&node) };
349
350            // Nodes that are not currently styled are never being rendered.
351            if node
352                .as_element()
353                .is_none_or(|element| element.style_data().is_none())
354            {
355                return NodeRenderingType::NotRendered;
356            }
357
358            let node = match pseudo {
359                Some(pseudo) => node.with_pseudo(pseudo),
360                None => Some(node),
361            };
362            let Some(node) = node else {
363                return NodeRenderingType::NotRendered;
364            };
365            node.rendering_type()
366        })
367    }
368
369    /// Return the node corresponding to the containing block of the provided node.
370    #[servo_tracing::instrument(skip_all)]
371    fn query_containing_block(&self, node: TrustedNodeAddress) -> Option<UntrustedNodeAddress> {
372        with_layout_state(|| {
373            let node = unsafe { ServoLayoutNode::new(&node) };
374            process_containing_block_query(node)
375        })
376    }
377
378    /// Return the node corresponding to the containing block of the provided node.
379    #[servo_tracing::instrument(skip_all)]
380    fn query_containing_block_is_descendant(
381        &self,
382        root: TrustedNodeAddress,
383        possible_descendant: TrustedNodeAddress,
384    ) -> bool {
385        with_layout_state(|| {
386            let (root, possible_descendant) = unsafe {
387                (
388                    ServoLayoutNode::new(&root),
389                    ServoLayoutNode::new(&possible_descendant),
390                )
391            };
392            process_containing_block_descendant_query(root, possible_descendant)
393        })
394    }
395
396    /// Return the resolved values of this node's padding rect.
397    #[servo_tracing::instrument(skip_all)]
398    fn query_padding(&self, node: TrustedNodeAddress) -> Option<PhysicalSides<Au>> {
399        with_layout_state(|| {
400            // If we have not built a fragment tree yet, there is no way we have layout information for
401            // this query, which can be run without forcing a layout (for IntersectionObserver).
402            if self.fragment_tree.borrow().is_none() {
403                return None;
404            }
405
406            let node = unsafe { ServoLayoutNode::new(&node) };
407            process_padding_request(node)
408        })
409    }
410
411    /// Return the union of this node's areas in the coordinate space of the Document. This is used
412    /// to implement `getBoundingClientRect()` and support many other API where the such query is
413    /// required.
414    ///
415    /// Part of <https://drafts.csswg.org/cssom-view-1/#element-get-the-bounding-box>.
416    #[servo_tracing::instrument(skip_all)]
417    fn query_box_area(
418        &self,
419        node: TrustedNodeAddress,
420        area: BoxAreaType,
421        exclude_transform_and_inline: bool,
422    ) -> Option<Rect<Au, CSSPixel>> {
423        with_layout_state(|| {
424            // If we have not built a fragment tree yet, there is no way we have layout information for
425            // this query, which can be run without forcing a layout (for IntersectionObserver).
426            if self.fragment_tree.borrow().is_none() {
427                return None;
428            }
429
430            let node = unsafe { ServoLayoutNode::new(&node) };
431            let stacking_context_tree = self.stacking_context_tree.borrow();
432            let stacking_context_tree = stacking_context_tree.as_ref()?;
433            let inclusion = if exclude_transform_and_inline {
434                BoxAreaInclusion::empty()
435            } else {
436                BoxAreaInclusion::Transforms | BoxAreaInclusion::Inlines
437            };
438
439            process_box_area_request(self, stacking_context_tree, node, area, inclusion)
440        })
441    }
442
443    /// Get a `Vec` of bounding boxes of this node's `Fragment`s specific area in the coordinate space of
444    /// the Document. This is used to implement `getClientRects()`.
445    ///
446    /// See <https://drafts.csswg.org/cssom-view/#dom-element-getclientrects>.
447    #[servo_tracing::instrument(skip_all)]
448    fn query_box_areas(&self, node: TrustedNodeAddress, area: BoxAreaType) -> CSSPixelRectVec {
449        with_layout_state(|| {
450            // If we have not built a fragment tree yet, there is no way we have layout information for
451            // this query, which can be run without forcing a layout (for IntersectionObserver).
452            if self.fragment_tree.borrow().is_none() {
453                return None;
454            }
455
456            let node = unsafe { ServoLayoutNode::new(&node) };
457            let stacking_context_tree = self.stacking_context_tree.borrow();
458            let stacking_context_tree = stacking_context_tree.as_ref()?;
459            Some(process_box_areas_request(
460                self,
461                stacking_context_tree,
462                node,
463                area,
464            ))
465        })
466        .unwrap_or_default()
467    }
468
469    #[servo_tracing::instrument(skip_all)]
470    fn query_client_rect(&self, node: TrustedNodeAddress) -> Rect<i32, CSSPixel> {
471        with_layout_state(|| {
472            let node = unsafe { ServoLayoutNode::new(&node) };
473            process_client_rect_request(node)
474        })
475    }
476
477    #[servo_tracing::instrument(skip_all)]
478    fn query_current_css_zoom(&self, node: TrustedNodeAddress) -> f32 {
479        with_layout_state(|| {
480            let node = unsafe { ServoLayoutNode::new(&node) };
481            process_current_css_zoom_query(node)
482        })
483    }
484
485    #[servo_tracing::instrument(skip_all)]
486    fn query_element_inner_outer_text(&self, node: layout_api::TrustedNodeAddress) -> String {
487        with_layout_state(|| {
488            let node = unsafe { ServoLayoutNode::new(&node) };
489            get_the_text_steps(node)
490        })
491    }
492    #[servo_tracing::instrument(skip_all)]
493    fn query_offset_parent(&self, node: TrustedNodeAddress) -> OffsetParentResponse {
494        with_layout_state(|| {
495            let node = unsafe { ServoLayoutNode::new(&node) };
496            let stacking_context_tree = self.stacking_context_tree.borrow();
497            let stacking_context_tree = stacking_context_tree.as_ref()?;
498            process_offset_parent_query(self, &stacking_context_tree.paint_info.scroll_tree, node)
499        })
500        .unwrap_or_default()
501    }
502
503    #[servo_tracing::instrument(skip_all)]
504    fn query_scroll_container(
505        &self,
506        node: Option<TrustedNodeAddress>,
507        flags: ScrollContainerQueryFlags,
508    ) -> Option<ScrollContainerResponse> {
509        with_layout_state(|| {
510            let node = unsafe { node.as_ref().map(|node| ServoLayoutNode::new(node)) };
511            let box_tree = self.box_tree.borrow();
512            let box_tree = box_tree.as_ref()?;
513            process_scroll_container_query(
514                node,
515                flags,
516                box_tree.viewport_overflow,
517                box_tree.writing_mode(),
518            )
519        })
520    }
521
522    #[servo_tracing::instrument(skip_all)]
523    fn query_resolved_style(
524        &self,
525        node: TrustedNodeAddress,
526        pseudo: Option<PseudoElement>,
527        property_id: PropertyId,
528        animations: DocumentAnimationSet,
529        animation_timeline_value: f64,
530    ) -> String {
531        with_layout_state(|| {
532            let node = unsafe { ServoLayoutNode::new(&node) };
533            let document = unsafe { node.dangerous_style_node() }.owner_doc();
534            let shared_locks = document.shared_style_locks();
535            let guards = StylesheetGuards {
536                author: &shared_locks.author.read(),
537                ua_or_user: &shared_locks.ua_or_user.read(),
538            };
539            let snapshot_map = SnapshotMap::new();
540
541            let shared_style_context = self.build_shared_style_context(
542                guards,
543                &snapshot_map,
544                animation_timeline_value,
545                &animations,
546                TraversalFlags::empty(),
547            );
548
549            let fragment_tree = self.fragment_tree.borrow();
550            let initial_containing_block = fragment_tree
551                .as_ref()
552                .map(|fragment_tree| &fragment_tree.initial_containing_block);
553
554            process_resolved_style_request(
555                &shared_style_context,
556                initial_containing_block,
557                node,
558                &pseudo,
559                &property_id,
560            )
561        })
562    }
563
564    fn query_accesskit_node(&self, node: TrustedNodeAddress) -> Option<Node> {
565        with_layout_state(|| {
566            let node = unsafe { ServoLayoutNode::new(&node) };
567            let accessibility_tree = self.accessibility_tree.borrow();
568            let accessibility_tree = accessibility_tree.as_ref()?;
569            accessibility_tree.accesskit_node_for_dom_node(&node)
570        })
571    }
572
573    #[servo_tracing::instrument(skip_all)]
574    fn query_resolved_font_style(
575        &self,
576        node: TrustedNodeAddress,
577        value: &str,
578        animations: DocumentAnimationSet,
579        animation_timeline_value: f64,
580    ) -> Option<ServoArc<Font>> {
581        with_layout_state(|| {
582            let node = unsafe { ServoLayoutNode::new(&node) };
583            let document = unsafe { node.dangerous_style_node() }.owner_doc();
584            let shared_locks = document.shared_style_locks();
585            let shared_author_lock = &shared_locks.author;
586            let guards = StylesheetGuards {
587                author: &shared_author_lock.read(),
588                ua_or_user: &shared_locks.ua_or_user.read(),
589            };
590            let snapshot_map = SnapshotMap::new();
591            let shared_style_context = self.build_shared_style_context(
592                guards,
593                &snapshot_map,
594                animation_timeline_value,
595                &animations,
596                TraversalFlags::empty(),
597            );
598
599            process_resolved_font_style_query(
600                &shared_style_context,
601                node,
602                value,
603                self.url.clone(),
604                shared_author_lock,
605            )
606        })
607    }
608
609    #[servo_tracing::instrument(skip_all)]
610    fn query_scrolling_area(&self, node: Option<TrustedNodeAddress>) -> Rect<i32, CSSPixel> {
611        with_layout_state(|| {
612            let node = node.map(|node| unsafe { ServoLayoutNode::new(&node) });
613            process_node_scroll_area_request(self, node, self.fragment_tree.borrow().clone())
614        })
615    }
616
617    #[servo_tracing::instrument(skip_all)]
618    fn query_text_index(
619        &self,
620        node: TrustedNodeAddress,
621        point_in_viewport: Point2D<Au, CSSPixel>,
622    ) -> Option<(OpaqueNode, Utf32CodeUnits)> {
623        with_layout_state(|| {
624            let node = unsafe { ServoLayoutNode::new(&node) };
625            let stacking_context_tree = self.stacking_context_tree.borrow();
626            let stacking_context_tree = stacking_context_tree.as_ref()?;
627            find_character_offset_in_fragment_descendants(
628                &node,
629                stacking_context_tree,
630                point_in_viewport,
631            )
632        })
633    }
634
635    #[servo_tracing::instrument(skip_all)]
636    fn query_text_segment(
637        &self,
638        node: TrustedNodeAddress,
639        offset: Utf32CodeUnitsOrNodeOffset,
640        granularity: SegmentGranularity,
641    ) -> Option<(
642        (OpaqueNode, Utf32CodeUnitsOrNodeOffset),
643        (OpaqueNode, Utf32CodeUnitsOrNodeOffset),
644    )> {
645        with_layout_state(|| {
646            let node = unsafe { ServoLayoutNode::new(&node) };
647            PositionInInlineFormattingContext::from_dom_position_in_text_node(&node, offset)?
648                .segment(granularity)
649        })
650    }
651
652    #[servo_tracing::instrument(skip_all)]
653    fn hit_test(
654        &self,
655        flags: HitTestFlags,
656        point: webrender_api::units::LayoutPoint,
657    ) -> HitTestResult {
658        with_layout_state(|| {
659            self.stacking_context_tree
660                .borrow_mut()
661                .as_mut()
662                .map(|tree| HitTest::run(flags, tree, point))
663                .unwrap_or_default()
664        })
665    }
666
667    #[servo_tracing::instrument(skip_all)]
668    fn query_effective_overflow(&self, node: TrustedNodeAddress) -> Option<AxesOverflow> {
669        with_layout_state(|| {
670            let node = unsafe { ServoLayoutNode::new(&node) };
671            process_effective_overflow_query(node)
672        })
673    }
674
675    fn exit_now(&mut self) {}
676
677    fn collect_reports(&self, reports: &mut Vec<Report>, ops: &mut MallocSizeOfOps) {
678        // TODO: Measure more than just display list, stylist, and font context.
679        let formatted_url = &format!("url({})", self.url);
680        reports.push(Report {
681            path: path![formatted_url, "layout-thread", "display-list"],
682            kind: ReportKind::ExplicitJemallocHeapSize,
683            size: 0,
684        });
685
686        reports.push(Report {
687            path: path![formatted_url, "layout-thread", "stylist"],
688            kind: ReportKind::ExplicitJemallocHeapSize,
689            size: self.stylist.size_of(ops),
690        });
691
692        reports.push(Report {
693            path: path![formatted_url, "layout-thread", "font-context"],
694            kind: ReportKind::ExplicitJemallocHeapSize,
695            size: self.font_context.conditional_size_of(ops),
696        });
697
698        reports.push(Report {
699            path: path![formatted_url, "layout-thread", "box-tree"],
700            kind: ReportKind::ExplicitJemallocHeapSize,
701            size: self
702                .box_tree
703                .borrow()
704                .as_ref()
705                .map_or(0, |tree| tree.conditional_size_of(ops)),
706        });
707
708        reports.push(Report {
709            path: path![formatted_url, "layout-thread", "fragment-tree"],
710            kind: ReportKind::ExplicitJemallocHeapSize,
711            size: self
712                .fragment_tree
713                .borrow()
714                .as_ref()
715                .map(|tree| tree.conditional_size_of(ops))
716                .unwrap_or_default(),
717        });
718
719        reports.push(Report {
720            path: path![formatted_url, "layout-thread", "stacking-context-tree"],
721            kind: ReportKind::ExplicitJemallocHeapSize,
722            size: self.stacking_context_tree.size_of(ops),
723        });
724
725        reports.extend(self.image_cache.memory_reports(formatted_url, ops));
726    }
727
728    fn set_quirks_mode(&mut self, quirks_mode: QuirksMode) {
729        self.stylist.set_quirks_mode(quirks_mode);
730    }
731
732    fn reflow(&mut self, reflow_request: ReflowRequest) -> Option<ReflowResult> {
733        time_profile!(
734            profile_time::ProfilerCategory::Layout,
735            self.profiler_metadata(),
736            self.time_profiler_chan.clone(),
737            || with_layout_state(|| self.handle_reflow(reflow_request)),
738        )
739    }
740
741    fn ensure_stacking_context_tree(&self, viewport_details: ViewportDetails) {
742        with_layout_state(|| {
743            if self.stacking_context_tree.borrow().is_some() &&
744                !self.need_new_stacking_context_tree.get()
745            {
746                return;
747            }
748            self.build_stacking_context_tree(viewport_details);
749        })
750    }
751
752    fn register_paint_worklet_modules(
753        &mut self,
754        _name: Atom,
755        _properties: Vec<Atom>,
756        _painter: Box<dyn Painter>,
757    ) {
758    }
759
760    fn set_scroll_offsets_from_renderer(
761        &mut self,
762        scroll_states: &FxHashMap<ExternalScrollId, LayoutVector2D>,
763    ) {
764        let mut stacking_context_tree = self.stacking_context_tree.borrow_mut();
765        let Some(stacking_context_tree) = stacking_context_tree.as_mut() else {
766            warn!("Received scroll offsets before finishing layout.");
767            return;
768        };
769
770        let offsets = stacking_context_tree
771            .paint_info
772            .scroll_tree
773            .set_all_scroll_offsets(scroll_states);
774
775        // Accessibility node bounds are relative to the viewport origin, so a renderer scroll
776        // makes every one of them stale without any reflow occurring. Requesting an accessibility
777        // update schedules a rendering update and prevents that update's reflow from being skipped,
778        // allowing the bounds to be recomputed against the new scroll offsets. See #47161 for a
779        // transform-based alternative to recomputing every node.
780        if self.accessibility_active() {
781            let mut accessibility_tree = self.accessibility_tree.borrow_mut();
782            if let Some(accessibility_tree) = accessibility_tree.as_mut() {
783                accessibility_tree.add_pending_scroll_updates(offsets);
784            };
785
786            self.set_force_accessibility_update_if_active();
787        }
788    }
789
790    fn scroll_offset(&self, id: ExternalScrollId) -> Option<LayoutVector2D> {
791        self.stacking_context_tree
792            .borrow_mut()
793            .as_mut()
794            .and_then(|tree| tree.paint_info.scroll_tree.scroll_offset(id))
795    }
796
797    fn needs_new_display_list(&self) -> bool {
798        self.need_new_display_list.get()
799    }
800
801    fn set_needs_new_display_list(&self) {
802        self.need_new_display_list.set(true);
803    }
804
805    /// <https://drafts.css-houdini.org/css-properties-values-api-1/#the-registerproperty-function>
806    fn stylist_mut(&mut self) -> &mut Stylist {
807        &mut self.stylist
808    }
809
810    fn set_accessibility_active(&self, active: bool, epoch: Epoch) {
811        self.accessibility_active.set(active);
812        if !active {
813            self.accessibility_tree.replace(None);
814            self.pending_accessibility_actions.borrow_mut().clear();
815            return;
816        }
817
818        self.set_force_accessibility_update_if_active();
819        let mut accessibility_tree = self.accessibility_tree.borrow_mut();
820        if accessibility_tree.is_none() {
821            *accessibility_tree = Some(AccessibilityTree::new(self.id.into(), epoch));
822        }
823    }
824
825    fn accessibility_active(&self) -> bool {
826        self.accessibility_active.get()
827    }
828
829    fn needs_accessibility_update(&self) -> bool {
830        if !self.accessibility_active() {
831            return false;
832        }
833        if self.force_accessibility_update_if_active.get() {
834            return true;
835        }
836        if !self.pending_accessibility_actions.borrow().is_empty() {
837            return true;
838        }
839
840        false
841    }
842
843    fn set_force_accessibility_update_if_active(&self) {
844        self.force_accessibility_update_if_active.set(true);
845    }
846
847    fn handle_accessibility_action(&self, action_request: ActionRequest) {
848        self.pending_accessibility_actions
849            .borrow_mut()
850            .push(action_request);
851    }
852
853    fn font_context(&self) -> &Arc<FontContext> {
854        &self.font_context
855    }
856}
857
858impl LayoutThread {
859    fn new(config: LayoutConfig) -> LayoutThread {
860        // Let webrender know about this pipeline by sending an empty display list.
861        config
862            .paint_api
863            .send_initial_transaction(config.webview_id, config.id.into());
864
865        let mut font = Font::initial_values();
866        let default_font_size = pref!(fonts_default_size);
867        font.font_size = FontSize {
868            computed_size: NonNegativeLength::new(default_font_size as f32),
869            used_size: NonNegativeLength::new(default_font_size as f32),
870            keyword_info: KeywordInfo::medium(),
871        };
872
873        // The device pixel ratio is incorrect (it does not have the hidpi value),
874        // but it will be set correctly when the initial reflow takes place.
875        let device = Device::new(
876            ComputedValues::initial_values_with_font_override(font),
877            Box::new(LayoutFontMetricsProvider(config.font_context.clone())),
878            Box::from(HTML_INPUT_TYPE_SUBMIT_DEFAULT_VALUE),
879            config.document_random_hasher_key,
880            MediaData {
881                media_type: MediaType::screen(),
882                quirks_mode: QuirksMode::NoQuirks,
883                viewport_size: config.viewport_details.size,
884                device_size: config.viewport_details.device_size.cast_unit(),
885                device_pixel_ratio: Scale::new(config.viewport_details.hidpi_scale_factor.get()),
886                prefers_color_scheme: config.theme.into(),
887                primary_pointer_capabilities: PointerCapabilities::default(),
888                all_pointer_capabilities: PointerCapabilities::default(),
889            },
890        );
891
892        let locked_script_channel = Mutex::new(config.script_chan.clone());
893        let pipeline_id = config.id;
894        let web_font_finished_loading_callback = move |event| {
895            let _ = locked_script_channel
896                .lock()
897                .send(ScriptThreadMessage::WebFontLoadFinished(pipeline_id, event));
898        };
899
900        LayoutThread {
901            id: config.id,
902            webview_id: config.webview_id,
903            url: config.url,
904            is_iframe: config.is_iframe,
905            time_profiler_chan: config.time_profiler_chan,
906            embedder_chan: config.embedder_chan.clone(),
907            registered_painters: RegisteredPaintersImpl(Default::default()),
908            image_cache: config.image_cache,
909            font_context: config.font_context,
910            have_added_user_agent_stylesheets: false,
911            have_ever_generated_display_list: Cell::new(false),
912            last_display_list_was_empty: Cell::new(true),
913            device_has_changed: false,
914            need_containing_block_calculation: Cell::new(false),
915            need_new_display_list: Cell::new(false),
916            need_new_stacking_context_tree: Cell::new(false),
917            box_tree: Default::default(),
918            fragment_tree: Default::default(),
919            stacking_context_tree: Default::default(),
920            paint_api: config.paint_api,
921            stylist: Stylist::new(device, QuirksMode::NoQuirks),
922            resolved_images_cache: Default::default(),
923            debug: opts::get().debug.clone(),
924            previously_highlighted_dom_node: Cell::new(None),
925            paint_timing_handler: Default::default(),
926            pending_container_timing_records: Default::default(),
927            user_stylesheets: config.user_stylesheets,
928            accessibility_active: Cell::new(false),
929            accessibility_tree: Default::default(),
930            force_accessibility_update_if_active: Cell::new(false),
931            pending_accessibility_actions: RefCell::new(vec![]),
932            web_font_finished_loading_callback: Arc::new(web_font_finished_loading_callback)
933                as StylesheetWebFontLoadFinishedCallback,
934        }
935    }
936
937    fn build_shared_style_context<'a>(
938        &'a self,
939        guards: StylesheetGuards<'a>,
940        snapshot_map: &'a SnapshotMap,
941        animation_timeline_value: f64,
942        animations: &DocumentAnimationSet,
943        traversal_flags: TraversalFlags,
944    ) -> SharedStyleContext<'a> {
945        SharedStyleContext {
946            stylist: &self.stylist,
947            options: GLOBAL_STYLE_DATA.options.clone(),
948            guards,
949            visited_styles_enabled: false,
950            animations: animations.clone(),
951            registered_speculative_painters: &self.registered_painters,
952            current_time_for_animations: animation_timeline_value,
953            traversal_flags,
954            snapshot_map,
955        }
956    }
957
958    /// In some cases, if a restyle isn't necessary we can skip doing any work for layout
959    /// entirely. This check allows us to return early from layout without doing any work
960    /// at all.
961    fn can_skip_reflow_request_entirely(&self, reflow_request: &ReflowRequest) -> bool {
962        // If a restyle is necessary, restyle and reflow is a necessity.
963        if reflow_request.restyle.is_some() {
964            return false;
965        }
966        // We always need to at least build a fragment tree.
967        if self.fragment_tree.borrow().is_none() {
968            return false;
969        }
970        // If the accessibility tree needs an update, we need reflow to build the accessibility tree.
971        if self.needs_accessibility_update() || reflow_request.accessibility.is_some() {
972            return false;
973        }
974
975        // If we have a fragment tree and it's up-to-date and this reflow
976        // doesn't need more reflow results, we can skip the rest of layout.
977        let necessary_phases = ReflowPhases::necessary(&reflow_request.reflow_goal);
978        if necessary_phases.is_empty() {
979            return true;
980        }
981
982        // If only the stacking context tree is required, and it's up-to-date,
983        // layout is unnecessary, otherwise a layout is necessary.
984        if necessary_phases == ReflowPhases::StackingContextTreeConstruction {
985            return self.stacking_context_tree.borrow().is_some() &&
986                !self.need_new_stacking_context_tree.get();
987        }
988
989        // Otherwise, the only interesting thing is whether the current display
990        // list is up-to-date.
991        assert_eq!(
992            necessary_phases,
993            ReflowPhases::StackingContextTreeConstruction | ReflowPhases::DisplayListConstruction
994        );
995        !self.need_new_display_list.get()
996    }
997
998    fn maybe_print_reflow_event(&self, reflow_request: &ReflowRequest) {
999        if !self
1000            .debug
1001            .is_enabled(DiagnosticsLoggingOption::RelayoutEvent)
1002        {
1003            return;
1004        }
1005
1006        println!(
1007            "**** Reflow({}) => {:?}, {:?}",
1008            self.id,
1009            reflow_request.reflow_goal,
1010            reflow_request
1011                .restyle
1012                .as_ref()
1013                .map(|restyle| restyle.reason)
1014                .unwrap_or_default()
1015        );
1016    }
1017
1018    /// Checks whether we need to update the scroll node, and report whether the
1019    /// node is scrolled. We need to update the scroll node whenever it is requested.
1020    fn handle_update_scroll_node_request(&self, reflow_request: &ReflowRequest) -> bool {
1021        if let ReflowGoal::UpdateScrollNode(external_scroll_id, offset) = reflow_request.reflow_goal
1022        {
1023            self.set_scroll_offset_from_script(external_scroll_id, offset)
1024        } else {
1025            false
1026        }
1027    }
1028
1029    fn handle_accessibility_tree_update(
1030        &self,
1031        root_element: &ServoLayoutNode,
1032        accessibility_damage: Option<AccessibilityDamageMap>,
1033        reflow_accessibility: Option<ReflowRequestAccessibility>,
1034        pending_accessibility_actions: &mut Vec<AccessibilityActionRequest>,
1035        reflow_statistics: &mut ReflowStatistics,
1036    ) -> bool {
1037        let Some(reflow_accessibility) = reflow_accessibility else {
1038            return false;
1039        };
1040        let Some(damage) = accessibility_damage else {
1041            return false;
1042        };
1043        if !self.needs_accessibility_update() && damage.is_empty() {
1044            return false;
1045        }
1046
1047        let mut accessibility_tree = self.accessibility_tree.borrow_mut();
1048        let Some(accessibility_tree) = accessibility_tree.as_mut() else {
1049            return false;
1050        };
1051
1052        let accessibility_tree = &mut *accessibility_tree;
1053
1054        let stacking_context_tree = self.stacking_context_tree.borrow();
1055        let Some(stacking_context_tree) = stacking_context_tree.as_ref() else {
1056            return false;
1057        };
1058        debug_assert!(!self.need_new_stacking_context_tree.get());
1059
1060        let accessibility_context = AccessibilityContext {
1061            layout_thread: self,
1062            stacking_context_tree,
1063            focused_element: reflow_accessibility.focused_element,
1064            rooted_nodes_for_integrity_check: reflow_accessibility.rooted_nodes_for_integrity_check,
1065        };
1066
1067        let action_requests = self.pending_accessibility_actions.take();
1068
1069        let (tree_update, counters) = accessibility_tree.update_tree(
1070            root_element,
1071            damage,
1072            action_requests,
1073            accessibility_context,
1074        );
1075        if let Some(tree_update) = tree_update {
1076            // FIXME: Handle send error. Could have a method on accessibility tree to
1077            // finalise after sending, removing accessibility damage? On fail, retain damage
1078            // for next reflow, as well as retaining document.needs_accessibility_update.
1079            let _ = self
1080                .embedder_chan
1081                .send(EmbedderMsg::AccessibilityTreeUpdate(
1082                    self.webview_id,
1083                    tree_update,
1084                    accessibility_tree.embedder_epoch(),
1085                ));
1086        }
1087
1088        reflow_statistics.nodes_updated_from_dom = counters.nodes_updated_from_dom;
1089        reflow_statistics.nodes_updated_from_tree = counters.nodes_updated_from_tree;
1090        reflow_statistics.nodes_updated_bounds = counters.nodes_updated_bounds;
1091        reflow_statistics.nodes_in_tree_update = counters.nodes_in_tree_update;
1092
1093        self.force_accessibility_update_if_active.set(false);
1094
1095        *pending_accessibility_actions = accessibility_tree.take_pending_actions();
1096
1097        true
1098    }
1099
1100    /// The high-level routine that performs layout.
1101    #[servo_tracing::instrument(
1102        skip_all,
1103        fields(
1104            goal = tracing::field::debug(&reflow_request.reflow_goal),
1105            webview_id = tracing::field::display(self.webview_id),
1106        )
1107    )]
1108    fn handle_reflow(&mut self, mut reflow_request: ReflowRequest) -> Option<ReflowResult> {
1109        self.maybe_print_reflow_event(&reflow_request);
1110
1111        if self.can_skip_reflow_request_entirely(&reflow_request) {
1112            // We can skip layout, but we might need to update a scroll node.
1113            return self
1114                .handle_update_scroll_node_request(&reflow_request)
1115                .then(|| ReflowResult {
1116                    reflow_phases_run: ReflowPhasesRun::UpdatedScrollNodeOffset,
1117                    ..Default::default()
1118                });
1119        }
1120
1121        let document = unsafe { ServoLayoutNode::new(&reflow_request.document) };
1122        let document = unsafe { document.dangerous_style_node() }
1123            .as_document()
1124            .unwrap();
1125        let Some(root_element) = document.root_element() else {
1126            debug!("layout: No root node: bailing");
1127            return self.maybe_clear_layout_trees_and_send_empty_display_list(&reflow_request);
1128        };
1129
1130        let image_resolver = Arc::new(ImageResolver {
1131            origin: reflow_request.origin.clone(),
1132            image_cache: self.image_cache.clone(),
1133            resolved_images_cache: self.resolved_images_cache.clone(),
1134            pending_images: Mutex::default(),
1135            pending_rasterization_images: Mutex::default(),
1136            pending_svg_elements_for_serialization: Mutex::default(),
1137            animating_images: reflow_request.animating_images.clone(),
1138            animation_timeline_value: reflow_request.animation_timeline_value,
1139        });
1140        let mut reflow_statistics = Default::default();
1141
1142        let mut reflow_accessibility = std::mem::take(&mut reflow_request.accessibility);
1143        let mut accessibility_damage = to_accessibility_damage_map(
1144            reflow_accessibility
1145                .as_mut()
1146                .map(|accessibility| std::mem::take(&mut accessibility.damage)),
1147        );
1148
1149        let (mut reflow_phases_run, iframe_sizes, changed_web_fonts) = self
1150            .restyle_and_build_trees(
1151                &mut reflow_request,
1152                document,
1153                root_element,
1154                &image_resolver,
1155                accessibility_damage.as_mut(),
1156            );
1157
1158        if self.build_stacking_context_tree_for_reflow(&reflow_request) {
1159            reflow_phases_run.insert(ReflowPhasesRun::BuiltStackingContextTree);
1160        }
1161        if self.build_display_list(&reflow_request, &image_resolver, &mut reflow_statistics) {
1162            reflow_phases_run.insert(ReflowPhasesRun::BuiltDisplayList);
1163        }
1164        if self.handle_update_scroll_node_request(&reflow_request) {
1165            reflow_phases_run.insert(ReflowPhasesRun::UpdatedScrollNodeOffset);
1166        }
1167        let mut pending_accessibility_actions = vec![];
1168        if self.handle_accessibility_tree_update(
1169            &root_element.as_node(),
1170            accessibility_damage,
1171            reflow_accessibility,
1172            &mut pending_accessibility_actions,
1173            &mut reflow_statistics,
1174        ) {
1175            reflow_phases_run.insert(ReflowPhasesRun::UpdatedAccessibilityTree);
1176        }
1177
1178        if self.debug.is_enabled(DiagnosticsLoggingOption::FlowTree) &&
1179            reflow_phases_run.contains(ReflowPhasesRun::RanLayout) &&
1180            let Some(fragment_tree) = &*self.fragment_tree.borrow()
1181        {
1182            fragment_tree.print();
1183        }
1184
1185        let pending_images = std::mem::take(&mut *image_resolver.pending_images.lock());
1186        let pending_rasterization_images =
1187            std::mem::take(&mut *image_resolver.pending_rasterization_images.lock());
1188        let pending_svg_elements_for_serialization =
1189            std::mem::take(&mut *image_resolver.pending_svg_elements_for_serialization.lock());
1190
1191        let lcp_candidate = self
1192            .paint_timing_handler
1193            .borrow()
1194            .as_ref()
1195            .map(|handler| handler.largest_contentful_paint_candidate())
1196            .unwrap_or_default();
1197
1198        Some(ReflowResult {
1199            reflow_phases_run,
1200            pending_images,
1201            pending_rasterization_images,
1202            pending_svg_elements_for_serialization,
1203            iframe_sizes: Some(iframe_sizes),
1204            reflow_statistics,
1205            changed_web_fonts,
1206            lcp_candidate,
1207            pending_accessibility_actions,
1208            container_timing_records: std::mem::take(
1209                &mut *self.pending_container_timing_records.borrow_mut(),
1210            ),
1211        })
1212    }
1213
1214    #[servo_tracing::instrument(skip_all)]
1215    fn prepare_stylist_for_reflow<'dom>(
1216        &mut self,
1217        reflow_request: &ReflowRequest,
1218        document: ServoDangerousStyleDocument<'dom>,
1219        guards: &StylesheetGuards,
1220        ua_stylesheets: &UserAgentStylesheets,
1221    ) -> StylistStylesheetUpdate {
1222        let need_user_agent_stylesheet_addition = !self.have_added_user_agent_stylesheets;
1223        if need_user_agent_stylesheet_addition {
1224            for stylesheet in &ua_stylesheets.user_agent_stylesheets {
1225                self.stylist
1226                    .append_stylesheet(stylesheet.clone(), guards.ua_or_user);
1227            }
1228
1229            if document.is_html_document() {
1230                self.stylist.append_stylesheet(
1231                    ua_stylesheets.html_mode_stylesheet.clone(),
1232                    guards.ua_or_user,
1233                );
1234
1235                if document.encoding() == ISO_8859_8 {
1236                    self.stylist.append_stylesheet(
1237                        ua_stylesheets.iso_8859_8_stylesheet.clone(),
1238                        guards.ua_or_user,
1239                    );
1240                }
1241            }
1242
1243            for user_stylesheet in self.user_stylesheets.iter() {
1244                self.stylist
1245                    .append_stylesheet(user_stylesheet.clone(), guards.ua_or_user);
1246            }
1247
1248            if self.stylist.quirks_mode() == QuirksMode::Quirks {
1249                self.stylist.append_stylesheet(
1250                    ua_stylesheets.quirks_mode_stylesheet.clone(),
1251                    guards.ua_or_user,
1252                );
1253            }
1254            self.have_added_user_agent_stylesheets = true;
1255        }
1256
1257        if reflow_request.stylesheets_changed() {
1258            self.stylist
1259                .force_stylesheet_origins_dirty(Origin::Author.into());
1260        }
1261
1262        document.flush_shadow_root_stylesheets_if_necessary(&mut self.stylist, guards.author);
1263
1264        let invalidation_set = self.stylist.flush(guards);
1265
1266        let changed_web_fonts =
1267            if need_user_agent_stylesheet_addition || reflow_request.stylesheets_changed() {
1268                self.font_context.invalidate_font_feature_values_map();
1269                // Load new @font-face rules and remove old ones if necessary.
1270                // TODO: Can we make the invalidation set tell us whether any @font-face rules changed?
1271                self.font_context.rebuild_font_face_set(
1272                    self.webview_id,
1273                    &self.stylist,
1274                    guards,
1275                    self.web_font_finished_loading_callback.clone(),
1276                    &reflow_request.document_context,
1277                )
1278            } else {
1279                WebFontSetDifference::default()
1280            };
1281
1282        StylistStylesheetUpdate {
1283            invalidation_set,
1284            changed_web_fonts,
1285        }
1286    }
1287
1288    #[servo_tracing::instrument(skip_all)]
1289    fn restyle_and_build_trees<'dom>(
1290        &mut self,
1291        reflow_request: &mut ReflowRequest,
1292        document: ServoDangerousStyleDocument<'_>,
1293        root_element: ServoLayoutElement<'dom>,
1294        image_resolver: &Arc<ImageResolver>,
1295        mut accessibility_damage: Option<&mut AccessibilityDamageMap<'dom>>,
1296    ) -> (ReflowPhasesRun, IFrameSizes, WebFontSetDifference) {
1297        let mut snapshot_map = SnapshotMap::new();
1298        let _snapshot_setter = match reflow_request.restyle.as_mut() {
1299            Some(restyle) => SnapshotSetter::new(restyle, &mut snapshot_map),
1300            None => return Default::default(),
1301        };
1302
1303        let shared_locks = document.shared_style_locks();
1304        let user_agent_stylesheets = get_ua_stylesheets(&shared_locks.ua_or_user);
1305        let guards = StylesheetGuards {
1306            author: &shared_locks.author.read(),
1307            ua_or_user: &shared_locks.ua_or_user.read(),
1308        };
1309
1310        let rayon_pool = STYLE_THREAD_POOL.lock();
1311        let rayon_pool = rayon_pool.pool();
1312        let rayon_pool = rayon_pool.as_ref();
1313
1314        let device_has_changed = std::mem::replace(&mut self.device_has_changed, false);
1315        let dangerous_root_element = unsafe { root_element.dangerous_style_element() };
1316        if device_has_changed {
1317            let sheet_origins_affected_by_device_change = self
1318                .stylist
1319                .media_features_change_changed_style(&guards, self.device());
1320            self.stylist
1321                .force_stylesheet_origins_dirty(sheet_origins_affected_by_device_change);
1322
1323            if let Some(mut data) = dangerous_root_element.mutate_data() {
1324                data.hint.insert(RestyleHint::recascade_subtree());
1325            }
1326        }
1327
1328        let stylist_update = self.prepare_stylist_for_reflow(
1329            reflow_request,
1330            document,
1331            &guards,
1332            &user_agent_stylesheets,
1333        );
1334        stylist_update
1335            .invalidation_set
1336            .process_style(dangerous_root_element, Some(&snapshot_map));
1337
1338        if self.previously_highlighted_dom_node.get() != reflow_request.highlighted_dom_node {
1339            // Need to manually force layout to build a new display list regardless of whether the box tree
1340            // changed or not.
1341            self.need_new_display_list.set(true);
1342        }
1343
1344        let layout_context = LayoutContext {
1345            style_context: self.build_shared_style_context(
1346                guards,
1347                &snapshot_map,
1348                reflow_request.animation_timeline_value,
1349                &reflow_request.animations,
1350                match reflow_request.stylesheets_changed() {
1351                    true => TraversalFlags::ForCSSRuleChanges,
1352                    false => TraversalFlags::empty(),
1353                },
1354            ),
1355            font_context: self.font_context.clone(),
1356            iframe_sizes: Mutex::default(),
1357            allow_parallel_layout: rayon_pool.is_some(),
1358            image_resolver: image_resolver.clone(),
1359            painter_id: self.webview_id.into(),
1360            parallelism_job_count_minimum: pref!(layout_parallelism_job_count_minimum) as usize,
1361            parallelism_job_size_minimum: pref!(layout_parallelism_job_size_minimum) as usize,
1362            device_size: reflow_request.viewport_details.device_size.cast_unit(),
1363        };
1364
1365        let restyle = reflow_request
1366            .restyle
1367            .as_ref()
1368            .expect("Should not get here if there is not restyle.");
1369
1370        let recalc_style_traversal;
1371        let dirty_root;
1372        {
1373            let _span = profile_traits::trace_span!("Styling").entered();
1374
1375            let original_dirty_root = unsafe {
1376                ServoLayoutNode::new(&restyle.dirty_root.unwrap())
1377                    .as_element()
1378                    .unwrap()
1379                    .dangerous_style_element()
1380            };
1381
1382            recalc_style_traversal = RecalcStyle::new(&layout_context);
1383            let token = {
1384                let shared = DomTraversal::<ServoDangerousStyleElement>::shared_context(
1385                    &recalc_style_traversal,
1386                );
1387                RecalcStyle::pre_traverse(original_dirty_root, shared)
1388            };
1389
1390            if !token.should_traverse() {
1391                layout_context.style_context.stylist.rule_tree().maybe_gc();
1392                return Default::default();
1393            }
1394
1395            dirty_root = driver::traverse_dom(&recalc_style_traversal, token, rayon_pool).as_node();
1396        }
1397
1398        let root_node = root_element.as_node();
1399        let damage_from_environment = if device_has_changed {
1400            LayoutDamage::Relayout
1401        } else {
1402            LayoutDamage::empty()
1403        };
1404
1405        let mut box_tree = self.box_tree.borrow_mut();
1406        let mut layout_roots = Vec::new();
1407        let damage = {
1408            let box_tree = &mut *box_tree;
1409            let mut compute_damage_and_build_box_tree = || {
1410                compute_damage_and_rebuild_box_tree(
1411                    box_tree,
1412                    &layout_context,
1413                    dirty_root.layout_node(),
1414                    root_node,
1415                    damage_from_environment,
1416                    &mut layout_roots,
1417                )
1418            };
1419
1420            if let Some(pool) = rayon_pool {
1421                pool.install(compute_damage_and_build_box_tree)
1422            } else {
1423                compute_damage_and_build_box_tree()
1424            }
1425        };
1426
1427        if damage.contains(LayoutDamage::RebuildStackingContextTree) {
1428            self.need_new_stacking_context_tree.set(true);
1429        }
1430        if damage.contains(LayoutDamage::Repaint) {
1431            self.need_new_display_list.set(true);
1432        }
1433
1434        let mut insert_accessibility_damage_if_necessary = |node: ServoLayoutNode<'dom>| {
1435            if let Some(map) = accessibility_damage.as_mut() {
1436                map.entry(node.opaque())
1437                    .or_insert((node, AccessibilityDamage::empty()))
1438                    .1
1439                    .insert(AccessibilityDamage::Layout);
1440            }
1441        };
1442
1443        if !damage.contains(LayoutDamage::Relayout) {
1444            if damage.contains(LayoutDamage::RecalculateOverflow) {
1445                assert!(self.need_new_display_list.get());
1446                assert!(self.need_new_stacking_context_tree.get());
1447                self.fragment_tree
1448                    .borrow()
1449                    .as_ref()
1450                    .expect("Should always have a FragmentTree when layout unnecessary")
1451                    .clear_scrollable_overflow();
1452            }
1453
1454            if !damage.contains(LayoutDamage::DescendantCollectedAsLayoutRoot) {
1455                layout_context.style_context.stylist.rule_tree().maybe_gc();
1456                return (
1457                    ReflowPhasesRun::empty(),
1458                    IFrameSizes::default(),
1459                    stylist_update.changed_web_fonts,
1460                );
1461            }
1462
1463            debug_assert!(!layout_roots.is_empty());
1464
1465            for layout_root in &layout_roots {
1466                insert_accessibility_damage_if_necessary(layout_root.node());
1467            }
1468
1469            if layout_roots
1470                .iter()
1471                .all(|layout_root| layout_root.try_layout(&layout_context))
1472            {
1473                return (
1474                    ReflowPhasesRun::RanLayout,
1475                    std::mem::take(&mut *layout_context.iframe_sizes.lock()),
1476                    stylist_update.changed_web_fonts,
1477                );
1478            }
1479
1480            // LayoutRoot layout has failed and now the layout root and descendants may have
1481            // been only partially laid out. As the next step is to do a full `FragmentTree`
1482            // layout, we need to ensure that none of the partial layout results corrupt
1483            // the upcoming full layout.
1484            for layout_root in layout_roots {
1485                layout_root.handle_failed_layout_root_layout();
1486            }
1487        }
1488
1489        insert_accessibility_damage_if_necessary(root_node);
1490
1491        let box_tree = &*box_tree;
1492        let viewport_size = self.stylist.device().au_viewport_size();
1493        let run_layout = || {
1494            box_tree
1495                .as_ref()
1496                .unwrap()
1497                .layout(recalc_style_traversal.context(), viewport_size)
1498        };
1499        let fragment_tree = Rc::new(if let Some(pool) = rayon_pool {
1500            pool.install(run_layout)
1501        } else {
1502            run_layout()
1503        });
1504
1505        *self.fragment_tree.borrow_mut() = Some(fragment_tree);
1506
1507        if self.debug.is_enabled(DiagnosticsLoggingOption::StyleTree) {
1508            println!(
1509                "{:?}",
1510                ShowSubtreeDataAndPrimaryValues(dangerous_root_element.as_node())
1511            );
1512        }
1513        if self.debug.is_enabled(DiagnosticsLoggingOption::RuleTree) {
1514            recalc_style_traversal
1515                .context()
1516                .style_context
1517                .stylist
1518                .rule_tree()
1519                .dump_stdout(&layout_context.style_context.guards);
1520        }
1521
1522        // GC the rule tree if some heuristics are met.
1523        layout_context.style_context.stylist.rule_tree().maybe_gc();
1524
1525        let mut iframe_sizes = layout_context.iframe_sizes.lock();
1526        (
1527            ReflowPhasesRun::RanLayout,
1528            std::mem::take(&mut *iframe_sizes),
1529            stylist_update.changed_web_fonts,
1530        )
1531    }
1532
1533    fn build_stacking_context_tree_for_reflow(&self, reflow_request: &ReflowRequest) -> bool {
1534        if !ReflowPhases::necessary(&reflow_request.reflow_goal)
1535            .contains(ReflowPhases::StackingContextTreeConstruction)
1536        {
1537            return false;
1538        }
1539        if !self.need_new_stacking_context_tree.get() {
1540            return false;
1541        }
1542
1543        self.build_stacking_context_tree(reflow_request.viewport_details)
1544    }
1545
1546    #[servo_tracing::instrument(name = "Stacking Context Tree Construction", skip_all)]
1547    fn build_stacking_context_tree(&self, viewport_details: ViewportDetails) -> bool {
1548        let Some(fragment_tree) = &*self.fragment_tree.borrow() else {
1549            return false;
1550        };
1551
1552        let mut stacking_context_tree = self.stacking_context_tree.borrow_mut();
1553        let old_scroll_offsets = stacking_context_tree
1554            .as_ref()
1555            .map(|tree| tree.paint_info.scroll_tree.scroll_offsets());
1556
1557        // This will be done during `StackingContextTree::new` below
1558        self.need_containing_block_calculation.set(false);
1559
1560        // Build the StackingContextTree. This turns the `FragmentTree` into a
1561        // tree of fragments in CSS painting order and also creates all
1562        // applicable spatial and clip nodes.
1563        let mut new_stacking_context_tree = StackingContextTree::new(
1564            fragment_tree,
1565            viewport_details,
1566            self.id.into(),
1567            !self.have_ever_generated_display_list.get(),
1568            &self.debug,
1569        );
1570
1571        // When a new StackingContextTree is built, it contains a freshly built
1572        // ScrollTree. We want to preserve any existing scroll offsets in that tree,
1573        // adjusted by any new scroll constraints.
1574        if let Some(old_scroll_offsets) = old_scroll_offsets {
1575            new_stacking_context_tree
1576                .paint_info
1577                .scroll_tree
1578                .set_all_scroll_offsets(&old_scroll_offsets);
1579        }
1580
1581        if self.debug.is_enabled(DiagnosticsLoggingOption::ScrollTree) {
1582            new_stacking_context_tree
1583                .paint_info
1584                .scroll_tree
1585                .debug_print();
1586        }
1587
1588        *stacking_context_tree = Some(new_stacking_context_tree);
1589
1590        // The stacking context tree is up-to-date again.
1591        self.need_new_stacking_context_tree.set(false);
1592        assert!(self.need_new_display_list.get());
1593
1594        true
1595    }
1596
1597    /// Build the display list for the current layout and send it to the renderer. If no display
1598    /// list is built, returns false.
1599    #[servo_tracing::instrument(name = "Display List Construction", skip_all)]
1600    fn build_display_list(
1601        &self,
1602        reflow_request: &ReflowRequest,
1603        image_resolver: &Arc<ImageResolver>,
1604        reflow_statistics: &mut ReflowStatistics,
1605    ) -> bool {
1606        if !ReflowPhases::necessary(&reflow_request.reflow_goal)
1607            .contains(ReflowPhases::DisplayListConstruction)
1608        {
1609            return false;
1610        }
1611        let Some(fragment_tree) = &*self.fragment_tree.borrow() else {
1612            return false;
1613        };
1614        let mut stacking_context_tree = self.stacking_context_tree.borrow_mut();
1615        let Some(stacking_context_tree) = stacking_context_tree.as_mut() else {
1616            return false;
1617        };
1618
1619        // If a non-display-list-generating reflow updated layout in a previous refow, we
1620        // cannot skip display list generation here the next time a display list is
1621        // requested.
1622        if !self.need_new_display_list.get() {
1623            return false;
1624        }
1625
1626        // TODO: Eventually this should be set when `paint_info` is created, but that requires
1627        // ensuring that the Epoch is passed to any method that can creates `StackingContextTree`.
1628        stacking_context_tree.paint_info.epoch = reflow_request.epoch;
1629
1630        let mut paint_timing_handler = self.paint_timing_handler.borrow_mut();
1631        // This ensures that we only create the PaintTimingHandler once per layout thread.
1632        let paint_timing_handler = match paint_timing_handler.as_mut() {
1633            Some(paint_timing_handler) => paint_timing_handler,
1634            None => {
1635                *paint_timing_handler = Some(PaintTimingHandler::new(
1636                    stacking_context_tree
1637                        .paint_info
1638                        .viewport_details
1639                        .layout_size(),
1640                ));
1641                paint_timing_handler.as_mut().unwrap()
1642            },
1643        };
1644
1645        let built_display_list = DisplayListBuilder::build(
1646            stacking_context_tree,
1647            fragment_tree,
1648            image_resolver.clone(),
1649            self.device().device_pixel_ratio(),
1650            reflow_request.highlighted_dom_node,
1651            &self.debug,
1652            paint_timing_handler,
1653            reflow_statistics,
1654            reflow_request.frame_focused,
1655        );
1656
1657        stacking_context_tree.paint_info.paint_timing_info = reflow_request.paint_timing_info;
1658        stacking_context_tree.paint_info.paint_timing_report = paint_timing_handler
1659            .mark_paint_timing(
1660                reflow_request.paint_timing_eligible,
1661                reflow_request.halt_lcp,
1662            );
1663
1664        if let Some(lcp_candidate) = paint_timing_handler.largest_contentful_paint_candidate() {
1665            stacking_context_tree.paint_info.lcp_candidate =
1666                Some((lcp_candidate.id, lcp_candidate.area));
1667        } else {
1668            stacking_context_tree.paint_info.lcp_candidate = None;
1669        }
1670
1671        // Paint only needs the IDs in order to attach a paint time to them; the records
1672        // themselves go to script on the `ReflowResult`.
1673        let container_timing_records = paint_timing_handler.take_container_timing_records();
1674        stacking_context_tree.paint_info.container_timing_candidates = container_timing_records
1675            .iter()
1676            .map(|record| record.id)
1677            .collect();
1678        *self.pending_container_timing_records.borrow_mut() = container_timing_records;
1679
1680        self.paint_api.send_display_list(
1681            self.webview_id,
1682            &stacking_context_tree.paint_info,
1683            built_display_list,
1684        );
1685
1686        let (keys, instance_keys) = self
1687            .font_context
1688            .collect_unused_webrender_resources(false /* all */);
1689        self.paint_api
1690            .remove_unused_font_resources(self.webview_id.into(), keys, instance_keys);
1691        self.last_display_list_was_empty.set(false);
1692        self.have_ever_generated_display_list.set(true);
1693        self.need_new_display_list.set(false);
1694        self.previously_highlighted_dom_node
1695            .set(reflow_request.highlighted_dom_node);
1696        true
1697    }
1698
1699    fn set_scroll_offset_from_script(
1700        &self,
1701        external_scroll_id: ExternalScrollId,
1702        offset: LayoutVector2D,
1703    ) -> bool {
1704        let mut stacking_context_tree = self.stacking_context_tree.borrow_mut();
1705        let Some(stacking_context_tree) = stacking_context_tree.as_mut() else {
1706            return false;
1707        };
1708
1709        if let Some(offset) = stacking_context_tree
1710            .paint_info
1711            .scroll_tree
1712            .set_scroll_offset_for_node_with_external_scroll_id(
1713                external_scroll_id,
1714                offset,
1715                ScrollType::Script,
1716            )
1717        {
1718            self.paint_api.scroll_node_by_delta(
1719                self.webview_id,
1720                self.id.into(),
1721                offset,
1722                external_scroll_id,
1723            );
1724
1725            if self.accessibility_active() &&
1726                let Some(accessibility_tree) = self.accessibility_tree.borrow_mut().as_mut()
1727            {
1728                accessibility_tree.add_pending_scroll_update(external_scroll_id, offset);
1729
1730                // Ensure the scroll updates are applied in the accessibility tree and sent to the
1731                // embedder, even if there are no other changes which affect the accessibility tree.
1732                self.set_force_accessibility_update_if_active();
1733            }
1734            true
1735        } else {
1736            false
1737        }
1738    }
1739
1740    /// Returns profiling information which is passed to the time profiler.
1741    fn profiler_metadata(&self) -> Option<TimerMetadata> {
1742        Some(TimerMetadata {
1743            url: self.url.to_string(),
1744            iframe: if self.is_iframe {
1745                TimerMetadataFrameType::IFrame
1746            } else {
1747                TimerMetadataFrameType::RootWindow
1748            },
1749            incremental: if self.have_ever_generated_display_list.get() {
1750                TimerMetadataReflowType::Incremental
1751            } else {
1752                TimerMetadataReflowType::FirstReflow
1753            },
1754        })
1755    }
1756
1757    /// Clear all cached layout trees and send an empty display list to paint (if necessary).
1758    fn maybe_clear_layout_trees_and_send_empty_display_list(
1759        &self,
1760        reflow_request: &ReflowRequest,
1761    ) -> Option<ReflowResult> {
1762        // Clear layout trees.
1763        self.box_tree.borrow_mut().take();
1764        self.fragment_tree.borrow_mut().take();
1765        self.stacking_context_tree.borrow_mut().take();
1766        self.need_new_display_list.set(false);
1767
1768        // If the last display list was also empty a new one is not necessary.
1769        if self.last_display_list_was_empty.get() {
1770            return None;
1771        }
1772
1773        // Send empty display list.
1774        let paint_info = PaintDisplayListInfo::new(
1775            reflow_request.viewport_details,
1776            Size2D::zero(),
1777            self.id.into(),
1778            reflow_request.epoch,
1779            AxesScrollSensitivity {
1780                x: ScrollType::InputEvents | ScrollType::Script,
1781                y: ScrollType::InputEvents | ScrollType::Script,
1782            },
1783            !self.have_ever_generated_display_list.get(),
1784        );
1785        let mut builder = webrender_api::DisplayListBuilder::new(paint_info.pipeline_id);
1786        builder.begin();
1787        let (_, empty_display_list) = builder.end();
1788
1789        self.paint_api
1790            .send_display_list(self.webview_id, &paint_info, empty_display_list);
1791        self.last_display_list_was_empty.set(true);
1792        self.have_ever_generated_display_list.set(true);
1793
1794        Some(ReflowResult {
1795            reflow_phases_run: ReflowPhasesRun::BuiltDisplayList,
1796            ..Default::default()
1797        })
1798    }
1799
1800    pub(crate) fn ensure_containing_block_calculation(&self) {
1801        if !self.need_containing_block_calculation.get() {
1802            return;
1803        }
1804        let fragment_tree = self.fragment_tree.borrow();
1805        fragment_tree.as_ref().expect("missing fragment tree").find(
1806            |fragment, _level, content_rect| {
1807                fragment.set_cumulative_content_rect(content_rect);
1808                None::<()>
1809            },
1810        );
1811        self.need_containing_block_calculation.set(false)
1812    }
1813}
1814
1815fn to_accessibility_damage_map<'dom>(
1816    damage_from_dom: Option<Vec<(TrustedNodeAddress, AccessibilityDamage)>>,
1817) -> Option<AccessibilityDamageMap<'dom>> {
1818    damage_from_dom.map(|vec| {
1819        vec.into_iter()
1820            .map(|(address, damage)| {
1821                let node = unsafe { ServoLayoutNode::new(&address) };
1822                (node.opaque(), (node, damage))
1823            })
1824            .collect()
1825    })
1826}
1827
1828fn get_ua_stylesheets(shared_lock: &SharedRwLock) -> Rc<UserAgentStylesheets> {
1829    // There is an assumption here that there is only a single ScriptThread per thread, which
1830    // is currently the case in Servo. If this were to change, these user agent stylesheets
1831    // would need to be managed by the ScriptThread instance.
1832    thread_local! {
1833        static USER_AGENT_STYLESHEETS: OnceCell<Rc<UserAgentStylesheets>> = const { OnceCell::new() };
1834    }
1835
1836    fn parse_ua_stylesheet(
1837        shared_lock: &SharedRwLock,
1838        filename: &str,
1839        content: &[u8],
1840    ) -> DocumentStyleSheet {
1841        let url = Url::parse(&format!("chrome://resources/{filename}")).unwrap_or_else(|_| {
1842            panic!("Could not parse user stylesheet URL: {filename}");
1843        });
1844        DocumentStyleSheet(ServoArc::new(Stylesheet::from_bytes(
1845            content,
1846            url.into(),
1847            None,
1848            None,
1849            Origin::UserAgent,
1850            ServoArc::new(shared_lock.wrap(MediaList::empty())),
1851            shared_lock.clone(),
1852            None,
1853            None,
1854            QuirksMode::NoQuirks,
1855        )))
1856    }
1857
1858    USER_AGENT_STYLESHEETS.with(|user_stylesheets| {
1859        user_stylesheets
1860            .get_or_init(|| {
1861                // FIXME: presentational-hints.css should be at author origin with zero specificity.
1862                //        (Does it make a difference?)
1863                let user_agent_stylesheets = vec![
1864                    parse_ua_stylesheet(shared_lock, "user-agent.css", USER_AGENT_CSS),
1865                    parse_ua_stylesheet(shared_lock, "servo.css", SERVO_CSS),
1866                    parse_ua_stylesheet(
1867                        shared_lock,
1868                        "presentational-hints.css",
1869                        PRESENTATIONAL_HINTS_CSS,
1870                    ),
1871                ];
1872
1873                let html_mode_stylesheet =
1874                    parse_ua_stylesheet(shared_lock, "html-mode.css", HTML_MODE_CSS);
1875
1876                let quirks_mode_stylesheet =
1877                    parse_ua_stylesheet(shared_lock, "quirks-mode.css", QUIRKS_MODE_CSS);
1878
1879                let iso_8859_8_stylesheet =
1880                    parse_ua_stylesheet(shared_lock, "iso-8859-8.css", ISO_8859_8_CSS);
1881
1882                Rc::new(UserAgentStylesheets {
1883                    user_agent_stylesheets,
1884                    html_mode_stylesheet,
1885                    quirks_mode_stylesheet,
1886                    iso_8859_8_stylesheet,
1887                })
1888            })
1889            .clone()
1890    })
1891}
1892
1893/// This structure holds the user-agent stylesheets.
1894pub struct UserAgentStylesheets {
1895    /// The user agent stylesheets.
1896    pub user_agent_stylesheets: Vec<DocumentStyleSheet>,
1897    /// The user agent stylesheet for HTML documents.
1898    pub html_mode_stylesheet: DocumentStyleSheet,
1899    /// The quirks mode stylesheet.
1900    pub quirks_mode_stylesheet: DocumentStyleSheet,
1901    /// The user agent stylesheet for documents that use the ISO-8859-8 encoding.
1902    pub iso_8859_8_stylesheet: DocumentStyleSheet,
1903}
1904
1905struct RegisteredPainterImpl {
1906    painter: Box<dyn Painter>,
1907    name: Atom,
1908    // FIXME: Should be a PrecomputedHashMap.
1909    properties: style::FxHashMap<Atom, PropertyId>,
1910}
1911
1912impl SpeculativePainter for RegisteredPainterImpl {
1913    fn speculatively_draw_a_paint_image(
1914        &self,
1915        properties: Vec<(Atom, String)>,
1916        arguments: Vec<String>,
1917    ) {
1918        self.painter
1919            .speculatively_draw_a_paint_image(properties, arguments);
1920    }
1921}
1922
1923impl RegisteredSpeculativePainter for RegisteredPainterImpl {
1924    fn properties(&self) -> &style::FxHashMap<Atom, PropertyId> {
1925        &self.properties
1926    }
1927    fn name(&self) -> Atom {
1928        self.name.clone()
1929    }
1930}
1931
1932impl Painter for RegisteredPainterImpl {
1933    fn draw_a_paint_image(
1934        &self,
1935        size: Size2D<f32, CSSPixel>,
1936        device_pixel_ratio: Scale<f32, CSSPixel, DevicePixel>,
1937        properties: Vec<(Atom, String)>,
1938        arguments: Vec<String>,
1939    ) -> Result<DrawAPaintImageResult, PaintWorkletError> {
1940        self.painter
1941            .draw_a_paint_image(size, device_pixel_ratio, properties, arguments)
1942    }
1943}
1944
1945struct RegisteredPaintersImpl(HashMap<Atom, RegisteredPainterImpl>);
1946
1947impl RegisteredSpeculativePainters for RegisteredPaintersImpl {
1948    fn get(&self, name: &Atom) -> Option<&dyn RegisteredSpeculativePainter> {
1949        self.0
1950            .get(name)
1951            .map(|painter| painter as &dyn RegisteredSpeculativePainter)
1952    }
1953}
1954
1955struct LayoutFontMetricsProvider(Arc<FontContext>);
1956
1957impl FontMetricsProvider for LayoutFontMetricsProvider {
1958    fn query_font_metrics(
1959        &self,
1960        _vertical: bool,
1961        font: &Font,
1962        base_size: CSSPixelLength,
1963        _flags: QueryFontMetricsFlags,
1964    ) -> FontMetrics {
1965        let font_context = &self.0;
1966        let font_group = self
1967            .0
1968            .font_group_with_size(ServoArc::new(font.clone()), base_size.into());
1969
1970        let Some(first_font_metrics) = font_group
1971            .first(font_context)
1972            .map(|font| font.metrics().clone())
1973        else {
1974            return Default::default();
1975        };
1976
1977        // Only use the x-height of this font if it is non-zero. Some fonts return
1978        // inaccurate metrics, which shouldn't be used.
1979        let x_height = Some(first_font_metrics.x_height)
1980            .filter(|x_height| !x_height.is_zero())
1981            .map(CSSPixelLength::from);
1982
1983        let zero_advance_measure = first_font_metrics
1984            .zero_horizontal_advance
1985            .or_else(|| {
1986                font_group
1987                    .find_by_codepoint(font_context, '0', None, Language::UNKNOWN)?
1988                    .metrics()
1989                    .zero_horizontal_advance
1990            })
1991            .map(CSSPixelLength::from);
1992
1993        let ic_width = first_font_metrics
1994            .ic_horizontal_advance
1995            .or_else(|| {
1996                font_group
1997                    .find_by_codepoint(font_context, '\u{6C34}', None, Language::UNKNOWN)?
1998                    .metrics()
1999                    .ic_horizontal_advance
2000            })
2001            .map(CSSPixelLength::from);
2002
2003        FontMetrics {
2004            x_height,
2005            zero_advance_measure,
2006            cap_height: None,
2007            ic_width,
2008            ascent: first_font_metrics.ascent.into(),
2009            script_percent_scale_down: None,
2010            script_script_percent_scale_down: None,
2011        }
2012    }
2013
2014    fn base_size_for_generic(&self, generic: GenericFontFamily) -> Length {
2015        Length::new(match generic {
2016            GenericFontFamily::Monospace => pref!(fonts_default_monospace_size),
2017            _ => pref!(fonts_default_size),
2018        } as f32)
2019        .max(Length::new(0.0))
2020    }
2021}
2022
2023impl Debug for LayoutFontMetricsProvider {
2024    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2025        f.debug_tuple("LayoutFontMetricsProvider").finish()
2026    }
2027}
2028
2029struct SnapshotSetter<'dom> {
2030    elements_with_snapshot: Vec<ServoLayoutElement<'dom>>,
2031}
2032
2033impl SnapshotSetter<'_> {
2034    fn new(restyle: &mut ReflowRequestRestyle, snapshot_map: &mut SnapshotMap) -> Self {
2035        debug!("Draining restyles: {}", restyle.pending_restyles.len());
2036        let restyles = std::mem::take(&mut restyle.pending_restyles);
2037
2038        let elements_with_snapshot: Vec<_> = restyles
2039            .iter()
2040            .filter(|r| r.1.snapshot.is_some())
2041            .map(|r| unsafe { ServoLayoutNode::new(&r.0).as_element().unwrap() })
2042            .collect();
2043
2044        for (element, restyle) in restyles {
2045            let element = unsafe { ServoLayoutNode::new(&element).as_element().unwrap() };
2046
2047            // If we haven't styled this node yet, we don't need to track a
2048            // restyle.
2049            let Some(mut style_data) = element
2050                .style_data()
2051                .map(|data| data.element_data.borrow_mut())
2052            else {
2053                element.unset_snapshot_flags();
2054                continue;
2055            };
2056
2057            debug!("Noting restyle for {:?}: {:?}", element, style_data);
2058            if let Some(s) = restyle.snapshot {
2059                element.set_has_snapshot();
2060                snapshot_map.insert(element.as_node().opaque(), s);
2061            }
2062
2063            // Stash the data on the element for processing by the style system.
2064            style_data.hint.insert(restyle.hint);
2065            style_data.damage = restyle.damage;
2066        }
2067        Self {
2068            elements_with_snapshot,
2069        }
2070    }
2071}
2072
2073impl Drop for SnapshotSetter<'_> {
2074    fn drop(&mut self) {
2075        for element in &self.elements_with_snapshot {
2076            element.unset_snapshot_flags();
2077        }
2078    }
2079}
2080
2081bitflags! {
2082    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
2083    pub struct ReflowPhases: u8 {
2084        const StackingContextTreeConstruction = 1 << 0;
2085        const DisplayListConstruction = 1 << 1;
2086    }
2087}
2088
2089impl ReflowPhases {
2090    /// Return the necessary phases of layout for the given [`ReflowGoal`]. Note that all
2091    /// [`ReflowGoals`] need the basic restyle + box tree layout + fragment tree layout,
2092    /// so [`ReflowPhases::empty()`] implies that.
2093    fn necessary(reflow_goal: &ReflowGoal) -> Self {
2094        let is_inset_longhand = |longhand: LonghandId| {
2095            matches!(
2096                longhand,
2097                LonghandId::Top |
2098                    LonghandId::Right |
2099                    LonghandId::Bottom |
2100                    LonghandId::Left |
2101                    LonghandId::InsetInlineStart |
2102                    LonghandId::InsetInlineEnd |
2103                    LonghandId::InsetBlockStart |
2104                    LonghandId::InsetBlockEnd
2105            )
2106        };
2107
2108        let is_inset_property =
2109            |property: NonCustomPropertyId| match property.longhand_or_shorthand() {
2110                Ok(longhand) => is_inset_longhand(longhand),
2111                // Special case for the `All` shorthand as it has many longhands.
2112                Err(ShorthandId::All) => true,
2113                Err(shorthand) => shorthand.longhands().any(is_inset_longhand),
2114            };
2115
2116        match reflow_goal {
2117            ReflowGoal::LayoutQuery(query) => match query {
2118                // Resolving insets requires the creation of the stacking context, but other style properties
2119                // do not. This should be kept in sync with `LayoutThread::query_resolved_style()`.
2120                QueryMsg::ResolvedStyleQuery(PropertyId::NonCustom(non_custom_property_id))
2121                    if is_inset_property(*non_custom_property_id) =>
2122                {
2123                    Self::StackingContextTreeConstruction
2124                },
2125                QueryMsg::ResolvedStyleQuery(_) => Self::empty(),
2126                QueryMsg::NodesFromPointQuery => {
2127                    Self::StackingContextTreeConstruction | Self::DisplayListConstruction
2128                },
2129                QueryMsg::AccessKitNodeQuery |
2130                QueryMsg::BoxArea |
2131                QueryMsg::BoxAreas |
2132                QueryMsg::ElementsFromPoint |
2133                QueryMsg::FlushForUpdateTheRenderingQuery |
2134                QueryMsg::OffsetParentQuery |
2135                QueryMsg::ScrollingAreaOrOffsetQuery |
2136                QueryMsg::TextIndexOrSegmentQuery => Self::StackingContextTreeConstruction,
2137                QueryMsg::ClientRectQuery |
2138                QueryMsg::CurrentCSSZoomQuery |
2139                QueryMsg::EffectiveOverflow |
2140                QueryMsg::ElementInnerOuterTextQuery |
2141                QueryMsg::InnerWindowDimensionsQuery |
2142                QueryMsg::PaddingQuery |
2143                QueryMsg::ResolvedFontStyleQuery |
2144                QueryMsg::ScrollParentQuery |
2145                QueryMsg::StyleQuery => Self::empty(),
2146            },
2147            ReflowGoal::UpdateScrollNode(..) | ReflowGoal::UpdateTheRendering => {
2148                Self::StackingContextTreeConstruction | Self::DisplayListConstruction
2149            },
2150        }
2151    }
2152}
2153
2154/// Summarizes changes after flushing stylesheets on the `Stylist`.
2155struct StylistStylesheetUpdate {
2156    /// Information about what kind of selectors changed.
2157    invalidation_set: StylesheetInvalidationSet,
2158    /// A list of changes to the set of web fonts.
2159    changed_web_fonts: WebFontSetDifference,
2160}