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