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