Skip to main content

script/dom/window/
window.rs

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