Skip to main content

script/dom/window/
window.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#![cfg_attr(crown, allow(crown::jscontext_first_arg))]
6
7use std::borrow::ToOwned;
8use std::cell::{Cell, RefCell, RefMut};
9use std::collections::HashSet;
10use std::collections::hash_map::Entry;
11use std::default::Default;
12use std::ffi::c_void;
13use std::io::{Write, stderr, stdout};
14use std::ptr::NonNull;
15use std::rc::{Rc, Weak};
16use std::sync::Arc;
17use std::time::{Duration, Instant};
18
19use accesskit::Action;
20use app_units::Au;
21use base64::Engine;
22use content_security_policy::Violation;
23use content_security_policy::sandboxing_directive::SandboxingFlagSet;
24use crossbeam_channel::{Sender, unbounded};
25use cssparser::SourceLocation;
26use dom_struct::dom_struct;
27use embedder_traits::user_contents::UserScript;
28use embedder_traits::{
29    AlertResponse, ConfirmResponse, EmbedderMsg, LoadStatus, PromptResponse, ScriptToEmbedderChan,
30    SimpleDialogRequest, Theme, UntrustedNodeAddress, ViewportDetails,
31};
32use euclid::{Point2D, Rect, Scale, Size2D, Vector2D};
33use fonts::{CspViolationHandler, FontContext, NetworkTimingHandler, WebFontSetDifference};
34use html5ever::LocalName;
35use js::context::{JSContext, NoGC};
36use js::conversions::ToJSValConvertible;
37use js::glue::DumpJSStack;
38use js::jsapi::{
39    GCReason, GetObjectRealmOrNull, JSContext as RawJSContext, JSObject, SetRealmPrincipals,
40};
41use js::jsval::{NullValue, UndefinedValue};
42use js::realm::{AutoRealm, CurrentRealm};
43use js::rust::wrappers2::{JS_GC, JS_MaybeGC};
44use js::rust::{
45    CustomAutoRooterGuard, HandleObject, HandleValue, MutableHandleObject, MutableHandleValue,
46};
47use layout_api::{
48    AccessibilityActionRequest, AxesOverflow, BoxAreaType, CSSPixelRectVec, ContainerTimingRecord,
49    FragmentType, HitTestFlags, LCPCandidate, Layout, LayoutImageDestination, PendingImage,
50    PendingImageState, PendingRasterizationImage, PhysicalSides, QueryMsg, ReflowGoal,
51    ReflowPhasesRun, ReflowRequest, ReflowRequestAccessibility, ReflowRequestRestyle,
52    ReflowStatistics, RestyleReason, ScrollContainerQueryFlags, ScrollContainerResponse,
53    SegmentGranularity, TrustedNodeAddress, combine_id_with_fragment_type,
54};
55use malloc_size_of::MallocSizeOf;
56use media::WindowGLContext;
57use net_traits::image_cache::{
58    ImageCache, ImageCacheResponseCallback, ImageCacheResponseMessage, ImageLoadListener,
59    ImageResponse, PendingImageId, PendingImageResponse, RasterizationCompleteResponse,
60};
61use net_traits::request::{Origin, Referrer, RequestClient, UpgradeInsecureNavigations};
62use net_traits::{ResourceFetchTiming, ResourceThreads};
63use num_traits::ToPrimitive;
64use paint_api::{CrossProcessPaintApi, PinchZoomInfos};
65use profile_traits::generic_channel as ProfiledGenericChannel;
66use profile_traits::mem::ProfilerChan as MemProfilerChan;
67use profile_traits::time::ProfilerChan as TimeProfilerChan;
68use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
69use script_bindings::cell::{DomRefCell, Ref};
70use script_bindings::dom::UnrootedDom;
71use script_bindings::domstring::TracedDOMString;
72use script_bindings::interfaces::{HasOrigin, WindowHelpers};
73use script_bindings::js::{JS_DefineProperty, PropertyFlags};
74use script_bindings::like::Setlike;
75use script_bindings::principals::ServoJSPrincipals;
76use script_bindings::reflector::DomObject;
77use script_bindings::root::Root;
78use script_traits::{ConstellationInputEvent, ScriptThreadMessage, WebViewState};
79use selectors::Parser;
80use selectors::attr::CaseSensitivity;
81use selectors::parser::is_css2_pseudo_element;
82use servo_arc::Arc as ServoArc;
83use servo_base::cross_process_instant::CrossProcessInstant;
84use servo_base::generic_channel::{self, GenericCallback, GenericSender};
85use servo_base::id::{BrowsingContextId, PipelineId, WebViewId};
86use servo_base::text::{Utf32CodeUnits, Utf32CodeUnitsOrNodeOffset};
87#[cfg(feature = "bluetooth")]
88use servo_bluetooth_traits::BluetoothRequest;
89#[cfg(feature = "webgl")]
90use servo_canvas_traits::webgl::WebGLChan;
91use servo_config::pref;
92use servo_constellation_traits::{
93    LoadData, LoadOrigin, ScreenshotReadinessResponse, ScriptToConstellationMessage,
94    ScriptToConstellationSender, StructuredSerializedData, WindowSizeType,
95};
96use servo_geometry::DeviceIndependentIntRect;
97use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
98use storage_traits::StorageThreads;
99use storage_traits::webstorage_thread::WebStorageType;
100use style::dom::OpaqueNode;
101use style::error_reporting::{ContextualParseError, ParseErrorReporter};
102use style::properties::PropertyId;
103use style::properties::style_structs::Font;
104use style::selector_parser::{PseudoElement, SelectorParser};
105use style::str::HTML_SPACE_CHARACTERS;
106use style::stylesheets::{Origin as StyleOrigin, UrlExtraData};
107use style_traits::CSSPixel;
108use stylo_atoms::Atom;
109use time::Duration as TimeDuration;
110use webrender_api::ExternalScrollId;
111use webrender_api::units::{DeviceIntSize, DevicePixel, LayoutPixel, LayoutPoint};
112
113use crate::dom::StatelessWorkletThreadPool;
114use crate::dom::bindings::callback::RootedCallback;
115use crate::dom::bindings::codegen::Bindings::AnimationFrameProviderBinding::FrameRequestCallback;
116use crate::dom::bindings::codegen::Bindings::DocumentBinding::{
117    DocumentMethods, DocumentReadyState, NamedPropertyValue,
118};
119use crate::dom::bindings::codegen::Bindings::HTMLIFrameElementBinding::HTMLIFrameElementMethods;
120use crate::dom::bindings::codegen::Bindings::HistoryBinding::History_Binding::HistoryMethods;
121use crate::dom::bindings::codegen::Bindings::ImageBitmapBinding::{
122    ImageBitmapOptions, ImageBitmapSource,
123};
124use crate::dom::bindings::codegen::Bindings::MediaQueryListBinding::MediaQueryList_Binding::MediaQueryListMethods;
125use crate::dom::bindings::codegen::Bindings::MessagePortBinding::StructuredSerializeOptions;
126use crate::dom::bindings::codegen::Bindings::ReportingObserverBinding::Report;
127use crate::dom::bindings::codegen::Bindings::RequestBinding::{RequestInfo, RequestInit};
128use crate::dom::bindings::codegen::Bindings::VoidFunctionBinding::VoidFunction;
129use crate::dom::bindings::codegen::Bindings::WindowBinding::{
130    self, DeferredRequestInit, ScrollBehavior, ScrollToOptions, WindowMethods,
131    WindowPostMessageOptions,
132};
133use crate::dom::bindings::codegen::UnionTypes::{
134    RequestOrUSVString, TrustedScriptOrString, TrustedScriptOrStringOrFunction,
135};
136use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
137use crate::dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
138use crate::dom::bindings::num::Finite;
139use crate::dom::bindings::refcounted::Trusted;
140use crate::dom::bindings::reflector::DomGlobal;
141use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
142use crate::dom::bindings::str::{DOMString, USVString};
143use crate::dom::bindings::structuredclone;
144use crate::dom::bindings::trace::{CustomTraceable, HashMapTracedValues, JSTraceable};
145use crate::dom::bindings::utils::GlobalStaticData;
146use crate::dom::bindings::weakref::DOMTracker;
147#[cfg(feature = "bluetooth")]
148use crate::dom::bluetooth::BluetoothExtraPermissionData;
149use crate::dom::closewatchermanager::CloseWatcherManager;
150use crate::dom::cookiestore::cookiestore::CookieStore;
151use crate::dom::csp::GlobalCspReporting;
152use crate::dom::css::cssstyledeclaration::{
153    CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner,
154};
155use crate::dom::customelementregistry::CustomElementRegistry;
156use crate::dom::document::focus::FocusableArea;
157use crate::dom::document::{
158    AbortReason, AnimationFrameCallback, Document, LocalDescendantNavigablesIterator,
159};
160use crate::dom::element::Element;
161use crate::dom::event::{Event, EventBubbles, EventCancelable};
162use crate::dom::eventtarget::EventTarget;
163use crate::dom::fetchlaterresult::FetchLaterResult;
164use crate::dom::geolocation::Geolocation;
165use crate::dom::globalscope::GlobalScope;
166use crate::dom::history::History;
167use crate::dom::html::htmlcollection::{CollectionFilter, HTMLCollection};
168use crate::dom::html::htmliframeelement::HTMLIFrameElement;
169use crate::dom::idbfactory::IDBFactory;
170use crate::dom::inputevent::HitTestResult;
171use crate::dom::location::Location;
172use crate::dom::medialist::MediaList;
173use crate::dom::mediaquerylist::{MediaQueryList, MediaQueryListMatchState};
174use crate::dom::mediaquerylistevent::MediaQueryListEvent;
175use crate::dom::messageevent::MessageEvent;
176use crate::dom::navigator::Navigator;
177use crate::dom::node::focus::FocusTrigger;
178use crate::dom::node::{Node, NodeDamage, NodeTraits, from_untrusted_node_address};
179use crate::dom::performance::performance::Performance;
180use crate::dom::performanceresourcetiming::InitiatorType;
181use crate::dom::promise::RootedPromise;
182use crate::dom::reporting::reportingendpoint::{ReportingEndpoint, SendReportsToEndpoints};
183use crate::dom::reporting::reportingobserver::ReportingObserver;
184use crate::dom::selection::Selection;
185use crate::dom::selection_range::RootedSelectionBoundary;
186use crate::dom::serviceworker::cachestorage::CacheStorage;
187use crate::dom::shadowroot::shadowroot::ShadowRoot;
188use crate::dom::storage::Storage;
189#[cfg(feature = "bluetooth")]
190use crate::dom::testrunner::TestRunner;
191use crate::dom::trustedtypes::trustedtypepolicyfactory::TrustedTypePolicyFactory;
192use crate::dom::types::{FontFace, ImageBitmap, SVGSVGElement, UIEvent};
193use crate::dom::visualviewport::{VisualViewport, VisualViewportChanges};
194#[cfg(feature = "webgpu")]
195use crate::dom::webgpu::identityhub::IdentityHub;
196use crate::dom::window::layout_image::fetch_image_for_layout;
197use crate::dom::window::screen::Screen;
198use crate::dom::window::scrolling_box::{ScrollingBox, ScrollingBoxSource};
199use crate::dom::window::useractivation::UserActivationTimestamp;
200use crate::dom::windowproxy::{WindowProxy, WindowProxyHandler};
201use crate::dom::worklet::Worklet;
202use crate::dom::workletglobalscope::WorkletGlobalScopeType;
203use crate::event_loop::script_thread::ScriptThread;
204use crate::event_loop::script_window_proxies::ScriptWindowProxies;
205use crate::event_loop::timers::{IsInterval, OneshotTimers, TimerCallback};
206use crate::event_loop::webdriver_handlers::find_node_by_unique_id_in_document;
207use crate::fetch::fetch;
208use crate::fetch::network_listener::{ResourceTimingListener, submit_timing};
209use crate::messaging::{MainThreadScriptMsg, ScriptEventLoopReceiver, ScriptEventLoopSender};
210use crate::realms::enter_auto_realm;
211use crate::runtime::job_queue::UserMicrotask;
212use crate::runtime::script_runtime::Runtime;
213use crate::tasks::task_manager::TaskManager;
214use crate::tasks::task_source::SendableTaskSource;
215use crate::unminify::unminified_path;
216use crate::window_named_properties;
217
218/// A callback to call when a response comes back from the `ImageCache`.
219///
220/// This is wrapped in a struct so that we can implement `MallocSizeOf`
221/// for this type.
222#[derive(MallocSizeOf)]
223pub struct PendingImageCallback(
224    #[ignore_malloc_size_of = "dyn Fn is currently impossible to measure"]
225    #[expect(clippy::type_complexity)]
226    Box<dyn Fn(PendingImageResponse, &mut JSContext) + 'static>,
227);
228
229/// Current state of the window object
230#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
231enum WindowState {
232    Alive,
233    Zombie, // Pipeline is closed, but the window hasn't been GCed yet.
234}
235
236/// How long we should wait before performing the initial reflow after `<body>` is parsed,
237/// assuming that `<body>` take this long to parse.
238const INITIAL_REFLOW_DELAY: Duration = Duration::from_millis(200);
239
240/// During loading and parsing, layouts are suppressed to avoid flashing incomplete page
241/// contents.
242///
243/// Exceptions:
244///  - Parsing the body takes so long, that layouts are no longer suppressed in order
245///    to show the user that the page is loading.
246///  - Script triggers a layout query or scroll event in which case, we want to layout
247///    but not display the contents.
248///  - The embedder or script aborted the document load.
249///
250/// For more information see: <https://github.com/servo/servo/pull/6028>.
251#[derive(Clone, Copy, MallocSizeOf)]
252enum LayoutBlocker {
253    /// The first load event hasn't been fired and we have not started to parse the `<body>` yet.
254    WaitingForParse,
255    /// The body is being parsed the `<body>` starting at the `Instant` specified.
256    Parsing(Instant),
257    /// The blocker is no longer blocked because one or more of the following things
258    /// are true:
259    ///
260    /// - The body finished parsing and the `load` event has been fired.
261    /// - Parsing took so long, that we are going to do layout anyway.
262    /// - The load was aborted.
263    ///
264    /// Note that subsequent changes to the body can trigger parsing again, but the `Window`
265    /// stays in this state.
266    NotBlocked,
267}
268
269impl LayoutBlocker {
270    fn layout_blocked(&self) -> bool {
271        !matches!(self, Self::NotBlocked)
272    }
273}
274
275/// An id used to cancel navigations; for now only used for planned form navigations.
276/// Loosely based on <https://html.spec.whatwg.org/multipage/#ongoing-navigation>.
277#[derive(Clone, Copy, Debug, Default, JSTraceable, MallocSizeOf, PartialEq)]
278pub(crate) struct OngoingNavigation(u32);
279
280type PendingImageRasterizationKey = (PendingImageId, DeviceIntSize);
281
282/// Ancillary data of pending image request that was initiated by layout during a reflow.
283/// This data is used to faciliate invalidating layout when the image data becomes available
284/// at some point in the future.
285#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
286#[derive(JSTraceable, MallocSizeOf)]
287struct PendingLayoutImageAncillaryData {
288    node: Dom<Node>,
289    #[no_trace]
290    destination: LayoutImageDestination,
291}
292
293#[dom_struct]
294pub(crate) struct Window {
295    globalscope: GlobalScope,
296    /// A `Weak` reference to this [`ScriptThread`] used to give to child [`Window`]s so
297    /// they can more easily call methods on the [`ScriptThread`] without constantly having
298    /// to pass it everywhere.
299    #[ignore_malloc_size_of = "Weak does not need to be accounted"]
300    #[no_trace]
301    weak_script_thread: Weak<ScriptThread>,
302    /// The [`WebViewState`] for this [`Window`], shared with all other
303    /// [`Window`]s in the same `EventLoop`.
304    #[no_trace]
305    #[conditional_malloc_size_of]
306    webview_state: Rc<WebViewState>,
307    script_chan: Sender<MainThreadScriptMsg>,
308    #[no_trace]
309    #[ignore_malloc_size_of = "TODO: Add MallocSizeOf support to layout"]
310    layout: RefCell<Box<dyn Layout>>,
311    navigator: MutNullableDom<Navigator>,
312    crypto: MutNullableDom<crate::dom::crypto::Crypto>,
313    #[no_trace]
314    image_cache_sender: Sender<ImageCacheResponseMessage>,
315    window_proxy: MutNullableDom<WindowProxy>,
316    document: MutNullableDom<Document>,
317    location: MutNullableDom<Location>,
318    performance: MutNullableDom<Performance>,
319    #[no_trace]
320    navigation_start: Cell<CrossProcessInstant>,
321    screen: MutNullableDom<Screen>,
322    session_storage: MutNullableDom<Storage>,
323    local_storage: MutNullableDom<Storage>,
324    /// <https://cookiestore.spec.whatwg.org/#globals>
325    cookie_store: MutNullableDom<CookieStore>,
326    status: DomRefCell<TracedDOMString>,
327    trusted_types: MutNullableDom<TrustedTypePolicyFactory>,
328
329    /// The start of something resembling
330    /// <https://html.spec.whatwg.org/multipage/#ongoing-navigation>
331    ongoing_navigation: Cell<OngoingNavigation>,
332
333    /// <https://w3c.github.io/ServiceWorker/#global-caches-attribute>
334    caches: MutNullableDom<CacheStorage>,
335
336    /// For sending timeline markers. Will be ignored if
337    /// no devtools server
338    #[no_trace]
339    #[cfg(feature = "devtools")]
340    devtools_markers: DomRefCell<FxHashSet<devtools_traits::TimelineMarkerType>>,
341    #[no_trace]
342    #[cfg(feature = "devtools")]
343    devtools_marker_sender:
344        DomRefCell<Option<GenericSender<Option<devtools_traits::TimelineMarker>>>>,
345
346    /// Most recent unhandled resize event, if any.
347    #[no_trace]
348    unhandled_resize_event: DomRefCell<Option<(ViewportDetails, WindowSizeType)>>,
349
350    /// The viewport at the time of the last "run the resize steps".
351    ///
352    /// This allows us to detect ABA changes, and suppress firing the event in that case.
353    #[no_trace]
354    viewport_details_at_last_resize_steps: Cell<ViewportDetails>,
355
356    /// Parent id associated with this page, if any.
357    #[no_trace]
358    parent_info: Option<PipelineId>,
359
360    /// Global static data related to the DOM.
361    dom_static: GlobalStaticData,
362
363    /// The JavaScript runtime.
364    #[conditional_malloc_size_of]
365    js_runtime: DomRefCell<Option<Rc<Runtime>>>,
366
367    /// The [`ViewportDetails`] of this [`Window`]'s frame.
368    #[no_trace]
369    viewport_details: Cell<ViewportDetails>,
370
371    /// A handle for communicating messages to the bluetooth thread.
372    #[no_trace]
373    #[cfg(feature = "bluetooth")]
374    bluetooth_thread: GenericSender<BluetoothRequest>,
375
376    #[cfg(feature = "bluetooth")]
377    bluetooth_extra_permission_data: BluetoothExtraPermissionData,
378
379    /// See the documentation for [`LayoutBlocker`]. Essentially, this flag prevents
380    /// layouts from happening before the first load event, apart from a few exceptional
381    /// cases.
382    #[no_trace]
383    layout_blocker: Cell<LayoutBlocker>,
384
385    /// The current state of the window object
386    current_state: Cell<WindowState>,
387
388    error_reporter: CSSErrorReporter,
389
390    /// All the MediaQueryLists we need to update
391    media_query_lists: DOMTracker<MediaQueryList>,
392
393    #[cfg(feature = "bluetooth")]
394    test_runner: MutNullableDom<TestRunner>,
395
396    /// A handle for communicating messages to the WebGL thread, if available.
397    #[no_trace]
398    #[cfg(feature = "webgl")]
399    webgl_chan: Option<WebGLChan>,
400
401    #[no_trace]
402    #[cfg(feature = "webxr")]
403    webxr_registry: Option<webxr_api::Registry>,
404
405    /// When an element triggers an image load or starts watching an image load from the
406    /// `ImageCache` it adds an entry to this list. When those loads are triggered from
407    /// layout, they also add an etry to [`Self::pending_layout_images`].
408    #[no_trace]
409    pending_image_callbacks: DomRefCell<FxHashMap<PendingImageId, Vec<PendingImageCallback>>>,
410
411    /// All of the elements that have an outstanding image request that was
412    /// initiated by layout during a reflow. They are stored in the [`ScriptThread`]
413    /// to ensure that the element can be marked dirty when the image data becomes
414    /// available at some point in the future.
415    pending_layout_images: DomRefCell<
416        HashMapTracedValues<PendingImageId, Vec<PendingLayoutImageAncillaryData>, FxBuildHasher>,
417    >,
418
419    /// Vector images for which layout has intiated rasterization at a specific size
420    /// and whose results are not yet available. They are stored in the [`ScriptThread`]
421    /// so that the element can be marked dirty once the rasterization is completed.
422    pending_images_for_rasterization: DomRefCell<
423        HashMapTracedValues<PendingImageRasterizationKey, Vec<Dom<Node>>, FxBuildHasher>,
424    >,
425
426    /// Directory to store unminified css for this window if unminify-css
427    /// opt is enabled.
428    unminified_css_dir: DomRefCell<Option<String>>,
429
430    /// Directory with stored unminified scripts
431    local_script_source: Option<String>,
432
433    /// Worklets
434    test_worklet: MutNullableDom<Worklet>,
435    /// <https://drafts.css-houdini.org/css-paint-api-1/#paint-worklet>
436    paint_worklet: MutNullableDom<Worklet>,
437
438    /// Flag to identify whether mutation observers are present(true)/absent(false)
439    exists_mut_observer: Cell<bool>,
440
441    /// Cross-process access to `Paint`.
442    #[no_trace]
443    paint_api: CrossProcessPaintApi,
444
445    /// The [`UserScript`]s added via `UserContentManager`. These are potentially shared with other
446    /// `WebView`s in this `ScriptThread`.
447    #[no_trace]
448    #[conditional_malloc_size_of]
449    user_scripts: Rc<Vec<UserScript>>,
450
451    /// Window's GL context from application
452    #[no_trace]
453    player_context: WindowGLContext,
454
455    /// Whether or not this [`Window`] is "throttled". When this is true animations will not run
456    /// and timers will be slowed down. [`Window`]s become throttled when their [`Document`] is
457    /// no longer active or when the `WebView` that contains them is hidden.
458    throttled: Cell<bool>,
459
460    /// A shared marker for the validity of any cached layout values. A value of true
461    /// indicates that any such values remain valid; any new layout that invalidates
462    /// those values will cause the marker to be set to false.
463    #[conditional_malloc_size_of]
464    layout_marker: DomRefCell<Rc<Cell<bool>>>,
465
466    /// <https://dom.spec.whatwg.org/#window-current-event>
467    current_event: MutNullableDom<Event>,
468
469    /// <https://w3c.github.io/reporting/#windoworworkerglobalscope-registered-reporting-observer-list>
470    reporting_observer_list: DomRefCell<Vec<Dom<ReportingObserver>>>,
471
472    /// <https://w3c.github.io/reporting/#windoworworkerglobalscope-reports>
473    report_list: DomRefCell<Vec<Report>>,
474
475    /// <https://w3c.github.io/reporting/#windoworworkerglobalscope-endpoints>
476    #[no_trace]
477    endpoints_list: DomRefCell<Vec<ReportingEndpoint>>,
478
479    /// The window proxies the script thread knows.
480    #[conditional_malloc_size_of]
481    script_window_proxies: Rc<ScriptWindowProxies>,
482
483    /// Whether or not this [`Window`] has a pending screenshot readiness request.
484    has_pending_screenshot_readiness_request: Cell<bool>,
485
486    /// Visual viewport interface that is associated to this [`Window`].
487    /// <https://drafts.csswg.org/cssom-view/#dom-window-visualviewport>
488    visual_viewport: MutNullableDom<VisualViewport>,
489
490    /// [`VisualViewport`] dimension changed and we need to process it on the next tick.
491    has_changed_visual_viewport_dimension: Cell<bool>,
492
493    /// Whether something has changed since the last "update the rendering" turn
494    /// that may affect media query results, like a theme change. Consumed
495    /// together with the `resized` signal to decide whether to re-evaluate
496    /// `MediaQueryList`s and dispatch `change` events.
497    pending_media_query_evaluation: Cell<bool>,
498
499    /// <https://html.spec.whatwg.org/multipage/#last-activation-timestamp>
500    #[no_trace]
501    last_activation_timestamp: Cell<UserActivationTimestamp>,
502
503    /// A flag to indicate whether the developer tools has requested
504    /// live updates from the window.
505    devtools_wants_updates: Cell<bool>,
506
507    /// <https://www.w3.org/TR/largest-contentful-paint/#has-dispatched-scroll-event>
508    has_dispatched_scroll_event: Cell<bool>,
509
510    /// <https://wicg.github.io/event-timing/#has-dispatched-input-event>
511    has_dispatched_input_event: Cell<bool>,
512
513    /// <https://html.spec.whatwg.org/multipage/#last-history-action-activation-timestamp>
514    #[no_trace]
515    last_history_action_activation_timestamp: Cell<UserActivationTimestamp>,
516
517    /// <https://html.spec.whatwg.org/multipage/#close-watcher-manager>
518    close_watcher_manager: CloseWatcherManager,
519}
520
521impl Window {
522    pub(crate) fn script_thread(&self) -> Rc<ScriptThread> {
523        Weak::upgrade(&self.weak_script_thread)
524            .expect("Weak reference should always be upgradable when a ScriptThread is running")
525    }
526
527    pub(crate) fn webview_id(&self) -> WebViewId {
528        self.webview_state.id
529    }
530
531    pub(crate) fn webview_state(&self) -> Rc<WebViewState> {
532        self.webview_state.clone()
533    }
534
535    pub(crate) fn as_global_scope(&self) -> &GlobalScope {
536        self.upcast::<GlobalScope>()
537    }
538
539    pub(crate) fn cookie_store(&self) -> Option<DomRoot<CookieStore>> {
540        self.cookie_store.get()
541    }
542
543    /// <https://www.w3.org/TR/largest-contentful-paint/#has-dispatched-scroll-event>
544    pub(crate) fn mark_has_dispatched_scroll_event(&self) {
545        self.has_dispatched_scroll_event.set(true);
546    }
547
548    /// <https://wicg.github.io/event-timing/#has-dispatched-input-event>
549    pub(crate) fn mark_has_dispatched_input_event(&self) {
550        self.has_dispatched_input_event.set(true);
551    }
552
553    pub(crate) fn layout(&self) -> Ref<'_, Box<dyn Layout>> {
554        self.layout.borrow()
555    }
556
557    pub(crate) fn layout_mut(&self) -> RefMut<'_, Box<dyn Layout>> {
558        self.layout.borrow_mut()
559    }
560
561    pub(crate) fn get_exists_mut_observer(&self) -> bool {
562        self.exists_mut_observer.get()
563    }
564
565    pub(crate) fn set_exists_mut_observer(&self) {
566        self.exists_mut_observer.set(true);
567    }
568
569    fn clear_js_runtime_common(&self) {
570        self.stop_geolocation_watches();
571        self.as_global_scope()
572            .remove_web_messaging_and_dedicated_workers_infra();
573        self.current_state.set(WindowState::Zombie);
574        self.as_global_scope()
575            .task_manager()
576            .cancel_all_tasks_and_ignore_future_tasks();
577    }
578
579    #[expect(unsafe_code)]
580    pub(crate) fn clear_js_runtime_for_script_deallocation(&self) {
581        self.clear_js_runtime_common();
582        unsafe {
583            *self.js_runtime.borrow_for_script_deallocation() = None;
584        }
585        self.window_proxy.set(None);
586    }
587
588    /// Tell the embedder to stop producing position updates for this `Window`, so that a
589    /// location subscription does not outlive the pipeline that asked for it.
590    fn stop_geolocation_watches(&self) {
591        if let Some(geolocation) = self.maybe_geolocation() {
592            geolocation.stop_all_watches();
593        }
594    }
595
596    /// The `Geolocation` object of this `Window`'s `Navigator`.
597    pub(crate) fn maybe_geolocation(&self) -> Option<DomRoot<Geolocation>> {
598        self.navigator.get()?.maybe_geolocation()
599    }
600
601    /// A convenience method for
602    /// <https://html.spec.whatwg.org/multipage/#a-browsing-context-is-discarded>
603    pub(crate) fn discard_browsing_context(&self) {
604        let proxy = self
605            .window_proxy
606            .get()
607            .expect("Discarding a BC from a window that has none");
608        proxy.discard_browsing_context();
609
610        // Step 4 of https://html.spec.whatwg.org/multipage/#discard-a-document
611        // Other steps performed when the `PipelineExit` message
612        // is handled by the ScriptThread.
613        self.as_global_scope()
614            .task_manager()
615            .cancel_all_tasks_and_ignore_future_tasks();
616
617        // Remove any devicechange callbacks from the WebXR registry
618        // so we don't hold any references to XRSystem
619        #[cfg(feature = "webxr")]
620        if let Some(mut registry) = self.webxr_registry() {
621            registry.remove_device_change_callbacks(self.pipeline_id());
622        }
623    }
624
625    /// Get a sender to the time profiler thread.
626    pub(crate) fn time_profiler_chan(&self) -> &TimeProfilerChan {
627        self.globalscope.time_profiler_chan()
628    }
629
630    /// <https://html.spec.whatwg.org/multipage/#script-settings-for-window-objects:concept-settings-object-origin>
631    pub(crate) fn origin(&self) -> MutableOrigin {
632        // > Return the origin of window's associated Document.
633        self.Document().origin().clone()
634    }
635
636    pub(crate) fn main_thread_script_chan(&self) -> &Sender<MainThreadScriptMsg> {
637        &self.script_chan
638    }
639
640    pub(crate) fn parent_info(&self) -> Option<PipelineId> {
641        self.parent_info
642    }
643
644    pub(crate) fn new_script_pair(&self) -> (ScriptEventLoopSender, ScriptEventLoopReceiver) {
645        let (sender, receiver) = unbounded();
646        (
647            ScriptEventLoopSender::MainThread(sender),
648            ScriptEventLoopReceiver::MainThread(receiver),
649        )
650    }
651
652    pub(crate) fn event_loop_sender(&self) -> ScriptEventLoopSender {
653        ScriptEventLoopSender::MainThread(self.script_chan.clone())
654    }
655
656    pub(crate) fn image_cache(&self) -> Arc<dyn ImageCache> {
657        self.Document().image_cache()
658    }
659
660    /// This can panic if it is called after the browsing context has been discarded
661    pub(crate) fn window_proxy(&self) -> DomRoot<WindowProxy> {
662        self.window_proxy.get().unwrap()
663    }
664
665    pub(crate) fn append_reporting_observer(&self, reporting_observer: &ReportingObserver) {
666        self.reporting_observer_list
667            .borrow_mut()
668            .push(Dom::from_ref(reporting_observer));
669    }
670
671    pub(crate) fn remove_reporting_observer(&self, reporting_observer: &ReportingObserver) {
672        let index = {
673            let list = self.reporting_observer_list.borrow();
674            list.iter()
675                .position(|observer| &**observer == reporting_observer)
676        };
677
678        if let Some(index) = index {
679            self.reporting_observer_list.borrow_mut().remove(index);
680        }
681    }
682
683    pub(crate) fn registered_reporting_observers(&self) -> Vec<DomRoot<ReportingObserver>> {
684        self.reporting_observer_list
685            .borrow()
686            .iter()
687            .map(|observer| DomRoot::from_ref(&**observer))
688            .collect()
689    }
690
691    pub(crate) fn append_report(&self, report: Report) {
692        self.report_list.borrow_mut().push(report);
693        let trusted_window = Trusted::new(self);
694        self.upcast::<GlobalScope>()
695            .task_manager()
696            .dom_manipulation_task_source()
697            .queue(task!(send_to_reporting_endpoints: move || {
698                let window = trusted_window.root();
699                let reports = std::mem::take(&mut *window.report_list.borrow_mut());
700                window.upcast::<GlobalScope>().send_reports_to_endpoints(
701                    reports,
702                    window.endpoints_list.borrow().clone(),
703                );
704            }));
705    }
706
707    pub(crate) fn buffered_reports(&self) -> Vec<Report> {
708        self.report_list.borrow().clone()
709    }
710
711    pub(crate) fn set_endpoints_list(&self, endpoints: Vec<ReportingEndpoint>) {
712        *self.endpoints_list.borrow_mut() = endpoints;
713    }
714
715    /// Returns the window proxy if it has not been discarded.
716    /// <https://html.spec.whatwg.org/multipage/#a-browsing-context-is-discarded>
717    pub(crate) fn undiscarded_window_proxy(&self) -> Option<DomRoot<WindowProxy>> {
718        self.window_proxy
719            .get()
720            .filter(|window_proxy| !window_proxy.is_browsing_context_discarded())
721    }
722
723    /// Get the active [`Document`] of top-level browsing context, or return [`Window`]'s [`Document`]
724    /// if it's browing context is the top-level browsing context. Returning none if the [`WindowProxy`]
725    /// is discarded or the [`Document`] is in another `ScriptThread`.
726    /// <https://html.spec.whatwg.org/multipage/#top-level-browsing-context>
727    pub(crate) fn top_level_document_if_local(&self) -> Option<DomRoot<Document>> {
728        if self.is_top_level() {
729            return Some(self.Document());
730        }
731
732        let window_proxy = self.undiscarded_window_proxy()?;
733        self.script_window_proxies
734            .find_window_proxy(window_proxy.webview_id().into())?
735            .document()
736    }
737
738    #[cfg(feature = "bluetooth")]
739    pub(crate) fn bluetooth_thread(&self) -> GenericSender<BluetoothRequest> {
740        self.bluetooth_thread.clone()
741    }
742
743    #[cfg(feature = "bluetooth")]
744    pub(crate) fn bluetooth_extra_permission_data(&self) -> &BluetoothExtraPermissionData {
745        &self.bluetooth_extra_permission_data
746    }
747
748    pub(crate) fn css_error_reporter(&self) -> &CSSErrorReporter {
749        &self.error_reporter
750    }
751
752    #[cfg(feature = "webgl")]
753    pub(crate) fn webgl_chan(&self) -> Option<WebGLChan> {
754        self.webgl_chan.clone()
755    }
756
757    #[cfg(feature = "webxr")]
758    pub(crate) fn webxr_registry(&self) -> Option<webxr_api::Registry> {
759        self.webxr_registry.clone()
760    }
761
762    fn new_paint_worklet(&self, cx: &mut JSContext) -> DomRoot<Worklet> {
763        debug!("Creating new paint worklet.");
764
765        let worklet_global_scope_init = self.into();
766        Worklet::new(
767            cx,
768            self,
769            WorkletGlobalScopeType::Paint,
770            Box::new(|| Rc::new(StatelessWorkletThreadPool::spawn(worklet_global_scope_init))),
771        )
772    }
773
774    pub(crate) fn register_image_cache_listener(
775        &self,
776        id: PendingImageId,
777        callback: impl Fn(PendingImageResponse, &mut JSContext) + 'static,
778    ) -> ImageCacheResponseCallback {
779        self.pending_image_callbacks
780            .borrow_mut()
781            .entry(id)
782            .or_default()
783            .push(PendingImageCallback(Box::new(callback)));
784
785        let image_cache_sender = self.image_cache_sender.clone();
786        Box::new(move |message| {
787            let _ = image_cache_sender.send(message);
788        })
789    }
790
791    fn pending_layout_image_notification(&self, no_gc: &NoGC, response: PendingImageResponse) {
792        let mut images = self.pending_layout_images.borrow_mut();
793        let nodes = images.entry(response.id);
794        let nodes = match nodes {
795            Entry::Occupied(nodes) => nodes,
796            Entry::Vacant(_) => return,
797        };
798        if matches!(
799            response.response,
800            ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode
801        ) {
802            for ancillary_data in nodes.get() {
803                match ancillary_data.destination {
804                    LayoutImageDestination::BoxTreeConstruction => {
805                        ancillary_data.node.dirty(no_gc, NodeDamage::Other);
806                    },
807                    LayoutImageDestination::DisplayListBuilding => {
808                        self.layout().set_needs_new_display_list();
809                    },
810                }
811            }
812        }
813
814        match response.response {
815            ImageResponse::MetadataLoaded(_) => {},
816            ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode => {
817                nodes.remove();
818            },
819        }
820    }
821
822    pub(crate) fn handle_image_rasterization_complete_notification(
823        &self,
824        no_gc: &NoGC,
825        response: RasterizationCompleteResponse,
826    ) {
827        let mut images = self.pending_images_for_rasterization.borrow_mut();
828        let nodes = images.entry((response.image_id, response.requested_size));
829        let nodes = match nodes {
830            Entry::Occupied(nodes) => nodes,
831            Entry::Vacant(_) => return,
832        };
833        for node in nodes.get() {
834            node.dirty(no_gc, NodeDamage::Other);
835        }
836        nodes.remove();
837    }
838
839    pub(crate) fn pending_image_notification(
840        &self,
841        response: PendingImageResponse,
842        cx: &mut JSContext,
843    ) {
844        // We take the images here, in order to prevent maintaining a mutable borrow when
845        // image callbacks are called. These, in turn, can trigger garbage collection.
846        // Normally this shouldn't trigger more pending image notifications, but just in
847        // case we do not want to cause a double borrow here.
848        let mut images = std::mem::take(&mut *self.pending_image_callbacks.borrow_mut());
849        let Entry::Occupied(callbacks) = images.entry(response.id) else {
850            let _ = std::mem::replace(&mut *self.pending_image_callbacks.borrow_mut(), images);
851            return;
852        };
853
854        for callback in callbacks.get() {
855            callback.0(response.clone(), cx);
856        }
857
858        match response.response {
859            ImageResponse::MetadataLoaded(_) => {},
860            ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode => {
861                callbacks.remove();
862            },
863        }
864
865        let _ = std::mem::replace(&mut *self.pending_image_callbacks.borrow_mut(), images);
866    }
867
868    pub(crate) fn paint_api(&self) -> &CrossProcessPaintApi {
869        &self.paint_api
870    }
871
872    pub(crate) fn userscripts(&self) -> &[UserScript] {
873        &self.user_scripts
874    }
875
876    pub(crate) fn get_player_context(&self) -> WindowGLContext {
877        self.player_context.clone()
878    }
879
880    // see note at https://dom.spec.whatwg.org/#concept-event-dispatch step 2
881    pub(crate) fn dispatch_event_with_target_override(&self, cx: &mut JSContext, event: &Event) {
882        event.dispatch(cx, self.upcast(), true);
883    }
884
885    pub(crate) fn font_context(&self) -> Arc<FontContext> {
886        self.layout().font_context().clone()
887    }
888
889    pub(crate) fn ongoing_navigation(&self) -> OngoingNavigation {
890        self.ongoing_navigation.get()
891    }
892
893    /// <https://html.spec.whatwg.org/multipage/#set-the-ongoing-navigation>
894    pub(crate) fn set_ongoing_navigation(&self) -> OngoingNavigation {
895        // Note: since this value, for now, is only used in a single `ScriptThread`,
896        // we just increment it (it is not a uuid), which implies not
897        // using a `newValue` variable.
898        let new_value = self.ongoing_navigation.get().0.wrapping_add(1);
899
900        // 1. If navigable's ongoing navigation is equal to newValue, then return.
901        // Note: cannot happen in the way it is currently used.
902
903        // TODO: 2. Inform the navigation API about aborting navigation given navigable.
904
905        // 3. Set navigable's ongoing navigation to newValue.
906        self.ongoing_navigation.set(OngoingNavigation(new_value));
907
908        // Note: Return the ongoing navigation for the caller to use.
909        OngoingNavigation(new_value)
910    }
911
912    /// <https://html.spec.whatwg.org/multipage/#nav-stop>
913    fn stop_loading(&self, cx: &mut JSContext) {
914        // 1. Let document be navigable's active document.
915        let document = self.Document();
916        let was_loading = document.ReadyState() != DocumentReadyState::Complete;
917
918        // 2. If document's unload counter is 0, and navigable's ongoing navigation is a navigation
919        // ID, then set the ongoing navigation for navigable to null.
920        //
921        // Note: since the concept of `navigable` is nascent in Servo, for now we only increment the
922        // `ongoing_navigation`(preventing planned form navigations).
923        //
924        // TODO: This should also send a `AbortLoadUrl` message (in case the navigation already
925        // started at the constellation).
926        self.set_ongoing_navigation();
927
928        // 3. Abort a document and its descendants given document.
929        document.abort_a_document_and_its_descendants(cx, AbortReason::StopLoading);
930
931        // This is not in the specification, but when a load is aborted in a frame, parent
932        // frames need to be notified that this frame is no longer blocking the load.
933        // See <https://github.com/whatwg/html/issues/10252>.
934        document.notify_constellation_that_load_finished(true /* aborted */);
935
936        if self.is_top_level() && was_loading {
937            self.send_to_embedder(EmbedderMsg::NotifyLoadStatusChanged(
938                self.webview_id(),
939                LoadStatus::Stopped,
940            ));
941        }
942    }
943
944    /// <https://html.spec.whatwg.org/multipage/#destroy-a-top-level-traversable>
945    fn destroy_top_level_traversable(&self, cx: &mut JSContext) {
946        // Step 1. Let browsingContext be traversable's active browsing context.
947        // TODO
948        // Step 2. For each historyEntry in traversable's session history entries:
949        // TODO
950        // Step 2.1. Let document be historyEntry's document.
951        let document = self.Document();
952        // Step 2.2. If document is not null, then destroy a document and its descendants given document.
953        document.destroy_document_and_its_descendants(cx);
954        // Step 3-6.
955        self.send_to_constellation(ScriptToConstellationMessage::DiscardTopLevelBrowsingContext);
956    }
957
958    /// <https://html.spec.whatwg.org/multipage/#definitely-close-a-top-level-traversable>
959    fn definitely_close(&self, cx: &mut JSContext) {
960        let document = self.Document();
961        // Step 1. Let toUnload be traversable's active document's inclusive descendant navigables.
962        //
963        // Implemented by passing `false` into the method below
964        // Step 2. If the result of checking if unloading is canceled for toUnload is not "continue", then return.
965        if !document.check_if_unloading_is_cancelled(cx, false) {
966            return;
967        }
968        // Step 3. Append the following session history traversal steps to traversable:
969        // TODO
970        // Step 3.2. Unload a document and its descendants given traversable's active document, null, and afterAllUnloads.
971        document.unload(cx, false);
972        // Step 3.1. Let afterAllUnloads be an algorithm step which destroys traversable.
973        self.destroy_top_level_traversable(cx);
974    }
975
976    /// <https://html.spec.whatwg.org/multipage/#cannot-show-simple-dialogs>
977    fn cannot_show_simple_dialogs(&self) -> bool {
978        // Step 1: If the active sandboxing flag set of window's associated Document has
979        // the sandboxed modals flag set, then return true.
980        if self
981            .Document()
982            .has_active_sandboxing_flag(SandboxingFlagSet::SANDBOXED_MODALS_FLAG)
983        {
984            return true;
985        }
986
987        // Step 2: If window's relevant settings object's origin and window's relevant settings
988        // object's top-level origin are not same origin-domain, then return true.
989        //
990        // TODO: This check doesn't work currently because it seems that comparing two
991        // opaque domains doesn't work between GlobalScope::top_level_creation_url and
992        // Document::origin().
993
994        // Step 3: If window's relevant agent's event loop's termination nesting level is nonzero,
995        // then optionally return true.
996        // TODO: This is unsupported currently.
997
998        // Step 4: Optionally, return true. (For example, the user agent might give the
999        // user the option to ignore all modal dialogs, and would thus abort at this step
1000        // whenever the method was invoked.)
1001        // TODO: The embedder currently cannot block an alert before it is sent to the embedder. This
1002        // requires changes to the API.
1003
1004        // Step 5: Return false.
1005        false
1006    }
1007
1008    /// <https://html.spec.whatwg.org/multipage/#notify-the-close-watcher-manager-about-user-activation>
1009    pub(crate) fn notify_the_close_watcher_manager_about_user_activation(&self) {
1010        // Step 1. Let manager be window's close watcher manager.
1011        let manager = self.close_watcher_manager();
1012
1013        // Step 2. If manager's next user interaction allows a new group is true, then increment
1014        // manager's allowed number of groups.
1015        if manager.next_user_interaction_allows_a_new_group() {
1016            manager.increment_allowed_number_of_groups();
1017        }
1018
1019        // Step 3. Set manager's next user interaction allows a new group to false.
1020        manager.set_next_user_interaction_allows_a_new_group(false);
1021    }
1022
1023    pub(crate) fn close_watcher_manager(&self) -> &CloseWatcherManager {
1024        &self.close_watcher_manager
1025    }
1026
1027    pub(crate) fn perform_a_microtask_checkpoint(&self, cx: &mut JSContext) {
1028        self.script_thread().perform_a_microtask_checkpoint(cx);
1029    }
1030
1031    /// Part of <https://fetch.spec.whatwg.org/#populate-request-from-client>
1032    pub(crate) fn request_client(&self, no_gc: Option<&NoGC>) -> RequestClient {
1033        // Step 1.2.2. If global is a Window object and global’s navigable is not null,
1034        // then set request’s traversable for user prompts to global’s navigable’s traversable navigable.
1035        let (
1036            preloaded_resources,
1037            insecure_requests_policy,
1038            has_trustworthy_ancestor_origin,
1039            policy_container,
1040            origin,
1041            network_partition_key,
1042        ) = if let Some(no_gc) = no_gc {
1043            let document = self.document_unrooted(no_gc);
1044            (
1045                document.preloaded_resources().clone(),
1046                document.insecure_requests_policy(),
1047                document.has_trustworthy_ancestor_or_current_origin(),
1048                document.policy_container().clone(),
1049                document.origin().clone(),
1050                document.determine_the_network_partition_key(),
1051            )
1052        } else {
1053            let document = self.Document();
1054            (
1055                document.preloaded_resources().clone(),
1056                document.insecure_requests_policy(),
1057                document.has_trustworthy_ancestor_or_current_origin(),
1058                document.policy_container().clone(),
1059                document.origin().clone(),
1060                document.determine_the_network_partition_key(),
1061            )
1062        };
1063        RequestClient {
1064            preloaded_resources,
1065            policy_container,
1066            origin: Origin::Origin(origin.immutable().clone()),
1067            is_nested_browsing_context: !self.is_top_level(),
1068            insecure_requests_policy,
1069            upgrade_insecure_navigations_set: self
1070                .as_global_scope()
1071                .upgrade_insecure_navigations_set()
1072                .clone(),
1073            has_trustworthy_ancestor_origin,
1074            network_partition_key,
1075        }
1076    }
1077
1078    #[expect(unsafe_code)]
1079    pub(crate) fn gc(&self, cx: &mut JSContext) {
1080        unsafe { JS_GC(cx, GCReason::API) };
1081    }
1082
1083    #[expect(unsafe_code)]
1084    pub(crate) fn maybe_gc(&self, cx: &mut JSContext) {
1085        unsafe { JS_MaybeGC(cx) };
1086    }
1087
1088    pub(crate) fn with_timers<T>(&self, f: impl FnOnce(&OneshotTimers) -> T) -> T {
1089        let document = self.Document();
1090        f(document.timers())
1091    }
1092
1093    /// <https://html.spec.whatwg.org/multipage/#process-close-watchers>
1094    pub(crate) fn process_close_watchers(&self, cx: &mut JSContext) -> bool {
1095        // Step 1. Let processedACloseWatcher be false.
1096        let mut processed_a_close_watcher = false;
1097
1098        // Step 2. If window's close watcher manager's groups is not empty:
1099        // Step 2.1. Let group be the last item in window's close watcher manager's groups.
1100        //
1101        // We need to clone the group as request_to_close can modify the groups.
1102        let close_watcher_manager = self.close_watcher_manager();
1103        let group = close_watcher_manager.groups().last().cloned();
1104        if let Some(group) = group {
1105            // Step 2.2. For each closeWatcher of group, in reverse order:
1106            for close_watcher in group.iter().rev() {
1107                // Step 2.2.1. If the result of running closeWatcher's get enabled state is true, set processedACloseWatcher to true.
1108                if close_watcher.get_enabled_state() {
1109                    processed_a_close_watcher = true;
1110                }
1111
1112                // Step 2.2.2. Let shouldProceed be the result of requesting to close closeWatcher with true.
1113                let should_proceed = close_watcher.request_to_close(cx, true);
1114
1115                // Step 2.2.3. If shouldProceed is false, then break.
1116                if !should_proceed {
1117                    break;
1118                }
1119            }
1120        }
1121
1122        // Step 3. If window's close watcher manager's allowed number of groups is greater than 1, decrement it by 1.
1123        if close_watcher_manager.allowed_number_of_groups() > 1 {
1124            close_watcher_manager.decrement_allowed_number_of_groups();
1125        }
1126
1127        // Step 4. Return processedACloseWatcher.
1128        processed_a_close_watcher
1129    }
1130}
1131
1132#[derive(Debug, MallocSizeOf)]
1133pub(crate) struct FontCspHandler {
1134    pub(crate) task_source: SendableTaskSource,
1135}
1136
1137impl CspViolationHandler for FontCspHandler {
1138    fn process_violations(&self, violations: Vec<Violation>) {
1139        self.task_source.queue(task!(csp_violation: move |cx| {
1140            if let Some(global) = GlobalScope::current() {
1141                global.report_csp_violations(cx, violations, None, None);
1142            }
1143        }));
1144    }
1145
1146    fn clone(&self) -> Box<dyn CspViolationHandler> {
1147        Box::new(Self {
1148            task_source: self.task_source.clone(),
1149        })
1150    }
1151}
1152
1153#[derive(Debug, MallocSizeOf)]
1154pub(crate) struct FontNetworkTimingHandler {
1155    pub(crate) task_source: SendableTaskSource,
1156}
1157
1158impl NetworkTimingHandler for FontNetworkTimingHandler {
1159    fn submit_timing(&self, url: ServoUrl, response: ResourceFetchTiming) {
1160        self.task_source.queue(task!(network_timing: move |cx| {
1161            let Some(global) = GlobalScope::current() else {
1162                return
1163            };
1164
1165            submit_timing(
1166                cx,
1167                &global,
1168                &FontFetchListener {
1169                    url,
1170                },
1171                &Ok(()),
1172                &response,
1173            );
1174        }));
1175    }
1176
1177    fn clone(&self) -> Box<dyn NetworkTimingHandler> {
1178        Box::new(Self {
1179            task_source: self.task_source.clone(),
1180        })
1181    }
1182}
1183
1184#[derive(Debug)]
1185struct FontFetchListener {
1186    url: ServoUrl,
1187}
1188
1189impl ResourceTimingListener for FontFetchListener {
1190    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
1191        (InitiatorType::Css, self.url.clone())
1192    }
1193}
1194
1195/// <https://html.spec.whatwg.org/multipage/#atob>
1196pub(crate) fn base64_btoa(input: DOMString) -> Fallible<DOMString> {
1197    // "The btoa() method must throw an InvalidCharacterError exception if
1198    //  the method's first argument contains any character whose code point
1199    //  is greater than U+00FF."
1200    if input.str().chars().any(|c: char| c > '\u{FF}') {
1201        Err(Error::InvalidCharacter(None))
1202    } else {
1203        // "Otherwise, the user agent must convert that argument to a
1204        //  sequence of octets whose nth octet is the eight-bit
1205        //  representation of the code point of the nth character of
1206        //  the argument,"
1207        let octets = input
1208            .str()
1209            .chars()
1210            .map(|c: char| c as u8)
1211            .collect::<Vec<u8>>();
1212
1213        // "and then must apply the base64 algorithm to that sequence of
1214        //  octets, and return the result. [RFC4648]"
1215        let config =
1216            base64::engine::general_purpose::GeneralPurposeConfig::new().with_encode_padding(true);
1217        let engine = base64::engine::GeneralPurpose::new(&base64::alphabet::STANDARD, config);
1218        Ok(DOMString::from(engine.encode(octets)))
1219    }
1220}
1221
1222/// <https://html.spec.whatwg.org/multipage/#atob>
1223pub(crate) fn base64_atob(input: DOMString) -> Fallible<DOMString> {
1224    // "Remove all space characters from input."
1225    fn is_html_space(c: char) -> bool {
1226        HTML_SPACE_CHARACTERS.contains(&c)
1227    }
1228    let without_spaces = input
1229        .str()
1230        .chars()
1231        .filter(|&c| !is_html_space(c))
1232        .collect::<String>();
1233    let mut input = &*without_spaces;
1234
1235    // "If the length of input divides by 4 leaving no remainder, then:
1236    //  if input ends with one or two U+003D EQUALS SIGN (=) characters,
1237    //  remove them from input."
1238    if input.len() % 4 == 0 {
1239        if input.ends_with("==") {
1240            input = &input[..input.len() - 2]
1241        } else if input.ends_with('=') {
1242            input = &input[..input.len() - 1]
1243        }
1244    }
1245
1246    // "If the length of input divides by 4 leaving a remainder of 1,
1247    //  throw an InvalidCharacterError exception and abort these steps."
1248    if input.len() % 4 == 1 {
1249        return Err(Error::InvalidCharacter(None));
1250    }
1251
1252    // "If input contains a character that is not in the following list of
1253    //  characters and character ranges, throw an InvalidCharacterError
1254    //  exception and abort these steps:
1255    //
1256    //  U+002B PLUS SIGN (+)
1257    //  U+002F SOLIDUS (/)
1258    //  Alphanumeric ASCII characters"
1259    if input
1260        .chars()
1261        .any(|c| c != '+' && c != '/' && !c.is_alphanumeric())
1262    {
1263        return Err(Error::InvalidCharacter(None));
1264    }
1265
1266    let config = base64::engine::general_purpose::GeneralPurposeConfig::new()
1267        .with_decode_padding_mode(base64::engine::DecodePaddingMode::RequireNone)
1268        .with_decode_allow_trailing_bits(true);
1269    let engine = base64::engine::GeneralPurpose::new(&base64::alphabet::STANDARD, config);
1270
1271    let data = engine
1272        .decode(input)
1273        .map_err(|_| Error::InvalidCharacter(None))?;
1274    Ok(data.iter().map(|&b| b as char).collect::<String>().into())
1275}
1276
1277impl WindowMethods<crate::DomTypeHolder> for Window {
1278    /// <https://html.spec.whatwg.org/multipage/#dom-alert>
1279    fn Alert_(&self) {
1280        // Step 2: If the method was invoked with no arguments, then let message be the
1281        // empty string; otherwise, let message be the method's first argument.
1282        self.Alert(DOMString::new());
1283    }
1284
1285    /// <https://html.spec.whatwg.org/multipage/#dom-alert>
1286    fn Alert(&self, mut message: DOMString) {
1287        // Step 1: If we cannot show simple dialogs for this, then return.
1288        if self.cannot_show_simple_dialogs() {
1289            return;
1290        }
1291
1292        // Step 2 is handled in the other variant of this method.
1293        //
1294        // Step 3: Set message to the result of normalizing newlines given message.
1295        message.normalize_newlines();
1296
1297        // Step 4. Set message to the result of optionally truncating message.
1298        // This is up to the embedder.
1299
1300        // Step 5: Let userPromptHandler be WebDriver BiDi user prompt opened with this,
1301        // "alert", and message.
1302        // TODO: Add support for WebDriver BiDi.
1303
1304        // Step 6: If userPromptHandler is "none", then:
1305        //  1. Show message to the user, treating U+000A LF as a line break.
1306        //  2. Optionally, pause while waiting for the user to acknowledge the message.
1307        {
1308            // Print to the console.
1309            // Ensure that stderr doesn't trample through the alert() we use to
1310            // communicate test results (see executorservo.py in wptrunner).
1311            let stderr = stderr();
1312            let mut stderr = stderr.lock();
1313            let stdout = stdout();
1314            let mut stdout = stdout.lock();
1315            writeln!(&mut stdout, "\nALERT: {message}").unwrap();
1316            stdout.flush().unwrap();
1317            stderr.flush().unwrap();
1318        }
1319
1320        let (sender, receiver) =
1321            ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1322        let dialog = SimpleDialogRequest::Alert {
1323            id: self.Document().embedder_controls().next_control_id(),
1324            message: String::from(message),
1325            response_sender: sender,
1326        };
1327        self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1328        receiver.recv().unwrap_or_else(|_| {
1329            // If the receiver is closed, we assume the dialog was cancelled.
1330            debug!("Alert dialog was cancelled or failed to show.");
1331            AlertResponse::Ok
1332        });
1333
1334        // Step 7: Invoke WebDriver BiDi user prompt closed with this, "alert", and true.
1335        // TODO: Implement support for WebDriver BiDi.
1336    }
1337
1338    /// <https://w3c.github.io/ServiceWorker/#global-caches-attribute>
1339    fn Caches(&self, cx: &mut JSContext) -> DomRoot<CacheStorage> {
1340        self.caches
1341            .or_init(|| CacheStorage::new(cx, self.as_global_scope()))
1342    }
1343
1344    /// <https://html.spec.whatwg.org/multipage/#dom-confirm>
1345    fn Confirm(&self, mut message: DOMString) -> bool {
1346        // Step 1: If we cannot show simple dialogs for this, then return false.
1347        if self.cannot_show_simple_dialogs() {
1348            return false;
1349        }
1350
1351        // Step 2: Set message to the result of normalizing newlines given message.
1352        message.normalize_newlines();
1353
1354        // Step 3: Set message to the result of optionally truncating message.
1355        // We let the embedder handle this.
1356
1357        // Step 4: Show message to the user, treating U+000A LF as a line break, and ask
1358        // the user to respond with a positive or negative response.
1359        let (sender, receiver) =
1360            ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1361        let dialog = SimpleDialogRequest::Confirm {
1362            id: self.Document().embedder_controls().next_control_id(),
1363            message: String::from(message),
1364            response_sender: sender,
1365        };
1366        self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1367
1368        // Step 5: Let userPromptHandler be WebDriver BiDi user prompt opened with this,
1369        // "confirm", and message.
1370        //
1371        // Step 6: Let accepted be false.
1372        //
1373        // Step 7: If userPromptHandler is "none", then:
1374        //  1. Pause until the user responds either positively or negatively.
1375        //  2. If the user responded positively, then set accepted to true.
1376        //
1377        // Step 8: If userPromptHandler is "accept", then set accepted to true.
1378        //
1379        // Step 9: Invoke WebDriver BiDi user prompt closed with this, "confirm", and accepted.
1380        // TODO: Implement WebDriver BiDi and handle these steps.
1381        //
1382        // Step 10: Return accepted.
1383        match receiver.recv() {
1384            Ok(ConfirmResponse::Ok) => true,
1385            Ok(ConfirmResponse::Cancel) => false,
1386            Err(_) => {
1387                warn!("Confirm dialog was cancelled or failed to show.");
1388                false
1389            },
1390        }
1391    }
1392
1393    /// <https://html.spec.whatwg.org/multipage/#dom-prompt>
1394    fn Prompt(&self, mut message: DOMString, default: DOMString) -> Option<DOMString> {
1395        // Step 1: If we cannot show simple dialogs for this, then return null.
1396        if self.cannot_show_simple_dialogs() {
1397            return None;
1398        }
1399
1400        // Step 2: Set message to the result of normalizing newlines given message.
1401        message.normalize_newlines();
1402
1403        // Step 3. Set message to the result of optionally truncating message.
1404        // Step 4: Set default to the result of optionally truncating default.
1405        // We let the embedder handle these steps.
1406
1407        // Step 5: Show message to the user, treating U+000A LF as a line break, and ask
1408        // the user to either respond with a string value or abort. The response must be
1409        // defaulted to the value given by default.
1410        let (sender, receiver) =
1411            ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1412        let dialog = SimpleDialogRequest::Prompt {
1413            id: self.Document().embedder_controls().next_control_id(),
1414            message: String::from(message),
1415            default: String::from(default),
1416            response_sender: sender,
1417        };
1418        self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1419
1420        // Step 6: Let userPromptHandler be WebDriver BiDi user prompt opened with this,
1421        // "prompt", and message.
1422        // TODO: Add support for WebDriver BiDi.
1423        //
1424        // Step 7: Let result be null.
1425        //
1426        // Step 8: If userPromptHandler is "none", then:
1427        //  1. Pause while waiting for the user's response.
1428        //  2. If the user did not abort, then set result to the string that the user responded with.
1429        //
1430        // Step 9: Otherwise, if userPromptHandler is "accept", then set result to the empty string.
1431        // TODO: Implement this.
1432        //
1433        // Step 10: Invoke WebDriver BiDi user prompt closed with this, "prompt", false if
1434        // result is null or true otherwise, and result.
1435        // TODO: Add support for WebDriver BiDi.
1436        //
1437        // Step 11: Return result.
1438        match receiver.recv() {
1439            Ok(PromptResponse::Ok(input)) => Some(input.into()),
1440            Ok(PromptResponse::Cancel) => None,
1441            Err(_) => {
1442                warn!("Prompt dialog was cancelled or failed to show.");
1443                None
1444            },
1445        }
1446    }
1447
1448    /// <https://html.spec.whatwg.org/multipage/#dom-window-stop>
1449    fn Stop(&self, cx: &mut JSContext) {
1450        // 1. If this's navigable is null, then return.
1451        // Note: Servo doesn't have a concept of navigable yet.
1452
1453        // 2. Stop loading this's navigable.
1454        self.stop_loading(cx);
1455    }
1456
1457    /// <https://html.spec.whatwg.org/multipage/#dom-window-focus>
1458    fn Focus(&self, cx: &mut JSContext) {
1459        // Step 1. Let current be this's navigable.
1460        // Note: We don't necessarily have access to the navigable, because it might
1461        // be in another process.
1462
1463        // Step 2. If current is null, then return.
1464        //
1465        // Note: This is equivalent to there being an active `Document`.
1466        let document = self.Document();
1467        if !document.is_active() {
1468            return;
1469        }
1470
1471        // Step 3. If the allow focus steps given current's active document return false, then return.
1472        // TODO: Implement this.
1473
1474        // Step 4. Run the focusing steps with current.
1475        document
1476            .focus_handler()
1477            .focus(cx, &FocusableArea::Viewport, FocusTrigger::Script);
1478
1479        // Step 5. If current is a top-level traversable, user agents are encouraged to trigger some
1480        // sort of notification to indicate to the user that the page is attempting to gain focus.
1481        //
1482        // Note: We currently don't do this. Most browsers don't.
1483    }
1484
1485    /// <https://html.spec.whatwg.org/multipage/#dom-window-blur>
1486    fn Blur(&self) {
1487        // > User agents are encouraged to ignore calls to this `blur()` method
1488        // > entirely.
1489    }
1490
1491    /// <https://html.spec.whatwg.org/multipage/#dom-open>
1492    fn Open(
1493        &self,
1494        cx: &mut JSContext,
1495        url: USVString,
1496        target: DOMString,
1497        features: DOMString,
1498    ) -> Fallible<Option<DomRoot<WindowProxy>>> {
1499        self.window_proxy().open(cx, url, target, features)
1500    }
1501
1502    /// <https://html.spec.whatwg.org/multipage/#dom-opener>
1503    fn GetOpener(&self, cx: &mut CurrentRealm, mut retval: MutableHandleValue) -> Fallible<()> {
1504        // Step 1, Let current be this Window object's browsing context.
1505        let current = match self.window_proxy.get() {
1506            Some(proxy) => proxy,
1507            // Step 2, If current is null, then return null.
1508            None => {
1509                retval.set(NullValue());
1510                return Ok(());
1511            },
1512        };
1513        // Still step 2, since the window's BC is the associated doc's BC,
1514        // see https://html.spec.whatwg.org/multipage/#window-bc
1515        // and a doc's BC is null if it has been discarded.
1516        // see https://html.spec.whatwg.org/multipage/#concept-document-bc
1517        if current.is_browsing_context_discarded() {
1518            retval.set(NullValue());
1519            return Ok(());
1520        }
1521        // Step 3 to 5.
1522        current.opener(cx, retval);
1523        Ok(())
1524    }
1525
1526    /// <https://html.spec.whatwg.org/multipage/#dom-opener>
1527    fn SetOpener(&self, cx: &mut JSContext, value: HandleValue) -> ErrorResult {
1528        // Step 1.
1529        if value.is_null() {
1530            if let Some(proxy) = self.window_proxy.get() {
1531                proxy.disown();
1532            }
1533            return Ok(());
1534        }
1535
1536        // Step 2.
1537        let obj = self.reflector().get_jsobject();
1538        let result = JS_DefineProperty(
1539            cx,
1540            obj,
1541            c"opener",
1542            value,
1543            PropertyFlags::ENUMERABLE | PropertyFlags::WRITABLE | PropertyFlags::CONFIGURABLE,
1544        );
1545
1546        if result { Ok(()) } else { Err(Error::JSFailed) }
1547    }
1548
1549    /// <https://html.spec.whatwg.org/multipage/#dom-window-closed>
1550    fn Closed(&self) -> bool {
1551        self.window_proxy
1552            .get()
1553            .map(|ref proxy| proxy.is_browsing_context_discarded() || proxy.is_closing())
1554            .unwrap_or(true)
1555    }
1556
1557    /// <https://html.spec.whatwg.org/multipage/#dom-window-close>
1558    fn Close(&self, cx: &mut JSContext) {
1559        // Step 1. Let thisTraversable be this's navigable.
1560        let window_proxy = match self.window_proxy.get() {
1561            Some(proxy) => proxy,
1562            // Step 2. If thisTraversable is not a top-level traversable, then return.
1563            None => return,
1564        };
1565        // Step 3. If thisTraversable's is closing is true, then return.
1566        if window_proxy.is_closing() {
1567            return;
1568        }
1569        // Note: check the length of the "session history", as opposed to the joint session history?
1570        // see https://github.com/whatwg/html/issues/3734
1571        if let Ok(history_length) = self.History(cx).GetLength() {
1572            let is_auxiliary = window_proxy.is_auxiliary();
1573
1574            // https://html.spec.whatwg.org/multipage/#script-closable
1575            let is_script_closable = (self.is_top_level() && history_length == 1) ||
1576                is_auxiliary ||
1577                pref!(dom_allow_scripts_to_close_windows);
1578
1579            // TODO: rest of Step 3:
1580            // Is the incumbent settings object's responsible browsing context familiar with current?
1581            // Is the incumbent settings object's responsible browsing context allowed to navigate current?
1582            if is_script_closable {
1583                // Step 6.1. Set thisTraversable's is closing to true.
1584                window_proxy.close();
1585
1586                // Step 6.2. Queue a task on the DOM manipulation task source to definitely close thisTraversable.
1587                let this = Trusted::new(self);
1588                let task = task!(window_close_browsing_context: move |cx| {
1589                    let window = this.root();
1590                    window.definitely_close(cx);
1591                });
1592                self.as_global_scope()
1593                    .task_manager()
1594                    .dom_manipulation_task_source()
1595                    .queue(task);
1596            }
1597        }
1598    }
1599
1600    /// <https://html.spec.whatwg.org/multipage/#dom-document-2>
1601    fn Document(&self) -> DomRoot<Document> {
1602        self.document
1603            .get()
1604            .expect("Document accessed before initialization.")
1605    }
1606
1607    /// <https://html.spec.whatwg.org/multipage/#dom-history>
1608    fn History(&self, cx: &mut JSContext) -> DomRoot<History> {
1609        self.Document().history(cx)
1610    }
1611
1612    /// <https://w3c.github.io/IndexedDB/#factory-interface>
1613    fn IndexedDB(&self, cx: &mut JSContext) -> DomRoot<IDBFactory> {
1614        self.upcast::<GlobalScope>().ensure_indexeddb_factory(cx)
1615    }
1616
1617    /// <https://html.spec.whatwg.org/multipage/#dom-window-customelements>
1618    fn CustomElements(&self, cx: &mut JSContext) -> DomRoot<CustomElementRegistry> {
1619        // Step 1: Assert: this's associated Document's custom element registry is
1620        // a CustomElementRegistry object.
1621        let document = self.Document();
1622        if let Some(registry) = document.custom_element_registry() {
1623            return registry;
1624        }
1625        // A Window's associated Document is always created with
1626        // a new CustomElementRegistry object.
1627        let registry = CustomElementRegistry::new(cx, self);
1628        document.set_custom_element_registry(&registry);
1629        // Step 2: Return this's associated Document's custom element registry.
1630        registry
1631    }
1632
1633    /// <https://html.spec.whatwg.org/multipage/#dom-location>
1634    fn Location(&self, cx: &mut JSContext) -> DomRoot<Location> {
1635        self.location.or_init(|| Location::new(cx, self))
1636    }
1637
1638    /// <https://html.spec.whatwg.org/multipage/#dom-sessionstorage>
1639    fn GetSessionStorage(&self, cx: &mut JSContext) -> Fallible<DomRoot<Storage>> {
1640        // Step 1. If this's associated Document's session storage holder is non-null,
1641        // then return this's associated Document's session storage holder.
1642        if let Some(storage) = self.session_storage.get() {
1643            return Ok(storage);
1644        }
1645
1646        // Step 2. Let map be the result of running obtain a session storage bottle map
1647        // with this's relevant settings object and "sessionStorage".
1648        // Step 3. If map is failure, then throw a "SecurityError" DOMException.
1649        if !self.origin().is_tuple() {
1650            return Err(Error::Security(Some(
1651                "Cannot access sessionStorage from opaque origin.".to_string(),
1652            )));
1653        }
1654
1655        // Step 4. Let storage be a new Storage object whose map is map.
1656        let storage = Storage::new(cx, self, WebStorageType::Session);
1657
1658        // Step 5. Set this's associated Document's session storage holder to storage.
1659        self.session_storage.set(Some(&storage));
1660
1661        // Step 6. Return storage.
1662        Ok(storage)
1663    }
1664
1665    /// <https://html.spec.whatwg.org/multipage/#dom-localstorage>
1666    fn GetLocalStorage(&self, cx: &mut JSContext) -> Fallible<DomRoot<Storage>> {
1667        // Step 1. If this's associated Document's local storage holder is non-null,
1668        // then return this's associated Document's local storage holder.
1669        if let Some(storage) = self.local_storage.get() {
1670            return Ok(storage);
1671        }
1672
1673        // Step 2. Let map be the result of running obtain a local storage bottle map
1674        // with this's relevant settings object and "localStorage".
1675        // Step 3. If map is failure, then throw a "SecurityError" DOMException.
1676        if !self.origin().is_tuple() {
1677            return Err(Error::Security(Some(
1678                "Cannot access localStorage from opaque origin.".to_string(),
1679            )));
1680        }
1681
1682        // Step 4. Let storage be a new Storage object whose map is map.
1683        let storage = Storage::new(cx, self, WebStorageType::Local);
1684
1685        // Step 5. Set this's associated Document's local storage holder to storage.
1686        self.local_storage.set(Some(&storage));
1687
1688        // Step 6. Return storage.
1689        Ok(storage)
1690    }
1691
1692    /// <https://cookiestore.spec.whatwg.org/#Window>
1693    fn CookieStore(&self, cx: &mut JSContext) -> DomRoot<CookieStore> {
1694        self.cookie_store
1695            .or_init(|| CookieStore::new(cx, self.upcast::<GlobalScope>()))
1696    }
1697
1698    /// <https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#dfn-GlobalCrypto>
1699    fn Crypto(&self, cx: &mut JSContext) -> DomRoot<crate::dom::crypto::Crypto> {
1700        self.crypto
1701            .or_init(|| crate::dom::crypto::Crypto::new(cx, self.as_global_scope()))
1702    }
1703
1704    /// <https://html.spec.whatwg.org/multipage/#dom-frameelement>
1705    fn GetFrameElement(&self) -> Option<DomRoot<Element>> {
1706        // Steps 1-3.
1707        let window_proxy = self.window_proxy.get()?;
1708
1709        // Step 4-5.
1710        let container = window_proxy.frame_element()?;
1711
1712        // Step 6.
1713        let container_doc = container.owner_document();
1714        let current_doc = GlobalScope::current()
1715            .expect("No current global object")
1716            .as_window()
1717            .Document();
1718        if !current_doc
1719            .origin()
1720            .same_origin_domain(&container_doc.origin())
1721        {
1722            return None;
1723        }
1724        // Step 7.
1725        Some(DomRoot::from_ref(container))
1726    }
1727
1728    /// <https://html.spec.whatwg.org/multipage/#dom-reporterror>
1729    fn ReportError(&self, cx: &mut JSContext, error: HandleValue) {
1730        self.as_global_scope().report_an_exception(cx, error);
1731    }
1732
1733    /// <https://html.spec.whatwg.org/multipage/#dom-navigator>
1734    fn Navigator(&self, cx: &mut JSContext) -> DomRoot<Navigator> {
1735        self.navigator.or_init(|| Navigator::new(cx, self))
1736    }
1737
1738    /// <https://html.spec.whatwg.org/multipage/#dom-clientinformation>
1739    fn ClientInformation(&self, cx: &mut JSContext) -> DomRoot<Navigator> {
1740        self.Navigator(cx)
1741    }
1742
1743    /// <https://html.spec.whatwg.org/multipage/#dom-settimeout>
1744    fn SetTimeout(
1745        &self,
1746        cx: &mut JSContext,
1747        callback: TrustedScriptOrStringOrFunction,
1748        timeout: i32,
1749        args: Vec<HandleValue>,
1750    ) -> Fallible<i32> {
1751        let callback = match callback {
1752            TrustedScriptOrStringOrFunction::String(i) => {
1753                TimerCallback::StringTimerCallback(TrustedScriptOrString::String(i))
1754            },
1755            TrustedScriptOrStringOrFunction::TrustedScript(i) => {
1756                TimerCallback::StringTimerCallback(TrustedScriptOrString::TrustedScript(i))
1757            },
1758            TrustedScriptOrStringOrFunction::Function(i) => TimerCallback::FunctionTimerCallback(i),
1759        };
1760        self.as_global_scope().set_timeout_or_interval(
1761            cx,
1762            callback,
1763            args,
1764            Duration::from_millis(timeout.max(0) as u64),
1765            IsInterval::NonInterval,
1766        )
1767    }
1768
1769    /// <https://html.spec.whatwg.org/multipage/#dom-windowtimers-cleartimeout>
1770    fn ClearTimeout(&self, handle: i32) {
1771        self.as_global_scope().clear_timeout_or_interval(handle);
1772    }
1773
1774    /// <https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval>
1775    fn SetInterval(
1776        &self,
1777        cx: &mut JSContext,
1778        callback: TrustedScriptOrStringOrFunction,
1779        timeout: i32,
1780        args: Vec<HandleValue>,
1781    ) -> Fallible<i32> {
1782        let callback = match callback {
1783            TrustedScriptOrStringOrFunction::String(i) => {
1784                TimerCallback::StringTimerCallback(TrustedScriptOrString::String(i))
1785            },
1786            TrustedScriptOrStringOrFunction::TrustedScript(i) => {
1787                TimerCallback::StringTimerCallback(TrustedScriptOrString::TrustedScript(i))
1788            },
1789            TrustedScriptOrStringOrFunction::Function(i) => TimerCallback::FunctionTimerCallback(i),
1790        };
1791        self.as_global_scope().set_timeout_or_interval(
1792            cx,
1793            callback,
1794            args,
1795            Duration::from_millis(timeout.max(0) as u64),
1796            IsInterval::Interval,
1797        )
1798    }
1799
1800    /// <https://html.spec.whatwg.org/multipage/#dom-windowtimers-clearinterval>
1801    fn ClearInterval(&self, handle: i32) {
1802        self.ClearTimeout(handle);
1803    }
1804
1805    /// <https://html.spec.whatwg.org/multipage/#dom-queuemicrotask>
1806    fn QueueMicrotask(&self, cx: &JSContext, callback: RootedCallback<VoidFunction>) {
1807        ScriptThread::enqueue_microtask(
1808            cx,
1809            Box::new(UserMicrotask {
1810                callback: callback.to_traced(),
1811                global: Dom::from_ref(&self.globalscope),
1812            }),
1813        );
1814    }
1815
1816    /// <https://html.spec.whatwg.org/multipage/#dom-createimagebitmap>
1817    fn CreateImageBitmap(
1818        &self,
1819        realm: &mut CurrentRealm,
1820        image: ImageBitmapSource,
1821        options: &ImageBitmapOptions,
1822    ) -> RootedPromise {
1823        ImageBitmap::create_image_bitmap(
1824            self.as_global_scope(),
1825            image,
1826            0,
1827            0,
1828            None,
1829            None,
1830            options,
1831            realm,
1832        )
1833    }
1834
1835    /// <https://html.spec.whatwg.org/multipage/#dom-createimagebitmap>
1836    fn CreateImageBitmap_(
1837        &self,
1838        realm: &mut CurrentRealm,
1839        image: ImageBitmapSource,
1840        sx: i32,
1841        sy: i32,
1842        sw: i32,
1843        sh: i32,
1844        options: &ImageBitmapOptions,
1845    ) -> RootedPromise {
1846        ImageBitmap::create_image_bitmap(
1847            self.as_global_scope(),
1848            image,
1849            sx,
1850            sy,
1851            Some(sw),
1852            Some(sh),
1853            options,
1854            realm,
1855        )
1856    }
1857
1858    /// <https://html.spec.whatwg.org/multipage/#dom-window>
1859    fn Window(&self) -> DomRoot<WindowProxy> {
1860        self.window_proxy()
1861    }
1862
1863    /// <https://html.spec.whatwg.org/multipage/#dom-self>
1864    fn Self_(&self) -> DomRoot<WindowProxy> {
1865        self.window_proxy()
1866    }
1867
1868    /// <https://html.spec.whatwg.org/multipage/#dom-frames>
1869    fn Frames(&self) -> DomRoot<WindowProxy> {
1870        self.window_proxy()
1871    }
1872
1873    /// <https://html.spec.whatwg.org/multipage/#accessing-other-browsing-contexts>
1874    fn Length(&self) -> u32 {
1875        self.Document().iframes().active_iframe_count() as u32
1876    }
1877
1878    /// <https://html.spec.whatwg.org/multipage/#dom-parent>
1879    fn GetParent(&self) -> Option<DomRoot<WindowProxy>> {
1880        // Steps 1-3.
1881        let window_proxy = self.undiscarded_window_proxy()?;
1882
1883        // Step 4.
1884        if let Some(parent) = window_proxy.parent() {
1885            return Some(DomRoot::from_ref(parent));
1886        }
1887        // Step 5.
1888        Some(window_proxy)
1889    }
1890
1891    /// <https://html.spec.whatwg.org/multipage/#dom-top>
1892    fn GetTop(&self) -> Option<DomRoot<WindowProxy>> {
1893        // Steps 1-3.
1894        let window_proxy = self.undiscarded_window_proxy()?;
1895
1896        // Steps 4-5.
1897        Some(DomRoot::from_ref(window_proxy.top()))
1898    }
1899
1900    // https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/
1901    // NavigationTiming/Overview.html#sec-window.performance-attribute
1902    fn Performance(&self, cx: &mut JSContext) -> DomRoot<Performance> {
1903        self.performance
1904            .or_init(|| Performance::new(cx, self.as_global_scope(), self.navigation_start.get()))
1905    }
1906
1907    // https://html.spec.whatwg.org/multipage/#globaleventhandlers
1908    global_event_handlers!();
1909
1910    // https://html.spec.whatwg.org/multipage/#windoweventhandlers
1911    window_event_handlers!();
1912
1913    /// <https://developer.mozilla.org/en-US/docs/Web/API/Window/screen>
1914    fn Screen(&self, cx: &mut JSContext) -> DomRoot<Screen> {
1915        self.screen.or_init(|| Screen::new(cx, self))
1916    }
1917
1918    /// <https://drafts.csswg.org/cssom-view/#dom-window-visualviewport>
1919    fn GetVisualViewport(&self, cx: &mut JSContext) -> Option<DomRoot<VisualViewport>> {
1920        // > If the associated document is fully active, the visualViewport attribute must return the
1921        // > VisualViewport object associated with the Window object’s associated document. Otherwise,
1922        // > it must return null.
1923        if !self.Document().is_fully_active() {
1924            return None;
1925        }
1926
1927        Some(self.get_or_init_visual_viewport(cx))
1928    }
1929
1930    /// <https://html.spec.whatwg.org/multipage/#dom-windowbase64-btoa>
1931    fn Btoa(&self, btoa: DOMString) -> Fallible<DOMString> {
1932        base64_btoa(btoa)
1933    }
1934
1935    /// <https://html.spec.whatwg.org/multipage/#dom-windowbase64-atob>
1936    fn Atob(&self, atob: DOMString) -> Fallible<DOMString> {
1937        base64_atob(atob)
1938    }
1939
1940    /// <https://html.spec.whatwg.org/multipage/#dom-window-requestanimationframe>
1941    fn RequestAnimationFrame(
1942        &self,
1943        callback: RootedCallback<FrameRequestCallback>,
1944    ) -> Fallible<u32> {
1945        Ok(self
1946            .Document()
1947            .request_animation_frame(AnimationFrameCallback::FrameRequestCallback {
1948                callback: callback.to_traced(),
1949            }))
1950    }
1951
1952    /// <https://html.spec.whatwg.org/multipage/#dom-window-cancelanimationframe>
1953    fn CancelAnimationFrame(&self, ident: u32) -> ErrorResult {
1954        let doc = self.Document();
1955        doc.cancel_animation_frame(ident);
1956        Ok(())
1957    }
1958
1959    /// <https://html.spec.whatwg.org/multipage/#dom-window-postmessage>
1960    fn PostMessage(
1961        &self,
1962        cx: &mut JSContext,
1963        message: HandleValue,
1964        target_origin: USVString,
1965        transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
1966    ) -> ErrorResult {
1967        let incumbent = GlobalScope::incumbent().expect("no incumbent global?");
1968        let source = incumbent.as_window();
1969        let source_origin = source.Document().origin().immutable().clone();
1970
1971        self.post_message_impl(&target_origin, source_origin, source, cx, message, transfer)
1972    }
1973
1974    /// <https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage>
1975    fn PostMessage_(
1976        &self,
1977        cx: &mut JSContext,
1978        message: HandleValue,
1979        options: &WindowPostMessageOptions,
1980    ) -> ErrorResult {
1981        auto_root!(&in(cx) let transfer =
1982            options
1983                .parent
1984                .transfer
1985                .iter()
1986                .map(|js| js.get())
1987                .collect::<Vec<_>>());
1988
1989        let incumbent = GlobalScope::incumbent().expect("no incumbent global?");
1990        let source = incumbent.as_window();
1991
1992        let source_origin = source.Document().origin().immutable().clone();
1993
1994        self.post_message_impl(
1995            &options.targetOrigin,
1996            source_origin,
1997            source,
1998            cx,
1999            message,
2000            transfer,
2001        )
2002    }
2003
2004    /// <https://html.spec.whatwg.org/multipage/#dom-window-captureevents>
2005    fn CaptureEvents(&self) {
2006        // This method intentionally does nothing
2007    }
2008
2009    /// <https://html.spec.whatwg.org/multipage/#dom-window-releaseevents>
2010    fn ReleaseEvents(&self) {
2011        // This method intentionally does nothing
2012    }
2013
2014    fn WebdriverElement(&self, id: DOMString) -> Option<DomRoot<Element>> {
2015        find_node_by_unique_id_in_document(&self.Document(), id.into()).and_then(Root::downcast)
2016    }
2017
2018    fn WebdriverFrame(&self, browsing_context_id: DOMString) -> Option<DomRoot<WindowProxy>> {
2019        self.Document()
2020            .iframes()
2021            .iter()
2022            .find(|iframe| {
2023                iframe
2024                    .browsing_context_id()
2025                    .as_ref()
2026                    .map(BrowsingContextId::to_string) ==
2027                    Some(browsing_context_id.to_string())
2028            })
2029            .and_then(|iframe| iframe.GetContentWindow())
2030    }
2031
2032    fn WebdriverWindow(&self, webview_id: DOMString) -> DomRoot<WindowProxy> {
2033        let window_proxy = &self
2034            .window_proxy
2035            .get()
2036            .expect("Should always have a WindowProxy when calling WebdriverWindow");
2037        assert!(
2038            self.is_top_level(),
2039            "Window must be top level browsing context."
2040        );
2041        assert!(self.webview_id().to_string() == webview_id);
2042        DomRoot::from_ref(window_proxy)
2043    }
2044
2045    fn WebdriverShadowRoot(&self, id: DOMString) -> Option<DomRoot<ShadowRoot>> {
2046        find_node_by_unique_id_in_document(&self.Document(), id.into()).and_then(Root::downcast)
2047    }
2048
2049    /// <https://drafts.csswg.org/cssom/#dom-window-getcomputedstyle>
2050    fn GetComputedStyle(
2051        &self,
2052        cx: &mut JSContext,
2053        element: &Element,
2054        pseudo: Option<DOMString>,
2055    ) -> DomRoot<CSSStyleDeclaration> {
2056        // Step 2: Let obj be elt.
2057        // We don't store CSSStyleOwner directly because it stores a `Dom` which must be
2058        // rooted. This avoids the rooting the value temporarily.
2059        let mut is_null = false;
2060
2061        // Step 3: If pseudoElt is provided, is not the empty string, and starts with a colon, then:
2062        let pseudo = pseudo
2063            .filter(|pseudo| pseudo.starts_with(':'))
2064            .and_then(|pseudo| {
2065                // Step 3.1: Parse pseudoElt as a <pseudo-element-selector>, and let type be the result.
2066                let pseudo = pseudo.str();
2067                let pseudo = pseudo
2068                    .strip_prefix("::")
2069                    .or_else(|| {
2070                        pseudo
2071                            .strip_prefix(":")
2072                            .filter(|pseudo_name| is_css2_pseudo_element(pseudo_name))
2073                    })
2074                    .and_then(|pseudo_name| {
2075                        SelectorParser {
2076                            stylesheet_origin: StyleOrigin::Author,
2077                            namespaces: &Default::default(),
2078                            url_data: &UrlExtraData(self.Document().url().get_arc()),
2079                            for_supports_rule: false,
2080                        }
2081                        .parse_pseudo_element(pseudo_name)
2082                        .ok()
2083                    });
2084                // Step 3.2: If type is failure, or is a ::slotted() or ::part()
2085                // pseudo-element, let obj be null.
2086                is_null = pseudo.is_none();
2087                pseudo
2088            });
2089
2090        // Step 4. Let decls be an empty list of CSS declarations.
2091        // Step 5: If obj is not null, and elt is connected, part of the flat tree, and
2092        // its shadow-including root has a browsing context which either doesn’t have a
2093        // browsing context container, or whose browsing context container is being
2094        // rendered, set decls to a list of all longhand properties that are supported CSS
2095        // properties, in lexicographical order, with the value being the resolved value
2096        // computed for obj using the style rules associated with doc.  Additionally,
2097        // append to decls all the custom properties whose computed value for obj is not
2098        // the guaranteed-invalid value.
2099        //
2100        // Note: The specification says to generate the list of declarations beforehand, yet
2101        // also says the list should be alive. This is why we do not do step 4 and 5 here.
2102        // See: https://github.com/w3c/csswg-drafts/issues/6144
2103        //
2104        // Step 6:  Return a live CSSStyleProperties object with the following properties:
2105        CSSStyleDeclaration::new(
2106            cx,
2107            self,
2108            if is_null {
2109                CSSStyleOwner::Null
2110            } else {
2111                CSSStyleOwner::Element(Dom::from_ref(element))
2112            },
2113            pseudo,
2114            CSSModificationAccess::Readonly,
2115        )
2116    }
2117
2118    // https://drafts.csswg.org/cssom-view/#dom-window-innerheight
2119    // TODO Include Scrollbar
2120    fn InnerHeight(&self) -> i32 {
2121        self.viewport_details
2122            .get()
2123            .size
2124            .height
2125            .to_i32()
2126            .unwrap_or(0)
2127    }
2128
2129    // https://drafts.csswg.org/cssom-view/#dom-window-innerwidth
2130    // TODO Include Scrollbar
2131    fn InnerWidth(&self) -> i32 {
2132        self.viewport_details.get().size.width.to_i32().unwrap_or(0)
2133    }
2134
2135    /// <https://drafts.csswg.org/cssom-view/#dom-window-scrollx>
2136    fn ScrollX(&self, cx: &mut JSContext) -> i32 {
2137        self.scroll_offset(cx).x as i32
2138    }
2139
2140    /// <https://drafts.csswg.org/cssom-view/#dom-window-pagexoffset>
2141    fn PageXOffset(&self, cx: &mut JSContext) -> i32 {
2142        self.ScrollX(cx)
2143    }
2144
2145    /// <https://drafts.csswg.org/cssom-view/#dom-window-scrolly>
2146    fn ScrollY(&self, cx: &mut JSContext) -> i32 {
2147        self.scroll_offset(cx).y as i32
2148    }
2149
2150    /// <https://drafts.csswg.org/cssom-view/#dom-window-pageyoffset>
2151    fn PageYOffset(&self, cx: &mut JSContext) -> i32 {
2152        self.ScrollY(cx)
2153    }
2154
2155    /// <https://drafts.csswg.org/cssom-view/#dom-window-scroll>
2156    fn Scroll(&self, cx: &mut JSContext, options: &ScrollToOptions) {
2157        // Step 1: If invoked with one argument, follow these substeps:
2158        // Step 1.1: Let options be the argument.
2159        // Step 1.2: Let x be the value of the left dictionary member of options, if
2160        // present, or the viewport’s current scroll position on the x axis otherwise.
2161        let x = options.left.unwrap_or(0.0) as f32;
2162
2163        // Step 1.3: Let y be the value of the top dictionary member of options, if
2164        // present, or the viewport’s current scroll position on the y axis otherwise.
2165        let y = options.top.unwrap_or(0.0) as f32;
2166
2167        // The rest of the specification continues from `Self::scroll`.
2168        self.scroll(cx, x, y, options.parent.behavior);
2169    }
2170
2171    /// <https://drafts.csswg.org/cssom-view/#dom-window-scroll>
2172    fn Scroll_(&self, cx: &mut JSContext, x: f64, y: f64) {
2173        // Step 2: If invoked with two arguments, follow these substeps:
2174        // Step 2.1 Let options be null converted to a ScrollToOptions dictionary. [WEBIDL]
2175        // Step 2.2: Let x and y be the arguments, respectively.
2176        self.scroll(cx, x as f32, y as f32, ScrollBehavior::Auto);
2177    }
2178
2179    /// <https://drafts.csswg.org/cssom-view/#dom-window-scrollto>
2180    ///
2181    /// > When the scrollTo() method is invoked, the user agent must act as if the
2182    /// > scroll() method was invoked with the same arguments.
2183    fn ScrollTo(&self, cx: &mut JSContext, options: &ScrollToOptions) {
2184        self.Scroll(cx, options);
2185    }
2186
2187    /// <https://drafts.csswg.org/cssom-view/#dom-window-scrollto>:
2188    ///
2189    /// > When the scrollTo() method is invoked, the user agent must act as if the
2190    /// > scroll() method was invoked with the same arguments.
2191    fn ScrollTo_(&self, cx: &mut JSContext, x: f64, y: f64) {
2192        self.Scroll_(cx, x, y)
2193    }
2194
2195    /// <https://drafts.csswg.org/cssom-view/#dom-window-scrollby>
2196    fn ScrollBy(&self, cx: &mut JSContext, options: &ScrollToOptions) {
2197        // When the scrollBy() method is invoked, the user agent must run these steps:
2198        // Step 1: If invoked with two arguments, follow these substeps:
2199        //   This doesn't apply here.
2200
2201        // Step 2: Normalize non-finite values for the left and top dictionary members of options.
2202        let mut options = options.clone();
2203        let x = options.left.unwrap_or(0.0);
2204        let x = if x.is_finite() { x } else { 0.0 };
2205        let y = options.top.unwrap_or(0.0);
2206        let y = if y.is_finite() { y } else { 0.0 };
2207
2208        // Step 3: Add the value of scrollX to the left dictionary member.
2209        options.left.replace(x + self.ScrollX(cx) as f64);
2210
2211        // Step 4. Add the value of scrollY to the top dictionary member.
2212        options.top.replace(y + self.ScrollY(cx) as f64);
2213
2214        // Step 5: Act as if the scroll() method was invoked with options as the only argument.
2215        self.Scroll(cx, &options)
2216    }
2217
2218    /// <https://drafts.csswg.org/cssom-view/#dom-window-scrollby>
2219    fn ScrollBy_(&self, cx: &mut JSContext, x: f64, y: f64) {
2220        // When the scrollBy() method is invoked, the user agent must run these steps:
2221        // Step 1: If invoked with two arguments, follow these substeps:
2222        // Step 1.1: Let options be null converted to a ScrollToOptions dictionary.
2223        let mut options = ScrollToOptions::empty();
2224
2225        // Step 1.2: Let x and y be the arguments, respectively.
2226        // Step 1.3: Let the left dictionary member of options have the value x.
2227        options.left.replace(x);
2228
2229        // Step 1.5:  Let the top dictionary member of options have the value y.
2230        options.top.replace(y);
2231
2232        // Now follow the specification for the one argument option.
2233        self.ScrollBy(cx, &options);
2234    }
2235
2236    /// <https://drafts.csswg.org/cssom-view/#dom-window-resizeto>
2237    fn ResizeTo(&self, width: i32, height: i32) {
2238        // Step 1
2239        let window_proxy = match self.window_proxy.get() {
2240            Some(proxy) => proxy,
2241            None => return,
2242        };
2243
2244        // If target is not an auxiliary browsing context that was created by a script
2245        // (as opposed to by an action of the user), then return.
2246        if !window_proxy.is_auxiliary() {
2247            return;
2248        }
2249
2250        let dpr = self.device_pixel_ratio();
2251        let size = Size2D::new(width, height).to_f32() * dpr;
2252        self.send_to_embedder(EmbedderMsg::ResizeTo(self.webview_id(), size.to_i32()));
2253    }
2254
2255    /// <https://drafts.csswg.org/cssom-view/#dom-window-resizeby>
2256    fn ResizeBy(&self, x: i32, y: i32) {
2257        let size = self.client_window().size();
2258        // Step 1
2259        self.ResizeTo(x + size.width, y + size.height)
2260    }
2261
2262    /// <https://drafts.csswg.org/cssom-view/#dom-window-moveto>
2263    fn MoveTo(&self, x: i32, y: i32) {
2264        // Step 1
2265        // TODO determine if this operation is allowed
2266        let dpr = self.device_pixel_ratio();
2267        let point = Point2D::new(x, y).to_f32() * dpr;
2268        let msg = EmbedderMsg::MoveTo(self.webview_id(), point.to_i32());
2269        self.send_to_embedder(msg);
2270    }
2271
2272    /// <https://drafts.csswg.org/cssom-view/#dom-window-moveby>
2273    fn MoveBy(&self, x: i32, y: i32) {
2274        let origin = self.client_window().min;
2275        // Step 1
2276        self.MoveTo(x + origin.x, y + origin.y)
2277    }
2278
2279    /// <https://drafts.csswg.org/cssom-view/#dom-window-screenx>
2280    fn ScreenX(&self) -> i32 {
2281        self.client_window().min.x
2282    }
2283
2284    /// <https://drafts.csswg.org/cssom-view/#ref-for-dom-window-screenleft>
2285    fn ScreenLeft(&self) -> i32 {
2286        self.client_window().min.x
2287    }
2288
2289    /// <https://drafts.csswg.org/cssom-view/#dom-window-screeny>
2290    fn ScreenY(&self) -> i32 {
2291        self.client_window().min.y
2292    }
2293
2294    /// <https://drafts.csswg.org/cssom-view/#ref-for-dom-window-screentop>
2295    fn ScreenTop(&self) -> i32 {
2296        self.client_window().min.y
2297    }
2298
2299    /// <https://drafts.csswg.org/cssom-view/#dom-window-outerheight>
2300    fn OuterHeight(&self) -> i32 {
2301        self.client_window().height()
2302    }
2303
2304    /// <https://drafts.csswg.org/cssom-view/#dom-window-outerwidth>
2305    fn OuterWidth(&self) -> i32 {
2306        self.client_window().width()
2307    }
2308
2309    /// <https://drafts.csswg.org/cssom-view/#dom-window-devicepixelratio>
2310    fn DevicePixelRatio(&self) -> Finite<f64> {
2311        Finite::wrap(self.device_pixel_ratio().get() as f64)
2312    }
2313
2314    /// <https://html.spec.whatwg.org/multipage/#dom-window-status>
2315    fn Status(&self) -> DOMString {
2316        self.status.borrow().clone().root()
2317    }
2318
2319    /// <https://html.spec.whatwg.org/multipage/#dom-window-status>
2320    fn SetStatus(&self, status: DOMString) {
2321        *self.status.borrow_mut() = status.traced()
2322    }
2323
2324    /// <https://drafts.csswg.org/cssom-view/#dom-window-matchmedia>
2325    fn MatchMedia(&self, cx: &mut JSContext, query: DOMString) -> DomRoot<MediaQueryList> {
2326        let media_query_list = MediaList::parse_media_list(&query.str(), self);
2327        let document = self.Document();
2328        let mql = MediaQueryList::new(cx, &document, media_query_list);
2329        self.media_query_lists.track(&*mql);
2330        mql
2331    }
2332
2333    /// <https://fetch.spec.whatwg.org/#dom-global-fetch>
2334    fn Fetch(
2335        &self,
2336        realm: &mut CurrentRealm,
2337        input: RequestOrUSVString,
2338        init: &RequestInit,
2339    ) -> RootedPromise {
2340        fetch::Fetch(self.upcast(), input, init, realm)
2341    }
2342
2343    /// <https://fetch.spec.whatwg.org/#dom-window-fetchlater>
2344    fn FetchLater(
2345        &self,
2346        cx: &mut JSContext,
2347        input: RequestInfo,
2348        init: &DeferredRequestInit,
2349    ) -> Fallible<DomRoot<FetchLaterResult>> {
2350        fetch::FetchLater(cx, self, input, init)
2351    }
2352
2353    #[cfg(feature = "bluetooth")]
2354    fn TestRunner(&self, cx: &mut JSContext) -> DomRoot<TestRunner> {
2355        self.test_runner
2356            .or_init(|| TestRunner::new(cx, self.upcast()))
2357    }
2358
2359    fn RunningAnimationCount(&self) -> u32 {
2360        self.document.get().map_or(0, |document| {
2361            document.animation_manager().running_animation_count() as u32
2362        })
2363    }
2364
2365    /// <https://html.spec.whatwg.org/multipage/#dom-name>
2366    fn SetName(&self, name: DOMString) {
2367        if let Some(proxy) = self.undiscarded_window_proxy() {
2368            proxy.set_name(name);
2369        }
2370    }
2371
2372    /// <https://html.spec.whatwg.org/multipage/#dom-name>
2373    fn Name(&self) -> DOMString {
2374        match self.undiscarded_window_proxy() {
2375            Some(proxy) => proxy.get_name(),
2376            None => DOMString::new(),
2377        }
2378    }
2379
2380    /// <https://html.spec.whatwg.org/multipage/#dom-origin>
2381    fn Origin(&self) -> USVString {
2382        USVString(self.origin().immutable().ascii_serialization().into_owned())
2383    }
2384
2385    /// <https://w3c.github.io/selection-api/#dom-window-getselection>
2386    fn GetSelection(&self, cx: &mut JSContext) -> Option<DomRoot<Selection>> {
2387        self.document.get().and_then(|d| d.GetSelection(cx))
2388    }
2389
2390    /// <https://dom.spec.whatwg.org/#dom-window-event>
2391    fn Event(&self, cx: &mut JSContext, rval: MutableHandleValue) {
2392        if let Some(ref event) = self.current_event.get() {
2393            event.reflector().get_jsobject().to_jsval(cx, rval);
2394        }
2395    }
2396
2397    fn IsSecureContext(&self) -> bool {
2398        self.as_global_scope().is_secure_context()
2399    }
2400
2401    /// <https://html.spec.whatwg.org/multipage/#dom-window-nameditem>
2402    fn NamedGetter(&self, cx: &mut JSContext, name: DOMString) -> Option<NamedPropertyValue> {
2403        if name.is_empty() {
2404            return None;
2405        }
2406        let document = self.Document();
2407
2408        // https://html.spec.whatwg.org/multipage/#document-tree-child-browsing-context-name-property-set
2409        let iframes: Vec<_> = document
2410            .iframes()
2411            .iter()
2412            .filter(|iframe| {
2413                if let Some(window) = iframe.GetContentWindow() {
2414                    return window.get_name() == name;
2415                }
2416                false
2417            })
2418            .collect();
2419
2420        let iframe_iter = iframes.iter().map(|iframe| iframe.upcast::<Element>());
2421
2422        let name = Atom::from(name);
2423
2424        // Step 1.
2425        let elements_with_name = document.get_elements_with_name(cx, &name);
2426        let name_iter = elements_with_name
2427            .iter()
2428            .map(|element| &**element)
2429            .filter(|elem| is_named_element_with_name_attribute(elem));
2430
2431        let elements_with_id = document.get_elements_with_id(cx, &name);
2432        let id_iter = elements_with_id
2433            .iter()
2434            .map(|element| &**element)
2435            .filter(|elem| is_named_element_with_id_attribute(elem));
2436
2437        // Step 2.
2438        for elem in iframe_iter.clone() {
2439            if let Some(nested_window_proxy) = elem
2440                .downcast::<HTMLIFrameElement>()
2441                .and_then(|iframe| iframe.GetContentWindow())
2442            {
2443                return Some(NamedPropertyValue::WindowProxy(nested_window_proxy));
2444            }
2445        }
2446
2447        let mut elements = iframe_iter.chain(name_iter).chain(id_iter);
2448
2449        let first = elements.next()?;
2450
2451        if elements.next().is_none() {
2452            // Step 3.
2453            return Some(NamedPropertyValue::Element(DomRoot::from_ref(first)));
2454        }
2455
2456        // Step 4.
2457        #[derive(JSTraceable, MallocSizeOf)]
2458        struct WindowNamedGetter {
2459            #[no_trace]
2460            name: Atom,
2461        }
2462        impl CollectionFilter for WindowNamedGetter {
2463            fn filter(&self, elem: &Element, _root: &Node) -> bool {
2464                let type_ = match elem.upcast::<Node>().type_id() {
2465                    NodeTypeId::Element(ElementTypeId::HTMLElement(type_)) => type_,
2466                    _ => return false,
2467                };
2468                if elem.get_id().as_ref() == Some(&self.name) {
2469                    return true;
2470                }
2471                match type_ {
2472                    HTMLElementTypeId::HTMLEmbedElement |
2473                    HTMLElementTypeId::HTMLFormElement |
2474                    HTMLElementTypeId::HTMLImageElement |
2475                    HTMLElementTypeId::HTMLObjectElement => {
2476                        elem.get_name().as_ref() == Some(&self.name)
2477                    },
2478                    _ => false,
2479                }
2480            }
2481        }
2482        let collection = HTMLCollection::create(
2483            cx,
2484            self,
2485            document.upcast(),
2486            Box::new(WindowNamedGetter { name }),
2487        );
2488        Some(NamedPropertyValue::HTMLCollection(collection))
2489    }
2490
2491    /// <https://html.spec.whatwg.org/multipage/#dom-tree-accessors:supported-property-names>
2492    fn SupportedPropertyNames(&self, no_gc: &NoGC) -> Vec<DOMString> {
2493        self.Document().SupportedPropertyNames(no_gc)
2494    }
2495
2496    /// <https://html.spec.whatwg.org/multipage/#dom-structuredclone>
2497    fn StructuredClone(
2498        &self,
2499        cx: &mut JSContext,
2500        value: HandleValue,
2501        options: &StructuredSerializeOptions,
2502        retval: MutableHandleValue,
2503    ) -> Fallible<()> {
2504        self.as_global_scope()
2505            .structured_clone(cx, value, options, retval)
2506    }
2507
2508    fn TrustedTypes(&self, cx: &mut JSContext) -> DomRoot<TrustedTypePolicyFactory> {
2509        self.trusted_types
2510            .or_init(|| TrustedTypePolicyFactory::new(cx, self.as_global_scope()))
2511    }
2512}
2513
2514impl Window {
2515    pub(crate) fn scroll_offset(&self, cx: &mut JSContext) -> Vector2D<f32, LayoutPixel> {
2516        self.scroll_offset_query_with_external_scroll_id(cx, self.pipeline_id().root_scroll_id())
2517    }
2518
2519    // https://heycam.github.io/webidl/#named-properties-object
2520    /// <https://html.spec.whatwg.org/multipage/#named-access-on-the-window-object>
2521    pub(crate) fn create_named_properties_object(
2522        cx: &mut JSContext,
2523        proto: HandleObject,
2524        object: MutableHandleObject,
2525    ) {
2526        window_named_properties::create(cx, proto, object)
2527    }
2528
2529    pub(crate) fn current_event(&self) -> Option<DomRoot<Event>> {
2530        self.current_event.get()
2531    }
2532
2533    pub(crate) fn set_current_event(&self, event: Option<&Event>) -> Option<DomRoot<Event>> {
2534        let current = self.current_event();
2535        self.current_event.set(event);
2536        current
2537    }
2538
2539    /// <https://html.spec.whatwg.org/multipage/#window-post-message-steps>
2540    fn post_message_impl(
2541        &self,
2542        target_origin: &USVString,
2543        source_origin: ImmutableOrigin,
2544        source: &Window,
2545        cx: &mut JSContext,
2546        message: HandleValue,
2547        transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
2548    ) -> ErrorResult {
2549        // Step 1-2, 6-8.
2550        let data = structuredclone::write(cx, message, Some(transfer))?;
2551
2552        // Step 3-5.
2553        let target_origin = match target_origin.0[..].as_ref() {
2554            "*" => None,
2555            "/" => Some(source_origin.clone()),
2556            url => match ServoUrl::parse(url) {
2557                Ok(url) => Some(url.origin()),
2558                Err(_) => return Err(Error::Syntax(None)),
2559            },
2560        };
2561
2562        // Step 9.
2563        self.post_message(target_origin, source_origin, &source.window_proxy(), data);
2564        Ok(())
2565    }
2566
2567    // https://drafts.css-houdini.org/css-paint-api-1/#paint-worklet
2568    pub(crate) fn paint_worklet(&self, cx: &mut JSContext) -> DomRoot<Worklet> {
2569        self.paint_worklet.or_init(|| self.new_paint_worklet(cx))
2570    }
2571
2572    pub(crate) fn clear_js_runtime(&self) {
2573        self.clear_js_runtime_common();
2574
2575        // Clean up any active promises
2576        // https://github.com/servo/servo/issues/15318
2577        self.Document().teardown_custom_element_registry();
2578
2579        *self.js_runtime.borrow_mut() = None;
2580
2581        if let Some(performance) = self.performance.get() {
2582            performance.clear_and_disable_performance_entry_buffer();
2583        }
2584
2585        // From <https://w3c.github.io/IndexedDB/#database-connection>
2586        // > The connection can be closed through several means. If the execution context where
2587        // > the connection was created is destroyed (for example due to the user navigating away
2588        // > from that page), the connection is closed.
2589        if let Some(factory) = self.upcast::<GlobalScope>().indexeddb_factory() {
2590            factory.abort_pending_upgrades_and_close_databases();
2591        }
2592
2593        // Callbacks may contain `Trusted` references, which are rooted and would
2594        // prevent the window from being GCed.
2595        self.pending_image_callbacks.borrow_mut().clear();
2596    }
2597
2598    /// <https://drafts.csswg.org/cssom-view/#dom-window-scroll>
2599    pub(crate) fn scroll(&self, cx: &mut JSContext, x: f32, y: f32, behavior: ScrollBehavior) {
2600        // Step 3: Normalize non-finite values for x and y.
2601        let xfinite = if x.is_finite() { x } else { 0.0 };
2602        let yfinite = if y.is_finite() { y } else { 0.0 };
2603
2604        // Step 4: If there is no viewport, abort these steps.
2605        // Currently every frame has a viewport in Servo.
2606
2607        // Step 5. Let `viewport width` be the width of the viewport excluding the width
2608        // of the scroll bar, if any.
2609        // Step 6. `Let viewport height` be the height of the viewport excluding the
2610        // height of the scroll bar, if any.
2611        //
2612        // TODO: Servo does not yet support scrollbars.
2613        let viewport = self.viewport_details.get().size;
2614
2615        // Step 7:
2616        // If the viewport has rightward overflow direction
2617        //    Let x be max(0, min(x, viewport scrolling area width - viewport width)).
2618        // If the viewport has leftward overflow direction
2619        //    Let x be min(0, max(x, viewport width - viewport scrolling area width)).
2620        // TODO: Implement this.
2621
2622        // Step 8:
2623        // If the viewport has downward overflow direction
2624        //    Let y be max(0, min(y, viewport scrolling area height - viewport height)).
2625        // If the viewport has upward overflow direction
2626        //    Let y be min(0, max(y, viewport height - viewport scrolling area height)).
2627        // TODO: Implement this.
2628
2629        // Step 9: Let position be the scroll position the viewport would have by aligning
2630        // the x-coordinate x of the viewport scrolling area with the left of the viewport
2631        // and aligning the y-coordinate y of the viewport scrolling area with the top of
2632        // the viewport.
2633        let scrolling_area = self.scrolling_area_query(cx, None).to_f32();
2634        let x = xfinite.clamp(0.0, 0.0f32.max(scrolling_area.width() - viewport.width));
2635        let y = yfinite.clamp(0.0, 0.0f32.max(scrolling_area.height() - viewport.height));
2636
2637        // Step 10: If position is the same as the viewport’s current scroll position, and
2638        // the viewport does not have an ongoing smooth scroll, abort these steps.
2639        let scroll_offset = self.scroll_offset(cx);
2640        if x == scroll_offset.x && y == scroll_offset.y {
2641            return;
2642        }
2643
2644        // Step 11: Let document be the viewport’s associated Document.
2645        // Step 12: Perform a scroll of the viewport to position, document’s root element
2646        // as the associated element, if there is one, or null otherwise, and the scroll
2647        // behavior being the value of the behavior dictionary member of options.
2648        self.perform_a_scroll(
2649            cx,
2650            x,
2651            y,
2652            self.pipeline_id().root_scroll_id(),
2653            behavior,
2654            None,
2655        );
2656    }
2657
2658    /// <https://drafts.csswg.org/cssom-view/#perform-a-scroll>
2659    pub(crate) fn perform_a_scroll(
2660        &self,
2661        cx: &mut JSContext,
2662        x: f32,
2663        y: f32,
2664        scroll_id: ExternalScrollId,
2665        _behavior: ScrollBehavior,
2666        element: Option<&Element>,
2667    ) {
2668        // Step 1. Abort any ongoing smooth scroll for box.
2669        // TODO: Implement this when we have smooth scrolling.
2670
2671        // Step 2. Resolve all pending scroll Promises whose scroll container is box with
2672        // an interrupted scroll result.
2673        // TODO: Implement this when we have smooth scrolling.
2674
2675        // Step 3. Let scrollPromise be a new Promise.
2676        // TODO: Implement this when we have smooth scrolling.
2677
2678        // Step 4. Return scrollPromise, and run the remaining steps in parallel.
2679        // TODO: Implement this when we have smooth scrolling.
2680
2681        // Step 5. If the user agent honors the scroll-behavior property and one of the
2682        // following is true:
2683        // * behavior is "auto" and element is not null and its computed value of the
2684        //   scroll-behavior property is smooth, or
2685        // * behavior is smooth
2686        // then perform a smooth scroll of box to position; otherwise, perform an instant
2687        // scroll of box to position.
2688        //
2689        // TODO(mrobinson, #18709): Add smooth scrolling support to WebRender so that we
2690        // can properly process ScrollBehavior here.
2691        let (reflow_phases_run, _) = self.reflow(
2692            cx,
2693            ReflowGoal::UpdateScrollNode(scroll_id, Vector2D::new(x, y)),
2694        );
2695        if reflow_phases_run.needs_frame() {
2696            self.paint_api()
2697                .generate_frame(vec![self.webview_id().into()]);
2698        }
2699
2700        // Step 6. Wait until either the position has finished updating, or scrollPromise
2701        // has been resolved.
2702        // TODO: Implement this when we have smooth scrolling.
2703
2704        // Step 7. If scrollPromise is still in the pending state:
2705        // Step 7.1. If the scroll position changed as a result of this call, emit the
2706        // scrollend event.
2707        if reflow_phases_run.contains(ReflowPhasesRun::UpdatedScrollNodeOffset) {
2708            match element {
2709                Some(element) if !scroll_id.is_root() => element.handle_scroll_event(),
2710                _ => self.Document().handle_viewport_scroll_event(),
2711            };
2712        }
2713
2714        // Step 7.2. Resolve scrollPromise with a non-interrupted scroll result.
2715        // TODO: Implement this when we have smooth scrolling.
2716    }
2717
2718    pub(crate) fn device_pixel_ratio(&self) -> Scale<f32, CSSPixel, DevicePixel> {
2719        self.viewport_details.get().hidpi_scale_factor
2720    }
2721
2722    fn client_window(&self) -> DeviceIndependentIntRect {
2723        let (sender, receiver) = generic_channel::channel().expect("Failed to create IPC channel!");
2724
2725        self.send_to_embedder(EmbedderMsg::GetWindowRect(self.webview_id(), sender));
2726
2727        receiver.recv().unwrap_or_default()
2728    }
2729
2730    /// Prepares to tick animations and then does a reflow which also advances the
2731    /// layout animation clock.
2732    pub(crate) fn advance_animation_clock(&self, no_gc: &NoGC, delta: TimeDuration) {
2733        self.Document()
2734            .advance_animation_timeline_for_testing(delta);
2735        ScriptThread::handle_tick_all_animations_for_testing(no_gc, self.pipeline_id());
2736    }
2737
2738    /// Reflows the page unconditionally if possible and not suppressed. This method will wait for
2739    /// the layout to complete. If there is no window size yet, the page is presumed invisible and
2740    /// no reflow is performed. If reflow is suppressed, no reflow will be performed for ForDisplay
2741    /// goals.
2742    ///
2743    /// NOTE: This method should almost never be called directly! Layout and rendering updates should
2744    /// happen as part of the HTML event loop via *update the rendering*.
2745    pub(crate) fn reflow(
2746        &self,
2747        cx: &mut JSContext,
2748        reflow_goal: ReflowGoal,
2749    ) -> (ReflowPhasesRun, ReflowStatistics) {
2750        let document = self.Document();
2751
2752        // Never reflow inactive Documents.
2753        if !document.is_fully_active() {
2754            return Default::default();
2755        }
2756
2757        self.document_unrooted(cx.no_gc())
2758            .ensure_safe_to_run_script_or_layout();
2759
2760        // Explicitly match, so that a variant addition (unlikely but possible)
2761        // would break here, and force considering if parents are already laid out
2762        // or need a flush.
2763        match reflow_goal {
2764            ReflowGoal::LayoutQuery(_) | ReflowGoal::UpdateScrollNode(..) => {
2765                self.flush_ancestor_layouts_if_necessary(cx);
2766            },
2767            ReflowGoal::UpdateTheRendering => { /* Parents will have already been processed */ },
2768        }
2769
2770        // If layouts are blocked, we block all layouts that are for display only. Other
2771        // layouts (for queries and scrolling) are not blocked, as they do not display
2772        // anything and script expects the layout to be up-to-date after they run.
2773        let pipeline_id = self.pipeline_id();
2774        if reflow_goal == ReflowGoal::UpdateTheRendering &&
2775            self.layout_blocker.get().layout_blocked()
2776        {
2777            debug!("Suppressing pre-load-event reflow pipeline {pipeline_id}");
2778            return Default::default();
2779        }
2780
2781        debug!("script: performing reflow for goal {reflow_goal:?}");
2782        #[cfg(feature = "devtools")]
2783        let marker = if self.need_emit_timeline_marker(devtools_traits::TimelineMarkerType::Reflow)
2784        {
2785            Some(devtools_traits::TimelineMarker::start("Reflow".to_owned()))
2786        } else {
2787            None
2788        };
2789
2790        if let Some(selection) = document.selection() {
2791            selection.update_overlaps_document_selection_flags(cx.no_gc());
2792        }
2793
2794        let restyle_reason = document.restyle_reason(cx.no_gc());
2795        document.clear_restyle_reasons();
2796        let restyle = if restyle_reason.needs_restyle() {
2797            debug!("Invalidating layout cache due to reflow condition {restyle_reason:?}",);
2798            // Invalidate any existing cached layout values.
2799            self.layout_marker.borrow().set(false);
2800            // Create a new layout caching token.
2801            *self.layout_marker.borrow_mut() = Rc::new(Cell::new(true));
2802
2803            // If the viewport changed and viewport units were used, all nodes need
2804            // to be restyled, because we currently do not track which ones rely on
2805            // viewport units.
2806            if restyle_reason.contains(RestyleReason::ViewportChanged) &&
2807                self.layout().device().used_viewport_size()
2808            {
2809                document.dirty_all_nodes(cx.no_gc());
2810            }
2811
2812            let stylesheets_changed = document.flush_stylesheets_for_reflow();
2813            let pending_restyles = document.drain_pending_restyles(cx.no_gc());
2814            let dirty_root = document
2815                .take_dirty_root()
2816                .filter(|_| !stylesheets_changed)
2817                .or_else(|| document.GetDocumentElement())
2818                .map(|root| root.upcast::<Node>().to_trusted_node_address());
2819
2820            Some(ReflowRequestRestyle {
2821                reason: restyle_reason,
2822                dirty_root,
2823                stylesheets_changed,
2824                pending_restyles,
2825            })
2826        } else {
2827            None
2828        };
2829
2830        // If there are any duplicate ids, their targets may need to be updated in the id map before
2831        // layout runs, so that the map can gather their elements in DOM order.
2832        document.id_map().resolve_all(cx.no_gc(), document.upcast());
2833
2834        let document_context = self.as_global_scope().web_font_context(cx.no_gc());
2835        let should_update_accessibility_tree = matches!(
2836            reflow_goal,
2837            ReflowGoal::UpdateTheRendering | ReflowGoal::LayoutQuery(QueryMsg::AccessKitNodeQuery)
2838        );
2839        let accessibility =
2840            if should_update_accessibility_tree && self.layout().accessibility_active() {
2841                let rooted_nodes_for_integrity_check =
2842                    document.rooted_nodes_for_accessibility_integrity_check();
2843                let focused_element = document
2844                    .focus_handler()
2845                    .focused_area()
2846                    .element()
2847                    .map(|element| element.upcast::<Node>().to_opaque());
2848                let damage = document
2849                    .accessibility_data_mut()
2850                    .drain_pending_accessibility_damage();
2851                Some(ReflowRequestAccessibility {
2852                    damage,
2853                    focused_element,
2854                    rooted_nodes_for_integrity_check,
2855                })
2856            } else {
2857                None
2858            };
2859
2860        // Send new document and relevant styles to layout.
2861        let reflow = ReflowRequest {
2862            document: document.upcast::<Node>().to_trusted_node_address(),
2863            epoch: document.current_rendering_epoch(),
2864            restyle,
2865            viewport_details: self.viewport_details.get(),
2866            origin: self.origin().immutable().clone(),
2867            reflow_goal,
2868            animation_timeline_value: document.current_animation_timeline_value(),
2869            animations: document.animation_manager().sets(),
2870            animating_images: document.animation_manager().animating_images(),
2871            highlighted_dom_node: document.highlighted_dom_node().map(|node| node.to_opaque()),
2872            frame_focused: self.webview_state().has_system_focus.get() &&
2873                document.focus_handler().has_focus(),
2874            halt_lcp: self.has_dispatched_scroll_event.get() ||
2875                self.has_dispatched_input_event.get(),
2876            paint_timing_eligible: document.paint_timing_eligible(),
2877            paint_timing_info: document.paint_timing_info(),
2878            document_context,
2879            accessibility,
2880        };
2881
2882        let Some(reflow_result) = self.layout.borrow_mut().reflow(reflow) else {
2883            return Default::default();
2884        };
2885
2886        self.handle_accessibility_actions(reflow_result.pending_accessibility_actions, cx);
2887
2888        debug!("script: layout complete");
2889        #[cfg(feature = "devtools")]
2890        if let Some(marker) = marker {
2891            self.emit_timeline_marker(marker.end());
2892        }
2893
2894        self.handle_new_or_removed_web_fonts_post_reflow(cx, reflow_result.changed_web_fonts);
2895
2896        self.handle_pending_images_post_reflow(
2897            cx,
2898            reflow_result.pending_images,
2899            reflow_result.pending_rasterization_images,
2900            reflow_result.pending_svg_elements_for_serialization,
2901        );
2902
2903        if let Some(candidate) = reflow_result.lcp_candidate {
2904            self.process_lcp_candidate_post_reflow(candidate, &document);
2905        }
2906
2907        if !reflow_result.container_timing_records.is_empty() {
2908            self.process_container_timing_records_post_reflow(
2909                reflow_result.container_timing_records,
2910                &document,
2911            );
2912        }
2913
2914        if let Some(iframe_sizes) = reflow_result.iframe_sizes {
2915            document
2916                .iframes()
2917                .handle_new_iframe_sizes_after_layout(cx, self, iframe_sizes);
2918        }
2919
2920        document.update_animations_post_reflow();
2921
2922        (
2923            reflow_result.reflow_phases_run,
2924            reflow_result.reflow_statistics,
2925        )
2926    }
2927
2928    pub(crate) fn request_screenshot_readiness(&self, cx: &mut JSContext) {
2929        self.has_pending_screenshot_readiness_request.set(true);
2930        self.maybe_resolve_pending_screenshot_readiness_requests(cx);
2931    }
2932
2933    pub(crate) fn maybe_resolve_pending_screenshot_readiness_requests(&self, cx: &mut JSContext) {
2934        let pending_request = self.has_pending_screenshot_readiness_request.get();
2935        if !pending_request {
2936            return;
2937        }
2938
2939        let document = self.Document();
2940        if document.ReadyState() != DocumentReadyState::Complete {
2941            return;
2942        }
2943
2944        if document.render_blocking_element_count() > 0 {
2945            return;
2946        }
2947
2948        // Checks if the html element has reftest-wait attribute present.
2949        // See http://testthewebforward.org/docs/reftests.html
2950        // and https://web-platform-tests.org/writing-tests/crashtest.html
2951        if document.GetDocumentElement().is_some_and(|elem| {
2952            elem.has_class(&atom!("reftest-wait"), CaseSensitivity::CaseSensitive) ||
2953                elem.has_class(&Atom::from("test-wait"), CaseSensitivity::CaseSensitive)
2954        }) {
2955            return;
2956        }
2957
2958        if self.font_context().web_fonts_still_loading() != 0 {
2959            return;
2960        }
2961
2962        if self.Document().Fonts(cx).waiting_to_fullfill_promise() {
2963            return;
2964        }
2965
2966        if !self.pending_layout_images.borrow().is_empty() ||
2967            !self.pending_images_for_rasterization.borrow().is_empty()
2968        {
2969            return;
2970        }
2971
2972        let document = self.Document();
2973        if document.needs_rendering_update(cx.no_gc()) {
2974            return;
2975        }
2976
2977        // When all these conditions are met, notify the Constellation that we are ready to
2978        // have our screenshot taken, when the given layout Epoch has been rendered.
2979        let epoch = document.current_rendering_epoch();
2980        let pipeline_id = self.pipeline_id();
2981        debug!("Ready to take screenshot of {pipeline_id:?} at epoch={epoch:?}");
2982
2983        self.send_to_constellation(
2984            ScriptToConstellationMessage::RespondToScreenshotReadinessRequest(
2985                ScreenshotReadinessResponse::Ready(epoch),
2986            ),
2987        );
2988        self.has_pending_screenshot_readiness_request.set(false);
2989    }
2990
2991    /// If parsing has taken a long time and reflows are still waiting for the `load` event,
2992    /// start allowing them. See <https://github.com/servo/servo/pull/6028>.
2993    pub(crate) fn reflow_if_reflow_timer_expired(&self, cx: &mut JSContext) {
2994        // Only trigger a long parsing time reflow if we are in the first parse of `<body>`
2995        // and it started more than `INITIAL_REFLOW_DELAY` ago.
2996        if !matches!(
2997            self.layout_blocker.get(),
2998            LayoutBlocker::Parsing(instant) if instant + INITIAL_REFLOW_DELAY < Instant::now()
2999        ) {
3000            return;
3001        }
3002        self.allow_layout_if_necessary(cx);
3003    }
3004
3005    /// Block layout for this `Window` until parsing is done. If parsing takes a long time,
3006    /// we want to layout anyway, so schedule a moment in the future for when layouts are
3007    /// allowed even though parsing isn't finished and we havne't sent a load event.
3008    pub(crate) fn prevent_layout_until_load_event(&self) {
3009        // If we have already started parsing or have already fired a load event, then
3010        // don't delay the first layout any longer.
3011        if !matches!(self.layout_blocker.get(), LayoutBlocker::WaitingForParse) {
3012            return;
3013        }
3014
3015        self.layout_blocker
3016            .set(LayoutBlocker::Parsing(Instant::now()));
3017    }
3018
3019    /// Inform the [`Window`] that layout is allowed either because `load` has happened
3020    /// or because parsing the `<body>` took so long that we cannot wait any longer.
3021    pub(crate) fn allow_layout_if_necessary(&self, cx: &mut JSContext) {
3022        if matches!(self.layout_blocker.get(), LayoutBlocker::NotBlocked) {
3023            return;
3024        }
3025
3026        self.layout_blocker.set(LayoutBlocker::NotBlocked);
3027
3028        // We do this immediately instead of scheduling a future task, because this can
3029        // happen if parsing is taking a very long time, which means that the
3030        // `ScriptThread` is busy doing the parsing and not doing layouts.
3031        //
3032        // TOOD(mrobinson): It's expected that this is necessary when in the process of
3033        // parsing, as we need to interrupt it to update contents, but why is this
3034        // necessary when parsing finishes? Not doing the synchronous update in that case
3035        // causes iframe tests to become flaky. It seems there's an issue with the timing of
3036        // iframe size updates.
3037        //
3038        // See <https://github.com/servo/servo/issues/14719>
3039        let document = self.Document();
3040        if !document.is_render_blocked() && document.update_the_rendering(cx).0.needs_frame() {
3041            self.paint_api()
3042                .generate_frame(vec![self.webview_id().into()]);
3043        }
3044    }
3045
3046    pub(crate) fn layout_blocked(&self) -> bool {
3047        self.layout_blocker.get().layout_blocked()
3048    }
3049
3050    fn flush_ancestor_layouts_if_necessary(&self, cx: &mut JSContext) {
3051        let Some(parent_pipeline_id) = self.parent_info else {
3052            return;
3053        };
3054        let Some(parent_window) = ScriptThread::find_window(parent_pipeline_id) else {
3055            return;
3056        };
3057        // If we can't run layout we need to abort, otherwise we'd run into the same check but as an assert
3058        // later.
3059        if !parent_window.Document().is_safe_to_run_script_or_layout() {
3060            return;
3061        }
3062        // This avoids unneccessary (work and) flashes of unstyled content according to:
3063        // <https://github.com/mozilla-firefox/firefox/blob/446c6e609dbd7c355c2fb27209dfe4833211991f/dom/base/Document.cpp#L11827-L11851>
3064        if parent_window.Document().is_render_blocked() {
3065            return;
3066        }
3067        parent_window.flush_ancestor_layouts_if_necessary(cx);
3068        if parent_window
3069            .document_unrooted(cx.no_gc())
3070            .restyle_reason(cx.no_gc())
3071            .needs_restyle()
3072        {
3073            parent_window.reflow(
3074                cx,
3075                ReflowGoal::LayoutQuery(QueryMsg::FlushForUpdateTheRenderingQuery),
3076            );
3077        }
3078    }
3079
3080    /// Trigger a reflow that is required by certain queries.
3081    pub(crate) fn layout_reflow(&self, cx: &mut JSContext, query_msg: QueryMsg) {
3082        self.reflow(cx, ReflowGoal::LayoutQuery(query_msg));
3083    }
3084
3085    /// Trigger a reflow that is required by a certain queries.
3086    #[expect(unsafe_code)]
3087    pub(crate) fn layout_reflow_deprecated(&self, query_msg: QueryMsg) {
3088        // TODO https://github.com/servo/servo/issues/44499
3089        let mut cx = unsafe { script_bindings::script_runtime::temp_cx() };
3090        self.reflow(&mut cx, ReflowGoal::LayoutQuery(query_msg));
3091    }
3092
3093    /// Trigger a reflow in preparation for subsequent queries that don't perform a reflow.
3094    pub(crate) fn reflow_for_non_flushing_update_the_rendering_queries(&self, cx: &mut JSContext) {
3095        self.reflow(
3096            cx,
3097            ReflowGoal::LayoutQuery(QueryMsg::FlushForUpdateTheRenderingQuery),
3098        );
3099    }
3100
3101    pub(crate) fn resolved_font_style_query(
3102        &self,
3103        cx: &mut JSContext,
3104        node: &Node,
3105        value: String,
3106    ) -> Option<ServoArc<Font>> {
3107        self.layout_reflow(cx, QueryMsg::ResolvedFontStyleQuery);
3108
3109        let document = self.Document();
3110        let animations = document.animation_manager().sets();
3111        self.layout.borrow().query_resolved_font_style(
3112            node.to_trusted_node_address(),
3113            &value,
3114            animations,
3115            document.current_animation_timeline_value(),
3116        )
3117    }
3118
3119    /// Query the ancestor node that establishes the containing block for the given node.
3120    /// <https://drafts.csswg.org/css-position-3/#def-cb>
3121    #[expect(unsafe_code)]
3122    pub(crate) fn containing_block_node_query_without_reflow(
3123        &self,
3124        node: &Node,
3125    ) -> Option<DomRoot<Node>> {
3126        self.layout
3127            .borrow()
3128            .query_containing_block(node.to_trusted_node_address())
3129            .map(|address| unsafe { from_untrusted_node_address(address) })
3130    }
3131
3132    /// Query whether a node is part of another node's containing block chain.
3133    /// <https://drafts.csswg.org/css-display/#containing-block-chain>
3134    pub(crate) fn is_containing_block_descendant_query_without_reflow(
3135        &self,
3136        possible_ancestor: &Node,
3137        possible_descendant: &Node,
3138    ) -> bool {
3139        self.layout.borrow().query_containing_block_is_descendant(
3140            possible_ancestor.to_trusted_node_address(),
3141            possible_descendant.to_trusted_node_address(),
3142        )
3143    }
3144
3145    /// Query the used padding values for the given node, but do not force a reflow.
3146    /// This is used for things like `ResizeObserver` which should observe the value
3147    /// from the most recent reflow, but do not need it to reflect the current state of
3148    /// the DOM / style.
3149    pub(crate) fn padding_query_without_reflow(&self, node: &Node) -> Option<PhysicalSides<Au>> {
3150        let layout = self.layout.borrow();
3151        layout.query_padding(node.to_trusted_node_address())
3152    }
3153
3154    /// Do the same kind of query as `Self::box_area_query`, but do not force a reflow.
3155    /// This is used for things like `IntersectionObserver` which should observe the value
3156    /// from the most recent reflow, but do not need it to reflect the current state of
3157    /// the DOM / style.
3158    pub(crate) fn box_area_query_without_reflow(
3159        &self,
3160        node: &Node,
3161        area: BoxAreaType,
3162        exclude_transform_and_inline: bool,
3163    ) -> Option<Rect<Au, CSSPixel>> {
3164        let layout = self.layout.borrow();
3165        layout.ensure_stacking_context_tree(self.viewport_details.get());
3166        layout.query_box_area(
3167            node.to_trusted_node_address(),
3168            area,
3169            exclude_transform_and_inline,
3170        )
3171    }
3172
3173    pub(crate) fn box_area_query(
3174        &self,
3175        cx: &mut JSContext,
3176        node: &Node,
3177        area: BoxAreaType,
3178        exclude_transform_and_inline: bool,
3179    ) -> Option<Rect<Au, CSSPixel>> {
3180        self.layout_reflow(cx, QueryMsg::BoxArea);
3181        self.box_area_query_without_reflow(node, area, exclude_transform_and_inline)
3182    }
3183
3184    pub(crate) fn box_areas_query(
3185        &self,
3186        cx: &mut JSContext,
3187        node: &Node,
3188        area: BoxAreaType,
3189    ) -> CSSPixelRectVec {
3190        self.layout_reflow(cx, QueryMsg::BoxAreas);
3191        self.layout
3192            .borrow()
3193            .query_box_areas(node.to_trusted_node_address(), area)
3194    }
3195
3196    pub(crate) fn client_rect_query(&self, cx: &mut JSContext, node: &Node) -> Rect<i32, CSSPixel> {
3197        self.layout_reflow(cx, QueryMsg::ClientRectQuery);
3198        self.layout
3199            .borrow()
3200            .query_client_rect(node.to_trusted_node_address())
3201    }
3202
3203    pub(crate) fn current_css_zoom_query(&self, cx: &mut JSContext, node: &Node) -> f32 {
3204        self.layout_reflow(cx, QueryMsg::CurrentCSSZoomQuery);
3205        self.layout
3206            .borrow()
3207            .query_current_css_zoom(node.to_trusted_node_address())
3208    }
3209
3210    /// <https://html.spec.whatwg.org/multipage/#dom-document-2>
3211    pub(crate) fn document_unrooted<'a>(&self, no_gc: &'a NoGC) -> UnrootedDom<'a, Document> {
3212        self.document
3213            .get_unrooted(no_gc)
3214            .expect("Document accessed before initialization.")
3215    }
3216
3217    /// Find the scroll area of the given node, if it is not None. If the node
3218    /// is None, find the scroll area of the viewport.
3219    pub(crate) fn scrolling_area_query(
3220        &self,
3221        cx: &mut JSContext,
3222        node: Option<&Node>,
3223    ) -> Rect<i32, CSSPixel> {
3224        self.layout_reflow(cx, QueryMsg::ScrollingAreaOrOffsetQuery);
3225        self.layout
3226            .borrow()
3227            .query_scrolling_area(node.map(Node::to_trusted_node_address))
3228    }
3229
3230    pub(crate) fn scroll_offset_query(
3231        &self,
3232        cx: &mut JSContext,
3233        node: &Node,
3234    ) -> Vector2D<f32, LayoutPixel> {
3235        let external_scroll_id = ExternalScrollId(
3236            combine_id_with_fragment_type(node.to_opaque().id(), FragmentType::FragmentBody),
3237            self.pipeline_id().into(),
3238        );
3239        self.scroll_offset_query_with_external_scroll_id(cx, external_scroll_id)
3240    }
3241
3242    fn scroll_offset_query_with_external_scroll_id(
3243        &self,
3244        cx: &mut JSContext,
3245        external_scroll_id: ExternalScrollId,
3246    ) -> Vector2D<f32, LayoutPixel> {
3247        self.layout_reflow(cx, QueryMsg::ScrollingAreaOrOffsetQuery);
3248        self.scroll_offset_query_with_external_scroll_id_no_reflow(external_scroll_id)
3249    }
3250
3251    fn scroll_offset_query_with_external_scroll_id_no_reflow(
3252        &self,
3253        external_scroll_id: ExternalScrollId,
3254    ) -> Vector2D<f32, LayoutPixel> {
3255        self.layout
3256            .borrow()
3257            .scroll_offset(external_scroll_id)
3258            .unwrap_or_default()
3259    }
3260
3261    /// <https://drafts.csswg.org/cssom-view/#scroll-an-element>
3262    // TODO(stevennovaryo): Need to update the scroll API to follow the spec since it is quite outdated.
3263    pub(crate) fn scroll_an_element(
3264        &self,
3265        cx: &mut JSContext,
3266        element: &Element,
3267        x: f32,
3268        y: f32,
3269        behavior: ScrollBehavior,
3270    ) {
3271        let scroll_id = ExternalScrollId(
3272            combine_id_with_fragment_type(
3273                element.upcast::<Node>().to_opaque().id(),
3274                FragmentType::FragmentBody,
3275            ),
3276            self.pipeline_id().into(),
3277        );
3278
3279        // Step 6.
3280        // > Perform a scroll of box to position, element as the associated element and behavior as
3281        // > the scroll behavior.
3282        self.perform_a_scroll(cx, x, y, scroll_id, behavior, Some(element));
3283    }
3284
3285    pub(crate) fn resolved_style_query(
3286        &self,
3287        element: TrustedNodeAddress,
3288        pseudo: Option<PseudoElement>,
3289        property: PropertyId,
3290    ) -> DOMString {
3291        self.layout_reflow_deprecated(QueryMsg::ResolvedStyleQuery(property.clone()));
3292
3293        let document = self.Document();
3294        let animations = document.animation_manager().sets();
3295        DOMString::from(self.layout.borrow().query_resolved_style(
3296            element,
3297            pseudo,
3298            property,
3299            animations,
3300            document.current_animation_timeline_value(),
3301        ))
3302    }
3303
3304    pub(crate) fn accesskit_node_query(
3305        &self,
3306        cx: &mut JSContext,
3307        element: TrustedNodeAddress,
3308    ) -> Option<accesskit::Node> {
3309        self.layout_reflow(cx, QueryMsg::AccessKitNodeQuery);
3310        self.layout.borrow().query_accesskit_node(element)
3311    }
3312
3313    /// If the given |browsing_context_id| refers to an `<iframe>` that is an element
3314    /// in this [`Window`] and that `<iframe>` has been laid out, return its size.
3315    /// Otherwise, return `None`.
3316    pub(crate) fn get_iframe_viewport_details_if_known(
3317        &self,
3318        cx: &mut JSContext,
3319        browsing_context_id: BrowsingContextId,
3320    ) -> Option<ViewportDetails> {
3321        // Reflow might fail, but do a best effort to return the right size.
3322        self.layout_reflow(cx, QueryMsg::InnerWindowDimensionsQuery);
3323        self.Document()
3324            .iframes()
3325            .viewport_details(browsing_context_id)
3326    }
3327
3328    #[expect(unsafe_code)]
3329    pub(crate) fn offset_parent_query(
3330        &self,
3331        cx: &mut JSContext,
3332        node: &Node,
3333    ) -> (Option<DomRoot<Element>>, Rect<Au, CSSPixel>) {
3334        self.layout_reflow(cx, QueryMsg::OffsetParentQuery);
3335        let response = self
3336            .layout
3337            .borrow()
3338            .query_offset_parent(node.to_trusted_node_address());
3339        let element = response.node_address.and_then(|parent_node_address| {
3340            let node = unsafe { from_untrusted_node_address(parent_node_address) };
3341            DomRoot::downcast(node)
3342        });
3343        (element, response.rect)
3344    }
3345
3346    pub(crate) fn scroll_container_query(
3347        &self,
3348        node: Option<&Node>,
3349        flags: ScrollContainerQueryFlags,
3350    ) -> Option<ScrollContainerResponse> {
3351        self.layout_reflow_deprecated(QueryMsg::ScrollParentQuery);
3352        self.layout
3353            .borrow()
3354            .query_scroll_container(node.map(Node::to_trusted_node_address), flags)
3355    }
3356
3357    #[expect(unsafe_code)]
3358    pub(crate) fn scrolling_box_query(
3359        &self,
3360        node: Option<&Node>,
3361        flags: ScrollContainerQueryFlags,
3362    ) -> Option<ScrollingBox> {
3363        self.scroll_container_query(node, flags)
3364            .and_then(|response| {
3365                Some(match response {
3366                    ScrollContainerResponse::Viewport(overflow, writing_mode) => (
3367                        ScrollingBoxSource::Viewport(self.Document()),
3368                        overflow,
3369                        writing_mode,
3370                    ),
3371                    ScrollContainerResponse::Element(
3372                        parent_node_address,
3373                        overflow,
3374                        writing_mode,
3375                    ) => {
3376                        let node = unsafe { from_untrusted_node_address(parent_node_address) };
3377                        (
3378                            ScrollingBoxSource::Element(DomRoot::downcast(node)?),
3379                            overflow,
3380                            writing_mode,
3381                        )
3382                    },
3383                })
3384            })
3385            .map(|(source, overflow, writing_mode)| {
3386                ScrollingBox::new(source, overflow, writing_mode)
3387            })
3388    }
3389
3390    #[expect(unsafe_code)]
3391    pub(crate) fn text_index_query_on_node_for_event(
3392        &self,
3393        cx: &mut JSContext,
3394        node: &Node,
3395        point_in_viewport: Point2D<Au, CSSPixel>,
3396    ) -> Option<(DomRoot<Node>, Utf32CodeUnits)> {
3397        self.layout_reflow(cx, QueryMsg::TextIndexOrSegmentQuery);
3398        let result = self
3399            .layout
3400            .borrow()
3401            .query_text_index(node.to_trusted_node_address(), point_in_viewport)?;
3402        let node = unsafe { from_untrusted_node_address(result.0.into()) };
3403        Some((node, result.1))
3404    }
3405
3406    /// For the given `CharacterData` node and UTF-32 text offset in that node, find
3407    /// the text segment with the given granularity within its containing inline
3408    /// formatting context. This returns `None` when the node isn't a `CharacterData`
3409    /// or the segment otherwise cannot be found.
3410    #[expect(unsafe_code)]
3411    pub(crate) fn query_text_segment(
3412        &self,
3413        cx: &mut JSContext,
3414        node: &Node,
3415        offset: Utf32CodeUnitsOrNodeOffset,
3416        granularity: SegmentGranularity,
3417    ) -> Option<(RootedSelectionBoundary, RootedSelectionBoundary)> {
3418        self.layout_reflow(cx, QueryMsg::TextIndexOrSegmentQuery);
3419        let ((start_node, start_offset), (end_node, end_offset)) = self
3420            .layout()
3421            .query_text_segment(node.to_trusted_node_address(), offset, granularity)?;
3422        let start = RootedSelectionBoundary::new_with_utf32_offset(
3423            unsafe { from_untrusted_node_address(start_node.into()) },
3424            start_offset,
3425        );
3426        let end = RootedSelectionBoundary::new_with_utf32_offset(
3427            unsafe { from_untrusted_node_address(end_node.into()) },
3428            end_offset,
3429        );
3430        Some((start, end))
3431    }
3432
3433    pub(crate) fn elements_from_point_query(
3434        &self,
3435        cx: &mut JSContext,
3436        flags: HitTestFlags,
3437        point: LayoutPoint,
3438    ) -> layout_api::HitTestResult {
3439        self.layout_reflow(cx, QueryMsg::ElementsFromPoint);
3440        self.layout().hit_test(flags, point)
3441    }
3442
3443    pub(crate) fn query_effective_overflow(
3444        &self,
3445        cx: &mut JSContext,
3446        node: &Node,
3447    ) -> Option<AxesOverflow> {
3448        self.layout_reflow(cx, QueryMsg::EffectiveOverflow);
3449        self.query_effective_overflow_without_reflow(node)
3450    }
3451
3452    pub(crate) fn query_effective_overflow_without_reflow(
3453        &self,
3454        node: &Node,
3455    ) -> Option<AxesOverflow> {
3456        self.layout
3457            .borrow()
3458            .query_effective_overflow(node.to_trusted_node_address())
3459    }
3460
3461    pub(crate) fn hit_test_from_input_event(
3462        &self,
3463        cx: &mut JSContext,
3464        flags: HitTestFlags,
3465        input_event: &ConstellationInputEvent,
3466    ) -> Option<HitTestResult> {
3467        self.hit_test_from_point_in_viewport(
3468            cx,
3469            flags,
3470            input_event.hit_test_result.as_ref()?.point_in_viewport,
3471        )
3472    }
3473
3474    #[expect(unsafe_code)]
3475    pub(crate) fn hit_test_from_point_in_viewport(
3476        &self,
3477        cx: &mut JSContext,
3478        flags: HitTestFlags,
3479        point_in_frame: Point2D<f32, CSSPixel>,
3480    ) -> Option<HitTestResult> {
3481        let result = self.elements_from_point_query(cx, flags, point_in_frame.cast_unit());
3482        let item = result.items.into_iter().next()?;
3483
3484        let point_relative_to_initial_containing_block =
3485            point_in_frame + self.scroll_offset(cx).cast_unit();
3486
3487        // SAFETY: This is safe because `Window::query_elements_from_point` has ensured that
3488        // layout has run and any OpaqueNodes that no longer refer to real nodes are gone.
3489        let from_opaque_node = |node: OpaqueNode| {
3490            let address = UntrustedNodeAddress(node.0 as *const c_void);
3491            unsafe { from_untrusted_node_address(address) }
3492        };
3493        Some(HitTestResult {
3494            node: from_opaque_node(item.node),
3495            dom_position_for_selection: result.dom_position_for_selection.map(|(node, offset)| {
3496                RootedSelectionBoundary::new_with_utf32_offset(from_opaque_node(node), offset)
3497            }),
3498            cursor: item.cursor,
3499            point_in_node: item.point_in_target,
3500            point_in_frame,
3501            point_relative_to_initial_containing_block,
3502        })
3503    }
3504
3505    pub(crate) fn init_window_proxy(&self, window_proxy: &WindowProxy) {
3506        assert!(
3507            self.window_proxy
3508                .get()
3509                .is_none_or(|current_proxy| &*current_proxy as *const WindowProxy == window_proxy)
3510        );
3511        self.window_proxy.set(Some(window_proxy));
3512    }
3513
3514    pub(crate) fn init_document(&self, document: &Document) {
3515        assert!(
3516            self.document
3517                .get()
3518                .is_none_or(|document| document.is_initial_about_blank())
3519        );
3520        assert!(document.window() == self);
3521        self.document.set(Some(document));
3522        self.update_jsprincipals_from_document(document);
3523        self.layout_mut().set_quirks_mode(document.quirks_mode());
3524    }
3525
3526    /// The `JSPrincipals` object inside a [`Window`] stores a mutable origin used for
3527    /// same-origin checks within SpiderMonkey. When the entire origin of a [`Window`]'s
3528    /// [`Document`] object is replaced or the [`Document`] object itself is replaced with a
3529    /// [`Document`] with a different origin, the `JSPrincipals` stored inside the [`Window`]
3530    /// also needs to change. This ensures that same origin checks are done against the correct
3531    /// origin.
3532    #[expect(unsafe_code)]
3533    pub(crate) fn update_jsprincipals_from_document(&self, document: &Document) {
3534        let realm = unsafe { GetObjectRealmOrNull(self.reflector().get_jsobject().get()) };
3535        let new_principals = ServoJSPrincipals::new::<crate::DomTypeHolder>(&document.origin());
3536        unsafe { SetRealmPrincipals(realm, new_principals.as_raw()) };
3537    }
3538
3539    pub(crate) fn load_data_for_document(
3540        &self,
3541        url: ServoUrl,
3542        pipeline_id: PipelineId,
3543    ) -> LoadData {
3544        let source_document = self.Document();
3545        let secure_context = if self.is_top_level() {
3546            None
3547        } else {
3548            Some(self.IsSecureContext())
3549        };
3550
3551        let upgrade_insecure_navigations_set = self
3552            .as_global_scope()
3553            .upgrade_insecure_navigations_set()
3554            .clone();
3555
3556        LoadData::new(
3557            LoadOrigin::Script(self.origin().snapshot()),
3558            url,
3559            source_document.about_base_url(),
3560            Some(pipeline_id),
3561            Referrer::ReferrerUrl(source_document.url()),
3562            source_document.get_referrer_policy(),
3563            secure_context,
3564            Some(source_document.insecure_requests_policy()),
3565            upgrade_insecure_navigations_set,
3566            source_document.has_trustworthy_ancestor_origin(),
3567            source_document.creation_sandboxing_flag_set_considering_parent_iframe(),
3568        )
3569    }
3570
3571    /// Handle a potential change to the [`ViewportDetails`] of this [`Window`],
3572    /// triggering a reflow if any change occurred.
3573    pub(crate) fn set_viewport_details(&self, viewport_details: ViewportDetails) {
3574        self.viewport_details.set(viewport_details);
3575        if !self.layout_mut().set_viewport_details(viewport_details) {
3576            return;
3577        }
3578        self.Document()
3579            .add_restyle_reason(RestyleReason::ViewportChanged);
3580    }
3581
3582    pub(crate) fn viewport_details(&self) -> ViewportDetails {
3583        self.viewport_details.get()
3584    }
3585
3586    pub(crate) fn get_or_init_visual_viewport(
3587        &self,
3588        cx: &mut JSContext,
3589    ) -> DomRoot<VisualViewport> {
3590        self.visual_viewport.or_init(|| {
3591            VisualViewport::new_from_layout_viewport(cx, self, self.viewport_details().size)
3592        })
3593    }
3594
3595    /// Update the [`VisualViewport`] of this [`Window`] if necessary and note the changes to be processed in the event loop.
3596    pub(crate) fn maybe_update_visual_viewport(
3597        &self,
3598        cx: &mut JSContext,
3599        pinch_zoom_infos: PinchZoomInfos,
3600    ) {
3601        // We doesn't need to do anything if the following condition is fulfilled. Since there are no JS listener
3602        // to fire and we could reconstruct visual viewport from layout viewport in case JS access it.
3603        if pinch_zoom_infos.rect == Rect::from_size(self.viewport_details().size) &&
3604            self.visual_viewport.get().is_none()
3605        {
3606            return;
3607        }
3608
3609        let visual_viewport = self.get_or_init_visual_viewport(cx);
3610        let changes = visual_viewport.update_from_pinch_zoom_infos(pinch_zoom_infos);
3611
3612        if changes.intersects(VisualViewportChanges::DimensionChanged) {
3613            self.has_changed_visual_viewport_dimension.set(true);
3614        }
3615        if changes.intersects(VisualViewportChanges::OffsetChanged) {
3616            visual_viewport.handle_scroll_event();
3617        }
3618    }
3619
3620    pub(crate) fn webview_theme(&self) -> Theme {
3621        self.webview_state.theme.get()
3622    }
3623
3624    pub(crate) fn refresh_theme(&self) {
3625        // The theme is chosen in this order of precedence:
3626        //  1. The devtools theme override
3627        //  2. The Document theme
3628        //  3. The theme set on the WebView
3629        let document = self.Document();
3630        let new_theme = document
3631            .theme_override()
3632            .or(document.theme())
3633            .unwrap_or(self.webview_theme());
3634        if !self.layout_mut().set_theme(new_theme) {
3635            return;
3636        }
3637        document.add_restyle_reason(RestyleReason::ThemeChanged);
3638        // The change in `prefers-color-scheme` may flip `MediaQueryList`
3639        // results so we flag the next "update the rendering" turn to re-evaluate them.
3640        self.pending_media_query_evaluation.set(true);
3641    }
3642
3643    /// Returns true and clears the flag if a media-feature change has
3644    /// occurred since the last call.
3645    pub(crate) fn take_pending_media_query_evaluation(&self) -> bool {
3646        self.pending_media_query_evaluation.replace(false)
3647    }
3648
3649    pub(crate) fn has_pending_media_query_evaluation(&self) -> bool {
3650        self.pending_media_query_evaluation.get()
3651    }
3652
3653    pub(crate) fn get_url(&self) -> ServoUrl {
3654        self.Document().url()
3655    }
3656
3657    pub(crate) fn windowproxy_handler(&self) -> &'static WindowProxyHandler {
3658        self.dom_static.windowproxy_handler
3659    }
3660
3661    pub(crate) fn add_resize_event(&self, event: ViewportDetails, event_type: WindowSizeType) {
3662        if self.viewport_details() == event {
3663            return;
3664        }
3665
3666        // Apply the new viewport, since the new size needs to be observable immediately.
3667        self.set_viewport_details(event);
3668
3669        // Whenever we receive a new resize event we forget about all the ones that came before
3670        // it, to avoid unnecessary relayouts
3671        *self.unhandled_resize_event.borrow_mut() = Some((event, event_type))
3672    }
3673
3674    pub(crate) fn take_unhandled_resize_event(&self) -> Option<(ViewportDetails, WindowSizeType)> {
3675        self.unhandled_resize_event.borrow_mut().take()
3676    }
3677
3678    /// Whether or not this [`Window`] has any resize events that have not been processed.
3679    pub(crate) fn has_unhandled_resize_event(&self) -> bool {
3680        self.unhandled_resize_event.borrow().is_some()
3681    }
3682
3683    pub(crate) fn suspend(&self, cx: &mut JSContext) {
3684        // Suspend timer events.
3685        self.as_global_scope().suspend();
3686
3687        // Set the window proxy to be a cross-origin window.
3688        if self.window_proxy().currently_active() == Some(self.global().pipeline_id()) {
3689            self.window_proxy().unset_currently_active(cx);
3690        }
3691
3692        // A hint to the JS runtime that now would be a good time to
3693        // GC any unreachable objects generated by user script,
3694        // or unattached DOM nodes. Attached DOM nodes can't be GCd yet,
3695        // as the document might be reactivated later.
3696        self.maybe_gc(cx);
3697    }
3698
3699    pub(crate) fn resume(&self, cx: &mut JSContext) {
3700        // Resume timer events.
3701        self.as_global_scope().resume();
3702
3703        // Set the window proxy to be this object.
3704        self.window_proxy().set_currently_active(cx, self);
3705
3706        // Push the document title to `Paint` since we are
3707        // activating this document due to a navigation.
3708        self.Document().title_changed();
3709    }
3710
3711    pub(crate) fn is_alive(&self) -> bool {
3712        self.current_state.get() == WindowState::Alive
3713    }
3714
3715    /// <https://html.spec.whatwg.org/multipage/#top-level-browsing-context>
3716    pub(crate) fn is_top_level(&self) -> bool {
3717        self.parent_info.is_none()
3718    }
3719
3720    /// Layout viewport part of:
3721    /// <https://drafts.csswg.org/cssom-view/#document-run-the-resize-steps>
3722    ///
3723    /// Handle the pending viewport resize.
3724    fn run_resize_steps_for_layout_viewport(&self, cx: &mut JSContext) -> bool {
3725        let Some((new_size, size_type)) = self.take_unhandled_resize_event() else {
3726            return false;
3727        };
3728
3729        // The viewport was already updated in `add_resize_event`, so these steps
3730        // only fire the event, and only if the viewport differs from the last one.
3731        let current_viewport = self.viewport_details();
3732        if current_viewport == self.viewport_details_at_last_resize_steps.get() {
3733            return false;
3734        }
3735        self.viewport_details_at_last_resize_steps
3736            .set(current_viewport);
3737
3738        debug!(
3739            "Running resize steps for pipeline {:?} with viewport {new_size:?}",
3740            self.pipeline_id(),
3741        );
3742
3743        // http://dev.w3.org/csswg/cssom-view/#resizing-viewports
3744        if size_type == WindowSizeType::Resize {
3745            let mut realm = enter_auto_realm(cx, self);
3746            let cx = &mut realm.current_realm();
3747            let uievent = UIEvent::new(
3748                cx,
3749                self,
3750                atom!("resize"),
3751                EventBubbles::DoesNotBubble,
3752                EventCancelable::NotCancelable,
3753                Some(self),
3754                0i32,
3755                0u32,
3756            );
3757            uievent.upcast::<Event>().fire(cx, self.upcast());
3758        }
3759
3760        true
3761    }
3762
3763    /// An implementation of:
3764    /// <https://drafts.csswg.org/cssom-view/#document-run-the-resize-steps>
3765    ///
3766    /// Returns true if there were any pending viewport resize events.
3767    pub(crate) fn run_the_resize_steps(&self, cx: &mut JSContext) -> bool {
3768        let layout_viewport_resized = self.run_resize_steps_for_layout_viewport(cx);
3769
3770        if self.has_changed_visual_viewport_dimension.get() {
3771            let visual_viewport = self.get_or_init_visual_viewport(cx);
3772
3773            let uievent = UIEvent::new(
3774                cx,
3775                self,
3776                atom!("resize"),
3777                EventBubbles::DoesNotBubble,
3778                EventCancelable::NotCancelable,
3779                Some(self),
3780                0i32,
3781                0u32,
3782            );
3783            uievent.upcast::<Event>().fire(cx, visual_viewport.upcast());
3784
3785            self.has_changed_visual_viewport_dimension.set(false);
3786        }
3787
3788        layout_viewport_resized
3789    }
3790
3791    /// Evaluate media query lists and report changes
3792    /// <https://drafts.csswg.org/cssom-view/#evaluate-media-queries-and-report-changes>
3793    pub(crate) fn evaluate_media_queries_and_report_changes(&self, cx: &mut JSContext) {
3794        let mut realm = enter_auto_realm(cx, self);
3795        let cx = &mut realm.current_realm();
3796        rooted_vec!(let mut mql_list);
3797
3798        self.media_query_lists.for_each(|mql| {
3799            if let MediaQueryListMatchState::Changed = mql.evaluate_changes() {
3800                // Recording list of changed Media Queries
3801                mql_list.push(Dom::from_ref(&*mql));
3802            }
3803        });
3804        // Sending change events for all changed Media Queries
3805        for mql in mql_list.iter() {
3806            let event = MediaQueryListEvent::new(
3807                cx,
3808                &mql.global(),
3809                atom!("change"),
3810                false,
3811                false,
3812                mql.Media(),
3813                mql.Matches(),
3814            );
3815            event
3816                .upcast::<Event>()
3817                .fire(cx, mql.upcast::<EventTarget>());
3818        }
3819    }
3820
3821    /// Set whether to use less resources by running timers at a heavily limited rate.
3822    pub(crate) fn set_throttled(&self, throttled: bool) {
3823        self.throttled.set(throttled);
3824        if throttled {
3825            self.as_global_scope().slow_down_timers();
3826        } else {
3827            self.as_global_scope().speed_up_timers();
3828        }
3829    }
3830
3831    pub(crate) fn throttled(&self) -> bool {
3832        self.throttled.get()
3833    }
3834
3835    pub(crate) fn unminified_css_dir(&self) -> Option<String> {
3836        self.unminified_css_dir.borrow().clone()
3837    }
3838
3839    pub(crate) fn local_script_source(&self) -> &Option<String> {
3840        &self.local_script_source
3841    }
3842
3843    pub(crate) fn set_navigation_start(&self) {
3844        self.navigation_start.set(CrossProcessInstant::now());
3845    }
3846
3847    pub(crate) fn navigation_start(&self) -> CrossProcessInstant {
3848        self.navigation_start.get()
3849    }
3850
3851    pub(crate) fn set_last_activation_timestamp(&self, time: UserActivationTimestamp) {
3852        self.last_activation_timestamp.set(time);
3853    }
3854
3855    pub(crate) fn set_last_history_action_activation_timestamp(
3856        &self,
3857        time: UserActivationTimestamp,
3858    ) {
3859        self.last_history_action_activation_timestamp.set(time);
3860    }
3861
3862    pub(crate) fn send_to_embedder(&self, msg: EmbedderMsg) {
3863        self.as_global_scope()
3864            .script_to_embedder_chan()
3865            .send(msg)
3866            .unwrap();
3867    }
3868
3869    pub(crate) fn send_to_constellation(&self, msg: ScriptToConstellationMessage) {
3870        self.as_global_scope()
3871            .script_to_constellation_chan()
3872            .send(msg)
3873            .unwrap();
3874    }
3875
3876    #[cfg(feature = "webxr")]
3877    pub(crate) fn in_immersive_xr_session(&self) -> bool {
3878        self.navigator
3879            .get()
3880            .as_ref()
3881            .and_then(|nav| nav.xr())
3882            .is_some_and(|xr| xr.pending_or_active_session())
3883    }
3884
3885    #[cfg(all(feature = "webgl", not(feature = "webxr")))]
3886    pub(crate) fn in_immersive_xr_session(&self) -> bool {
3887        false
3888    }
3889
3890    /// Adds and removes entries from `document.fonts` as needed after a reflow.
3891    fn handle_new_or_removed_web_fonts_post_reflow(
3892        &self,
3893        cx: &mut JSContext,
3894        changed_web_fonts: WebFontSetDifference,
3895    ) {
3896        if changed_web_fonts.is_empty() {
3897            return;
3898        }
3899
3900        let document = self.Document();
3901        let fonts = document.Fonts(cx);
3902        if !changed_web_fonts.removed_font_faces.is_empty() {
3903            fonts.notify_font_face_rules_removed(&changed_web_fonts.removed_font_faces);
3904        }
3905
3906        if !changed_web_fonts.removed_font_faces.is_empty() ||
3907            changed_web_fonts.cascade_index_of_any_rule_changed
3908        {
3909            // TODO: This should only dirty nodes that are rendered using any of the removed
3910            // web fonts!
3911            document.dirty_all_nodes(cx.no_gc());
3912        }
3913
3914        if !changed_web_fonts.added_font_faces.is_empty() {
3915            fonts.switch_to_loading(cx);
3916
3917            for new_web_font in changed_web_fonts.added_font_faces {
3918                if let Some(font_face) = FontFace::new_for_web_font(cx, self.upcast(), new_web_font)
3919                {
3920                    fonts.add(cx, font_face);
3921                }
3922            }
3923        }
3924    }
3925
3926    /// Resolve the LCP candidate OpaqueNode to a DOM Element and store it on the document.
3927    #[expect(unsafe_code)]
3928    fn process_lcp_candidate_post_reflow(&self, candidate: LCPCandidate, document: &Document) {
3929        let element = candidate.node.and_then(|node| {
3930            let node_address = UntrustedNodeAddress(node.id() as *const c_void);
3931            let node = unsafe { from_untrusted_node_address(node_address) };
3932            DomRoot::downcast::<Element>(node)
3933        });
3934        document.store_lcp_candidate(candidate, element.as_deref());
3935    }
3936
3937    /// Resolve each Container Timing record's [`OpaqueNode`]s to DOM elements and park
3938    /// the record on the document, keyed by its ID, until paint reports the time the
3939    /// frame carrying it was composited.
3940    ///
3941    /// <https://wicg.github.io/container-timing/>
3942    #[expect(unsafe_code)]
3943    fn process_container_timing_records_post_reflow(
3944        &self,
3945        records: Vec<ContainerTimingRecord>,
3946        document: &Document,
3947    ) {
3948        // Safety: these are nodes layout saw during the display list build for this same
3949        // reflow, so they are still live. Same reasoning as
3950        // `process_lcp_candidate_post_reflow` above.
3951        let resolve = |node: OpaqueNode| unsafe {
3952            let node_address = UntrustedNodeAddress(node.id() as *const c_void);
3953            DomRoot::downcast::<Element>(from_untrusted_node_address(node_address))
3954        };
3955
3956        for record in records {
3957            let Some(root_element) = resolve(record.root_element) else {
3958                continue;
3959            };
3960            // Layout only knows that this element was a container root when its boxes were
3961            // built. Read the identifier now, and skip the record if the attribute has
3962            // since been removed.
3963            let Some(identifier) =
3964                root_element.get_attribute_string_value(&LocalName::from("containertiming"))
3965            else {
3966                continue;
3967            };
3968            let last_painted_element = record.last_painted_element.and_then(resolve);
3969            document.store_container_timing_record(
3970                record,
3971                identifier.into(),
3972                &root_element,
3973                last_painted_element.as_deref(),
3974            );
3975        }
3976    }
3977
3978    #[expect(unsafe_code)]
3979    fn handle_pending_images_post_reflow(
3980        &self,
3981        cx: &mut JSContext,
3982        pending_images: Vec<PendingImage>,
3983        pending_rasterization_images: Vec<PendingRasterizationImage>,
3984        pending_svg_element_for_serialization: Vec<UntrustedNodeAddress>,
3985    ) {
3986        let pipeline_id = self.pipeline_id();
3987        let image_cache = self.image_cache();
3988        for image in pending_images {
3989            let id = image.id;
3990            let node = unsafe { from_untrusted_node_address(image.node) };
3991
3992            if let PendingImageState::Unrequested(ref url) = image.state {
3993                fetch_image_for_layout(
3994                    url.clone(),
3995                    &node,
3996                    id,
3997                    image.is_internal_request,
3998                    image_cache.clone(),
3999                );
4000            }
4001
4002            let mut images = self.pending_layout_images.borrow_mut();
4003            if !images.contains_key(&id) {
4004                let trusted_node = Trusted::new(&*node);
4005                let sender = self.register_image_cache_listener(id, move |response, cx| {
4006                    trusted_node
4007                        .root()
4008                        .owner_window()
4009                        .pending_layout_image_notification(cx.no_gc(), response);
4010                });
4011
4012                image_cache.add_listener(ImageLoadListener::new(sender, pipeline_id, id));
4013            }
4014
4015            let nodes = images.entry(id).or_default();
4016            if !nodes.iter().any(|n| *n.node == *node) {
4017                nodes.push(PendingLayoutImageAncillaryData {
4018                    node: Dom::from_ref(&*node),
4019                    destination: image.destination,
4020                });
4021            }
4022        }
4023
4024        for image in pending_rasterization_images {
4025            let node = unsafe { from_untrusted_node_address(image.node) };
4026
4027            let mut images = self.pending_images_for_rasterization.borrow_mut();
4028            if !images.contains_key(&(image.id, image.size)) {
4029                let image_cache_sender = self.image_cache_sender.clone();
4030                image_cache.add_rasterization_complete_listener(
4031                    pipeline_id,
4032                    image.id,
4033                    image.size,
4034                    Box::new(move |response| {
4035                        let _ = image_cache_sender.send(response);
4036                    }),
4037                );
4038            }
4039
4040            let nodes = images.entry((image.id, image.size)).or_default();
4041            if !nodes.iter().any(|n| **n == *node) {
4042                nodes.push(Dom::from_ref(&*node));
4043            }
4044        }
4045
4046        for node in pending_svg_element_for_serialization.into_iter() {
4047            let node = unsafe { from_untrusted_node_address(node) };
4048            let svg = node.downcast::<SVGSVGElement>().unwrap();
4049            svg.serialize_and_cache_subtree(cx);
4050            node.dirty(cx.no_gc(), NodeDamage::Other);
4051        }
4052    }
4053
4054    #[expect(unsafe_code)]
4055    fn handle_accessibility_actions(
4056        &self,
4057        actions: Vec<AccessibilityActionRequest>,
4058        cx: &mut JSContext,
4059    ) {
4060        for action_request in actions {
4061            let target_opaque = action_request.target;
4062            let target = unsafe { from_untrusted_node_address(target_opaque.into()) };
4063            if action_request.action == Action::Click {
4064                target.fire_synthetic_pointer_event_not_trusted(cx, atom!("click"));
4065            }
4066        }
4067    }
4068
4069    /// <https://html.spec.whatwg.org/multipage/#sticky-activation>
4070    pub(crate) fn has_sticky_activation(&self) -> bool {
4071        // > When the current high resolution time given W is greater than or equal to the last activation timestamp in W, W is said to have sticky activation.
4072        UserActivationTimestamp::TimeStamp(CrossProcessInstant::now()) >=
4073            self.last_activation_timestamp.get()
4074    }
4075
4076    /// <https://html.spec.whatwg.org/multipage/#history-action-activation>
4077    pub(crate) fn has_history_action_activation(&self) -> bool {
4078        // > When the last history-action activation timestamp of W
4079        // > is not equal to the last activation timestamp of W,
4080        // > then W is said to have history-action activation.
4081        self.last_history_action_activation_timestamp.get() != self.last_activation_timestamp.get()
4082    }
4083
4084    /// <https://html.spec.whatwg.org/multipage/#transient-activation>
4085    pub(crate) fn has_transient_activation(&self) -> bool {
4086        // > When the current high resolution time given W is greater than or equal to the last activation timestamp in W, and less than the last activation
4087        // > timestamp in W plus the transient activation duration, then W is said to have transient activation.
4088        let current_time = CrossProcessInstant::now();
4089        UserActivationTimestamp::TimeStamp(current_time) >= self.last_activation_timestamp.get() &&
4090            UserActivationTimestamp::TimeStamp(current_time) <
4091                self.last_activation_timestamp.get() +
4092                    pref!(dom_transient_activation_duration_ms)
4093    }
4094
4095    pub(crate) fn consume_last_activation_timestamp(&self) {
4096        if self.last_activation_timestamp.get() != UserActivationTimestamp::PositiveInfinity {
4097            self.set_last_activation_timestamp(UserActivationTimestamp::NegativeInfinity);
4098        }
4099    }
4100
4101    /// <https://html.spec.whatwg.org/multipage/#consume-user-activation>
4102    pub(crate) fn consume_user_activation(&self) {
4103        // Step 1.
4104        // > If W's navigable is null, then return.
4105        if self.undiscarded_window_proxy().is_none() {
4106            return;
4107        }
4108
4109        // Step 2.
4110        // > Let top be W's navigable's top-level traversable.
4111        // TODO: This wouldn't work if top level document is in another ScriptThread.
4112        let Some(top_level_document) = self.top_level_document_if_local() else {
4113            return;
4114        };
4115
4116        // Step 3.
4117        // > Let navigables be the inclusive descendant navigables of top's active document.
4118        // Step 4.
4119        // > Let windows be the list of Window objects constructed by taking the active window of each item in navigables.
4120        // Step 5.
4121        // > For each window in windows, if window's last activation timestamp is not positive infinity, then set window's last activation timestamp to negative infinity.
4122        // TODO: this would not work for disimilar origin descendant, since we doesn't store the document in this script thread.
4123        top_level_document
4124            .window()
4125            .consume_last_activation_timestamp();
4126        for document in LocalDescendantNavigablesIterator::new(&top_level_document) {
4127            document.window().consume_last_activation_timestamp();
4128        }
4129    }
4130
4131    /// <https://html.spec.whatwg.org/multipage/#consume-history-action-user-activation>
4132    pub(crate) fn consume_history_action_user_activation(&self) {
4133        // Step 1. If W's navigable is null, then return.
4134        if self.undiscarded_window_proxy().is_none() {
4135            return;
4136        }
4137
4138        // Step 2. Let top be W's navigable's top-level traversable.
4139        // TODO: This wouldn't work if top level document is in another ScriptThread.
4140        let Some(top_level_document) = self.top_level_document_if_local() else {
4141            return;
4142        };
4143
4144        // Step 3. Let navigables be the inclusive descendant navigables of top's active document.
4145        // Step 4. Let windows be the list of Window objects constructed by taking the active window
4146        // of each item in navigables.
4147        // Step 5. For each window in windows, set window's last history-action activation timestamp
4148        // to window's last activation timestamp.
4149        // TODO: this would not work for disimilar origin descendant, since we doesn't store the document in this script thread.
4150        top_level_document
4151            .window()
4152            .set_last_history_action_activation_timestamp(
4153                top_level_document.window().last_activation_timestamp.get(),
4154            );
4155        for document in LocalDescendantNavigablesIterator::new(&top_level_document) {
4156            document
4157                .window()
4158                .set_last_history_action_activation_timestamp(
4159                    document.window().last_activation_timestamp.get(),
4160                );
4161        }
4162    }
4163
4164    #[allow(clippy::too_many_arguments)]
4165    pub(crate) fn new(
4166        cx: &mut JSContext,
4167        webview_state: Rc<WebViewState>,
4168        runtime: Rc<Runtime>,
4169        script_chan: Sender<MainThreadScriptMsg>,
4170        layout: Box<dyn Layout>,
4171        image_cache_sender: Sender<ImageCacheResponseMessage>,
4172        resource_threads: ResourceThreads,
4173        storage_threads: StorageThreads,
4174        #[cfg(feature = "bluetooth")] bluetooth_thread: GenericSender<BluetoothRequest>,
4175        mem_profiler_chan: MemProfilerChan,
4176        time_profiler_chan: TimeProfilerChan,
4177        #[cfg(feature = "devtools")] devtools_chan: Option<
4178            GenericCallback<devtools_traits::ScriptToDevtoolsControlMsg>,
4179        >,
4180        script_to_constellation_sender: ScriptToConstellationSender,
4181        embedder_chan: ScriptToEmbedderChan,
4182        control_chan: GenericSender<ScriptThreadMessage>,
4183        pipeline_id: PipelineId,
4184        parent_info: Option<PipelineId>,
4185        viewport_details: ViewportDetails,
4186        origin: MutableOrigin,
4187        creation_url: ServoUrl,
4188        top_level_creation_url: ServoUrl,
4189        navigation_start: CrossProcessInstant,
4190        #[cfg(feature = "webgl")] webgl_chan: Option<WebGLChan>,
4191        #[cfg(feature = "webxr")] webxr_registry: Option<webxr_api::Registry>,
4192        paint_api: CrossProcessPaintApi,
4193        unminify_js: bool,
4194        unminify_css: bool,
4195        local_script_source: Option<String>,
4196        user_scripts: Rc<Vec<UserScript>>,
4197        player_context: WindowGLContext,
4198        #[cfg(feature = "webgpu")] gpu_id_hub: Arc<IdentityHub>,
4199        inherited_secure_context: Option<bool>,
4200        inherited_upgrade_insecure_navigations_set: HashSet<UpgradeInsecureNavigations>,
4201        weak_script_thread: Weak<ScriptThread>,
4202    ) -> DomRoot<Self> {
4203        let error_reporter = CSSErrorReporter {
4204            pipelineid: pipeline_id,
4205            script_chan: control_chan,
4206        };
4207
4208        let win = Box::new(Self {
4209            webview_state,
4210            globalscope: GlobalScope::new_inherited(
4211                #[cfg(feature = "devtools")]
4212                devtools_chan,
4213                mem_profiler_chan,
4214                time_profiler_chan,
4215                script_to_constellation_sender,
4216                embedder_chan,
4217                resource_threads,
4218                storage_threads,
4219                creation_url,
4220                Some(top_level_creation_url),
4221                #[cfg(feature = "webgpu")]
4222                gpu_id_hub,
4223                inherited_secure_context,
4224                inherited_upgrade_insecure_navigations_set,
4225                unminify_js,
4226            ),
4227            caches: Default::default(),
4228            ongoing_navigation: Default::default(),
4229            script_chan,
4230            layout: RefCell::new(layout),
4231            image_cache_sender,
4232            navigator: Default::default(),
4233            crypto: Default::default(),
4234            location: Default::default(),
4235            window_proxy: Default::default(),
4236            document: Default::default(),
4237            performance: Default::default(),
4238            navigation_start: Cell::new(navigation_start),
4239            screen: Default::default(),
4240            session_storage: Default::default(),
4241            local_storage: Default::default(),
4242            cookie_store: Default::default(),
4243            status: DomRefCell::new(DOMString::new().traced()),
4244            parent_info,
4245            dom_static: GlobalStaticData::new(),
4246            js_runtime: DomRefCell::new(Some(runtime)),
4247            #[cfg(feature = "bluetooth")]
4248            bluetooth_thread,
4249            #[cfg(feature = "bluetooth")]
4250            bluetooth_extra_permission_data: BluetoothExtraPermissionData::new(),
4251            unhandled_resize_event: Default::default(),
4252            viewport_details_at_last_resize_steps: Cell::new(viewport_details),
4253            viewport_details: Cell::new(viewport_details),
4254            layout_blocker: Cell::new(LayoutBlocker::WaitingForParse),
4255            current_state: Cell::new(WindowState::Alive),
4256            #[cfg(feature = "devtools")]
4257            devtools_marker_sender: Default::default(),
4258            #[cfg(feature = "devtools")]
4259            devtools_markers: Default::default(),
4260            error_reporter,
4261            media_query_lists: DOMTracker::new(),
4262            #[cfg(feature = "bluetooth")]
4263            test_runner: Default::default(),
4264            #[cfg(feature = "webgl")]
4265            webgl_chan,
4266            #[cfg(feature = "webxr")]
4267            webxr_registry,
4268            pending_image_callbacks: Default::default(),
4269            pending_layout_images: Default::default(),
4270            pending_images_for_rasterization: Default::default(),
4271            unminified_css_dir: DomRefCell::new(if unminify_css {
4272                Some(unminified_path("unminified-css"))
4273            } else {
4274                None
4275            }),
4276            local_script_source,
4277            test_worklet: Default::default(),
4278            paint_worklet: Default::default(),
4279            exists_mut_observer: Cell::new(false),
4280            paint_api,
4281            user_scripts,
4282            player_context,
4283            throttled: Cell::new(false),
4284            layout_marker: DomRefCell::new(Rc::new(Cell::new(true))),
4285            current_event: MutNullableDom::new(None),
4286            trusted_types: Default::default(),
4287            reporting_observer_list: Default::default(),
4288            report_list: Default::default(),
4289            endpoints_list: Default::default(),
4290            script_window_proxies: ScriptThread::window_proxies(),
4291            has_pending_screenshot_readiness_request: Default::default(),
4292            visual_viewport: Default::default(),
4293            weak_script_thread,
4294            has_changed_visual_viewport_dimension: Default::default(),
4295            pending_media_query_evaluation: Default::default(),
4296            last_activation_timestamp: Cell::new(UserActivationTimestamp::PositiveInfinity),
4297            devtools_wants_updates: Default::default(),
4298            has_dispatched_scroll_event: Cell::new(false),
4299            has_dispatched_input_event: Cell::new(false),
4300            // https://html.spec.whatwg.org/multipage/#last-history-action-activation-timestamp
4301            // > A last history-action activation timestamp, which is either a DOMHighResTimeStamp
4302            // > or positive infinity, initially positive infinity.
4303            last_history_action_activation_timestamp: Cell::new(
4304                UserActivationTimestamp::PositiveInfinity,
4305            ),
4306            close_watcher_manager: CloseWatcherManager::new(),
4307        });
4308
4309        WindowBinding::Wrap::<crate::DomTypeHolder>(cx, &origin, win)
4310    }
4311
4312    pub(crate) fn task_manager(&self) -> Rc<TaskManager> {
4313        self.Document().task_manager()
4314    }
4315
4316    pub(crate) fn pipeline_id(&self) -> PipelineId {
4317        self.Document().pipeline_id()
4318    }
4319
4320    #[cfg(feature = "devtools")]
4321    pub(crate) fn live_devtools_updates(&self) -> bool {
4322        self.devtools_wants_updates.get()
4323    }
4324
4325    #[cfg(feature = "devtools")]
4326    pub(crate) fn set_devtools_wants_updates(&self, value: bool) {
4327        self.devtools_wants_updates.set(value);
4328    }
4329
4330    /// Create a new cached instance of the given value.
4331    pub(crate) fn cache_layout_value<T>(&self, value: T) -> LayoutValue<T>
4332    where
4333        T: Copy + MallocSizeOf,
4334    {
4335        LayoutValue::new(self.layout_marker.borrow().clone(), value)
4336    }
4337
4338    /// This method is an approximation of the specification [algorithm].
4339    /// It exists in this form because we still store some fields in Window/GlobalScope
4340    /// that realistically are specific to the active document. Where possible they
4341    /// should be migrated to Document and WorkerGlobalScope, but currently doing so would result
4342    /// in much more complicated code. This method is the compromise, where we mutate the values
4343    /// in place to match the values that the specification expects.
4344    ///
4345    /// [algorithm] <https://html.spec.whatwg.org/multipage/#set-up-a-window-environment-settings-object>
4346    pub(crate) fn set_up_a_window_environment_settings_object(
4347        &self,
4348        layout: Box<dyn Layout>,
4349        creation_url: ServoUrl,
4350        top_level_creation_url: ServoUrl,
4351        navigation_start: CrossProcessInstant,
4352        viewport_details: ViewportDetails,
4353    ) {
4354        *self.layout.borrow_mut() = layout;
4355        self.set_viewport_details(viewport_details);
4356        self.navigation_start.set(navigation_start);
4357
4358        // Step 6. Set settings object's creation URL to creationURL, settings object's top-level
4359        // creation URL to topLevelCreationURL, and settings object's top-level origin to topLevelOrigin.
4360        let global = self.upcast::<GlobalScope>();
4361        global.set_creation_url(creation_url);
4362        global.set_top_level_creation_url(top_level_creation_url);
4363
4364        self.Document().detach_window();
4365    }
4366}
4367
4368#[cfg(feature = "devtools")]
4369impl Window {
4370    pub(crate) fn need_emit_timeline_marker(
4371        &self,
4372        timeline_type: devtools_traits::TimelineMarkerType,
4373    ) -> bool {
4374        let markers = self.devtools_markers.borrow();
4375        markers.contains(&timeline_type)
4376    }
4377
4378    pub(crate) fn emit_timeline_marker(&self, marker: devtools_traits::TimelineMarker) {
4379        let sender = self.devtools_marker_sender.borrow();
4380        let sender = sender.as_ref().expect("There is no marker sender");
4381        sender.send(Some(marker)).unwrap();
4382    }
4383
4384    pub(crate) fn set_devtools_timeline_markers(
4385        &self,
4386        markers: Vec<devtools_traits::TimelineMarkerType>,
4387        reply: GenericSender<Option<devtools_traits::TimelineMarker>>,
4388    ) {
4389        *self.devtools_marker_sender.borrow_mut() = Some(reply);
4390        self.devtools_markers.borrow_mut().extend(markers);
4391    }
4392
4393    pub(crate) fn drop_devtools_timeline_markers(
4394        &self,
4395        markers: Vec<devtools_traits::TimelineMarkerType>,
4396    ) {
4397        let mut devtools_markers = self.devtools_markers.borrow_mut();
4398        for marker in markers {
4399            devtools_markers.remove(&marker);
4400        }
4401        if devtools_markers.is_empty() {
4402            *self.devtools_marker_sender.borrow_mut() = None;
4403        }
4404    }
4405}
4406/// An instance of a value associated with a particular snapshot of layout. This stored
4407/// value can only be read as long as the associated layout marker that is considered
4408/// valid. It will automatically become unavailable when the next layout operation is
4409/// performed.
4410#[derive(MallocSizeOf)]
4411pub(crate) struct LayoutValue<T: MallocSizeOf> {
4412    #[conditional_malloc_size_of]
4413    is_valid: Rc<Cell<bool>>,
4414    value: T,
4415}
4416
4417#[expect(unsafe_code)]
4418unsafe impl<T: JSTraceable + MallocSizeOf> JSTraceable for LayoutValue<T> {
4419    unsafe fn trace(&self, trc: *mut js::jsapi::JSTracer) {
4420        unsafe { self.value.trace(trc) };
4421    }
4422}
4423
4424impl<T: Copy + MallocSizeOf> LayoutValue<T> {
4425    fn new(marker: Rc<Cell<bool>>, value: T) -> Self {
4426        LayoutValue {
4427            is_valid: marker,
4428            value,
4429        }
4430    }
4431
4432    /// Retrieve the stored value if it is still valid.
4433    pub(crate) fn get(&self) -> Result<T, ()> {
4434        if self.is_valid.get() {
4435            return Ok(self.value);
4436        }
4437        Err(())
4438    }
4439}
4440
4441impl Window {
4442    // https://html.spec.whatwg.org/multipage/#dom-window-postmessage step 7.
4443    pub(crate) fn post_message(
4444        &self,
4445        target_origin: Option<ImmutableOrigin>,
4446        source_origin: ImmutableOrigin,
4447        source: &WindowProxy,
4448        data: StructuredSerializedData,
4449    ) {
4450        let this = Trusted::new(self);
4451        let source = Trusted::new(source);
4452        let task = task!(post_serialised_message: move |cx| {
4453            let this = this.root();
4454            let source = source.root();
4455            let document = this.Document();
4456
4457            // Step 7.1.
4458            if let Some(ref target_origin) = target_origin
4459                && !target_origin.same_origin(&*document.origin()) {
4460                    return;
4461                }
4462
4463            // Steps 7.2.-7.5.
4464            let obj = this.reflector().get_jsobject();
4465            let mut realm = AutoRealm::new(cx, NonNull::new(obj.get()).unwrap());
4466            let cx = &mut *realm;
4467            rooted!(&in(cx) let mut message_clone = UndefinedValue());
4468            if let Ok(ports) = structuredclone::read(cx, this.upcast(), data, message_clone.handle_mut()) {
4469                // Step 7.6, 7.7
4470                MessageEvent::dispatch_jsval(
4471                    cx,
4472                    this.upcast(),
4473                    this.upcast(),
4474                    message_clone.handle(),
4475                    Some(source_origin.ascii_serialization().as_ref()),
4476                    Some(&*source),
4477                    ports,
4478                );
4479            } else {
4480                // Step 4, fire messageerror.
4481                MessageEvent::dispatch_error(
4482                    cx,
4483                    this.upcast(),
4484                    this.upcast(),
4485                );
4486            }
4487        });
4488        // TODO(#12718): Use the "posted message task source".
4489        self.as_global_scope()
4490            .task_manager()
4491            .dom_manipulation_task_source()
4492            .queue(task);
4493    }
4494}
4495
4496#[derive(Clone, MallocSizeOf)]
4497pub(crate) struct CSSErrorReporter {
4498    pub(crate) pipelineid: PipelineId,
4499    pub(crate) script_chan: GenericSender<ScriptThreadMessage>,
4500}
4501unsafe_no_jsmanaged_fields!(CSSErrorReporter);
4502
4503impl ParseErrorReporter for CSSErrorReporter {
4504    fn report_error(
4505        &self,
4506        url: &UrlExtraData,
4507        location: SourceLocation,
4508        error: ContextualParseError,
4509    ) {
4510        if log_enabled!(log::Level::Info) {
4511            info!(
4512                "Url:\t{}\n{}:{} {}",
4513                url.0.as_str(),
4514                location.line,
4515                location.column,
4516                error
4517            )
4518        }
4519
4520        // TODO: report a real filename
4521        #[cfg(feature = "devtools")]
4522        let _ = self.script_chan.send(ScriptThreadMessage::ReportCSSError(
4523            self.pipelineid,
4524            url.0.to_string(),
4525            location.line,
4526            location.column,
4527            error.to_string(),
4528        ));
4529    }
4530}
4531
4532fn is_named_element_with_name_attribute(elem: &Element) -> bool {
4533    let type_ = match elem.upcast::<Node>().type_id() {
4534        NodeTypeId::Element(ElementTypeId::HTMLElement(type_)) => type_,
4535        _ => return false,
4536    };
4537    matches!(
4538        type_,
4539        HTMLElementTypeId::HTMLEmbedElement |
4540            HTMLElementTypeId::HTMLFormElement |
4541            HTMLElementTypeId::HTMLImageElement |
4542            HTMLElementTypeId::HTMLObjectElement
4543    )
4544}
4545
4546fn is_named_element_with_id_attribute(elem: &Element) -> bool {
4547    elem.is_html_element() || elem.is_svg_element()
4548}
4549
4550#[expect(unsafe_code)]
4551#[unsafe(no_mangle)]
4552/// Helper for interactive debugging sessions in lldb/gdb.
4553unsafe extern "C" fn dump_js_stack(cx: *mut RawJSContext) {
4554    unsafe {
4555        DumpJSStack(cx, true, false, false);
4556    }
4557}
4558
4559impl WindowHelpers for Window {
4560    fn create_named_properties_object(
4561        cx: &mut JSContext,
4562        proto: HandleObject,
4563        object: MutableHandleObject,
4564    ) {
4565        Self::create_named_properties_object(cx, proto, object)
4566    }
4567}
4568
4569impl HasOrigin for Window {
4570    fn origin(&self) -> MutableOrigin {
4571        Window::origin(self)
4572    }
4573}