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
5use std::borrow::ToOwned;
6use std::cell::{Cell, RefCell, RefMut};
7use std::collections::HashSet;
8use std::collections::hash_map::Entry;
9use std::default::Default;
10use std::ffi::c_void;
11use std::io::{Write, stderr, stdout};
12use std::ptr::NonNull;
13use std::rc::{Rc, Weak};
14use std::sync::Arc;
15use std::time::{Duration, Instant};
16
17use app_units::Au;
18use base64::Engine;
19use content_security_policy::Violation;
20use content_security_policy::sandboxing_directive::SandboxingFlagSet;
21use crossbeam_channel::{Sender, unbounded};
22use cssparser::SourceLocation;
23use devtools_traits::{ScriptToDevtoolsControlMsg, TimelineMarker, TimelineMarkerType};
24use dom_struct::dom_struct;
25use embedder_traits::user_contents::UserScript;
26use embedder_traits::{
27    AlertResponse, ConfirmResponse, EmbedderMsg, PromptResponse, ScriptToEmbedderChan,
28    SimpleDialogRequest, Theme, UntrustedNodeAddress, ViewportDetails, WebDriverLoadStatus,
29};
30use euclid::{Point2D, Rect, Scale, Size2D, Vector2D};
31use fonts::{
32    CspViolationHandler, FontContext, NetworkTimingHandler, WebFontDocumentContext,
33    WebFontSetDifference,
34};
35use js::context::{JSContext, NoGC};
36use js::conversions::ToJSValConvertible;
37use js::glue::DumpJSStack;
38use js::jsapi::{
39    GCReason, GetObjectRealmOrNull, Heap, JSContext as RawJSContext, JSObject, JSPROP_ENUMERATE,
40    SetRealmPrincipals,
41};
42use js::jsval::{NullValue, UndefinedValue};
43use js::realm::{AutoRealm, CurrentRealm};
44use js::rust::wrappers2::{JS_DefineProperty, JS_GC};
45use js::rust::{
46    CustomAutoRooter, CustomAutoRooterGuard, HandleObject, HandleValue, MutableHandleObject,
47    MutableHandleValue,
48};
49use layout_api::{
50    AxesOverflow, BoxAreaType, CSSPixelRectVec, FragmentType, HitTestFlags, Layout,
51    LayoutImageDestination, PendingImage, PendingImageState, PendingRasterizationImage,
52    PhysicalSides, QueryMsg, ReflowGoal, ReflowPhasesRun, ReflowRequest, ReflowRequestRestyle,
53    ReflowStatistics, RestyleReason, ScrollContainerQueryFlags, ScrollContainerResponse,
54    TrustedNodeAddress, combine_id_with_fragment_type,
55};
56use malloc_size_of::MallocSizeOf;
57use media::WindowGLContext;
58use net_traits::image_cache::{
59    ImageCache, ImageCacheResponseCallback, ImageCacheResponseMessage, ImageLoadListener,
60    ImageResponse, PendingImageId, PendingImageResponse, RasterizationCompleteResponse,
61};
62use net_traits::request::{Origin, Referrer, RequestClient};
63use net_traits::{ResourceFetchTiming, ResourceThreads};
64use num_traits::ToPrimitive;
65use paint_api::largest_contentful_paint_candidate::LCPCandidate;
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::Promise;
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::microtask::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    throttled: Cell<bool>,
453
454    /// A shared marker for the validity of any cached layout values. A value of true
455    /// indicates that any such values remain valid; any new layout that invalidates
456    /// those values will cause the marker to be set to false.
457    #[conditional_malloc_size_of]
458    layout_marker: DomRefCell<Rc<Cell<bool>>>,
459
460    /// <https://dom.spec.whatwg.org/#window-current-event>
461    current_event: DomRefCell<Option<Dom<Event>>>,
462
463    /// <https://w3c.github.io/reporting/#windoworworkerglobalscope-registered-reporting-observer-list>
464    reporting_observer_list: DomRefCell<Vec<Dom<ReportingObserver>>>,
465
466    /// <https://w3c.github.io/reporting/#windoworworkerglobalscope-reports>
467    report_list: DomRefCell<Vec<Report>>,
468
469    /// <https://w3c.github.io/reporting/#windoworworkerglobalscope-endpoints>
470    #[no_trace]
471    endpoints_list: DomRefCell<Vec<ReportingEndpoint>>,
472
473    /// The window proxies the script thread knows.
474    #[conditional_malloc_size_of]
475    script_window_proxies: Rc<ScriptWindowProxies>,
476
477    /// Whether or not this [`Window`] has a pending screenshot readiness request.
478    has_pending_screenshot_readiness_request: Cell<bool>,
479
480    /// Visual viewport interface that is associated to this [`Window`].
481    /// <https://drafts.csswg.org/cssom-view/#dom-window-visualviewport>
482    visual_viewport: MutNullableDom<VisualViewport>,
483
484    /// [`VisualViewport`] dimension changed and we need to process it on the next tick.
485    has_changed_visual_viewport_dimension: Cell<bool>,
486
487    /// Whether something has changed since the last "update the rendering" turn
488    /// that may affect media query results, like a theme change. Consumed
489    /// together with the `resized` signal to decide whether to re-evaluate
490    /// `MediaQueryList`s and dispatch `change` events.
491    pending_media_query_evaluation: Cell<bool>,
492
493    /// <https://html.spec.whatwg.org/multipage/#last-activation-timestamp>
494    #[no_trace]
495    last_activation_timestamp: Cell<UserActivationTimestamp>,
496
497    /// A flag to indicate whether the developer tools has requested
498    /// live updates from the window.
499    devtools_wants_updates: Cell<bool>,
500
501    /// <https://www.w3.org/TR/largest-contentful-paint/#has-dispatched-scroll-event>
502    has_dispatched_scroll_event: Cell<bool>,
503
504    /// <https://wicg.github.io/event-timing/#has-dispatched-input-event>
505    has_dispatched_input_event: Cell<bool>,
506}
507
508impl Window {
509    pub(crate) fn script_thread(&self) -> Rc<ScriptThread> {
510        Weak::upgrade(&self.weak_script_thread)
511            .expect("Weak reference should always be upgradable when a ScriptThread is running")
512    }
513
514    pub(crate) fn webview_id(&self) -> WebViewId {
515        self.webview_id
516    }
517
518    pub(crate) fn as_global_scope(&self) -> &GlobalScope {
519        self.upcast::<GlobalScope>()
520    }
521
522    /// <https://www.w3.org/TR/largest-contentful-paint/#has-dispatched-scroll-event>
523    pub(crate) fn mark_has_dispatched_scroll_event(&self) {
524        self.has_dispatched_scroll_event.set(true);
525    }
526
527    /// <https://wicg.github.io/event-timing/#has-dispatched-input-event>
528    pub(crate) fn mark_has_dispatched_input_event(&self) {
529        self.has_dispatched_input_event.set(true);
530    }
531
532    pub(crate) fn layout(&self) -> Ref<'_, Box<dyn Layout>> {
533        self.layout.borrow()
534    }
535
536    pub(crate) fn layout_mut(&self) -> RefMut<'_, Box<dyn Layout>> {
537        self.layout.borrow_mut()
538    }
539
540    pub(crate) fn get_exists_mut_observer(&self) -> bool {
541        self.exists_mut_observer.get()
542    }
543
544    pub(crate) fn set_exists_mut_observer(&self) {
545        self.exists_mut_observer.set(true);
546    }
547
548    #[expect(unsafe_code)]
549    pub(crate) fn clear_js_runtime_for_script_deallocation(&self) {
550        self.as_global_scope()
551            .remove_web_messaging_and_dedicated_workers_infra();
552        unsafe {
553            *self.js_runtime.borrow_for_script_deallocation() = None;
554            self.window_proxy.set(None);
555            self.current_state.set(WindowState::Zombie);
556            self.as_global_scope()
557                .task_manager()
558                .cancel_all_tasks_and_ignore_future_tasks();
559        }
560    }
561
562    /// A convenience method for
563    /// <https://html.spec.whatwg.org/multipage/#a-browsing-context-is-discarded>
564    pub(crate) fn discard_browsing_context(&self) {
565        let proxy = self
566            .window_proxy
567            .get()
568            .expect("Discarding a BC from a window that has none");
569        proxy.discard_browsing_context();
570
571        // Step 4 of https://html.spec.whatwg.org/multipage/#discard-a-document
572        // Other steps performed when the `PipelineExit` message
573        // is handled by the ScriptThread.
574        self.as_global_scope()
575            .task_manager()
576            .cancel_all_tasks_and_ignore_future_tasks();
577    }
578
579    /// Get a sender to the time profiler thread.
580    pub(crate) fn time_profiler_chan(&self) -> &TimeProfilerChan {
581        self.globalscope.time_profiler_chan()
582    }
583
584    /// <https://html.spec.whatwg.org/multipage/#script-settings-for-window-objects:concept-settings-object-origin>
585    pub(crate) fn origin(&self) -> MutableOrigin {
586        // > Return the origin of window's associated Document.
587        self.Document().origin().clone()
588    }
589
590    pub(crate) fn main_thread_script_chan(&self) -> &Sender<MainThreadScriptMsg> {
591        &self.script_chan
592    }
593
594    pub(crate) fn parent_info(&self) -> Option<PipelineId> {
595        self.parent_info
596    }
597
598    pub(crate) fn new_script_pair(&self) -> (ScriptEventLoopSender, ScriptEventLoopReceiver) {
599        let (sender, receiver) = unbounded();
600        (
601            ScriptEventLoopSender::MainThread(sender),
602            ScriptEventLoopReceiver::MainThread(receiver),
603        )
604    }
605
606    pub(crate) fn event_loop_sender(&self) -> ScriptEventLoopSender {
607        ScriptEventLoopSender::MainThread(self.script_chan.clone())
608    }
609
610    pub(crate) fn image_cache(&self) -> Arc<dyn ImageCache> {
611        self.Document().image_cache()
612    }
613
614    /// This can panic if it is called after the browsing context has been discarded
615    pub(crate) fn window_proxy(&self) -> DomRoot<WindowProxy> {
616        self.window_proxy.get().unwrap()
617    }
618
619    pub(crate) fn append_reporting_observer(&self, reporting_observer: &ReportingObserver) {
620        self.reporting_observer_list
621            .borrow_mut()
622            .push(Dom::from_ref(reporting_observer));
623    }
624
625    pub(crate) fn remove_reporting_observer(&self, reporting_observer: &ReportingObserver) {
626        let index = {
627            let list = self.reporting_observer_list.borrow();
628            list.iter()
629                .position(|observer| &**observer == reporting_observer)
630        };
631
632        if let Some(index) = index {
633            self.reporting_observer_list.borrow_mut().remove(index);
634        }
635    }
636
637    pub(crate) fn registered_reporting_observers(&self) -> Vec<DomRoot<ReportingObserver>> {
638        self.reporting_observer_list
639            .borrow()
640            .iter()
641            .map(|observer| DomRoot::from_ref(&**observer))
642            .collect()
643    }
644
645    pub(crate) fn append_report(&self, report: Report) {
646        self.report_list.borrow_mut().push(report);
647        let trusted_window = Trusted::new(self);
648        self.upcast::<GlobalScope>()
649            .task_manager()
650            .dom_manipulation_task_source()
651            .queue(task!(send_to_reporting_endpoints: move || {
652                let window = trusted_window.root();
653                let reports = std::mem::take(&mut *window.report_list.borrow_mut());
654                window.upcast::<GlobalScope>().send_reports_to_endpoints(
655                    reports,
656                    window.endpoints_list.borrow().clone(),
657                );
658            }));
659    }
660
661    pub(crate) fn buffered_reports(&self) -> Vec<Report> {
662        self.report_list.borrow().clone()
663    }
664
665    pub(crate) fn set_endpoints_list(&self, endpoints: Vec<ReportingEndpoint>) {
666        *self.endpoints_list.borrow_mut() = endpoints;
667    }
668
669    /// Returns the window proxy if it has not been discarded.
670    /// <https://html.spec.whatwg.org/multipage/#a-browsing-context-is-discarded>
671    pub(crate) fn undiscarded_window_proxy(&self) -> Option<DomRoot<WindowProxy>> {
672        self.window_proxy
673            .get()
674            .filter(|window_proxy| !window_proxy.is_browsing_context_discarded())
675    }
676
677    /// Get the active [`Document`] of top-level browsing context, or return [`Window`]'s [`Document`]
678    /// if it's browing context is the top-level browsing context. Returning none if the [`WindowProxy`]
679    /// is discarded or the [`Document`] is in another `ScriptThread`.
680    /// <https://html.spec.whatwg.org/multipage/#top-level-browsing-context>
681    pub(crate) fn top_level_document_if_local(&self) -> Option<DomRoot<Document>> {
682        if self.is_top_level() {
683            return Some(self.Document());
684        }
685
686        let window_proxy = self.undiscarded_window_proxy()?;
687        self.script_window_proxies
688            .find_window_proxy(window_proxy.webview_id().into())?
689            .document()
690    }
691
692    #[cfg(feature = "bluetooth")]
693    pub(crate) fn bluetooth_thread(&self) -> GenericSender<BluetoothRequest> {
694        self.bluetooth_thread.clone()
695    }
696
697    #[cfg(feature = "bluetooth")]
698    pub(crate) fn bluetooth_extra_permission_data(&self) -> &BluetoothExtraPermissionData {
699        &self.bluetooth_extra_permission_data
700    }
701
702    pub(crate) fn css_error_reporter(&self) -> &CSSErrorReporter {
703        &self.error_reporter
704    }
705
706    #[cfg(feature = "webgl")]
707    pub(crate) fn webgl_chan(&self) -> Option<WebGLChan> {
708        self.webgl_chan.clone()
709    }
710
711    // TODO: rename the function to webgl_chan after the existing `webgl_chan` function is removed.
712    #[cfg(feature = "webgl")]
713    pub(crate) fn webgl_chan_value(&self) -> Option<WebGLChan> {
714        self.webgl_chan.clone()
715    }
716
717    #[cfg(feature = "webxr")]
718    pub(crate) fn webxr_registry(&self) -> Option<webxr_api::Registry> {
719        self.webxr_registry.clone()
720    }
721
722    fn new_paint_worklet(&self, cx: &mut JSContext) -> DomRoot<Worklet> {
723        debug!("Creating new paint worklet.");
724
725        let worklet_global_scope_init = self.into();
726        Worklet::new(
727            cx,
728            self,
729            WorkletGlobalScopeType::Paint,
730            Box::new(|| Rc::new(StatelessWorkletThreadPool::spawn(worklet_global_scope_init))),
731        )
732    }
733
734    pub(crate) fn register_image_cache_listener(
735        &self,
736        id: PendingImageId,
737        callback: impl Fn(PendingImageResponse, &mut JSContext) + 'static,
738    ) -> ImageCacheResponseCallback {
739        self.pending_image_callbacks
740            .borrow_mut()
741            .entry(id)
742            .or_default()
743            .push(PendingImageCallback(Box::new(callback)));
744
745        let image_cache_sender = self.image_cache_sender.clone();
746        Box::new(move |message| {
747            let _ = image_cache_sender.send(message);
748        })
749    }
750
751    fn pending_layout_image_notification(&self, no_gc: &NoGC, response: PendingImageResponse) {
752        let mut images = self.pending_layout_images.borrow_mut();
753        let nodes = images.entry(response.id);
754        let nodes = match nodes {
755            Entry::Occupied(nodes) => nodes,
756            Entry::Vacant(_) => return,
757        };
758        if matches!(
759            response.response,
760            ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode
761        ) {
762            for ancillary_data in nodes.get() {
763                match ancillary_data.destination {
764                    LayoutImageDestination::BoxTreeConstruction => {
765                        ancillary_data.node.dirty(no_gc, NodeDamage::Other);
766                    },
767                    LayoutImageDestination::DisplayListBuilding => {
768                        self.layout().set_needs_new_display_list();
769                    },
770                }
771            }
772        }
773
774        match response.response {
775            ImageResponse::MetadataLoaded(_) => {},
776            ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode => {
777                nodes.remove();
778            },
779        }
780    }
781
782    pub(crate) fn handle_image_rasterization_complete_notification(
783        &self,
784        no_gc: &NoGC,
785        response: RasterizationCompleteResponse,
786    ) {
787        let mut images = self.pending_images_for_rasterization.borrow_mut();
788        let nodes = images.entry((response.image_id, response.requested_size));
789        let nodes = match nodes {
790            Entry::Occupied(nodes) => nodes,
791            Entry::Vacant(_) => return,
792        };
793        for node in nodes.get() {
794            node.dirty(no_gc, NodeDamage::Other);
795        }
796        nodes.remove();
797    }
798
799    pub(crate) fn pending_image_notification(
800        &self,
801        response: PendingImageResponse,
802        cx: &mut JSContext,
803    ) {
804        // We take the images here, in order to prevent maintaining a mutable borrow when
805        // image callbacks are called. These, in turn, can trigger garbage collection.
806        // Normally this shouldn't trigger more pending image notifications, but just in
807        // case we do not want to cause a double borrow here.
808        let mut images = std::mem::take(&mut *self.pending_image_callbacks.borrow_mut());
809        let Entry::Occupied(callbacks) = images.entry(response.id) else {
810            let _ = std::mem::replace(&mut *self.pending_image_callbacks.borrow_mut(), images);
811            return;
812        };
813
814        for callback in callbacks.get() {
815            callback.0(response.clone(), cx);
816        }
817
818        match response.response {
819            ImageResponse::MetadataLoaded(_) => {},
820            ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode => {
821                callbacks.remove();
822            },
823        }
824
825        let _ = std::mem::replace(&mut *self.pending_image_callbacks.borrow_mut(), images);
826    }
827
828    pub(crate) fn paint_api(&self) -> &CrossProcessPaintApi {
829        &self.paint_api
830    }
831
832    pub(crate) fn userscripts(&self) -> &[UserScript] {
833        &self.user_scripts
834    }
835
836    pub(crate) fn get_player_context(&self) -> WindowGLContext {
837        self.player_context.clone()
838    }
839
840    // see note at https://dom.spec.whatwg.org/#concept-event-dispatch step 2
841    pub(crate) fn dispatch_event_with_target_override(&self, cx: &mut JSContext, event: &Event) {
842        event.dispatch(cx, self.upcast(), true);
843    }
844
845    pub(crate) fn font_context(&self) -> Arc<FontContext> {
846        self.layout().font_context().clone()
847    }
848
849    pub(crate) fn ongoing_navigation(&self) -> OngoingNavigation {
850        self.ongoing_navigation.get()
851    }
852
853    /// <https://html.spec.whatwg.org/multipage/#set-the-ongoing-navigation>
854    pub(crate) fn set_ongoing_navigation(&self) -> OngoingNavigation {
855        // Note: since this value, for now, is only used in a single `ScriptThread`,
856        // we just increment it (it is not a uuid), which implies not
857        // using a `newValue` variable.
858        let new_value = self.ongoing_navigation.get().0.wrapping_add(1);
859
860        // 1. If navigable's ongoing navigation is equal to newValue, then return.
861        // Note: cannot happen in the way it is currently used.
862
863        // TODO: 2. Inform the navigation API about aborting navigation given navigable.
864
865        // 3. Set navigable's ongoing navigation to newValue.
866        self.ongoing_navigation.set(OngoingNavigation(new_value));
867
868        // Note: Return the ongoing navigation for the caller to use.
869        OngoingNavigation(new_value)
870    }
871
872    /// <https://html.spec.whatwg.org/multipage/#nav-stop>
873    fn stop_loading(&self, cx: &mut JSContext) {
874        // 1. Let document be navigable's active document.
875        let doc = self.Document();
876
877        // 2. If document's unload counter is 0,
878        // and navigable's ongoing navigation is a navigation ID,
879        // then set the ongoing navigation for navigable to null.
880        //
881        // Note: since the concept of `navigable` is nascent in Servo,
882        // for now we do two things:
883        // - increment the `ongoing_navigation`(preventing planned form navigations).
884        // - Send a `AbortLoadUrl` message(in case the navigation
885        // already started at the constellation).
886        self.set_ongoing_navigation();
887
888        // 3. Abort a document and its descendants given document.
889        doc.abort_a_document_and_its_descendants(cx);
890    }
891
892    /// <https://html.spec.whatwg.org/multipage/#destroy-a-top-level-traversable>
893    fn destroy_top_level_traversable(&self, cx: &mut JSContext) {
894        // Step 1. Let browsingContext be traversable's active browsing context.
895        // TODO
896        // Step 2. For each historyEntry in traversable's session history entries:
897        // TODO
898        // Step 2.1. Let document be historyEntry's document.
899        let document = self.Document();
900        // Step 2.2. If document is not null, then destroy a document and its descendants given document.
901        document.destroy_document_and_its_descendants(cx);
902        // Step 3-6.
903        self.send_to_constellation(ScriptToConstellationMessage::DiscardTopLevelBrowsingContext);
904    }
905
906    /// <https://html.spec.whatwg.org/multipage/#definitely-close-a-top-level-traversable>
907    fn definitely_close(&self, cx: &mut JSContext) {
908        let document = self.Document();
909        // Step 1. Let toUnload be traversable's active document's inclusive descendant navigables.
910        //
911        // Implemented by passing `false` into the method below
912        // Step 2. If the result of checking if unloading is canceled for toUnload is not "continue", then return.
913        if !document.check_if_unloading_is_cancelled(cx, false) {
914            return;
915        }
916        // Step 3. Append the following session history traversal steps to traversable:
917        // TODO
918        // Step 3.2. Unload a document and its descendants given traversable's active document, null, and afterAllUnloads.
919        document.unload(cx, false);
920        // Step 3.1. Let afterAllUnloads be an algorithm step which destroys traversable.
921        self.destroy_top_level_traversable(cx);
922    }
923
924    /// <https://html.spec.whatwg.org/multipage/#cannot-show-simple-dialogs>
925    fn cannot_show_simple_dialogs(&self) -> bool {
926        // Step 1: If the active sandboxing flag set of window's associated Document has
927        // the sandboxed modals flag set, then return true.
928        if self
929            .Document()
930            .has_active_sandboxing_flag(SandboxingFlagSet::SANDBOXED_MODALS_FLAG)
931        {
932            return true;
933        }
934
935        // Step 2: If window's relevant settings object's origin and window's relevant settings
936        // object's top-level origin are not same origin-domain, then return true.
937        //
938        // TODO: This check doesn't work currently because it seems that comparing two
939        // opaque domains doesn't work between GlobalScope::top_level_creation_url and
940        // Document::origin().
941
942        // Step 3: If window's relevant agent's event loop's termination nesting level is nonzero,
943        // then optionally return true.
944        // TODO: This is unsupported currently.
945
946        // Step 4: Optionally, return true. (For example, the user agent might give the
947        // user the option to ignore all modal dialogs, and would thus abort at this step
948        // whenever the method was invoked.)
949        // TODO: The embedder currently cannot block an alert before it is sent to the embedder. This
950        // requires changes to the API.
951
952        // Step 5: Return false.
953        false
954    }
955
956    pub(crate) fn perform_a_microtask_checkpoint(&self, cx: &mut JSContext) {
957        self.script_thread().perform_a_microtask_checkpoint(cx);
958    }
959
960    pub(crate) fn web_font_context(&self, no_gc: &NoGC) -> WebFontDocumentContext {
961        let global = self.as_global_scope();
962        let task_source = global
963            .task_manager()
964            .dom_manipulation_task_source()
965            .to_sendable();
966        let target_global = Trusted::new(global);
967        let document = self.document_unrooted(no_gc);
968        WebFontDocumentContext {
969            policy_container: document.policy_container().clone(),
970            request_client: self.request_client(Some(no_gc)),
971            document_url: document.base_url(),
972            csp_handler: Box::new(FontCspHandler {
973                global: target_global.clone(),
974                task_source: task_source.clone(),
975            }),
976            network_timing_handler: Box::new(FontNetworkTimingHandler {
977                global: target_global,
978                task_source,
979            }),
980        }
981    }
982
983    /// Part of <https://fetch.spec.whatwg.org/#populate-request-from-client>
984    pub(crate) fn request_client(&self, no_gc: Option<&NoGC>) -> RequestClient {
985        // Step 1.2.2. If global is a Window object and global’s navigable is not null,
986        // then set request’s traversable for user prompts to global’s navigable’s traversable navigable.
987        let (
988            preloaded_resources,
989            insecure_requests_policy,
990            has_trustworthy_ancestor_origin,
991            policy_container,
992            origin,
993        ) = if let Some(no_gc) = no_gc {
994            let document = self.document_unrooted(no_gc);
995            (
996                document.preloaded_resources().clone(),
997                document.insecure_requests_policy(),
998                document.has_trustworthy_ancestor_or_current_origin(),
999                document.policy_container().clone(),
1000                document.origin().clone(),
1001            )
1002        } else {
1003            let document = self.Document();
1004            (
1005                document.preloaded_resources().clone(),
1006                document.insecure_requests_policy(),
1007                document.has_trustworthy_ancestor_or_current_origin(),
1008                document.policy_container().clone(),
1009                document.origin().clone(),
1010            )
1011        };
1012        RequestClient {
1013            preloaded_resources,
1014            policy_container,
1015            origin: Origin::Origin(origin.immutable().clone()),
1016            is_nested_browsing_context: !self.is_top_level(),
1017            insecure_requests_policy,
1018            has_trustworthy_ancestor_origin,
1019        }
1020    }
1021
1022    #[expect(unsafe_code)]
1023    pub(crate) fn gc(&self, cx: &mut JSContext) {
1024        unsafe { JS_GC(cx, GCReason::API) };
1025    }
1026
1027    pub(crate) fn with_timers<T>(&self, f: impl FnOnce(&OneshotTimers) -> T) -> T {
1028        let document = self.Document();
1029        f(document.timers())
1030    }
1031}
1032
1033#[derive(Debug, MallocSizeOf)]
1034struct FontCspHandler {
1035    global: Trusted<GlobalScope>,
1036    task_source: SendableTaskSource,
1037}
1038
1039impl CspViolationHandler for FontCspHandler {
1040    fn process_violations(&self, violations: Vec<Violation>) {
1041        let global = self.global.clone();
1042        self.task_source.queue(task!(csp_violation: move |cx| {
1043            global.root().report_csp_violations(cx, violations, None, None);
1044        }));
1045    }
1046
1047    fn clone(&self) -> Box<dyn CspViolationHandler> {
1048        Box::new(Self {
1049            global: self.global.clone(),
1050            task_source: self.task_source.clone(),
1051        })
1052    }
1053}
1054
1055#[derive(Debug, MallocSizeOf)]
1056struct FontNetworkTimingHandler {
1057    global: Trusted<GlobalScope>,
1058    task_source: SendableTaskSource,
1059}
1060
1061impl NetworkTimingHandler for FontNetworkTimingHandler {
1062    fn submit_timing(&self, url: ServoUrl, response: ResourceFetchTiming) {
1063        let global = self.global.clone();
1064        self.task_source.queue(task!(network_timing: move |cx| {
1065            submit_timing(
1066                cx,
1067                &FontFetchListener {
1068                    url,
1069                    global
1070                },
1071                &Ok(()),
1072                &response,
1073            );
1074        }));
1075    }
1076
1077    fn clone(&self) -> Box<dyn NetworkTimingHandler> {
1078        Box::new(Self {
1079            global: self.global.clone(),
1080            task_source: self.task_source.clone(),
1081        })
1082    }
1083}
1084
1085#[derive(Debug)]
1086struct FontFetchListener {
1087    global: Trusted<GlobalScope>,
1088    url: ServoUrl,
1089}
1090
1091impl ResourceTimingListener for FontFetchListener {
1092    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
1093        (InitiatorType::Css, self.url.clone())
1094    }
1095
1096    fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
1097        self.global.root()
1098    }
1099}
1100
1101// https://html.spec.whatwg.org/multipage/#atob
1102pub(crate) fn base64_btoa(input: DOMString) -> Fallible<DOMString> {
1103    // "The btoa() method must throw an InvalidCharacterError exception if
1104    //  the method's first argument contains any character whose code point
1105    //  is greater than U+00FF."
1106    if input.str().chars().any(|c: char| c > '\u{FF}') {
1107        Err(Error::InvalidCharacter(None))
1108    } else {
1109        // "Otherwise, the user agent must convert that argument to a
1110        //  sequence of octets whose nth octet is the eight-bit
1111        //  representation of the code point of the nth character of
1112        //  the argument,"
1113        let octets = input
1114            .str()
1115            .chars()
1116            .map(|c: char| c as u8)
1117            .collect::<Vec<u8>>();
1118
1119        // "and then must apply the base64 algorithm to that sequence of
1120        //  octets, and return the result. [RFC4648]"
1121        let config =
1122            base64::engine::general_purpose::GeneralPurposeConfig::new().with_encode_padding(true);
1123        let engine = base64::engine::GeneralPurpose::new(&base64::alphabet::STANDARD, config);
1124        Ok(DOMString::from(engine.encode(octets)))
1125    }
1126}
1127
1128// https://html.spec.whatwg.org/multipage/#atob
1129pub(crate) fn base64_atob(input: DOMString) -> Fallible<DOMString> {
1130    // "Remove all space characters from input."
1131    fn is_html_space(c: char) -> bool {
1132        HTML_SPACE_CHARACTERS.contains(&c)
1133    }
1134    let without_spaces = input
1135        .str()
1136        .chars()
1137        .filter(|&c| !is_html_space(c))
1138        .collect::<String>();
1139    let mut input = &*without_spaces;
1140
1141    // "If the length of input divides by 4 leaving no remainder, then:
1142    //  if input ends with one or two U+003D EQUALS SIGN (=) characters,
1143    //  remove them from input."
1144    if input.len() % 4 == 0 {
1145        if input.ends_with("==") {
1146            input = &input[..input.len() - 2]
1147        } else if input.ends_with('=') {
1148            input = &input[..input.len() - 1]
1149        }
1150    }
1151
1152    // "If the length of input divides by 4 leaving a remainder of 1,
1153    //  throw an InvalidCharacterError exception and abort these steps."
1154    if input.len() % 4 == 1 {
1155        return Err(Error::InvalidCharacter(None));
1156    }
1157
1158    // "If input contains a character that is not in the following list of
1159    //  characters and character ranges, throw an InvalidCharacterError
1160    //  exception and abort these steps:
1161    //
1162    //  U+002B PLUS SIGN (+)
1163    //  U+002F SOLIDUS (/)
1164    //  Alphanumeric ASCII characters"
1165    if input
1166        .chars()
1167        .any(|c| c != '+' && c != '/' && !c.is_alphanumeric())
1168    {
1169        return Err(Error::InvalidCharacter(None));
1170    }
1171
1172    let config = base64::engine::general_purpose::GeneralPurposeConfig::new()
1173        .with_decode_padding_mode(base64::engine::DecodePaddingMode::RequireNone)
1174        .with_decode_allow_trailing_bits(true);
1175    let engine = base64::engine::GeneralPurpose::new(&base64::alphabet::STANDARD, config);
1176
1177    let data = engine
1178        .decode(input)
1179        .map_err(|_| Error::InvalidCharacter(None))?;
1180    Ok(data.iter().map(|&b| b as char).collect::<String>().into())
1181}
1182
1183impl WindowMethods<crate::DomTypeHolder> for Window {
1184    /// <https://html.spec.whatwg.org/multipage/#dom-alert>
1185    fn Alert_(&self) {
1186        // Step 2: If the method was invoked with no arguments, then let message be the
1187        // empty string; otherwise, let message be the method's first argument.
1188        self.Alert(DOMString::new());
1189    }
1190
1191    /// <https://html.spec.whatwg.org/multipage/#dom-alert>
1192    fn Alert(&self, mut message: DOMString) {
1193        // Step 1: If we cannot show simple dialogs for this, then return.
1194        if self.cannot_show_simple_dialogs() {
1195            return;
1196        }
1197
1198        // Step 2 is handled in the other variant of this method.
1199        //
1200        // Step 3: Set message to the result of normalizing newlines given message.
1201        message.normalize_newlines();
1202
1203        // Step 4. Set message to the result of optionally truncating message.
1204        // This is up to the embedder.
1205
1206        // Step 5: Let userPromptHandler be WebDriver BiDi user prompt opened with this,
1207        // "alert", and message.
1208        // TODO: Add support for WebDriver BiDi.
1209
1210        // Step 6: If userPromptHandler is "none", then:
1211        //  1. Show message to the user, treating U+000A LF as a line break.
1212        //  2. Optionally, pause while waiting for the user to acknowledge the message.
1213        {
1214            // Print to the console.
1215            // Ensure that stderr doesn't trample through the alert() we use to
1216            // communicate test results (see executorservo.py in wptrunner).
1217            let stderr = stderr();
1218            let mut stderr = stderr.lock();
1219            let stdout = stdout();
1220            let mut stdout = stdout.lock();
1221            writeln!(&mut stdout, "\nALERT: {message}").unwrap();
1222            stdout.flush().unwrap();
1223            stderr.flush().unwrap();
1224        }
1225
1226        let (sender, receiver) =
1227            ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1228        let dialog = SimpleDialogRequest::Alert {
1229            id: self.Document().embedder_controls().next_control_id(),
1230            message: String::from(message),
1231            response_sender: sender,
1232        };
1233        self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1234        receiver.recv().unwrap_or_else(|_| {
1235            // If the receiver is closed, we assume the dialog was cancelled.
1236            debug!("Alert dialog was cancelled or failed to show.");
1237            AlertResponse::Ok
1238        });
1239
1240        // Step 7: Invoke WebDriver BiDi user prompt closed with this, "alert", and true.
1241        // TODO: Implement support for WebDriver BiDi.
1242    }
1243
1244    /// <https://w3c.github.io/ServiceWorker/#global-caches-attribute>
1245    fn Caches(&self, cx: &mut JSContext) -> DomRoot<CacheStorage> {
1246        self.caches
1247            .or_init(|| CacheStorage::new(cx, self.as_global_scope()))
1248    }
1249
1250    /// <https://html.spec.whatwg.org/multipage/#dom-confirm>
1251    fn Confirm(&self, mut message: DOMString) -> bool {
1252        // Step 1: If we cannot show simple dialogs for this, then return false.
1253        if self.cannot_show_simple_dialogs() {
1254            return false;
1255        }
1256
1257        // Step 2: Set message to the result of normalizing newlines given message.
1258        message.normalize_newlines();
1259
1260        // Step 3: Set message to the result of optionally truncating message.
1261        // We let the embedder handle this.
1262
1263        // Step 4: Show message to the user, treating U+000A LF as a line break, and ask
1264        // the user to respond with a positive or negative response.
1265        let (sender, receiver) =
1266            ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1267        let dialog = SimpleDialogRequest::Confirm {
1268            id: self.Document().embedder_controls().next_control_id(),
1269            message: String::from(message),
1270            response_sender: sender,
1271        };
1272        self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1273
1274        // Step 5: Let userPromptHandler be WebDriver BiDi user prompt opened with this,
1275        // "confirm", and message.
1276        //
1277        // Step 6: Let accepted be false.
1278        //
1279        // Step 7: If userPromptHandler is "none", then:
1280        //  1. Pause until the user responds either positively or negatively.
1281        //  2. If the user responded positively, then set accepted to true.
1282        //
1283        // Step 8: If userPromptHandler is "accept", then set accepted to true.
1284        //
1285        // Step 9: Invoke WebDriver BiDi user prompt closed with this, "confirm", and accepted.
1286        // TODO: Implement WebDriver BiDi and handle these steps.
1287        //
1288        // Step 10: Return accepted.
1289        match receiver.recv() {
1290            Ok(ConfirmResponse::Ok) => true,
1291            Ok(ConfirmResponse::Cancel) => false,
1292            Err(_) => {
1293                warn!("Confirm dialog was cancelled or failed to show.");
1294                false
1295            },
1296        }
1297    }
1298
1299    /// <https://html.spec.whatwg.org/multipage/#dom-prompt>
1300    fn Prompt(&self, mut message: DOMString, default: DOMString) -> Option<DOMString> {
1301        // Step 1: If we cannot show simple dialogs for this, then return null.
1302        if self.cannot_show_simple_dialogs() {
1303            return None;
1304        }
1305
1306        // Step 2: Set message to the result of normalizing newlines given message.
1307        message.normalize_newlines();
1308
1309        // Step 3. Set message to the result of optionally truncating message.
1310        // Step 4: Set default to the result of optionally truncating default.
1311        // We let the embedder handle these steps.
1312
1313        // Step 5: Show message to the user, treating U+000A LF as a line break, and ask
1314        // the user to either respond with a string value or abort. The response must be
1315        // defaulted to the value given by default.
1316        let (sender, receiver) =
1317            ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1318        let dialog = SimpleDialogRequest::Prompt {
1319            id: self.Document().embedder_controls().next_control_id(),
1320            message: String::from(message),
1321            default: String::from(default),
1322            response_sender: sender,
1323        };
1324        self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1325
1326        // Step 6: Let userPromptHandler be WebDriver BiDi user prompt opened with this,
1327        // "prompt", and message.
1328        // TODO: Add support for WebDriver BiDi.
1329        //
1330        // Step 7: Let result be null.
1331        //
1332        // Step 8: If userPromptHandler is "none", then:
1333        //  1. Pause while waiting for the user's response.
1334        //  2. If the user did not abort, then set result to the string that the user responded with.
1335        //
1336        // Step 9: Otherwise, if userPromptHandler is "accept", then set result to the empty string.
1337        // TODO: Implement this.
1338        //
1339        // Step 10: Invoke WebDriver BiDi user prompt closed with this, "prompt", false if
1340        // result is null or true otherwise, and result.
1341        // TODO: Add support for WebDriver BiDi.
1342        //
1343        // Step 11: Return result.
1344        match receiver.recv() {
1345            Ok(PromptResponse::Ok(input)) => Some(input.into()),
1346            Ok(PromptResponse::Cancel) => None,
1347            Err(_) => {
1348                warn!("Prompt dialog was cancelled or failed to show.");
1349                None
1350            },
1351        }
1352    }
1353
1354    /// <https://html.spec.whatwg.org/multipage/#dom-window-stop>
1355    fn Stop(&self, cx: &mut JSContext) {
1356        // 1. If this's navigable is null, then return.
1357        // Note: Servo doesn't have a concept of navigable yet.
1358
1359        // 2. Stop loading this's navigable.
1360        self.stop_loading(cx);
1361    }
1362
1363    /// <https://html.spec.whatwg.org/multipage/#dom-window-focus>
1364    fn Focus(&self, cx: &mut JSContext) {
1365        // Step 1. Let current be this's navigable.
1366        // Note: We don't necessarily have access to the navigable, because it might
1367        // be in another process.
1368
1369        // Step 2. If current is null, then return.
1370        //
1371        // Note: This is equivalent to there being an active `Document`.
1372        let document = self.Document();
1373        if !document.is_active() {
1374            return;
1375        }
1376
1377        // Step 3. If the allow focus steps given current's active document return false, then return.
1378        // TODO: Implement this.
1379
1380        // Step 4. Run the focusing steps with current.
1381        document.focus_handler().focus(cx, &FocusableArea::Viewport);
1382
1383        // Step 5. If current is a top-level traversable, user agents are encouraged to trigger some
1384        // sort of notification to indicate to the user that the page is attempting to gain focus.
1385        //
1386        // Note: We currently don't do this. Most browsers don't.
1387    }
1388
1389    /// <https://html.spec.whatwg.org/multipage/#dom-window-blur>
1390    fn Blur(&self) {
1391        // > User agents are encouraged to ignore calls to this `blur()` method
1392        // > entirely.
1393    }
1394
1395    /// <https://html.spec.whatwg.org/multipage/#dom-open>
1396    fn Open(
1397        &self,
1398        cx: &mut JSContext,
1399        url: USVString,
1400        target: DOMString,
1401        features: DOMString,
1402    ) -> Fallible<Option<DomRoot<WindowProxy>>> {
1403        self.window_proxy().open(cx, url, target, features)
1404    }
1405
1406    /// <https://html.spec.whatwg.org/multipage/#dom-opener>
1407    fn GetOpener(&self, cx: &mut CurrentRealm, mut retval: MutableHandleValue) -> Fallible<()> {
1408        // Step 1, Let current be this Window object's browsing context.
1409        let current = match self.window_proxy.get() {
1410            Some(proxy) => proxy,
1411            // Step 2, If current is null, then return null.
1412            None => {
1413                retval.set(NullValue());
1414                return Ok(());
1415            },
1416        };
1417        // Still step 2, since the window's BC is the associated doc's BC,
1418        // see https://html.spec.whatwg.org/multipage/#window-bc
1419        // and a doc's BC is null if it has been discarded.
1420        // see https://html.spec.whatwg.org/multipage/#concept-document-bc
1421        if current.is_browsing_context_discarded() {
1422            retval.set(NullValue());
1423            return Ok(());
1424        }
1425        // Step 3 to 5.
1426        current.opener(cx, retval);
1427        Ok(())
1428    }
1429
1430    #[expect(unsafe_code)]
1431    /// <https://html.spec.whatwg.org/multipage/#dom-opener>
1432    fn SetOpener(&self, cx: &mut JSContext, value: HandleValue) -> ErrorResult {
1433        // Step 1.
1434        if value.is_null() {
1435            if let Some(proxy) = self.window_proxy.get() {
1436                proxy.disown();
1437            }
1438            return Ok(());
1439        }
1440
1441        // Step 2.
1442        let obj = self.reflector().get_jsobject();
1443        let result = unsafe {
1444            JS_DefineProperty(cx, obj, c"opener".as_ptr(), value, JSPROP_ENUMERATE as u32)
1445        };
1446
1447        if result { Ok(()) } else { Err(Error::JSFailed) }
1448    }
1449
1450    /// <https://html.spec.whatwg.org/multipage/#dom-window-closed>
1451    fn Closed(&self) -> bool {
1452        self.window_proxy
1453            .get()
1454            .map(|ref proxy| proxy.is_browsing_context_discarded() || proxy.is_closing())
1455            .unwrap_or(true)
1456    }
1457
1458    /// <https://html.spec.whatwg.org/multipage/#dom-window-close>
1459    fn Close(&self, cx: &mut JSContext) {
1460        // Step 1. Let thisTraversable be this's navigable.
1461        let window_proxy = match self.window_proxy.get() {
1462            Some(proxy) => proxy,
1463            // Step 2. If thisTraversable is not a top-level traversable, then return.
1464            None => return,
1465        };
1466        // Step 3. If thisTraversable's is closing is true, then return.
1467        if window_proxy.is_closing() {
1468            return;
1469        }
1470        // Note: check the length of the "session history", as opposed to the joint session history?
1471        // see https://github.com/whatwg/html/issues/3734
1472        if let Ok(history_length) = self.History(cx).GetLength() {
1473            let is_auxiliary = window_proxy.is_auxiliary();
1474
1475            // https://html.spec.whatwg.org/multipage/#script-closable
1476            let is_script_closable = (self.is_top_level() && history_length == 1) ||
1477                is_auxiliary ||
1478                pref!(dom_allow_scripts_to_close_windows);
1479
1480            // TODO: rest of Step 3:
1481            // Is the incumbent settings object's responsible browsing context familiar with current?
1482            // Is the incumbent settings object's responsible browsing context allowed to navigate current?
1483            if is_script_closable {
1484                // Step 6.1. Set thisTraversable's is closing to true.
1485                window_proxy.close();
1486
1487                // Step 6.2. Queue a task on the DOM manipulation task source to definitely close thisTraversable.
1488                let this = Trusted::new(self);
1489                let task = task!(window_close_browsing_context: move |cx| {
1490                    let window = this.root();
1491                    window.definitely_close(cx);
1492                });
1493                self.as_global_scope()
1494                    .task_manager()
1495                    .dom_manipulation_task_source()
1496                    .queue(task);
1497            }
1498        }
1499    }
1500
1501    /// <https://html.spec.whatwg.org/multipage/#dom-document-2>
1502    fn Document(&self) -> DomRoot<Document> {
1503        self.document
1504            .get()
1505            .expect("Document accessed before initialization.")
1506    }
1507
1508    /// <https://html.spec.whatwg.org/multipage/#dom-history>
1509    fn History(&self, cx: &mut JSContext) -> DomRoot<History> {
1510        self.Document().history(cx)
1511    }
1512
1513    /// <https://w3c.github.io/IndexedDB/#factory-interface>
1514    fn IndexedDB(&self, cx: &mut JSContext) -> DomRoot<IDBFactory> {
1515        self.upcast::<GlobalScope>().ensure_indexeddb_factory(cx)
1516    }
1517
1518    /// <https://html.spec.whatwg.org/multipage/#dom-window-customelements>
1519    fn CustomElements(&self, cx: &mut JSContext) -> DomRoot<CustomElementRegistry> {
1520        // Step 1: Assert: this's associated Document's custom element registry is
1521        // a CustomElementRegistry object.
1522        let document = self.Document();
1523        if let Some(registry) = document.custom_element_registry() {
1524            return registry;
1525        }
1526        // A Window's associated Document is always created with
1527        // a new CustomElementRegistry object.
1528        let registry = CustomElementRegistry::new(cx, self);
1529        document.set_custom_element_registry(&registry);
1530        // Step 2: Return this's associated Document's custom element registry.
1531        registry
1532    }
1533
1534    /// <https://html.spec.whatwg.org/multipage/#dom-location>
1535    fn Location(&self, cx: &mut JSContext) -> DomRoot<Location> {
1536        self.location.or_init(|| Location::new(cx, self))
1537    }
1538
1539    /// <https://html.spec.whatwg.org/multipage/#dom-sessionstorage>
1540    fn GetSessionStorage(&self, cx: &mut JSContext) -> Fallible<DomRoot<Storage>> {
1541        // Step 1. If this's associated Document's session storage holder is non-null,
1542        // then return this's associated Document's session storage holder.
1543        if let Some(storage) = self.session_storage.get() {
1544            return Ok(storage);
1545        }
1546
1547        // Step 2. Let map be the result of running obtain a session storage bottle map
1548        // with this's relevant settings object and "sessionStorage".
1549        // Step 3. If map is failure, then throw a "SecurityError" DOMException.
1550        if !self.origin().is_tuple() {
1551            return Err(Error::Security(Some(
1552                "Cannot access sessionStorage from opaque origin.".to_string(),
1553            )));
1554        }
1555
1556        // Step 4. Let storage be a new Storage object whose map is map.
1557        let storage = Storage::new(cx, self, WebStorageType::Session);
1558
1559        // Step 5. Set this's associated Document's session storage holder to storage.
1560        self.session_storage.set(Some(&storage));
1561
1562        // Step 6. Return storage.
1563        Ok(storage)
1564    }
1565
1566    /// <https://html.spec.whatwg.org/multipage/#dom-localstorage>
1567    fn GetLocalStorage(&self, cx: &mut JSContext) -> Fallible<DomRoot<Storage>> {
1568        // Step 1. If this's associated Document's local storage holder is non-null,
1569        // then return this's associated Document's local storage holder.
1570        if let Some(storage) = self.local_storage.get() {
1571            return Ok(storage);
1572        }
1573
1574        // Step 2. Let map be the result of running obtain a local storage bottle map
1575        // with this's relevant settings object and "localStorage".
1576        // Step 3. If map is failure, then throw a "SecurityError" DOMException.
1577        if !self.origin().is_tuple() {
1578            return Err(Error::Security(Some(
1579                "Cannot access localStorage from opaque origin.".to_string(),
1580            )));
1581        }
1582
1583        // Step 4. Let storage be a new Storage object whose map is map.
1584        let storage = Storage::new(cx, self, WebStorageType::Local);
1585
1586        // Step 5. Set this's associated Document's local storage holder to storage.
1587        self.local_storage.set(Some(&storage));
1588
1589        // Step 6. Return storage.
1590        Ok(storage)
1591    }
1592
1593    /// <https://cookiestore.spec.whatwg.org/#Window>
1594    fn CookieStore(&self, cx: &mut JSContext) -> DomRoot<CookieStore> {
1595        self.cookie_store
1596            .or_init(|| CookieStore::new(cx, self.upcast::<GlobalScope>()))
1597    }
1598
1599    /// <https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#dfn-GlobalCrypto>
1600    #[cfg(feature = "webcrypto")]
1601    fn Crypto(&self, cx: &mut JSContext) -> DomRoot<crate::dom::crypto::Crypto> {
1602        self.crypto
1603            .or_init(|| crate::dom::crypto::Crypto::new(cx, self.as_global_scope()))
1604    }
1605
1606    /// <https://html.spec.whatwg.org/multipage/#dom-frameelement>
1607    fn GetFrameElement(&self) -> Option<DomRoot<Element>> {
1608        // Steps 1-3.
1609        let window_proxy = self.window_proxy.get()?;
1610
1611        // Step 4-5.
1612        let container = window_proxy.frame_element()?;
1613
1614        // Step 6.
1615        let container_doc = container.owner_document();
1616        let current_doc = GlobalScope::current()
1617            .expect("No current global object")
1618            .as_window()
1619            .Document();
1620        if !current_doc
1621            .origin()
1622            .same_origin_domain(&container_doc.origin())
1623        {
1624            return None;
1625        }
1626        // Step 7.
1627        Some(DomRoot::from_ref(container))
1628    }
1629
1630    /// <https://html.spec.whatwg.org/multipage/#dom-reporterror>
1631    fn ReportError(&self, cx: &mut JSContext, error: HandleValue) {
1632        self.as_global_scope().report_an_exception(cx, error);
1633    }
1634
1635    /// <https://html.spec.whatwg.org/multipage/#dom-navigator>
1636    fn Navigator(&self, cx: &mut JSContext) -> DomRoot<Navigator> {
1637        self.navigator.or_init(|| Navigator::new(cx, self))
1638    }
1639
1640    /// <https://html.spec.whatwg.org/multipage/#dom-clientinformation>
1641    fn ClientInformation(&self, cx: &mut JSContext) -> DomRoot<Navigator> {
1642        self.Navigator(cx)
1643    }
1644
1645    /// <https://html.spec.whatwg.org/multipage/#dom-settimeout>
1646    fn SetTimeout(
1647        &self,
1648        cx: &mut JSContext,
1649        callback: TrustedScriptOrStringOrFunction,
1650        timeout: i32,
1651        args: Vec<HandleValue>,
1652    ) -> Fallible<i32> {
1653        let callback = match callback {
1654            TrustedScriptOrStringOrFunction::String(i) => {
1655                TimerCallback::StringTimerCallback(TrustedScriptOrString::String(i))
1656            },
1657            TrustedScriptOrStringOrFunction::TrustedScript(i) => {
1658                TimerCallback::StringTimerCallback(TrustedScriptOrString::TrustedScript(i))
1659            },
1660            TrustedScriptOrStringOrFunction::Function(i) => TimerCallback::FunctionTimerCallback(i),
1661        };
1662        self.as_global_scope().set_timeout_or_interval(
1663            cx,
1664            callback,
1665            args,
1666            Duration::from_millis(timeout.max(0) as u64),
1667            IsInterval::NonInterval,
1668        )
1669    }
1670
1671    /// <https://html.spec.whatwg.org/multipage/#dom-windowtimers-cleartimeout>
1672    fn ClearTimeout(&self, handle: i32) {
1673        self.as_global_scope().clear_timeout_or_interval(handle);
1674    }
1675
1676    /// <https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval>
1677    fn SetInterval(
1678        &self,
1679        cx: &mut JSContext,
1680        callback: TrustedScriptOrStringOrFunction,
1681        timeout: i32,
1682        args: Vec<HandleValue>,
1683    ) -> Fallible<i32> {
1684        let callback = match callback {
1685            TrustedScriptOrStringOrFunction::String(i) => {
1686                TimerCallback::StringTimerCallback(TrustedScriptOrString::String(i))
1687            },
1688            TrustedScriptOrStringOrFunction::TrustedScript(i) => {
1689                TimerCallback::StringTimerCallback(TrustedScriptOrString::TrustedScript(i))
1690            },
1691            TrustedScriptOrStringOrFunction::Function(i) => TimerCallback::FunctionTimerCallback(i),
1692        };
1693        self.as_global_scope().set_timeout_or_interval(
1694            cx,
1695            callback,
1696            args,
1697            Duration::from_millis(timeout.max(0) as u64),
1698            IsInterval::Interval,
1699        )
1700    }
1701
1702    /// <https://html.spec.whatwg.org/multipage/#dom-windowtimers-clearinterval>
1703    fn ClearInterval(&self, handle: i32) {
1704        self.ClearTimeout(handle);
1705    }
1706
1707    /// <https://html.spec.whatwg.org/multipage/#dom-queuemicrotask>
1708    fn QueueMicrotask(&self, cx: &JSContext, callback: Rc<VoidFunction>) {
1709        ScriptThread::enqueue_microtask(
1710            cx,
1711            Box::new(UserMicrotask {
1712                callback,
1713                global: Dom::from_ref(&self.globalscope),
1714            }),
1715        );
1716    }
1717
1718    /// <https://html.spec.whatwg.org/multipage/#dom-createimagebitmap>
1719    fn CreateImageBitmap(
1720        &self,
1721        realm: &mut CurrentRealm,
1722        image: ImageBitmapSource,
1723        options: &ImageBitmapOptions,
1724    ) -> Rc<Promise> {
1725        ImageBitmap::create_image_bitmap(
1726            self.as_global_scope(),
1727            image,
1728            0,
1729            0,
1730            None,
1731            None,
1732            options,
1733            realm,
1734        )
1735    }
1736
1737    /// <https://html.spec.whatwg.org/multipage/#dom-createimagebitmap>
1738    fn CreateImageBitmap_(
1739        &self,
1740        realm: &mut CurrentRealm,
1741        image: ImageBitmapSource,
1742        sx: i32,
1743        sy: i32,
1744        sw: i32,
1745        sh: i32,
1746        options: &ImageBitmapOptions,
1747    ) -> Rc<Promise> {
1748        ImageBitmap::create_image_bitmap(
1749            self.as_global_scope(),
1750            image,
1751            sx,
1752            sy,
1753            Some(sw),
1754            Some(sh),
1755            options,
1756            realm,
1757        )
1758    }
1759
1760    /// <https://html.spec.whatwg.org/multipage/#dom-window>
1761    fn Window(&self) -> DomRoot<WindowProxy> {
1762        self.window_proxy()
1763    }
1764
1765    /// <https://html.spec.whatwg.org/multipage/#dom-self>
1766    fn Self_(&self) -> DomRoot<WindowProxy> {
1767        self.window_proxy()
1768    }
1769
1770    /// <https://html.spec.whatwg.org/multipage/#dom-frames>
1771    fn Frames(&self) -> DomRoot<WindowProxy> {
1772        self.window_proxy()
1773    }
1774
1775    /// <https://html.spec.whatwg.org/multipage/#accessing-other-browsing-contexts>
1776    fn Length(&self) -> u32 {
1777        self.Document().iframes().iter().count() as u32
1778    }
1779
1780    /// <https://html.spec.whatwg.org/multipage/#dom-parent>
1781    fn GetParent(&self) -> Option<DomRoot<WindowProxy>> {
1782        // Steps 1-3.
1783        let window_proxy = self.undiscarded_window_proxy()?;
1784
1785        // Step 4.
1786        if let Some(parent) = window_proxy.parent() {
1787            return Some(DomRoot::from_ref(parent));
1788        }
1789        // Step 5.
1790        Some(window_proxy)
1791    }
1792
1793    /// <https://html.spec.whatwg.org/multipage/#dom-top>
1794    fn GetTop(&self) -> Option<DomRoot<WindowProxy>> {
1795        // Steps 1-3.
1796        let window_proxy = self.undiscarded_window_proxy()?;
1797
1798        // Steps 4-5.
1799        Some(DomRoot::from_ref(window_proxy.top()))
1800    }
1801
1802    // https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/
1803    // NavigationTiming/Overview.html#sec-window.performance-attribute
1804    fn Performance(&self, cx: &mut JSContext) -> DomRoot<Performance> {
1805        self.performance
1806            .or_init(|| Performance::new(cx, self.as_global_scope(), self.navigation_start.get()))
1807    }
1808
1809    // https://html.spec.whatwg.org/multipage/#globaleventhandlers
1810    global_event_handlers!();
1811
1812    // https://html.spec.whatwg.org/multipage/#windoweventhandlers
1813    window_event_handlers!();
1814
1815    /// <https://developer.mozilla.org/en-US/docs/Web/API/Window/screen>
1816    fn Screen(&self, cx: &mut JSContext) -> DomRoot<Screen> {
1817        self.screen.or_init(|| Screen::new(cx, self))
1818    }
1819
1820    /// <https://drafts.csswg.org/cssom-view/#dom-window-visualviewport>
1821    fn GetVisualViewport(&self, cx: &mut JSContext) -> Option<DomRoot<VisualViewport>> {
1822        // > If the associated document is fully active, the visualViewport attribute must return the
1823        // > VisualViewport object associated with the Window object’s associated document. Otherwise,
1824        // > it must return null.
1825        if !self.Document().is_fully_active() {
1826            return None;
1827        }
1828
1829        Some(self.get_or_init_visual_viewport(cx))
1830    }
1831
1832    /// <https://html.spec.whatwg.org/multipage/#dom-windowbase64-btoa>
1833    fn Btoa(&self, btoa: DOMString) -> Fallible<DOMString> {
1834        base64_btoa(btoa)
1835    }
1836
1837    /// <https://html.spec.whatwg.org/multipage/#dom-windowbase64-atob>
1838    fn Atob(&self, atob: DOMString) -> Fallible<DOMString> {
1839        base64_atob(atob)
1840    }
1841
1842    /// <https://html.spec.whatwg.org/multipage/#dom-window-requestanimationframe>
1843    fn RequestAnimationFrame(&self, callback: Rc<FrameRequestCallback>) -> Fallible<u32> {
1844        Ok(self
1845            .Document()
1846            .request_animation_frame(AnimationFrameCallback::FrameRequestCallback { callback }))
1847    }
1848
1849    /// <https://html.spec.whatwg.org/multipage/#dom-window-cancelanimationframe>
1850    fn CancelAnimationFrame(&self, ident: u32) -> ErrorResult {
1851        let doc = self.Document();
1852        doc.cancel_animation_frame(ident);
1853        Ok(())
1854    }
1855
1856    /// <https://html.spec.whatwg.org/multipage/#dom-window-postmessage>
1857    fn PostMessage(
1858        &self,
1859        cx: &mut JSContext,
1860        message: HandleValue,
1861        target_origin: USVString,
1862        transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
1863    ) -> ErrorResult {
1864        let incumbent = GlobalScope::incumbent().expect("no incumbent global?");
1865        let source = incumbent.as_window();
1866        let source_origin = source.Document().origin().immutable().clone();
1867
1868        self.post_message_impl(&target_origin, source_origin, source, cx, message, transfer)
1869    }
1870
1871    /// <https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage>
1872    fn PostMessage_(
1873        &self,
1874        cx: &mut JSContext,
1875        message: HandleValue,
1876        options: RootedTraceableBox<WindowPostMessageOptions>,
1877    ) -> ErrorResult {
1878        let mut rooted = CustomAutoRooter::new(
1879            options
1880                .parent
1881                .transfer
1882                .iter()
1883                .map(|js: &RootedTraceableBox<Heap<*mut JSObject>>| js.get())
1884                .collect(),
1885        );
1886        #[expect(unsafe_code)]
1887        let transfer = unsafe { CustomAutoRooterGuard::new(cx.raw_cx(), &mut rooted) };
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    ) -> Rc<Promise> {
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
2260            .get()
2261            .map_or(0, |d| d.animations().running_animation_count() as u32)
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 => "".into(),
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.animations().sets.clone(),
2735            animating_images: document.image_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            document_context,
2740            accessibility_damage,
2741            rooted_nodes_for_accessibility_integrity_check,
2742        };
2743
2744        let Some(reflow_result) = self.layout.borrow_mut().reflow(reflow) else {
2745            return Default::default();
2746        };
2747
2748        debug!("script: layout complete");
2749        if let Some(marker) = marker {
2750            self.emit_timeline_marker(marker.end());
2751        }
2752
2753        self.handle_new_or_removed_web_fonts_post_reflow(cx, reflow_result.changed_web_fonts);
2754
2755        self.handle_pending_images_post_reflow(
2756            cx,
2757            reflow_result.pending_images,
2758            reflow_result.pending_rasterization_images,
2759            reflow_result.pending_svg_elements_for_serialization,
2760        );
2761
2762        if let Some(candidate) = &reflow_result.lcp_candidate &&
2763            let Some(node_address) = reflow_result.lcp_node_address
2764        {
2765            self.process_lcp_candidate_post_reflow(candidate, node_address, &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.animations().sets.clone();
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.animations().sets.clone();
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(
3741        &self,
3742        candidate: &LCPCandidate,
3743        node_address: UntrustedNodeAddress,
3744        document: &Document,
3745    ) {
3746        let node = unsafe { from_untrusted_node_address(node_address) };
3747        if let Some(element) = DomRoot::downcast::<Element>(node) {
3748            document.store_lcp_candidate(candidate.id, &element);
3749        }
3750    }
3751
3752    #[expect(unsafe_code)]
3753    fn handle_pending_images_post_reflow(
3754        &self,
3755        cx: &mut JSContext,
3756        pending_images: Vec<PendingImage>,
3757        pending_rasterization_images: Vec<PendingRasterizationImage>,
3758        pending_svg_element_for_serialization: Vec<UntrustedNodeAddress>,
3759    ) {
3760        let pipeline_id = self.pipeline_id();
3761        let image_cache = self.image_cache();
3762        for image in pending_images {
3763            let id = image.id;
3764            let node = unsafe { from_untrusted_node_address(image.node) };
3765
3766            if let PendingImageState::Unrequested(ref url) = image.state {
3767                fetch_image_for_layout(
3768                    url.clone(),
3769                    &node,
3770                    id,
3771                    image.is_internal_request,
3772                    image_cache.clone(),
3773                );
3774            }
3775
3776            let mut images = self.pending_layout_images.borrow_mut();
3777            if !images.contains_key(&id) {
3778                let trusted_node = Trusted::new(&*node);
3779                let sender = self.register_image_cache_listener(id, move |response, cx| {
3780                    trusted_node
3781                        .root()
3782                        .owner_window()
3783                        .pending_layout_image_notification(cx.no_gc(), response);
3784                });
3785
3786                image_cache.add_listener(ImageLoadListener::new(sender, pipeline_id, id));
3787            }
3788
3789            let nodes = images.entry(id).or_default();
3790            if !nodes.iter().any(|n| *n.node == *node) {
3791                nodes.push(PendingLayoutImageAncillaryData {
3792                    node: Dom::from_ref(&*node),
3793                    destination: image.destination,
3794                });
3795            }
3796        }
3797
3798        for image in pending_rasterization_images {
3799            let node = unsafe { from_untrusted_node_address(image.node) };
3800
3801            let mut images = self.pending_images_for_rasterization.borrow_mut();
3802            if !images.contains_key(&(image.id, image.size)) {
3803                let image_cache_sender = self.image_cache_sender.clone();
3804                image_cache.add_rasterization_complete_listener(
3805                    pipeline_id,
3806                    image.id,
3807                    image.size,
3808                    Box::new(move |response| {
3809                        let _ = image_cache_sender.send(response);
3810                    }),
3811                );
3812            }
3813
3814            let nodes = images.entry((image.id, image.size)).or_default();
3815            if !nodes.iter().any(|n| **n == *node) {
3816                nodes.push(Dom::from_ref(&*node));
3817            }
3818        }
3819
3820        for node in pending_svg_element_for_serialization.into_iter() {
3821            let node = unsafe { from_untrusted_node_address(node) };
3822            let svg = node.downcast::<SVGSVGElement>().unwrap();
3823            svg.serialize_and_cache_subtree(cx);
3824            node.dirty(cx.no_gc(), NodeDamage::Other);
3825        }
3826    }
3827
3828    /// <https://html.spec.whatwg.org/multipage/#sticky-activation>
3829    pub(crate) fn has_sticky_activation(&self) -> bool {
3830        // > 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.
3831        UserActivationTimestamp::TimeStamp(CrossProcessInstant::now()) >=
3832            self.last_activation_timestamp.get()
3833    }
3834
3835    /// <https://html.spec.whatwg.org/multipage/#transient-activation>
3836    pub(crate) fn has_transient_activation(&self) -> bool {
3837        // > 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
3838        // > timestamp in W plus the transient activation duration, then W is said to have transient activation.
3839        let current_time = CrossProcessInstant::now();
3840        UserActivationTimestamp::TimeStamp(current_time) >= self.last_activation_timestamp.get() &&
3841            UserActivationTimestamp::TimeStamp(current_time) <
3842                self.last_activation_timestamp.get() +
3843                    pref!(dom_transient_activation_duration_ms)
3844    }
3845
3846    pub(crate) fn consume_last_activation_timestamp(&self) {
3847        if self.last_activation_timestamp.get() != UserActivationTimestamp::PositiveInfinity {
3848            self.set_last_activation_timestamp(UserActivationTimestamp::NegativeInfinity);
3849        }
3850    }
3851
3852    /// <https://html.spec.whatwg.org/multipage/#consume-user-activation>
3853    pub(crate) fn consume_user_activation(&self) {
3854        // Step 1.
3855        // > If W's navigable is null, then return.
3856        if self.undiscarded_window_proxy().is_none() {
3857            return;
3858        }
3859
3860        // Step 2.
3861        // > Let top be W's navigable's top-level traversable.
3862        // TODO: This wouldn't work if top level document is in another ScriptThread.
3863        let Some(top_level_document) = self.top_level_document_if_local() else {
3864            return;
3865        };
3866
3867        // Step 3.
3868        // > Let navigables be the inclusive descendant navigables of top's active document.
3869        // Step 4.
3870        // > Let windows be the list of Window objects constructed by taking the active window of each item in navigables.
3871        // Step 5.
3872        // > 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.
3873        // TODO: this would not work for disimilar origin descendant, since we doesn't store the document in this script thread.
3874        top_level_document
3875            .window()
3876            .consume_last_activation_timestamp();
3877        for document in SameOriginDescendantNavigablesIterator::new(&top_level_document) {
3878            document.window().consume_last_activation_timestamp();
3879        }
3880    }
3881
3882    #[allow(clippy::too_many_arguments)]
3883    pub(crate) fn new(
3884        cx: &mut JSContext,
3885        webview_id: WebViewId,
3886        runtime: Rc<Runtime>,
3887        script_chan: Sender<MainThreadScriptMsg>,
3888        layout: Box<dyn Layout>,
3889        image_cache_sender: Sender<ImageCacheResponseMessage>,
3890        resource_threads: ResourceThreads,
3891        storage_threads: StorageThreads,
3892        #[cfg(feature = "bluetooth")] bluetooth_thread: GenericSender<BluetoothRequest>,
3893        mem_profiler_chan: MemProfilerChan,
3894        time_profiler_chan: TimeProfilerChan,
3895        devtools_chan: Option<GenericCallback<ScriptToDevtoolsControlMsg>>,
3896        script_to_constellation_sender: ScriptToConstellationSender,
3897        embedder_chan: ScriptToEmbedderChan,
3898        control_chan: GenericSender<ScriptThreadMessage>,
3899        pipeline_id: PipelineId,
3900        parent_info: Option<PipelineId>,
3901        viewport_details: ViewportDetails,
3902        origin: MutableOrigin,
3903        creation_url: ServoUrl,
3904        top_level_creation_url: ServoUrl,
3905        navigation_start: CrossProcessInstant,
3906        #[cfg(feature = "webgl")] webgl_chan: Option<WebGLChan>,
3907        #[cfg(feature = "webxr")] webxr_registry: Option<webxr_api::Registry>,
3908        paint_api: CrossProcessPaintApi,
3909        unminify_js: bool,
3910        unminify_css: bool,
3911        local_script_source: Option<String>,
3912        user_scripts: Rc<Vec<UserScript>>,
3913        player_context: WindowGLContext,
3914        #[cfg(feature = "webgpu")] gpu_id_hub: Arc<IdentityHub>,
3915        inherited_secure_context: Option<bool>,
3916        embedder_theme: Theme,
3917        weak_script_thread: Weak<ScriptThread>,
3918    ) -> DomRoot<Self> {
3919        let error_reporter = CSSErrorReporter {
3920            pipelineid: pipeline_id,
3921            script_chan: control_chan,
3922        };
3923
3924        let win = Box::new(Self {
3925            webview_id,
3926            globalscope: GlobalScope::new_inherited(
3927                devtools_chan,
3928                mem_profiler_chan,
3929                time_profiler_chan,
3930                script_to_constellation_sender,
3931                embedder_chan,
3932                resource_threads,
3933                storage_threads,
3934                creation_url,
3935                Some(top_level_creation_url),
3936                #[cfg(feature = "webgpu")]
3937                gpu_id_hub,
3938                inherited_secure_context,
3939                unminify_js,
3940            ),
3941            caches: Default::default(),
3942            ongoing_navigation: Default::default(),
3943            script_chan,
3944            layout: RefCell::new(layout),
3945            image_cache_sender,
3946            navigator: Default::default(),
3947            #[cfg(feature = "webcrypto")]
3948            crypto: Default::default(),
3949            location: Default::default(),
3950            window_proxy: Default::default(),
3951            document: Default::default(),
3952            performance: Default::default(),
3953            navigation_start: Cell::new(navigation_start),
3954            screen: Default::default(),
3955            session_storage: Default::default(),
3956            local_storage: Default::default(),
3957            cookie_store: Default::default(),
3958            status: DomRefCell::new(DOMString::new()),
3959            parent_info,
3960            dom_static: GlobalStaticData::new(),
3961            js_runtime: DomRefCell::new(Some(runtime)),
3962            #[cfg(feature = "bluetooth")]
3963            bluetooth_thread,
3964            #[cfg(feature = "bluetooth")]
3965            bluetooth_extra_permission_data: BluetoothExtraPermissionData::new(),
3966            unhandled_resize_event: Default::default(),
3967            viewport_details_at_last_resize_steps: Cell::new(viewport_details),
3968            viewport_details: Cell::new(viewport_details),
3969            layout_blocker: Cell::new(LayoutBlocker::WaitingForParse),
3970            current_state: Cell::new(WindowState::Alive),
3971            devtools_marker_sender: Default::default(),
3972            devtools_markers: Default::default(),
3973            webdriver_load_status_sender: Default::default(),
3974            error_reporter,
3975            media_query_lists: DOMTracker::new(),
3976            #[cfg(feature = "bluetooth")]
3977            test_runner: Default::default(),
3978            #[cfg(feature = "webgl")]
3979            webgl_chan,
3980            #[cfg(feature = "webxr")]
3981            webxr_registry,
3982            pending_image_callbacks: Default::default(),
3983            pending_layout_images: Default::default(),
3984            pending_images_for_rasterization: Default::default(),
3985            unminified_css_dir: DomRefCell::new(if unminify_css {
3986                Some(unminified_path("unminified-css"))
3987            } else {
3988                None
3989            }),
3990            local_script_source,
3991            test_worklet: Default::default(),
3992            paint_worklet: Default::default(),
3993            exists_mut_observer: Cell::new(false),
3994            paint_api,
3995            user_scripts,
3996            player_context,
3997            throttled: Cell::new(false),
3998            layout_marker: DomRefCell::new(Rc::new(Cell::new(true))),
3999            current_event: DomRefCell::new(None),
4000            embedder_theme: Cell::new(embedder_theme),
4001            trusted_types: Default::default(),
4002            reporting_observer_list: Default::default(),
4003            report_list: Default::default(),
4004            endpoints_list: Default::default(),
4005            script_window_proxies: ScriptThread::window_proxies(),
4006            has_pending_screenshot_readiness_request: Default::default(),
4007            visual_viewport: Default::default(),
4008            weak_script_thread,
4009            has_changed_visual_viewport_dimension: Default::default(),
4010            pending_media_query_evaluation: Default::default(),
4011            last_activation_timestamp: Cell::new(UserActivationTimestamp::PositiveInfinity),
4012            devtools_wants_updates: Default::default(),
4013            has_dispatched_scroll_event: Cell::new(false),
4014            has_dispatched_input_event: Cell::new(false),
4015        });
4016
4017        WindowBinding::Wrap::<crate::DomTypeHolder>(cx, &origin, win)
4018    }
4019
4020    pub(crate) fn task_manager(&self) -> Rc<TaskManager> {
4021        self.Document().task_manager()
4022    }
4023
4024    pub(crate) fn pipeline_id(&self) -> PipelineId {
4025        self.Document().pipeline_id()
4026    }
4027
4028    pub(crate) fn live_devtools_updates(&self) -> bool {
4029        self.devtools_wants_updates.get()
4030    }
4031
4032    pub(crate) fn set_devtools_wants_updates(&self, value: bool) {
4033        self.devtools_wants_updates.set(value);
4034    }
4035
4036    /// Create a new cached instance of the given value.
4037    pub(crate) fn cache_layout_value<T>(&self, value: T) -> LayoutValue<T>
4038    where
4039        T: Copy + MallocSizeOf,
4040    {
4041        LayoutValue::new(self.layout_marker.borrow().clone(), value)
4042    }
4043
4044    /// This method is an approximation of the specification [algorithm].
4045    /// It exists in this form because we still store some fields in Window/GlobalScope
4046    /// that realistically are specific to the active document. Where possible they
4047    /// should be migrated to Document and WorkerGlobalScope, but currently doing so would result
4048    /// in much more complicated code. This method is the compromise, where we mutate the values
4049    /// in place to match the values that the specification expects.
4050    ///
4051    /// [algorithm] <https://html.spec.whatwg.org/multipage/#set-up-a-window-environment-settings-object>
4052    pub(crate) fn set_up_a_window_environment_settings_object(
4053        &self,
4054        layout: Box<dyn Layout>,
4055        creation_url: ServoUrl,
4056        top_level_creation_url: ServoUrl,
4057        navigation_start: CrossProcessInstant,
4058        viewport_details: ViewportDetails,
4059    ) {
4060        *self.layout.borrow_mut() = layout;
4061        self.set_viewport_details(viewport_details);
4062        self.navigation_start.set(navigation_start);
4063
4064        // Step 6. Set settings object's creation URL to creationURL, settings object's top-level
4065        //   creation URL to topLevelCreationURL, and settings object's top-level origin to topLevelOrigin.
4066        let global = self.upcast::<GlobalScope>();
4067        global.set_creation_url(creation_url);
4068        global.set_top_level_creation_url(top_level_creation_url);
4069
4070        self.Document().detach_window();
4071    }
4072}
4073
4074/// An instance of a value associated with a particular snapshot of layout. This stored
4075/// value can only be read as long as the associated layout marker that is considered
4076/// valid. It will automatically become unavailable when the next layout operation is
4077/// performed.
4078#[derive(MallocSizeOf)]
4079pub(crate) struct LayoutValue<T: MallocSizeOf> {
4080    #[conditional_malloc_size_of]
4081    is_valid: Rc<Cell<bool>>,
4082    value: T,
4083}
4084
4085#[expect(unsafe_code)]
4086unsafe impl<T: JSTraceable + MallocSizeOf> JSTraceable for LayoutValue<T> {
4087    unsafe fn trace(&self, trc: *mut js::jsapi::JSTracer) {
4088        unsafe { self.value.trace(trc) };
4089    }
4090}
4091
4092impl<T: Copy + MallocSizeOf> LayoutValue<T> {
4093    fn new(marker: Rc<Cell<bool>>, value: T) -> Self {
4094        LayoutValue {
4095            is_valid: marker,
4096            value,
4097        }
4098    }
4099
4100    /// Retrieve the stored value if it is still valid.
4101    pub(crate) fn get(&self) -> Result<T, ()> {
4102        if self.is_valid.get() {
4103            return Ok(self.value);
4104        }
4105        Err(())
4106    }
4107}
4108
4109impl Window {
4110    // https://html.spec.whatwg.org/multipage/#dom-window-postmessage step 7.
4111    pub(crate) fn post_message(
4112        &self,
4113        target_origin: Option<ImmutableOrigin>,
4114        source_origin: ImmutableOrigin,
4115        source: &WindowProxy,
4116        data: StructuredSerializedData,
4117    ) {
4118        let this = Trusted::new(self);
4119        let source = Trusted::new(source);
4120        let task = task!(post_serialised_message: move |cx| {
4121            let this = this.root();
4122            let source = source.root();
4123            let document = this.Document();
4124
4125            // Step 7.1.
4126            if let Some(ref target_origin) = target_origin
4127                && !target_origin.same_origin(&*document.origin()) {
4128                    return;
4129                }
4130
4131            // Steps 7.2.-7.5.
4132            let obj = this.reflector().get_jsobject();
4133            let mut realm = AutoRealm::new(cx, NonNull::new(obj.get()).unwrap());
4134            let cx = &mut *realm;
4135            rooted!(&in(cx) let mut message_clone = UndefinedValue());
4136            if let Ok(ports) = structuredclone::read(cx, this.upcast(), data, message_clone.handle_mut()) {
4137                // Step 7.6, 7.7
4138                MessageEvent::dispatch_jsval(
4139                    cx,
4140                    this.upcast(),
4141                    this.upcast(),
4142                    message_clone.handle(),
4143                    Some(source_origin.ascii_serialization().as_ref()),
4144                    Some(&*source),
4145                    ports,
4146                );
4147            } else {
4148                // Step 4, fire messageerror.
4149                MessageEvent::dispatch_error(
4150                    cx,
4151                    this.upcast(),
4152                    this.upcast(),
4153                );
4154            }
4155        });
4156        // TODO(#12718): Use the "posted message task source".
4157        self.as_global_scope()
4158            .task_manager()
4159            .dom_manipulation_task_source()
4160            .queue(task);
4161    }
4162}
4163
4164#[derive(Clone, MallocSizeOf)]
4165pub(crate) struct CSSErrorReporter {
4166    pub(crate) pipelineid: PipelineId,
4167    pub(crate) script_chan: GenericSender<ScriptThreadMessage>,
4168}
4169unsafe_no_jsmanaged_fields!(CSSErrorReporter);
4170
4171impl ParseErrorReporter for CSSErrorReporter {
4172    fn report_error(
4173        &self,
4174        url: &UrlExtraData,
4175        location: SourceLocation,
4176        error: ContextualParseError,
4177    ) {
4178        if log_enabled!(log::Level::Info) {
4179            info!(
4180                "Url:\t{}\n{}:{} {}",
4181                url.0.as_str(),
4182                location.line,
4183                location.column,
4184                error
4185            )
4186        }
4187
4188        // TODO: report a real filename
4189        let _ = self.script_chan.send(ScriptThreadMessage::ReportCSSError(
4190            self.pipelineid,
4191            url.0.to_string(),
4192            location.line,
4193            location.column,
4194            error.to_string(),
4195        ));
4196    }
4197}
4198
4199fn is_named_element_with_name_attribute(elem: &Element) -> bool {
4200    let type_ = match elem.upcast::<Node>().type_id() {
4201        NodeTypeId::Element(ElementTypeId::HTMLElement(type_)) => type_,
4202        _ => return false,
4203    };
4204    matches!(
4205        type_,
4206        HTMLElementTypeId::HTMLEmbedElement |
4207            HTMLElementTypeId::HTMLFormElement |
4208            HTMLElementTypeId::HTMLImageElement |
4209            HTMLElementTypeId::HTMLObjectElement
4210    )
4211}
4212
4213fn is_named_element_with_id_attribute(elem: &Element) -> bool {
4214    elem.is_html_element() || elem.is_svg_element()
4215}
4216
4217#[expect(unsafe_code)]
4218#[unsafe(no_mangle)]
4219/// Helper for interactive debugging sessions in lldb/gdb.
4220unsafe extern "C" fn dump_js_stack(cx: *mut RawJSContext) {
4221    unsafe {
4222        DumpJSStack(cx, true, false, false);
4223    }
4224}
4225
4226impl WindowHelpers for Window {
4227    fn create_named_properties_object(
4228        cx: &mut JSContext,
4229        proto: HandleObject,
4230        object: MutableHandleObject,
4231    ) {
4232        Self::create_named_properties_object(cx, proto, object)
4233    }
4234}
4235
4236impl HasOrigin for Window {
4237    fn origin(&self) -> MutableOrigin {
4238        Window::origin(self)
4239    }
4240}