servo-layout-api 0.1.0-rc1

A component of the servo web-engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

//! This module contains traits in script used generically in the rest of Servo.
//! The traits are here instead of in script so that these modules won't have
//! to depend on script.

#![deny(unsafe_code)]

mod layout_damage;
pub mod wrapper_traits;

use std::any::Any;
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::AtomicIsize;
use std::thread::JoinHandle;
use std::time::Duration;

use app_units::Au;
use background_hang_monitor_api::BackgroundHangMonitorRegister;
use bitflags::bitflags;
use embedder_traits::{Cursor, Theme, UntrustedNodeAddress, ViewportDetails};
use euclid::{Point2D, Rect};
use fonts::{FontContext, WebFontDocumentContext};
pub use layout_damage::LayoutDamage;
use libc::c_void;
use malloc_size_of::{MallocSizeOf as MallocSizeOfTrait, MallocSizeOfOps, malloc_size_of_is_0};
use malloc_size_of_derive::MallocSizeOf;
use net_traits::image_cache::{ImageCache, ImageCacheFactory, PendingImageId};
use paint_api::CrossProcessPaintApi;
use parking_lot::RwLock;
use pixels::RasterImage;
use profile_traits::mem::Report;
use profile_traits::time;
use rustc_hash::FxHashMap;
use script_traits::{InitialScriptState, Painter, ScriptThreadMessage};
use serde::{Deserialize, Serialize};
use servo_arc::Arc as ServoArc;
use servo_base::Epoch;
use servo_base::generic_channel::GenericSender;
use servo_base::id::{BrowsingContextId, PipelineId, WebViewId};
use servo_url::{ImmutableOrigin, ServoUrl};
use style::Atom;
use style::animation::DocumentAnimationSet;
use style::attr::{AttrValue, parse_integer, parse_unsigned_integer};
use style::context::QuirksMode;
use style::data::ElementDataWrapper;
use style::device::Device;
use style::dom::OpaqueNode;
use style::invalidation::element::restyle_hints::RestyleHint;
use style::properties::style_structs::Font;
use style::properties::{ComputedValues, PropertyId};
use style::selector_parser::{PseudoElement, RestyleDamage, Snapshot};
use style::str::char_is_whitespace;
use style::stylesheets::{DocumentStyleSheet, Stylesheet};
use style::stylist::Stylist;
use style::thread_state::{self, ThreadState};
use style::values::computed::Overflow;
use style_traits::CSSPixel;
use webrender_api::units::{DeviceIntSize, LayoutPoint, LayoutVector2D};
use webrender_api::{ExternalScrollId, ImageKey};

pub trait GenericLayoutDataTrait: Any + MallocSizeOfTrait {
    fn as_any(&self) -> &dyn Any;
}

pub type GenericLayoutData = dyn GenericLayoutDataTrait + Send + Sync;

#[derive(Default, MallocSizeOf)]
pub struct StyleData {
    /// Data that the style system associates with a node. When the
    /// style system is being used standalone, this is all that hangs
    /// off the node. This must be first to permit the various
    /// transmutations between ElementData and PersistentLayoutData.
    pub element_data: ElementDataWrapper,

    /// Information needed during parallel traversals.
    pub parallel: DomParallelInfo,
}

/// Information that we need stored in each DOM node.
#[derive(Default, MallocSizeOf)]
pub struct DomParallelInfo {
    /// The number of children remaining to process during bottom-up traversal.
    pub children_to_process: AtomicIsize,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LayoutNodeType {
    Element(LayoutElementType),
    Text,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LayoutElementType {
    Element,
    HTMLBodyElement,
    HTMLBRElement,
    HTMLCanvasElement,
    HTMLHtmlElement,
    HTMLIFrameElement,
    HTMLImageElement,
    HTMLInputElement,
    HTMLMediaElement,
    HTMLObjectElement,
    HTMLOptGroupElement,
    HTMLOptionElement,
    HTMLParagraphElement,
    HTMLPreElement,
    HTMLSelectElement,
    HTMLTableCellElement,
    HTMLTableColElement,
    HTMLTableElement,
    HTMLTableRowElement,
    HTMLTableSectionElement,
    HTMLTextAreaElement,
    SVGImageElement,
    SVGSVGElement,
}

pub struct HTMLCanvasData {
    pub image_key: Option<ImageKey>,
    pub width: u32,
    pub height: u32,
}

pub struct SVGElementData<'dom> {
    /// The SVG's XML source represented as a base64 encoded `data:` url.
    pub source: Option<Result<ServoUrl, ()>>,
    pub width: Option<&'dom AttrValue>,
    pub height: Option<&'dom AttrValue>,
    pub svg_id: String,
    pub view_box: Option<&'dom AttrValue>,
}

impl SVGElementData<'_> {
    pub fn ratio_from_view_box(&self) -> Option<f32> {
        let mut iter = self.view_box?.chars();
        let _min_x = parse_integer(&mut iter).ok()?;
        let _min_y = parse_integer(&mut iter).ok()?;

        let width = parse_unsigned_integer(&mut iter).ok()?;
        if width == 0 {
            return None;
        }

        let height = parse_unsigned_integer(&mut iter).ok()?;
        if height == 0 {
            return None;
        }

        let mut iter = iter.skip_while(|c| char_is_whitespace(*c));
        iter.next().is_none().then(|| width as f32 / height as f32)
    }
}

/// The address of a node known to be valid. These are sent from script to layout.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TrustedNodeAddress(pub *const c_void);

#[expect(unsafe_code)]
unsafe impl Send for TrustedNodeAddress {}

/// Whether the pending image needs to be fetched or is waiting on an existing fetch.
#[derive(Debug)]
pub enum PendingImageState {
    Unrequested(ServoUrl),
    PendingResponse,
}

/// The destination in layout where an image is needed.
#[derive(Debug, MallocSizeOf)]
pub enum LayoutImageDestination {
    BoxTreeConstruction,
    DisplayListBuilding,
}

/// The data associated with an image that is not yet present in the image cache.
/// Used by the script thread to hold on to DOM elements that need to be repainted
/// when an image fetch is complete.
#[derive(Debug)]
pub struct PendingImage {
    pub state: PendingImageState,
    pub node: UntrustedNodeAddress,
    pub id: PendingImageId,
    pub origin: ImmutableOrigin,
    pub destination: LayoutImageDestination,
}

/// A data structure to tarck vector image that are fully loaded (i.e has a parsed SVG
/// tree) but not yet rasterized to the size needed by layout. The rasterization is
/// happening in the image cache.
#[derive(Debug)]
pub struct PendingRasterizationImage {
    pub node: UntrustedNodeAddress,
    pub id: PendingImageId,
    pub size: DeviceIntSize,
}

#[derive(Clone, Copy, Debug, MallocSizeOf)]
pub struct MediaFrame {
    pub image_key: webrender_api::ImageKey,
    pub width: i32,
    pub height: i32,
}

pub struct MediaMetadata {
    pub width: u32,
    pub height: u32,
}

pub struct HTMLMediaData {
    pub current_frame: Option<MediaFrame>,
    pub metadata: Option<MediaMetadata>,
}

pub struct LayoutConfig {
    pub id: PipelineId,
    pub webview_id: WebViewId,
    pub url: ServoUrl,
    pub is_iframe: bool,
    pub script_chan: GenericSender<ScriptThreadMessage>,
    pub image_cache: Arc<dyn ImageCache>,
    pub font_context: Arc<FontContext>,
    pub time_profiler_chan: time::ProfilerChan,
    pub paint_api: CrossProcessPaintApi,
    pub viewport_details: ViewportDetails,
    pub user_stylesheets: Rc<Vec<DocumentStyleSheet>>,
    pub theme: Theme,
}

pub trait LayoutFactory: Send + Sync {
    fn create(&self, config: LayoutConfig) -> Box<dyn Layout>;
}

pub trait Layout {
    /// Get a reference to this Layout's Stylo `Device` used to handle media queries and
    /// resolve font metrics.
    fn device(&self) -> &Device;

    /// Set the theme on this [`Layout`]'s [`Device`]. The caller should also trigger a
    /// new layout when this happens, though it can happen later. Returns `true` if the
    /// [`Theme`] actually changed or `false` otherwise.
    fn set_theme(&mut self, theme: Theme) -> bool;

    /// Set the [`ViewportDetails`] on this [`Layout`]'s [`Device`]. The caller should also
    /// trigger a new layout when this happens, though it can happen later. Returns `true`
    /// if the [`ViewportDetails`] actually changed or `false` otherwise.
    fn set_viewport_details(&mut self, viewport_details: ViewportDetails) -> bool;

    /// Load all fonts from the given stylesheet, returning the number of fonts that
    /// need to be loaded.
    fn load_web_fonts_from_stylesheet(
        &self,
        stylesheet: &ServoArc<Stylesheet>,
        font_context: &WebFontDocumentContext,
    );

    /// Add a stylesheet to this Layout. This will add it to the Layout's `Stylist` as well as
    /// loading all web fonts defined in the stylesheet. The second stylesheet is the insertion
    /// point (if it exists, the sheet needs to be inserted before it).
    fn add_stylesheet(
        &mut self,
        stylesheet: ServoArc<Stylesheet>,
        before_stylsheet: Option<ServoArc<Stylesheet>>,
        font_context: &WebFontDocumentContext,
    );

    /// Inform the layout that its ScriptThread is about to exit.
    fn exit_now(&mut self);

    /// Requests that layout measure its memory usage. The resulting reports are sent back
    /// via the supplied channel.
    fn collect_reports(&self, reports: &mut Vec<Report>, ops: &mut MallocSizeOfOps);

    /// Sets quirks mode for the document, causing the quirks mode stylesheet to be used.
    fn set_quirks_mode(&mut self, quirks_mode: QuirksMode);

    /// Removes a stylesheet from the Layout.
    fn remove_stylesheet(&mut self, stylesheet: ServoArc<Stylesheet>);

    /// Removes an image from the Layout image resolver cache.
    fn remove_cached_image(&mut self, image_url: &ServoUrl);

    /// Requests a reflow.
    fn reflow(&mut self, reflow_request: ReflowRequest) -> Option<ReflowResult>;

    /// Do not request a reflow, but ensure that any previous reflow completes building a stacking
    /// context tree so that it is ready to query the final size of any elements in script.
    fn ensure_stacking_context_tree(&self, viewport_details: ViewportDetails);

    /// Tells layout that script has added some paint worklet modules.
    fn register_paint_worklet_modules(
        &mut self,
        name: Atom,
        properties: Vec<Atom>,
        painter: Box<dyn Painter>,
    );

    /// Set the scroll states of this layout after a `Paint` scroll.
    fn set_scroll_offsets_from_renderer(
        &mut self,
        scroll_states: &FxHashMap<ExternalScrollId, LayoutVector2D>,
    );

    /// Get the scroll offset of the given scroll node with id of [`ExternalScrollId`] or `None` if it does
    /// not exist in the tree.
    fn scroll_offset(&self, id: ExternalScrollId) -> Option<LayoutVector2D>;

    /// Returns true if this layout needs to produce a new display list for rendering updates.
    fn needs_new_display_list(&self) -> bool;

    /// Marks that this layout needs to produce a new display list for rendering updates.
    fn set_needs_new_display_list(&self);

    fn query_padding(&self, node: TrustedNodeAddress) -> Option<PhysicalSides>;
    fn query_box_area(
        &self,
        node: TrustedNodeAddress,
        area: BoxAreaType,
        exclude_transform_and_inline: bool,
    ) -> Option<Rect<Au, CSSPixel>>;
    fn query_box_areas(&self, node: TrustedNodeAddress, area: BoxAreaType) -> CSSPixelRectIterator;
    fn query_client_rect(&self, node: TrustedNodeAddress) -> Rect<i32, CSSPixel>;
    fn query_current_css_zoom(&self, node: TrustedNodeAddress) -> f32;
    fn query_element_inner_outer_text(&self, node: TrustedNodeAddress) -> String;
    fn query_offset_parent(&self, node: TrustedNodeAddress) -> OffsetParentResponse;
    /// Query the scroll container for the given node. If node is `None`, the scroll container for
    /// the viewport is returned.
    fn query_scroll_container(
        &self,
        node: Option<TrustedNodeAddress>,
        flags: ScrollContainerQueryFlags,
    ) -> Option<ScrollContainerResponse>;
    fn query_resolved_style(
        &self,
        node: TrustedNodeAddress,
        pseudo: Option<PseudoElement>,
        property_id: PropertyId,
        animations: DocumentAnimationSet,
        animation_timeline_value: f64,
    ) -> String;
    fn query_resolved_font_style(
        &self,
        node: TrustedNodeAddress,
        value: &str,
        animations: DocumentAnimationSet,
        animation_timeline_value: f64,
    ) -> Option<ServoArc<Font>>;
    fn query_scrolling_area(&self, node: Option<TrustedNodeAddress>) -> Rect<i32, CSSPixel>;
    /// Find the character offset of the point in the given node, if it has text content.
    fn query_text_index(
        &self,
        node: TrustedNodeAddress,
        point: Point2D<Au, CSSPixel>,
    ) -> Option<usize>;
    fn query_elements_from_point(
        &self,
        point: LayoutPoint,
        flags: ElementsFromPointFlags,
    ) -> Vec<ElementsFromPointResult>;
    fn query_effective_overflow(&self, node: TrustedNodeAddress) -> Option<AxesOverflow>;
    fn stylist_mut(&mut self) -> &mut Stylist;

    fn set_accessibility_active(&self, active: bool);
}

/// This trait is part of `layout_api` because it depends on both `script_traits`
/// and also `LayoutFactory` from this crate. If it was in `script_traits` there would be a
/// circular dependency.
pub trait ScriptThreadFactory {
    /// Create a `ScriptThread`.
    fn create(
        state: InitialScriptState,
        layout_factory: Arc<dyn LayoutFactory>,
        image_cache_factory: Arc<dyn ImageCacheFactory>,
        background_hang_monitor_register: Box<dyn BackgroundHangMonitorRegister>,
    ) -> JoinHandle<()>;
}

/// Type of the area of CSS box for query.
/// See <https://www.w3.org/TR/css-box-3/#box-model>.
#[derive(Copy, Clone)]
pub enum BoxAreaType {
    Content,
    Padding,
    Border,
}

pub type CSSPixelRectIterator = Box<dyn Iterator<Item = Rect<Au, CSSPixel>>>;

#[derive(Default)]
pub struct PhysicalSides {
    pub left: Au,
    pub top: Au,
    pub right: Au,
    pub bottom: Au,
}

#[derive(Clone, Default)]
pub struct OffsetParentResponse {
    pub node_address: Option<UntrustedNodeAddress>,
    pub rect: Rect<Au, CSSPixel>,
}

bitflags! {
    #[derive(PartialEq)]
    pub struct ScrollContainerQueryFlags: u8 {
        /// Whether or not this query is for the purposes of a `scrollParent` layout query.
        const ForScrollParent = 1 << 0;
        /// Whether or not to consider the original element's scroll box for the return value.
        const Inclusive = 1 << 1;
    }
}

#[derive(Clone, Copy, Debug, MallocSizeOf)]
pub struct AxesOverflow {
    pub x: Overflow,
    pub y: Overflow,
}

impl Default for AxesOverflow {
    fn default() -> Self {
        Self {
            x: Overflow::Visible,
            y: Overflow::Visible,
        }
    }
}

impl From<&ComputedValues> for AxesOverflow {
    fn from(style: &ComputedValues) -> Self {
        Self {
            x: style.clone_overflow_x(),
            y: style.clone_overflow_y(),
        }
    }
}

impl AxesOverflow {
    pub fn to_scrollable(&self) -> Self {
        Self {
            x: self.x.to_scrollable(),
            y: self.y.to_scrollable(),
        }
    }

    /// Whether or not the `overflow` value establishes a scroll container.
    pub fn establishes_scroll_container(&self) -> bool {
        // Checking one axis suffices, because the computed value ensures that
        // either both axes are scrollable, or none is scrollable.
        self.x.is_scrollable()
    }
}

#[derive(Clone)]
pub enum ScrollContainerResponse {
    Viewport(AxesOverflow),
    Element(UntrustedNodeAddress, AxesOverflow),
}

#[derive(Debug, PartialEq)]
pub enum QueryMsg {
    BoxArea,
    BoxAreas,
    ClientRectQuery,
    CurrentCSSZoomQuery,
    EffectiveOverflow,
    ElementInnerOuterTextQuery,
    ElementsFromPoint,
    InnerWindowDimensionsQuery,
    NodesFromPointQuery,
    OffsetParentQuery,
    ScrollParentQuery,
    ResolvedFontStyleQuery,
    ResolvedStyleQuery,
    ScrollingAreaOrOffsetQuery,
    StyleQuery,
    TextIndexQuery,
    PaddingQuery,
}

/// The goal of a reflow request.
///
/// Please do not add any other types of reflows. In general, all reflow should
/// go through the *update the rendering* step of the HTML specification. Exceptions
/// should have careful review.
#[derive(Debug, PartialEq)]
pub enum ReflowGoal {
    /// A reflow has been requesting by the *update the rendering* step of the HTML
    /// event loop. This nominally driven by the display's VSync.
    UpdateTheRendering,

    /// Script has done a layout query and this reflow ensurs that layout is up-to-date
    /// with the latest changes to the DOM.
    LayoutQuery(QueryMsg),

    /// Tells layout about a single new scrolling offset from the script. The rest will
    /// remain untouched. Layout will forward whether the element is scrolled through
    /// [ReflowResult].
    UpdateScrollNode(ExternalScrollId, LayoutVector2D),
}

#[derive(Clone, Debug, MallocSizeOf)]
pub struct IFrameSize {
    pub browsing_context_id: BrowsingContextId,
    pub pipeline_id: PipelineId,
    pub viewport_details: ViewportDetails,
}

pub type IFrameSizes = FxHashMap<BrowsingContextId, IFrameSize>;

bitflags! {
    /// Conditions which cause a [`Document`] to need to be restyled during reflow, which
    /// might cause the rest of layout to happen as well.
    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
    pub struct RestyleReason: u16 {
        const StylesheetsChanged = 1 << 0;
        const DOMChanged = 1 << 1;
        const PendingRestyles = 1 << 2;
        const HighlightedDOMNodeChanged = 1 << 3;
        const ThemeChanged = 1 << 4;
        const ViewportChanged = 1 << 5;
        const PaintWorkletLoaded = 1 << 6;
    }
}

malloc_size_of_is_0!(RestyleReason);

impl RestyleReason {
    pub fn needs_restyle(&self) -> bool {
        !self.is_empty()
    }
}

/// Information derived from a layout pass that needs to be returned to the script thread.
#[derive(Debug, Default)]
pub struct ReflowResult {
    /// The phases that were run during this reflow.
    pub reflow_phases_run: ReflowPhasesRun,
    pub reflow_statistics: ReflowStatistics,
    /// The list of images that were encountered that are in progress.
    pub pending_images: Vec<PendingImage>,
    /// The list of vector images that were encountered that still need to be rasterized.
    pub pending_rasterization_images: Vec<PendingRasterizationImage>,
    /// The list of `SVGSVGElement`s encountered in the DOM that need to be serialized.
    /// This is needed to support inline SVGs as the serialization needs to happen on
    /// the script thread.
    pub pending_svg_elements_for_serialization: Vec<UntrustedNodeAddress>,
    /// The list of iframes in this layout and their sizes, used in order
    /// to communicate them with the Constellation and also the `Window`
    /// element of their content pages. Returning None if incremental reflow
    /// finished before reaching this stage of the layout. I.e., no update
    /// required.
    pub iframe_sizes: Option<IFrameSizes>,
}

bitflags! {
    /// The phases of reflow that were run when processing a reflow in layout.
    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
    pub struct ReflowPhasesRun: u8 {
        const RanLayout = 1 << 0;
        const CalculatedOverflow = 1 << 1;
        const BuiltStackingContextTree = 1 << 2;
        const BuiltDisplayList = 1 << 3;
        const UpdatedScrollNodeOffset = 1 << 4;
        /// Image data for a WebRender image key has been updated, without necessarily
        /// updating style or layout. This is used when updating canvas contents and
        /// progressing to a new animated image frame.
        const UpdatedImageData = 1 << 5;
    }
}

impl ReflowPhasesRun {
    pub fn needs_frame(&self) -> bool {
        self.intersects(
            Self::BuiltDisplayList | Self::UpdatedScrollNodeOffset | Self::UpdatedImageData,
        )
    }
}

#[derive(Debug, Default)]
pub struct ReflowStatistics {
    pub rebuilt_fragment_count: u32,
    pub restyle_fragment_count: u32,
}

/// Information needed for a script-initiated reflow that requires a restyle
/// and reconstruction of box and fragment trees.
#[derive(Debug)]
pub struct ReflowRequestRestyle {
    /// Whether or not (and for what reasons) restyle needs to happen.
    pub reason: RestyleReason,
    /// The dirty root from which to restyle.
    pub dirty_root: Option<TrustedNodeAddress>,
    /// Whether the document's stylesheets have changed since the last script reflow.
    pub stylesheets_changed: bool,
    /// Restyle snapshot map.
    pub pending_restyles: Vec<(TrustedNodeAddress, PendingRestyle)>,
}

/// Information needed for a script-initiated reflow.
#[derive(Debug)]
pub struct ReflowRequest {
    /// The document node.
    pub document: TrustedNodeAddress,
    /// The current layout [`Epoch`] managed by the script thread.
    pub epoch: Epoch,
    /// If a restyle is necessary, all of the informatio needed to do that restyle.
    pub restyle: Option<ReflowRequestRestyle>,
    /// The current [`ViewportDetails`] to use for this reflow.
    pub viewport_details: ViewportDetails,
    /// The goal of this reflow.
    pub reflow_goal: ReflowGoal,
    /// The number of objects in the dom #10110
    pub dom_count: u32,
    /// The current window origin
    pub origin: ImmutableOrigin,
    /// The current animation timeline value.
    pub animation_timeline_value: f64,
    /// The set of animations for this document.
    pub animations: DocumentAnimationSet,
    /// An [`AnimatingImages`] struct used to track images that are animating.
    pub animating_images: Arc<RwLock<AnimatingImages>>,
    /// The node highlighted by the devtools, if any
    pub highlighted_dom_node: Option<OpaqueNode>,
    /// The current font context.
    pub document_context: WebFontDocumentContext,
}

impl ReflowRequest {
    pub fn stylesheets_changed(&self) -> bool {
        self.restyle
            .as_ref()
            .is_some_and(|restyle| restyle.stylesheets_changed)
    }
}

/// A pending restyle.
#[derive(Debug, Default, MallocSizeOf)]
pub struct PendingRestyle {
    /// If this element had a state or attribute change since the last restyle, track
    /// the original condition of the element.
    pub snapshot: Option<Snapshot>,

    /// Any explicit restyles hints that have been accumulated for this element.
    pub hint: RestyleHint,

    /// Any explicit restyles damage that have been accumulated for this element.
    pub damage: RestyleDamage,
}

/// The type of fragment that a scroll root is created for.
///
/// This can only ever grow to maximum 4 entries. That's because we cram the value of this enum
/// into the lower 2 bits of the `OpaqueNodeId`, which otherwise contains a 32-bit-aligned
/// or 64-bit-aligned heap address depending on the machine.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
pub enum FragmentType {
    /// A StackingContext for the fragment body itself.
    FragmentBody,
    /// A StackingContext created to contain ::before pseudo-element content.
    BeforePseudoContent,
    /// A StackingContext created to contain ::after pseudo-element content.
    AfterPseudoContent,
}

impl From<Option<PseudoElement>> for FragmentType {
    fn from(value: Option<PseudoElement>) -> Self {
        match value {
            Some(PseudoElement::After) => FragmentType::AfterPseudoContent,
            Some(PseudoElement::Before) => FragmentType::BeforePseudoContent,
            _ => FragmentType::FragmentBody,
        }
    }
}

pub fn combine_id_with_fragment_type(id: usize, fragment_type: FragmentType) -> u64 {
    debug_assert_eq!(id & (fragment_type as usize), 0);
    (id as u64) | (fragment_type as u64)
}

pub fn node_id_from_scroll_id(id: usize) -> usize {
    id & !3
}

#[derive(Clone, Debug, MallocSizeOf)]
pub struct ImageAnimationState {
    #[ignore_malloc_size_of = "RasterImage"]
    pub image: Arc<RasterImage>,
    pub active_frame: usize,
    frame_start_time: f64,
}

impl ImageAnimationState {
    pub fn new(image: Arc<RasterImage>, last_update_time: f64) -> Self {
        Self {
            image,
            active_frame: 0,
            frame_start_time: last_update_time,
        }
    }

    pub fn image_key(&self) -> Option<ImageKey> {
        self.image.id
    }

    pub fn duration_to_next_frame(&self, now: f64) -> Duration {
        let frame_delay = self
            .image
            .frames
            .get(self.active_frame)
            .expect("Image frame should always be valid")
            .delay
            .unwrap_or_default();

        let time_since_frame_start = (now - self.frame_start_time).max(0.0) * 1000.0;
        let time_since_frame_start = Duration::from_secs_f64(time_since_frame_start);
        frame_delay - time_since_frame_start.min(frame_delay)
    }

    /// check whether image active frame need to be updated given current time,
    /// return true if there are image that need to be updated.
    /// false otherwise.
    pub fn update_frame_for_animation_timeline_value(&mut self, now: f64) -> bool {
        if self.image.frames.len() <= 1 {
            return false;
        }
        let image = &self.image;
        let time_interval_since_last_update = now - self.frame_start_time;
        let mut remain_time_interval = time_interval_since_last_update -
            image
                .frames
                .get(self.active_frame)
                .unwrap()
                .delay()
                .unwrap()
                .as_secs_f64();
        let mut next_active_frame_id = self.active_frame;
        while remain_time_interval > 0.0 {
            next_active_frame_id = (next_active_frame_id + 1) % image.frames.len();
            remain_time_interval -= image
                .frames
                .get(next_active_frame_id)
                .unwrap()
                .delay()
                .unwrap()
                .as_secs_f64();
        }
        if self.active_frame == next_active_frame_id {
            return false;
        }
        self.active_frame = next_active_frame_id;
        self.frame_start_time = now;
        true
    }
}

/// Describe an item that matched a hit-test query.
#[derive(Debug)]
pub struct ElementsFromPointResult {
    /// An [`OpaqueNode`] that contains a pointer to the node hit by
    /// this hit test result.
    pub node: OpaqueNode,
    /// The [`Point2D`] of the original query point relative to the
    /// node fragment rectangle.
    pub point_in_target: Point2D<f32, CSSPixel>,
    /// The [`Cursor`] that's defined on the item that is hit by this
    /// hit test result.
    pub cursor: Cursor,
}

bitflags! {
    pub struct ElementsFromPointFlags: u8 {
        /// Whether or not to find all of the items for a hit test or stop at the
        /// first hit.
        const FindAll = 0b00000001;
    }
}

#[derive(Debug, Default, MallocSizeOf)]
pub struct AnimatingImages {
    /// A map from the [`OpaqueNode`] to the state of an animating image. This is used
    /// to update frames in script and to track newly animating nodes.
    pub node_to_state_map: FxHashMap<OpaqueNode, ImageAnimationState>,
    /// Whether or not this map has changed during a layout. This is used by script to
    /// trigger future animation updates.
    pub dirty: bool,
}

impl AnimatingImages {
    pub fn maybe_insert_or_update(
        &mut self,
        node: OpaqueNode,
        image: Arc<RasterImage>,
        current_timeline_value: f64,
    ) {
        let entry = self.node_to_state_map.entry(node).or_insert_with(|| {
            self.dirty = true;
            ImageAnimationState::new(image.clone(), current_timeline_value)
        });

        // If the entry exists, but it is for a different image id, replace it as the image
        // has changed during this layout.
        if entry.image.id != image.id {
            self.dirty = true;
            *entry = ImageAnimationState::new(image.clone(), current_timeline_value);
        }
    }

    pub fn remove(&mut self, node: OpaqueNode) {
        if self.node_to_state_map.remove(&node).is_some() {
            self.dirty = true;
        }
    }

    /// Clear the dirty bit on this [`AnimatingImages`] and return the previous value.
    pub fn clear_dirty(&mut self) -> bool {
        std::mem::take(&mut self.dirty)
    }

    pub fn is_empty(&self) -> bool {
        self.node_to_state_map.is_empty()
    }
}

struct ThreadStateRestorer;

impl ThreadStateRestorer {
    fn new() -> Self {
        #[cfg(debug_assertions)]
        {
            thread_state::exit(ThreadState::SCRIPT);
            thread_state::enter(ThreadState::LAYOUT);
        }
        Self
    }
}

impl Drop for ThreadStateRestorer {
    fn drop(&mut self) {
        #[cfg(debug_assertions)]
        {
            thread_state::exit(ThreadState::LAYOUT);
            thread_state::enter(ThreadState::SCRIPT);
        }
    }
}

/// Set up the thread-local state to reflect that layout code is about to run,
/// then call the provided function.
/// This must be used when running code that will interact with the DOM tree
/// through types like `ServoLayoutNode`, `ServoLayoutElement`, and `LayoutDom`,
/// which have rules about how they must be used from layout worker threads.
pub fn with_layout_state<R>(f: impl FnOnce() -> R) -> R {
    let _guard = ThreadStateRestorer::new();
    f()
}

#[cfg(test)]
mod test {
    use std::sync::Arc;
    use std::time::Duration;

    use pixels::{CorsStatus, ImageFrame, ImageMetadata, PixelFormat, RasterImage};

    use crate::ImageAnimationState;

    #[test]
    fn test() {
        let image_frames: Vec<ImageFrame> = std::iter::repeat_with(|| ImageFrame {
            delay: Some(Duration::from_millis(100)),
            byte_range: 0..1,
            width: 100,
            height: 100,
        })
        .take(10)
        .collect();
        let image = RasterImage {
            metadata: ImageMetadata {
                width: 100,
                height: 100,
            },
            format: PixelFormat::BGRA8,
            id: None,
            bytes: Arc::new(vec![1]),
            frames: image_frames,
            cors_status: CorsStatus::Unsafe,
            is_opaque: false,
        };
        let mut image_animation_state = ImageAnimationState::new(Arc::new(image), 0.0);

        assert_eq!(image_animation_state.active_frame, 0);
        assert_eq!(image_animation_state.frame_start_time, 0.0);
        assert_eq!(
            image_animation_state.update_frame_for_animation_timeline_value(0.101),
            true
        );
        assert_eq!(image_animation_state.active_frame, 1);
        assert_eq!(image_animation_state.frame_start_time, 0.101);
        assert_eq!(
            image_animation_state.update_frame_for_animation_timeline_value(0.116),
            false
        );
        assert_eq!(image_animation_state.active_frame, 1);
        assert_eq!(image_animation_state.frame_start_time, 0.101);
    }
}