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