1#![deny(unsafe_code)]
10
11mod accessibility;
12mod container_timing_record;
13mod largest_contentful_paint_candidate;
14mod layout_damage;
15mod layout_dom;
16mod layout_element;
17mod layout_node;
18mod pseudo_element_chain;
19mod writing_mode_ext;
20
21use std::any::Any;
22use std::rc::Rc;
23use std::sync::Arc;
24use std::sync::atomic::AtomicIsize;
25use std::thread::JoinHandle;
26use std::time::Duration;
27
28pub use accessibility::{
29 ACCESSKIT_ROLE_TO_ARIA_ROLE, ARIA_ROLE_TO_ACCESSKIT_ROLE, AccessibilityDamage,
30 SUPPORTED_ARIA_ROLES,
31};
32use accesskit::{Action, ActionData, ActionRequest};
33use app_units::Au;
34use background_hang_monitor_api::BackgroundHangMonitorRegister;
35use bitflags::bitflags;
36pub use container_timing_record::ContainerTimingRecord;
37use embedder_traits::{Cursor, ScriptToEmbedderChan, Theme, UntrustedNodeAddress, ViewportDetails};
38use euclid::{Point2D, Rect};
39use fonts::{FontContext, WebFontDocumentContext, WebFontSetDifference};
40pub use largest_contentful_paint_candidate::LCPCandidate;
41pub use layout_damage::LayoutDamage;
42pub use layout_dom::{
43 DangerousStyleElementOf, DangerousStyleNodeOf, LayoutDomTypeBundle, LayoutElementOf,
44 LayoutNodeOf,
45};
46pub use layout_element::{DangerousStyleElement, LayoutElement};
47pub use layout_node::{DangerousStyleNode, LayoutNode};
48use libc::c_void;
49use malloc_size_of::{MallocSizeOf as MallocSizeOfTrait, MallocSizeOfOps, malloc_size_of_is_0};
50use malloc_size_of_derive::MallocSizeOf;
51use net_traits::image_cache::{ImageCache, ImageCacheFactory, PendingImageId};
52use net_traits::request::InternalRequest;
53use paint_api::CrossProcessPaintApi;
54use paint_api::display_list::PaintTimingInfo;
55use parking_lot::RwLock;
56use pixels::{RasterImage, Repeat};
57use profile_traits::mem::Report;
58use profile_traits::time;
59pub use pseudo_element_chain::PseudoElementChain;
60use rustc_hash::{FxHashMap, FxHashSet};
61use script_traits::{InitialScriptState, Painter, ScriptThreadMessage};
62use serde::{Deserialize, Serialize};
63use servo_arc::Arc as ServoArc;
64use servo_base::Epoch;
65use servo_base::generic_channel::GenericSender;
66use servo_base::id::{BrowsingContextId, PipelineId, WebViewId};
67use servo_base::text::{RangeAny, Utf32CodeUnits, Utf32CodeUnitsOrNodeOffset};
68use servo_url::{ImmutableOrigin, ServoUrl};
69use style::Atom;
70use style::animation::DocumentAnimationSet;
71use style::attr::AttrValue;
72use style::context::QuirksMode;
73use style::data::ElementDataWrapper;
74use style::device::Device;
75use style::dom::OpaqueNode;
76use style::invalidation::element::restyle_hints::RestyleHint;
77use style::logical_geometry::WritingMode;
78use style::properties::style_structs::Font;
79use style::properties::{ComputedValues, PropertyId};
80use style::selector_parser::{PseudoElement, RestyleDamage, Snapshot};
81use style::stylesheets::{DocumentStyleSheet, Stylesheet};
82use style::stylist::Stylist;
83#[cfg(debug_assertions)]
84use style::thread_state::{self, ThreadState};
85use style::values::computed::Overflow;
86use style_traits::CSSPixel;
87use uuid::Uuid;
88use webrender_api::units::{DeviceIntSize, LayoutPoint, LayoutVector2D};
89use webrender_api::{ExternalScrollId, ImageKey};
90
91pub use crate::writing_mode_ext::WritingModeExt;
92
93pub trait GenericLayoutDataTrait: Any + MallocSizeOfTrait + Send + Sync + 'static {
94 fn as_any(&self) -> &dyn Any;
95
96 fn set_text_run_selection(
98 &self,
99 new_range: Option<RangeAny<Utf32CodeUnits>>,
100 new_paints_caret: bool,
101 ) -> bool;
102
103 fn set_element_selection(&self, selected: bool) -> bool;
106
107 fn rendered_text(&self, range: RangeAny<Utf32CodeUnits>) -> Option<String>;
110}
111
112pub trait LayoutDataTrait: GenericLayoutDataTrait + Default {}
113pub type GenericLayoutData = dyn GenericLayoutDataTrait;
114
115#[derive(Default, MallocSizeOf)]
116pub struct StyleData {
117 pub element_data: ElementDataWrapper,
122
123 pub parallel: DomParallelInfo,
125}
126
127#[derive(Default, MallocSizeOf)]
129pub struct DomParallelInfo {
130 pub children_to_process: AtomicIsize,
132}
133
134#[derive(Clone, Copy, Debug, Eq, PartialEq)]
135pub enum LayoutNodeType {
136 Element(LayoutElementType),
137 Text,
138}
139
140#[derive(Clone, Copy, Debug, Eq, PartialEq)]
141pub enum LayoutElementType {
142 Element,
143 HTMLBodyElement,
144 HTMLButtonElement,
145 HTMLBRElement,
146 HTMLCanvasElement,
147 HTMLHtmlElement,
148 HTMLIFrameElement,
149 HTMLImageElement,
150 HTMLInputElement,
151 HTMLMediaElement,
152 HTMLMeterElement,
153 HTMLObjectElement,
154 HTMLOptGroupElement,
155 HTMLOptionElement,
156 HTMLParagraphElement,
157 HTMLPreElement,
158 HTMLProgressElement,
159 HTMLSelectElement,
160 HTMLTableCellElement,
161 HTMLTableColElement,
162 HTMLTableElement,
163 HTMLTableRowElement,
164 HTMLTableSectionElement,
165 HTMLTextAreaElement,
166 SVGImageElement,
167 SVGSVGElement,
168}
169
170pub struct HTMLCanvasData {
171 pub image_key: Option<ImageKey>,
172 pub width: u32,
173 pub height: u32,
174}
175
176pub struct SVGElementData<'dom> {
177 pub source: Option<Result<ServoUrl, ()>>,
179 pub view_box_ratio: Option<f32>,
180 pub width: Option<&'dom AttrValue>,
181 pub height: Option<&'dom AttrValue>,
182 pub svg_id: Uuid,
183}
184
185#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
187pub struct TrustedNodeAddress(pub *const c_void);
188
189#[expect(unsafe_code)]
190unsafe impl Send for TrustedNodeAddress {}
191
192#[derive(Debug)]
194pub enum PendingImageState {
195 Unrequested(ServoUrl),
196 PendingResponse,
197}
198
199#[derive(Debug, MallocSizeOf)]
201pub enum LayoutImageDestination {
202 BoxTreeConstruction,
203 DisplayListBuilding,
204}
205
206#[derive(Debug)]
210pub struct PendingImage {
211 pub state: PendingImageState,
212 pub node: UntrustedNodeAddress,
213 pub id: PendingImageId,
214 pub origin: ImmutableOrigin,
215 pub destination: LayoutImageDestination,
216 pub is_internal_request: InternalRequest,
217}
218
219#[derive(Debug)]
223pub struct PendingRasterizationImage {
224 pub node: UntrustedNodeAddress,
225 pub id: PendingImageId,
226 pub size: DeviceIntSize,
227}
228
229#[derive(Clone, Copy, Debug, MallocSizeOf)]
230pub struct MediaFrame {
231 pub image_key: webrender_api::ImageKey,
232 pub width: i32,
233 pub height: i32,
234}
235
236pub struct MediaMetadata {
237 pub width: u32,
238 pub height: u32,
239}
240
241pub struct HTMLMediaData {
242 pub current_frame: Option<MediaFrame>,
243 pub metadata: Option<MediaMetadata>,
244 pub poster_or_src_url: Option<ServoUrl>,
245}
246
247#[derive(Debug)]
248pub struct AccessibilityActionRequest {
249 pub action: Action,
250 pub target: OpaqueNode,
251 pub data: Option<ActionData>,
252}
253
254pub struct LayoutConfig {
255 pub id: PipelineId,
256 pub webview_id: WebViewId,
257 pub url: ServoUrl,
258 pub is_iframe: bool,
259 pub script_chan: GenericSender<ScriptThreadMessage>,
260 pub image_cache: Arc<dyn ImageCache>,
261 pub font_context: Arc<FontContext>,
262 pub time_profiler_chan: time::ProfilerChan,
263 pub paint_api: CrossProcessPaintApi,
264 pub viewport_details: ViewportDetails,
265 pub user_stylesheets: Rc<Vec<DocumentStyleSheet>>,
266 pub theme: Theme,
267 pub embedder_chan: ScriptToEmbedderChan,
268 pub document_random_hasher_key: (u64, u64),
272}
273
274bitflags! {
275 #[derive(Copy, Clone)]
276 pub struct HitTestFlags: u8 {
277 const IncludeDomPosition = 0b0000_0001;
279 }
280}
281
282pub trait LayoutFactory: Send + Sync {
283 fn create(&self, config: LayoutConfig) -> Box<dyn Layout>;
284}
285
286pub trait Layout {
287 fn device(&self) -> &Device;
290
291 fn set_theme(&mut self, theme: Theme) -> bool;
295
296 fn set_viewport_details(&mut self, viewport_details: ViewportDetails) -> bool;
300
301 fn add_stylesheet(
306 &mut self,
307 stylesheet: ServoArc<Stylesheet>,
308 before_stylesheet: Option<ServoArc<Stylesheet>>,
309 );
310
311 fn exit_now(&mut self);
313
314 fn collect_reports(&self, reports: &mut Vec<Report>, ops: &mut MallocSizeOfOps);
317
318 fn set_quirks_mode(&mut self, quirks_mode: QuirksMode);
320
321 fn remove_stylesheet(&mut self, stylesheet: ServoArc<Stylesheet>);
323
324 fn remove_cached_image(&mut self, image_url: &ServoUrl);
326
327 fn reflow(&mut self, reflow_request: ReflowRequest) -> Option<ReflowResult>;
329
330 fn ensure_stacking_context_tree(&self, viewport_details: ViewportDetails);
333
334 fn register_paint_worklet_modules(
336 &mut self,
337 name: Atom,
338 properties: Vec<Atom>,
339 painter: Box<dyn Painter>,
340 );
341
342 fn set_scroll_offsets_from_renderer(
344 &mut self,
345 scroll_states: &FxHashMap<ExternalScrollId, LayoutVector2D>,
346 );
347
348 fn scroll_offset(&self, id: ExternalScrollId) -> Option<LayoutVector2D>;
351
352 fn needs_new_display_list(&self) -> bool;
354
355 fn set_needs_new_display_list(&self);
357
358 fn node_rendering_type(
361 &self,
362 node: TrustedNodeAddress,
363 pseudo: Option<PseudoElement>,
364 ) -> NodeRenderingType;
365
366 fn query_containing_block(&self, node: TrustedNodeAddress) -> Option<UntrustedNodeAddress>;
367 fn query_containing_block_is_descendant(
368 &self,
369 root: TrustedNodeAddress,
370 possible_descendant: TrustedNodeAddress,
371 ) -> bool;
372 fn query_padding(&self, node: TrustedNodeAddress) -> Option<PhysicalSides<Au>>;
373 fn query_box_area(
374 &self,
375 node: TrustedNodeAddress,
376 area: BoxAreaType,
377 exclude_transform_and_inline: bool,
378 ) -> Option<Rect<Au, CSSPixel>>;
379 fn query_box_areas(&self, node: TrustedNodeAddress, area: BoxAreaType) -> CSSPixelRectVec;
380 fn query_client_rect(&self, node: TrustedNodeAddress) -> Rect<i32, CSSPixel>;
381 fn query_current_css_zoom(&self, node: TrustedNodeAddress) -> f32;
382 fn query_element_inner_outer_text(&self, node: TrustedNodeAddress) -> String;
383 fn query_offset_parent(&self, node: TrustedNodeAddress) -> OffsetParentResponse;
384 fn query_scroll_container(
387 &self,
388 node: Option<TrustedNodeAddress>,
389 flags: ScrollContainerQueryFlags,
390 ) -> Option<ScrollContainerResponse>;
391 fn query_resolved_style(
392 &self,
393 node: TrustedNodeAddress,
394 pseudo: Option<PseudoElement>,
395 property_id: PropertyId,
396 animations: DocumentAnimationSet,
397 animation_timeline_value: f64,
398 ) -> String;
399
400 fn query_accesskit_node(&self, node: TrustedNodeAddress) -> Option<accesskit::Node>;
401
402 fn query_resolved_font_style(
403 &self,
404 node: TrustedNodeAddress,
405 value: &str,
406 animations: DocumentAnimationSet,
407 animation_timeline_value: f64,
408 ) -> Option<ServoArc<Font>>;
409 fn query_scrolling_area(&self, node: Option<TrustedNodeAddress>) -> Rect<i32, CSSPixel>;
410 fn query_text_index(
414 &self,
415 node: TrustedNodeAddress,
416 point_in_viewport: Point2D<Au, CSSPixel>,
417 ) -> Option<(OpaqueNode, Utf32CodeUnits)>;
418 fn query_text_segment(
421 &self,
422 node: TrustedNodeAddress,
423 offset: Utf32CodeUnitsOrNodeOffset,
424 granularity: SegmentGranularity,
425 ) -> Option<(
426 (OpaqueNode, Utf32CodeUnitsOrNodeOffset),
427 (OpaqueNode, Utf32CodeUnitsOrNodeOffset),
428 )>;
429 fn hit_test(&self, flags: HitTestFlags, point: LayoutPoint) -> HitTestResult;
430 fn query_effective_overflow(&self, node: TrustedNodeAddress) -> Option<AxesOverflow>;
431 fn stylist_mut(&mut self) -> &mut Stylist;
432
433 fn set_accessibility_active(&self, enabled: bool, epoch: Epoch);
436
437 fn accessibility_active(&self) -> bool;
439
440 fn needs_accessibility_update(&self) -> bool;
451
452 fn set_force_accessibility_update_if_active(&self);
455
456 fn handle_accessibility_action(&self, action_request: ActionRequest);
458
459 fn font_context(&self) -> &Arc<FontContext>;
460}
461
462#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
464pub enum SegmentGranularity {
465 Word,
467 HardLineBreak,
470}
471
472pub trait ScriptThreadFactory {
476 fn create(
478 state: InitialScriptState,
479 layout_factory: Arc<dyn LayoutFactory>,
480 image_cache_factory: Arc<dyn ImageCacheFactory>,
481 background_hang_monitor_register: Box<dyn BackgroundHangMonitorRegister>,
482 ) -> JoinHandle<()>;
483}
484
485#[derive(Copy, Clone)]
488pub enum BoxAreaType {
489 Content,
490 Padding,
491 Border,
492}
493
494pub type CSSPixelRectVec = Vec<Rect<Au, CSSPixel>>;
495
496#[derive(Copy, Clone)]
499pub enum NodeRenderingType {
500 Rendered,
502 DelegatesRendering,
504 NotRendered,
507}
508
509pub type PhysicalSides<U> = euclid::SideOffsets2D<U, CSSPixel>;
510
511#[derive(Clone, Default)]
512pub struct OffsetParentResponse {
513 pub node_address: Option<UntrustedNodeAddress>,
514 pub rect: Rect<Au, CSSPixel>,
515}
516
517bitflags! {
518 #[derive(PartialEq)]
519 pub struct ScrollContainerQueryFlags: u8 {
520 const ForScrollParent = 1 << 0;
522 const Inclusive = 1 << 1;
524 }
525}
526
527#[derive(Clone, Copy, Debug, MallocSizeOf)]
528pub struct AxesOverflow {
529 pub x: Overflow,
530 pub y: Overflow,
531}
532
533impl Default for AxesOverflow {
534 fn default() -> Self {
535 Self {
536 x: Overflow::Visible,
537 y: Overflow::Visible,
538 }
539 }
540}
541
542impl From<&ComputedValues> for AxesOverflow {
543 fn from(style: &ComputedValues) -> Self {
544 Self {
545 x: style.slow_clone_overflow_x(),
546 y: style.slow_clone_overflow_y(),
547 }
548 }
549}
550
551impl AxesOverflow {
552 pub fn to_scrollable(&self) -> Self {
553 Self {
554 x: self.x.to_scrollable(),
555 y: self.y.to_scrollable(),
556 }
557 }
558
559 pub fn establishes_scroll_container(&self) -> bool {
561 self.x.is_scrollable()
564 }
565}
566
567#[derive(Clone)]
568pub enum ScrollContainerResponse {
569 Viewport(AxesOverflow, WritingMode),
570 Element(UntrustedNodeAddress, AxesOverflow, WritingMode),
571}
572
573#[derive(Debug, PartialEq)]
574pub enum QueryMsg {
575 BoxArea,
576 BoxAreas,
577 ClientRectQuery,
578 CurrentCSSZoomQuery,
579 EffectiveOverflow,
580 ElementInnerOuterTextQuery,
581 ElementsFromPoint,
582 InnerWindowDimensionsQuery,
583 NodesFromPointQuery,
584 OffsetParentQuery,
585 ScrollParentQuery,
586 ResolvedFontStyleQuery,
587 ResolvedStyleQuery(PropertyId),
590 ScrollingAreaOrOffsetQuery,
591 StyleQuery,
592 TextIndexOrSegmentQuery,
593 PaddingQuery,
594 FlushForUpdateTheRenderingQuery,
595 AccessKitNodeQuery,
596}
597
598#[derive(Debug, PartialEq)]
604pub enum ReflowGoal {
605 UpdateTheRendering,
608
609 LayoutQuery(QueryMsg),
612
613 UpdateScrollNode(ExternalScrollId, LayoutVector2D),
617}
618
619#[derive(Clone, Debug, MallocSizeOf)]
620pub struct IFrameSize {
621 pub browsing_context_id: BrowsingContextId,
622 pub pipeline_id: PipelineId,
623 pub viewport_details: ViewportDetails,
624}
625
626pub type IFrameSizes = FxHashMap<BrowsingContextId, IFrameSize>;
627
628bitflags! {
629 #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
632 pub struct RestyleReason: u16 {
633 const StylesheetsChanged = 1 << 0;
634 const DOMChanged = 1 << 1;
635 const PendingRestyles = 1 << 2;
636 const HighlightedDOMNodeChanged = 1 << 3;
637 const ThemeChanged = 1 << 4;
638 const ViewportChanged = 1 << 5;
639 const PaintWorkletLoaded = 1 << 6;
640 }
641}
642
643malloc_size_of_is_0!(RestyleReason);
644
645impl RestyleReason {
646 pub fn needs_restyle(&self) -> bool {
647 !self.is_empty()
648 }
649}
650
651#[derive(Default)]
653pub struct ReflowResult {
654 pub reflow_phases_run: ReflowPhasesRun,
656 pub reflow_statistics: ReflowStatistics,
657 pub pending_images: Vec<PendingImage>,
659 pub pending_rasterization_images: Vec<PendingRasterizationImage>,
661 pub pending_svg_elements_for_serialization: Vec<UntrustedNodeAddress>,
665 pub iframe_sizes: Option<IFrameSizes>,
671 pub changed_web_fonts: WebFontSetDifference,
673 pub lcp_candidate: Option<LCPCandidate>,
675 pub pending_accessibility_actions: Vec<AccessibilityActionRequest>,
677 pub container_timing_records: Vec<ContainerTimingRecord>,
679}
680
681bitflags! {
682 #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
684 pub struct ReflowPhasesRun: u8 {
685 const RanLayout = 1 << 0;
686 const BuiltStackingContextTree = 1 << 2;
687 const BuiltDisplayList = 1 << 3;
688 const UpdatedScrollNodeOffset = 1 << 4;
689 const UpdatedImageData = 1 << 5;
693 const UpdatedAccessibilityTree = 1 << 6;
694 }
695}
696
697impl ReflowPhasesRun {
698 pub fn needs_frame(&self) -> bool {
699 self.intersects(
700 Self::BuiltDisplayList | Self::UpdatedScrollNodeOffset | Self::UpdatedImageData,
701 )
702 }
703}
704
705#[derive(Debug, Default)]
706pub struct ReflowStatistics {
707 pub rebuilt_fragment_count: u32,
709 pub restyle_fragment_count: u32,
711 pub only_descendants_changed_count: u32,
714 pub nodes_updated_from_dom: u32,
717 pub nodes_updated_from_tree: u32,
720 pub nodes_updated_bounds: u32,
723 pub nodes_in_tree_update: u32,
725}
726
727#[derive(Debug)]
730pub struct ReflowRequestRestyle {
731 pub reason: RestyleReason,
733 pub dirty_root: Option<TrustedNodeAddress>,
735 pub stylesheets_changed: bool,
737 pub pending_restyles: Vec<(TrustedNodeAddress, PendingRestyle)>,
739}
740
741#[derive(Debug)]
744pub struct ReflowRequestAccessibility {
745 pub damage: Vec<(TrustedNodeAddress, AccessibilityDamage)>,
747 pub focused_element: Option<OpaqueNode>,
749 pub rooted_nodes_for_integrity_check: Option<FxHashSet<OpaqueNode>>,
753}
754
755#[derive(Debug)]
757pub struct ReflowRequest {
758 pub document: TrustedNodeAddress,
760 pub epoch: Epoch,
762 pub restyle: Option<ReflowRequestRestyle>,
764 pub viewport_details: ViewportDetails,
766 pub reflow_goal: ReflowGoal,
768 pub origin: ImmutableOrigin,
770 pub animation_timeline_value: f64,
772 pub animations: DocumentAnimationSet,
774 pub animating_images: Arc<RwLock<AnimatingImages>>,
776 pub highlighted_dom_node: Option<OpaqueNode>,
778 pub frame_focused: bool,
781 pub halt_lcp: bool,
785 pub paint_timing_eligible: bool,
788 pub paint_timing_info: PaintTimingInfo,
791 pub document_context: WebFontDocumentContext,
793 pub accessibility: Option<ReflowRequestAccessibility>,
795}
796
797impl ReflowRequest {
798 pub fn stylesheets_changed(&self) -> bool {
799 self.restyle
800 .as_ref()
801 .is_some_and(|restyle| restyle.stylesheets_changed)
802 }
803}
804
805#[derive(Debug, Default, MallocSizeOf)]
807pub struct PendingRestyle {
808 pub snapshot: Option<Snapshot>,
811
812 pub hint: RestyleHint,
814
815 pub damage: RestyleDamage,
817}
818
819#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
825pub enum FragmentType {
826 FragmentBody,
828 BeforePseudoContent,
830 AfterPseudoContent,
832}
833
834impl From<Option<PseudoElement>> for FragmentType {
835 fn from(value: Option<PseudoElement>) -> Self {
836 match value {
837 Some(PseudoElement::After) => FragmentType::AfterPseudoContent,
838 Some(PseudoElement::Before) => FragmentType::BeforePseudoContent,
839 _ => FragmentType::FragmentBody,
840 }
841 }
842}
843
844pub fn combine_id_with_fragment_type(id: usize, fragment_type: FragmentType) -> u64 {
845 debug_assert_eq!(id & (fragment_type as usize), 0);
846 (id as u64) | (fragment_type as u64)
847}
848
849pub fn node_id_from_scroll_id(id: usize) -> usize {
850 id & !3
851}
852
853#[derive(Clone, Debug, MallocSizeOf)]
854pub struct ImageAnimationState {
855 #[conditional_malloc_size_of]
856 pub image: Arc<RasterImage>,
857 pub active_frame: usize,
858 frame_start_time: f64,
859
860 pub completed_loops: Option<u32>,
865}
866
867impl ImageAnimationState {
868 pub fn new(image: Arc<RasterImage>, last_update_time: f64) -> Self {
869 let completd_loops = match &image.loop_count {
870 None => unreachable!("Loop count of an animated Image should never be None"),
871 Some(repeat) if Repeat::Infinite == *repeat => None,
872 _ => Some(0),
873 };
874
875 Self {
876 image,
877 active_frame: 0,
878 frame_start_time: last_update_time,
879 completed_loops: completd_loops,
880 }
881 }
882
883 pub fn image_key(&self) -> Option<ImageKey> {
884 self.image.id
885 }
886
887 pub fn duration_to_next_frame(&self, now: f64) -> Option<Duration> {
888 if self.is_finished() {
889 return None;
890 }
891 let frame_delay = self
892 .image
893 .frames
894 .get(self.active_frame)
895 .expect("Image frame should always be valid")
896 .delay
897 .unwrap_or_default();
898
899 let time_since_frame_start = (now - self.frame_start_time).max(0.0) * 1000.0;
900 let time_since_frame_start = Duration::from_secs_f64(time_since_frame_start);
901 Some(frame_delay - time_since_frame_start.min(frame_delay))
902 }
903
904 pub fn update_frame_for_animation_timeline_value(&mut self, now: f64) -> bool {
908 if self.image.frames.len() <= 1 || self.is_finished() {
909 return false;
910 }
911 let time_interval_since_last_update = now - self.frame_start_time;
912 let mut remain_time_interval = time_interval_since_last_update -
913 self.image
914 .frames
915 .get(self.active_frame)
916 .unwrap()
917 .delay()
918 .unwrap()
919 .as_secs_f64();
920 let mut next_active_frame_id = self.active_frame;
921
922 let frame_count = self.image.frames.len();
923 while remain_time_interval > 0.0 {
924 next_active_frame_id = (next_active_frame_id + 1) % frame_count;
925
926 if next_active_frame_id == 0 {
928 self.advance_completed_loops();
929
930 if self.is_finished() {
933 if self.active_frame == frame_count - 1 {
934 return false;
935 }
936 self.active_frame = frame_count - 1;
937 self.frame_start_time = now;
938 return true;
939 }
940 }
941
942 remain_time_interval -= self
943 .image
944 .frames
945 .get(next_active_frame_id)
946 .unwrap()
947 .delay()
948 .unwrap()
949 .as_secs_f64();
950 }
951 if self.active_frame == next_active_frame_id {
952 return false;
953 }
954 self.active_frame = next_active_frame_id;
955 self.frame_start_time = now;
956 true
957 }
958
959 fn is_finished(&self) -> bool {
961 let Some(Repeat::Finite(maximum_loops)) = self.image.loop_count.as_ref() else {
962 return false;
963 };
964 self.completed_loops
965 .is_some_and(|completed_loops| completed_loops >= maximum_loops.get())
966 }
967
968 fn advance_completed_loops(&mut self) {
970 if let Some(completed_loops) = self.completed_loops.as_mut() {
971 *completed_loops += 1;
972 }
973 }
974}
975
976#[derive(Debug, Default)]
978pub struct HitTestResult {
979 pub items: Vec<HitTestResultItem>,
980 pub dom_position_for_selection: Option<(OpaqueNode, Utf32CodeUnitsOrNodeOffset)>,
981}
982
983#[derive(Debug)]
985pub struct HitTestResultItem {
986 pub node: OpaqueNode,
989 pub point_in_target: Point2D<f32, CSSPixel>,
992 pub cursor: Cursor,
995}
996
997#[derive(Debug, Default, MallocSizeOf)]
998pub struct AnimatingImages {
999 pub node_to_state_map: FxHashMap<OpaqueNode, ImageAnimationState>,
1002 pub dirty: bool,
1005}
1006
1007impl AnimatingImages {
1008 pub fn maybe_insert_or_update(
1009 &mut self,
1010 node: OpaqueNode,
1011 image: Arc<RasterImage>,
1012 current_timeline_value: f64,
1013 ) {
1014 let entry = self.node_to_state_map.entry(node).or_insert_with(|| {
1015 self.dirty = true;
1016 ImageAnimationState::new(image.clone(), current_timeline_value)
1017 });
1018
1019 if entry.image.id != image.id {
1022 self.dirty = true;
1023 *entry = ImageAnimationState::new(image.clone(), current_timeline_value);
1024 }
1025 }
1026
1027 pub fn remove(&mut self, node: OpaqueNode) {
1028 if self.node_to_state_map.remove(&node).is_some() {
1029 self.dirty = true;
1030 }
1031 }
1032
1033 pub fn clear_dirty(&mut self) -> bool {
1035 std::mem::take(&mut self.dirty)
1036 }
1037
1038 pub fn is_empty(&self) -> bool {
1039 self.node_to_state_map.is_empty()
1040 }
1041}
1042
1043struct ThreadStateRestorer;
1044
1045impl ThreadStateRestorer {
1046 fn new() -> Self {
1047 #[cfg(debug_assertions)]
1048 {
1049 thread_state::exit(ThreadState::SCRIPT);
1050 thread_state::enter(ThreadState::LAYOUT);
1051 }
1052 Self
1053 }
1054}
1055
1056impl Drop for ThreadStateRestorer {
1057 fn drop(&mut self) {
1058 #[cfg(debug_assertions)]
1059 {
1060 thread_state::exit(ThreadState::LAYOUT);
1061 thread_state::enter(ThreadState::SCRIPT);
1062 }
1063 }
1064}
1065
1066pub fn with_layout_state<R>(f: impl FnOnce() -> R) -> R {
1072 let _guard = ThreadStateRestorer::new();
1073 f()
1074}
1075
1076#[cfg(test)]
1077mod test {
1078 use std::num::NonZeroU32;
1079 use std::sync::Arc;
1080 use std::time::Duration;
1081
1082 use pixels::{CorsStatus, ImageFrame, ImageMetadata, PixelFormat, RasterImage, Repeat};
1083
1084 use crate::ImageAnimationState;
1085
1086 #[test]
1087 fn test_animated_image_update() {
1088 let image_frames: Vec<ImageFrame> = std::iter::repeat_with(|| ImageFrame {
1089 delay: Some(Duration::from_millis(100)),
1090 byte_range: 0..1,
1091 width: 100,
1092 height: 100,
1093 })
1094 .take(10)
1095 .collect();
1096 let image = RasterImage {
1097 metadata: ImageMetadata {
1098 width: 100,
1099 height: 100,
1100 },
1101 format: PixelFormat::BGRA8,
1102 id: None,
1103 bytes: Arc::new(vec![1]),
1104 frames: image_frames,
1105 cors_status: CorsStatus::Unsafe,
1106 load_time: None,
1107 loop_count: Some(Repeat::Infinite),
1108 is_opaque: false,
1109 };
1110 let mut image_animation_state = ImageAnimationState::new(Arc::new(image), 0.0);
1111
1112 assert_eq!(image_animation_state.active_frame, 0);
1113 assert_eq!(image_animation_state.frame_start_time, 0.0);
1114 assert_eq!(
1115 image_animation_state.update_frame_for_animation_timeline_value(0.101),
1116 true
1117 );
1118 assert_eq!(image_animation_state.active_frame, 1);
1119 assert_eq!(image_animation_state.frame_start_time, 0.101);
1120 assert_eq!(
1121 image_animation_state.update_frame_for_animation_timeline_value(0.116),
1122 false
1123 );
1124 assert_eq!(image_animation_state.active_frame, 1);
1125 assert_eq!(image_animation_state.frame_start_time, 0.101);
1126 }
1127
1128 #[test]
1129 fn test_finite_image_repeat() {
1130 let image_frames: Vec<ImageFrame> = std::iter::repeat_with(|| ImageFrame {
1131 delay: Some(Duration::from_millis(100)),
1132 byte_range: 0..1,
1133 width: 100,
1134 height: 100,
1135 })
1136 .take(2)
1137 .collect();
1138 let image = RasterImage {
1139 metadata: ImageMetadata {
1140 width: 100,
1141 height: 100,
1142 },
1143 format: PixelFormat::BGRA8,
1144 id: None,
1145 bytes: Arc::new(vec![1]),
1146 frames: image_frames,
1147 cors_status: CorsStatus::Unsafe,
1148 load_time: None,
1149 loop_count: Some(Repeat::Finite(NonZeroU32::new(1).unwrap())),
1150 is_opaque: false,
1151 };
1152 let mut image_animation_state = ImageAnimationState::new(Arc::new(image), 0.0);
1153
1154 assert_eq!(image_animation_state.active_frame, 0);
1155 assert_eq!(image_animation_state.frame_start_time, 0.0);
1156 assert_eq!(
1157 image_animation_state.update_frame_for_animation_timeline_value(0.101),
1158 true
1159 );
1160 assert_eq!(image_animation_state.active_frame, 1);
1161 assert_eq!(image_animation_state.frame_start_time, 0.101);
1162 assert_eq!(
1163 image_animation_state.update_frame_for_animation_timeline_value(0.202),
1164 false
1165 );
1166 assert_eq!(
1167 image_animation_state.update_frame_for_animation_timeline_value(0.303),
1168 false
1169 );
1170
1171 assert_eq!(image_animation_state.active_frame, 1);
1172 }
1173}