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