1#![cfg_attr(crown, allow(crown::jscontext_first_arg))]
6
7use std::borrow::ToOwned;
8use std::cell::{Cell, RefCell, RefMut};
9use std::collections::hash_map::Entry;
10use std::default::Default;
11use std::ffi::c_void;
12use std::io::{Write, stderr, stdout};
13use std::ptr::NonNull;
14use std::rc::{Rc, Weak};
15use std::sync::Arc;
16use std::time::{Duration, Instant};
17
18use accesskit::Action;
19use app_units::Au;
20use base64::Engine;
21use content_security_policy::Violation;
22use content_security_policy::sandboxing_directive::SandboxingFlagSet;
23use crossbeam_channel::{Sender, unbounded};
24use cssparser::SourceLocation;
25use dom_struct::dom_struct;
26use embedder_traits::user_contents::UserScript;
27use embedder_traits::{
28 AlertResponse, ConfirmResponse, EmbedderMsg, PromptResponse, ScriptToEmbedderChan,
29 SimpleDialogRequest, Theme, UntrustedNodeAddress, ViewportDetails, WebDriverLoadStatus,
30};
31use euclid::{Point2D, Rect, Scale, Size2D, Vector2D};
32use fonts::{
33 CspViolationHandler, FontContext, NetworkTimingHandler, WebFontDocumentContext,
34 WebFontSetDifference,
35};
36use html5ever::LocalName;
37use js::context::{JSContext, NoGC};
38use js::conversions::ToJSValConvertible;
39use js::glue::DumpJSStack;
40use js::jsapi::{
41 GCReason, GetObjectRealmOrNull, Heap, JSContext as RawJSContext, JSObject, SetRealmPrincipals,
42};
43use js::jsval::{NullValue, UndefinedValue};
44use js::realm::{AutoRealm, CurrentRealm};
45use js::rust::wrappers2::JS_GC;
46use js::rust::{
47 CustomAutoRooterGuard, HandleObject, HandleValue, MutableHandleObject, MutableHandleValue,
48};
49use layout_api::{
50 AccessibilityActionRequest, AxesOverflow, BoxAreaType, CSSPixelRectVec, ContainerTimingRecord,
51 FragmentType, HitTestFlags, LCPCandidate, Layout, LayoutImageDestination, PendingImage,
52 PendingImageState, PendingRasterizationImage, PhysicalSides, QueryMsg, ReflowGoal,
53 ReflowPhasesRun, ReflowRequest, ReflowRequestAccessibility, ReflowRequestRestyle,
54 ReflowStatistics, RestyleReason, ScrollContainerQueryFlags, ScrollContainerResponse,
55 SegmentGranularity, TrustedNodeAddress, combine_id_with_fragment_type,
56};
57use malloc_size_of::MallocSizeOf;
58use media::WindowGLContext;
59use net_traits::image_cache::{
60 ImageCache, ImageCacheResponseCallback, ImageCacheResponseMessage, ImageLoadListener,
61 ImageResponse, PendingImageId, PendingImageResponse, RasterizationCompleteResponse,
62};
63use net_traits::request::{Origin, Referrer, RequestClient};
64use net_traits::{ResourceFetchTiming, ResourceThreads};
65use num_traits::ToPrimitive;
66use paint_api::{CrossProcessPaintApi, PinchZoomInfos};
67use profile_traits::generic_channel as ProfiledGenericChannel;
68use profile_traits::mem::ProfilerChan as MemProfilerChan;
69use profile_traits::time::ProfilerChan as TimeProfilerChan;
70use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
71use script_bindings::cell::{DomRefCell, Ref};
72use script_bindings::dom::UnrootedDom;
73use script_bindings::interfaces::{HasOrigin, WindowHelpers};
74use script_bindings::js::{JS_DefineProperty, PropertyFlags};
75use script_bindings::like::Setlike;
76use script_bindings::principals::ServoJSPrincipals;
77use script_bindings::reflector::DomObject;
78use script_bindings::root::Root;
79use script_traits::{ConstellationInputEvent, ScriptThreadMessage, WebViewState};
80use selectors::attr::CaseSensitivity;
81use servo_arc::Arc as ServoArc;
82use servo_base::cross_process_instant::CrossProcessInstant;
83use servo_base::generic_channel::{self, GenericCallback, GenericSender};
84use servo_base::id::{BrowsingContextId, PipelineId, WebViewId};
85use servo_base::text::{Utf32CodeUnits, Utf32CodeUnitsOrNodeOffset};
86#[cfg(feature = "bluetooth")]
87use servo_bluetooth_traits::BluetoothRequest;
88#[cfg(feature = "webgl")]
89use servo_canvas_traits::webgl::WebGLChan;
90use servo_config::pref;
91use servo_constellation_traits::{
92 LoadData, LoadOrigin, ScreenshotReadinessResponse, ScriptToConstellationMessage,
93 ScriptToConstellationSender, StructuredSerializedData, WindowSizeType,
94};
95use servo_geometry::DeviceIndependentIntRect;
96use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
97use storage_traits::StorageThreads;
98use storage_traits::webstorage_thread::WebStorageType;
99use style::dom::OpaqueNode;
100use style::error_reporting::{ContextualParseError, ParseErrorReporter};
101use style::properties::PropertyId;
102use style::properties::style_structs::Font;
103use style::selector_parser::PseudoElement;
104use style::str::HTML_SPACE_CHARACTERS;
105use style::stylesheets::UrlExtraData;
106use style_traits::CSSPixel;
107use stylo_atoms::Atom;
108use time::Duration as TimeDuration;
109use webrender_api::ExternalScrollId;
110use webrender_api::units::{DeviceIntSize, DevicePixel, LayoutPixel, LayoutPoint};
111
112use crate::dom::StatelessWorkletThreadPool;
113use crate::dom::bindings::callback::RootedCallback;
114use crate::dom::bindings::codegen::Bindings::AnimationFrameProviderBinding::FrameRequestCallback;
115use crate::dom::bindings::codegen::Bindings::DocumentBinding::{
116 DocumentMethods, DocumentReadyState, NamedPropertyValue,
117};
118use crate::dom::bindings::codegen::Bindings::HTMLIFrameElementBinding::HTMLIFrameElementMethods;
119use crate::dom::bindings::codegen::Bindings::HistoryBinding::History_Binding::HistoryMethods;
120use crate::dom::bindings::codegen::Bindings::ImageBitmapBinding::{
121 ImageBitmapOptions, ImageBitmapSource,
122};
123use crate::dom::bindings::codegen::Bindings::MediaQueryListBinding::MediaQueryList_Binding::MediaQueryListMethods;
124use crate::dom::bindings::codegen::Bindings::MessagePortBinding::StructuredSerializeOptions;
125use crate::dom::bindings::codegen::Bindings::ReportingObserverBinding::Report;
126use crate::dom::bindings::codegen::Bindings::RequestBinding::{RequestInfo, RequestInit};
127use crate::dom::bindings::codegen::Bindings::VoidFunctionBinding::VoidFunction;
128use crate::dom::bindings::codegen::Bindings::WindowBinding::{
129 self, DeferredRequestInit, ScrollBehavior, ScrollToOptions, WindowMethods,
130 WindowPostMessageOptions,
131};
132use crate::dom::bindings::codegen::UnionTypes::{
133 RequestOrUSVString, TrustedScriptOrString, TrustedScriptOrStringOrFunction,
134};
135use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
136use crate::dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
137use crate::dom::bindings::num::Finite;
138use crate::dom::bindings::refcounted::Trusted;
139use crate::dom::bindings::reflector::DomGlobal;
140use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
141use crate::dom::bindings::str::{DOMString, USVString};
142use crate::dom::bindings::structuredclone;
143use crate::dom::bindings::trace::{
144 CustomTraceable, HashMapTracedValues, JSTraceable, RootedTraceableBox,
145};
146use crate::dom::bindings::utils::GlobalStaticData;
147use crate::dom::bindings::weakref::DOMTracker;
148#[cfg(feature = "bluetooth")]
149use crate::dom::bluetooth::BluetoothExtraPermissionData;
150use crate::dom::cookiestore::cookiestore::CookieStore;
151use crate::dom::csp::GlobalCspReporting;
152use crate::dom::css::cssstyledeclaration::{
153 CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner,
154};
155use crate::dom::customelementregistry::CustomElementRegistry;
156use crate::dom::document::focus::FocusableArea;
157use crate::dom::document::{
158 AbortReason, AnimationFrameCallback, Document, SameOriginDescendantNavigablesIterator,
159};
160use crate::dom::element::Element;
161use crate::dom::event::{Event, EventBubbles, EventCancelable};
162use crate::dom::eventtarget::EventTarget;
163use crate::dom::fetchlaterresult::FetchLaterResult;
164use crate::dom::globalscope::GlobalScope;
165use crate::dom::history::History;
166use crate::dom::html::htmlcollection::{CollectionFilter, HTMLCollection};
167use crate::dom::html::htmliframeelement::HTMLIFrameElement;
168use crate::dom::idbfactory::IDBFactory;
169use crate::dom::inputevent::HitTestResult;
170use crate::dom::location::Location;
171use crate::dom::medialist::MediaList;
172use crate::dom::mediaquerylist::{MediaQueryList, MediaQueryListMatchState};
173use crate::dom::mediaquerylistevent::MediaQueryListEvent;
174use crate::dom::messageevent::MessageEvent;
175use crate::dom::navigator::Navigator;
176use crate::dom::node::{Node, NodeDamage, NodeTraits, from_untrusted_node_address};
177use crate::dom::performance::performance::Performance;
178use crate::dom::performanceresourcetiming::InitiatorType;
179use crate::dom::promise::RootedPromise;
180use crate::dom::reporting::reportingendpoint::{ReportingEndpoint, SendReportsToEndpoints};
181use crate::dom::reporting::reportingobserver::ReportingObserver;
182use crate::dom::selection::Selection;
183use crate::dom::selection_range::RootedSelectionBoundary;
184use crate::dom::serviceworker::cachestorage::CacheStorage;
185use crate::dom::shadowroot::shadowroot::ShadowRoot;
186use crate::dom::storage::Storage;
187#[cfg(feature = "bluetooth")]
188use crate::dom::testrunner::TestRunner;
189use crate::dom::trustedtypes::trustedtypepolicyfactory::TrustedTypePolicyFactory;
190use crate::dom::types::{FontFace, ImageBitmap, SVGSVGElement, UIEvent};
191use crate::dom::visualviewport::{VisualViewport, VisualViewportChanges};
192#[cfg(feature = "webgpu")]
193use crate::dom::webgpu::identityhub::IdentityHub;
194use crate::dom::window::layout_image::fetch_image_for_layout;
195use crate::dom::window::screen::Screen;
196use crate::dom::window::scrolling_box::{ScrollingBox, ScrollingBoxSource};
197use crate::dom::window::useractivation::UserActivationTimestamp;
198use crate::dom::windowproxy::{WindowProxy, WindowProxyHandler};
199use crate::dom::worklet::Worklet;
200use crate::dom::workletglobalscope::WorkletGlobalScopeType;
201use crate::event_loop::script_thread::ScriptThread;
202use crate::event_loop::script_window_proxies::ScriptWindowProxies;
203use crate::event_loop::timers::{IsInterval, OneshotTimers, TimerCallback};
204use crate::event_loop::webdriver_handlers::find_node_by_unique_id_in_document;
205use crate::fetch::fetch;
206use crate::fetch::network_listener::{ResourceTimingListener, submit_timing};
207use crate::messaging::{MainThreadScriptMsg, ScriptEventLoopReceiver, ScriptEventLoopSender};
208use crate::realms::enter_auto_realm;
209use crate::runtime::job_queue::UserMicrotask;
210use crate::runtime::script_runtime::Runtime;
211use crate::tasks::task_manager::TaskManager;
212use crate::tasks::task_source::SendableTaskSource;
213use crate::unminify::unminified_path;
214use crate::window_named_properties;
215
216#[derive(MallocSizeOf)]
221pub struct PendingImageCallback(
222 #[ignore_malloc_size_of = "dyn Fn is currently impossible to measure"]
223 #[expect(clippy::type_complexity)]
224 Box<dyn Fn(PendingImageResponse, &mut JSContext) + 'static>,
225);
226
227#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
229enum WindowState {
230 Alive,
231 Zombie, }
233
234const INITIAL_REFLOW_DELAY: Duration = Duration::from_millis(200);
237
238#[derive(Clone, Copy, MallocSizeOf)]
249enum LayoutBlocker {
250 WaitingForParse,
252 Parsing(Instant),
254 FiredLoadEventOrParsingTimerExpired,
258}
259
260impl LayoutBlocker {
261 fn layout_blocked(&self) -> bool {
262 !matches!(self, Self::FiredLoadEventOrParsingTimerExpired)
263 }
264}
265
266#[derive(Clone, Copy, Debug, Default, JSTraceable, MallocSizeOf, PartialEq)]
269pub(crate) struct OngoingNavigation(u32);
270
271type PendingImageRasterizationKey = (PendingImageId, DeviceIntSize);
272
273#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
277#[derive(JSTraceable, MallocSizeOf)]
278struct PendingLayoutImageAncillaryData {
279 node: Dom<Node>,
280 #[no_trace]
281 destination: LayoutImageDestination,
282}
283
284#[dom_struct]
285pub(crate) struct Window {
286 globalscope: GlobalScope,
287 #[ignore_malloc_size_of = "Weak does not need to be accounted"]
291 #[no_trace]
292 weak_script_thread: Weak<ScriptThread>,
293 #[no_trace]
296 #[conditional_malloc_size_of]
297 webview_state: Rc<WebViewState>,
298 script_chan: Sender<MainThreadScriptMsg>,
299 #[no_trace]
300 #[ignore_malloc_size_of = "TODO: Add MallocSizeOf support to layout"]
301 layout: RefCell<Box<dyn Layout>>,
302 navigator: MutNullableDom<Navigator>,
303 #[cfg(feature = "webcrypto")]
304 crypto: MutNullableDom<crate::dom::crypto::Crypto>,
305 #[no_trace]
306 image_cache_sender: Sender<ImageCacheResponseMessage>,
307 window_proxy: MutNullableDom<WindowProxy>,
308 document: MutNullableDom<Document>,
309 location: MutNullableDom<Location>,
310 performance: MutNullableDom<Performance>,
311 #[no_trace]
312 navigation_start: Cell<CrossProcessInstant>,
313 screen: MutNullableDom<Screen>,
314 session_storage: MutNullableDom<Storage>,
315 local_storage: MutNullableDom<Storage>,
316 cookie_store: MutNullableDom<CookieStore>,
318 status: DomRefCell<DOMString>,
319 trusted_types: MutNullableDom<TrustedTypePolicyFactory>,
320
321 ongoing_navigation: Cell<OngoingNavigation>,
324
325 caches: MutNullableDom<CacheStorage>,
327
328 #[no_trace]
331 #[cfg(feature = "devtools")]
332 devtools_markers: DomRefCell<FxHashSet<devtools_traits::TimelineMarkerType>>,
333 #[no_trace]
334 #[cfg(feature = "devtools")]
335 devtools_marker_sender:
336 DomRefCell<Option<GenericSender<Option<devtools_traits::TimelineMarker>>>>,
337
338 #[no_trace]
340 unhandled_resize_event: DomRefCell<Option<(ViewportDetails, WindowSizeType)>>,
341
342 #[no_trace]
346 viewport_details_at_last_resize_steps: Cell<ViewportDetails>,
347
348 #[no_trace]
350 parent_info: Option<PipelineId>,
351
352 dom_static: GlobalStaticData,
354
355 #[conditional_malloc_size_of]
357 js_runtime: DomRefCell<Option<Rc<Runtime>>>,
358
359 #[no_trace]
361 viewport_details: Cell<ViewportDetails>,
362
363 #[no_trace]
365 #[cfg(feature = "bluetooth")]
366 bluetooth_thread: GenericSender<BluetoothRequest>,
367
368 #[cfg(feature = "bluetooth")]
369 bluetooth_extra_permission_data: BluetoothExtraPermissionData,
370
371 #[no_trace]
375 layout_blocker: Cell<LayoutBlocker>,
376
377 #[no_trace]
379 webdriver_load_status_sender: RefCell<Option<GenericSender<WebDriverLoadStatus>>>,
380
381 current_state: Cell<WindowState>,
383
384 error_reporter: CSSErrorReporter,
385
386 media_query_lists: DOMTracker<MediaQueryList>,
388
389 #[cfg(feature = "bluetooth")]
390 test_runner: MutNullableDom<TestRunner>,
391
392 #[no_trace]
394 #[cfg(feature = "webgl")]
395 webgl_chan: Option<WebGLChan>,
396
397 #[ignore_malloc_size_of = "defined in webxr"]
398 #[no_trace]
399 #[cfg(feature = "webxr")]
400 webxr_registry: Option<webxr_api::Registry>,
401
402 #[no_trace]
406 pending_image_callbacks: DomRefCell<FxHashMap<PendingImageId, Vec<PendingImageCallback>>>,
407
408 pending_layout_images: DomRefCell<
413 HashMapTracedValues<PendingImageId, Vec<PendingLayoutImageAncillaryData>, FxBuildHasher>,
414 >,
415
416 pending_images_for_rasterization: DomRefCell<
420 HashMapTracedValues<PendingImageRasterizationKey, Vec<Dom<Node>>, FxBuildHasher>,
421 >,
422
423 unminified_css_dir: DomRefCell<Option<String>>,
426
427 local_script_source: Option<String>,
429
430 test_worklet: MutNullableDom<Worklet>,
432 paint_worklet: MutNullableDom<Worklet>,
434
435 exists_mut_observer: Cell<bool>,
437
438 #[no_trace]
440 paint_api: CrossProcessPaintApi,
441
442 #[no_trace]
445 #[conditional_malloc_size_of]
446 user_scripts: Rc<Vec<UserScript>>,
447
448 #[no_trace]
450 player_context: WindowGLContext,
451
452 throttled: Cell<bool>,
456
457 #[conditional_malloc_size_of]
461 layout_marker: DomRefCell<Rc<Cell<bool>>>,
462
463 current_event: MutNullableDom<Event>,
465
466 reporting_observer_list: DomRefCell<Vec<Dom<ReportingObserver>>>,
468
469 report_list: DomRefCell<Vec<Report>>,
471
472 #[no_trace]
474 endpoints_list: DomRefCell<Vec<ReportingEndpoint>>,
475
476 #[conditional_malloc_size_of]
478 script_window_proxies: Rc<ScriptWindowProxies>,
479
480 has_pending_screenshot_readiness_request: Cell<bool>,
482
483 visual_viewport: MutNullableDom<VisualViewport>,
486
487 has_changed_visual_viewport_dimension: Cell<bool>,
489
490 pending_media_query_evaluation: Cell<bool>,
495
496 #[no_trace]
498 last_activation_timestamp: Cell<UserActivationTimestamp>,
499
500 devtools_wants_updates: Cell<bool>,
503
504 has_dispatched_scroll_event: Cell<bool>,
506
507 has_dispatched_input_event: Cell<bool>,
509}
510
511impl Window {
512 pub(crate) fn script_thread(&self) -> Rc<ScriptThread> {
513 Weak::upgrade(&self.weak_script_thread)
514 .expect("Weak reference should always be upgradable when a ScriptThread is running")
515 }
516
517 pub(crate) fn webview_id(&self) -> WebViewId {
518 self.webview_state.id
519 }
520
521 pub(crate) fn webview_state(&self) -> Rc<WebViewState> {
522 self.webview_state.clone()
523 }
524
525 pub(crate) fn as_global_scope(&self) -> &GlobalScope {
526 self.upcast::<GlobalScope>()
527 }
528
529 pub(crate) fn mark_has_dispatched_scroll_event(&self) {
531 self.has_dispatched_scroll_event.set(true);
532 }
533
534 pub(crate) fn mark_has_dispatched_input_event(&self) {
536 self.has_dispatched_input_event.set(true);
537 }
538
539 pub(crate) fn layout(&self) -> Ref<'_, Box<dyn Layout>> {
540 self.layout.borrow()
541 }
542
543 pub(crate) fn layout_mut(&self) -> RefMut<'_, Box<dyn Layout>> {
544 self.layout.borrow_mut()
545 }
546
547 pub(crate) fn get_exists_mut_observer(&self) -> bool {
548 self.exists_mut_observer.get()
549 }
550
551 pub(crate) fn set_exists_mut_observer(&self) {
552 self.exists_mut_observer.set(true);
553 }
554
555 #[expect(unsafe_code)]
556 pub(crate) fn clear_js_runtime_for_script_deallocation(&self) {
557 self.as_global_scope()
558 .remove_web_messaging_and_dedicated_workers_infra();
559 unsafe {
560 *self.js_runtime.borrow_for_script_deallocation() = None;
561 self.window_proxy.set(None);
562 self.current_state.set(WindowState::Zombie);
563 self.as_global_scope()
564 .task_manager()
565 .cancel_all_tasks_and_ignore_future_tasks();
566 }
567 }
568
569 pub(crate) fn discard_browsing_context(&self) {
572 let proxy = self
573 .window_proxy
574 .get()
575 .expect("Discarding a BC from a window that has none");
576 proxy.discard_browsing_context();
577
578 self.as_global_scope()
582 .task_manager()
583 .cancel_all_tasks_and_ignore_future_tasks();
584 }
585
586 pub(crate) fn time_profiler_chan(&self) -> &TimeProfilerChan {
588 self.globalscope.time_profiler_chan()
589 }
590
591 pub(crate) fn origin(&self) -> MutableOrigin {
593 self.Document().origin().clone()
595 }
596
597 pub(crate) fn main_thread_script_chan(&self) -> &Sender<MainThreadScriptMsg> {
598 &self.script_chan
599 }
600
601 pub(crate) fn parent_info(&self) -> Option<PipelineId> {
602 self.parent_info
603 }
604
605 pub(crate) fn new_script_pair(&self) -> (ScriptEventLoopSender, ScriptEventLoopReceiver) {
606 let (sender, receiver) = unbounded();
607 (
608 ScriptEventLoopSender::MainThread(sender),
609 ScriptEventLoopReceiver::MainThread(receiver),
610 )
611 }
612
613 pub(crate) fn event_loop_sender(&self) -> ScriptEventLoopSender {
614 ScriptEventLoopSender::MainThread(self.script_chan.clone())
615 }
616
617 pub(crate) fn image_cache(&self) -> Arc<dyn ImageCache> {
618 self.Document().image_cache()
619 }
620
621 pub(crate) fn window_proxy(&self) -> DomRoot<WindowProxy> {
623 self.window_proxy.get().unwrap()
624 }
625
626 pub(crate) fn append_reporting_observer(&self, reporting_observer: &ReportingObserver) {
627 self.reporting_observer_list
628 .borrow_mut()
629 .push(Dom::from_ref(reporting_observer));
630 }
631
632 pub(crate) fn remove_reporting_observer(&self, reporting_observer: &ReportingObserver) {
633 let index = {
634 let list = self.reporting_observer_list.borrow();
635 list.iter()
636 .position(|observer| &**observer == reporting_observer)
637 };
638
639 if let Some(index) = index {
640 self.reporting_observer_list.borrow_mut().remove(index);
641 }
642 }
643
644 pub(crate) fn registered_reporting_observers(&self) -> Vec<DomRoot<ReportingObserver>> {
645 self.reporting_observer_list
646 .borrow()
647 .iter()
648 .map(|observer| DomRoot::from_ref(&**observer))
649 .collect()
650 }
651
652 pub(crate) fn append_report(&self, report: Report) {
653 self.report_list.borrow_mut().push(report);
654 let trusted_window = Trusted::new(self);
655 self.upcast::<GlobalScope>()
656 .task_manager()
657 .dom_manipulation_task_source()
658 .queue(task!(send_to_reporting_endpoints: move || {
659 let window = trusted_window.root();
660 let reports = std::mem::take(&mut *window.report_list.borrow_mut());
661 window.upcast::<GlobalScope>().send_reports_to_endpoints(
662 reports,
663 window.endpoints_list.borrow().clone(),
664 );
665 }));
666 }
667
668 pub(crate) fn buffered_reports(&self) -> Vec<Report> {
669 self.report_list.borrow().clone()
670 }
671
672 pub(crate) fn set_endpoints_list(&self, endpoints: Vec<ReportingEndpoint>) {
673 *self.endpoints_list.borrow_mut() = endpoints;
674 }
675
676 pub(crate) fn undiscarded_window_proxy(&self) -> Option<DomRoot<WindowProxy>> {
679 self.window_proxy
680 .get()
681 .filter(|window_proxy| !window_proxy.is_browsing_context_discarded())
682 }
683
684 pub(crate) fn top_level_document_if_local(&self) -> Option<DomRoot<Document>> {
689 if self.is_top_level() {
690 return Some(self.Document());
691 }
692
693 let window_proxy = self.undiscarded_window_proxy()?;
694 self.script_window_proxies
695 .find_window_proxy(window_proxy.webview_id().into())?
696 .document()
697 }
698
699 #[cfg(feature = "bluetooth")]
700 pub(crate) fn bluetooth_thread(&self) -> GenericSender<BluetoothRequest> {
701 self.bluetooth_thread.clone()
702 }
703
704 #[cfg(feature = "bluetooth")]
705 pub(crate) fn bluetooth_extra_permission_data(&self) -> &BluetoothExtraPermissionData {
706 &self.bluetooth_extra_permission_data
707 }
708
709 pub(crate) fn css_error_reporter(&self) -> &CSSErrorReporter {
710 &self.error_reporter
711 }
712
713 #[cfg(feature = "webgl")]
714 pub(crate) fn webgl_chan(&self) -> Option<WebGLChan> {
715 self.webgl_chan.clone()
716 }
717
718 #[cfg(feature = "webgl")]
720 pub(crate) fn webgl_chan_value(&self) -> Option<WebGLChan> {
721 self.webgl_chan.clone()
722 }
723
724 #[cfg(feature = "webxr")]
725 pub(crate) fn webxr_registry(&self) -> Option<webxr_api::Registry> {
726 self.webxr_registry.clone()
727 }
728
729 fn new_paint_worklet(&self, cx: &mut JSContext) -> DomRoot<Worklet> {
730 debug!("Creating new paint worklet.");
731
732 let worklet_global_scope_init = self.into();
733 Worklet::new(
734 cx,
735 self,
736 WorkletGlobalScopeType::Paint,
737 Box::new(|| Rc::new(StatelessWorkletThreadPool::spawn(worklet_global_scope_init))),
738 )
739 }
740
741 pub(crate) fn register_image_cache_listener(
742 &self,
743 id: PendingImageId,
744 callback: impl Fn(PendingImageResponse, &mut JSContext) + 'static,
745 ) -> ImageCacheResponseCallback {
746 self.pending_image_callbacks
747 .borrow_mut()
748 .entry(id)
749 .or_default()
750 .push(PendingImageCallback(Box::new(callback)));
751
752 let image_cache_sender = self.image_cache_sender.clone();
753 Box::new(move |message| {
754 let _ = image_cache_sender.send(message);
755 })
756 }
757
758 fn pending_layout_image_notification(&self, no_gc: &NoGC, response: PendingImageResponse) {
759 let mut images = self.pending_layout_images.borrow_mut();
760 let nodes = images.entry(response.id);
761 let nodes = match nodes {
762 Entry::Occupied(nodes) => nodes,
763 Entry::Vacant(_) => return,
764 };
765 if matches!(
766 response.response,
767 ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode
768 ) {
769 for ancillary_data in nodes.get() {
770 match ancillary_data.destination {
771 LayoutImageDestination::BoxTreeConstruction => {
772 ancillary_data.node.dirty(no_gc, NodeDamage::Other);
773 },
774 LayoutImageDestination::DisplayListBuilding => {
775 self.layout().set_needs_new_display_list();
776 },
777 }
778 }
779 }
780
781 match response.response {
782 ImageResponse::MetadataLoaded(_) => {},
783 ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode => {
784 nodes.remove();
785 },
786 }
787 }
788
789 pub(crate) fn handle_image_rasterization_complete_notification(
790 &self,
791 no_gc: &NoGC,
792 response: RasterizationCompleteResponse,
793 ) {
794 let mut images = self.pending_images_for_rasterization.borrow_mut();
795 let nodes = images.entry((response.image_id, response.requested_size));
796 let nodes = match nodes {
797 Entry::Occupied(nodes) => nodes,
798 Entry::Vacant(_) => return,
799 };
800 for node in nodes.get() {
801 node.dirty(no_gc, NodeDamage::Other);
802 }
803 nodes.remove();
804 }
805
806 pub(crate) fn pending_image_notification(
807 &self,
808 response: PendingImageResponse,
809 cx: &mut JSContext,
810 ) {
811 let mut images = std::mem::take(&mut *self.pending_image_callbacks.borrow_mut());
816 let Entry::Occupied(callbacks) = images.entry(response.id) else {
817 let _ = std::mem::replace(&mut *self.pending_image_callbacks.borrow_mut(), images);
818 return;
819 };
820
821 for callback in callbacks.get() {
822 callback.0(response.clone(), cx);
823 }
824
825 match response.response {
826 ImageResponse::MetadataLoaded(_) => {},
827 ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode => {
828 callbacks.remove();
829 },
830 }
831
832 let _ = std::mem::replace(&mut *self.pending_image_callbacks.borrow_mut(), images);
833 }
834
835 pub(crate) fn paint_api(&self) -> &CrossProcessPaintApi {
836 &self.paint_api
837 }
838
839 pub(crate) fn userscripts(&self) -> &[UserScript] {
840 &self.user_scripts
841 }
842
843 pub(crate) fn get_player_context(&self) -> WindowGLContext {
844 self.player_context.clone()
845 }
846
847 pub(crate) fn dispatch_event_with_target_override(&self, cx: &mut JSContext, event: &Event) {
849 event.dispatch(cx, self.upcast(), true);
850 }
851
852 pub(crate) fn font_context(&self) -> Arc<FontContext> {
853 self.layout().font_context().clone()
854 }
855
856 pub(crate) fn ongoing_navigation(&self) -> OngoingNavigation {
857 self.ongoing_navigation.get()
858 }
859
860 pub(crate) fn set_ongoing_navigation(&self) -> OngoingNavigation {
862 let new_value = self.ongoing_navigation.get().0.wrapping_add(1);
866
867 self.ongoing_navigation.set(OngoingNavigation(new_value));
874
875 OngoingNavigation(new_value)
877 }
878
879 fn stop_loading(&self, cx: &mut JSContext) {
881 let doc = self.Document();
883
884 self.set_ongoing_navigation();
894
895 doc.abort_a_document_and_its_descendants(cx, AbortReason::StopLoading);
897 }
898
899 fn destroy_top_level_traversable(&self, cx: &mut JSContext) {
901 let document = self.Document();
907 document.destroy_document_and_its_descendants(cx);
909 self.send_to_constellation(ScriptToConstellationMessage::DiscardTopLevelBrowsingContext);
911 }
912
913 fn definitely_close(&self, cx: &mut JSContext) {
915 let document = self.Document();
916 if !document.check_if_unloading_is_cancelled(cx, false) {
921 return;
922 }
923 document.unload(cx, false);
927 self.destroy_top_level_traversable(cx);
929 }
930
931 fn cannot_show_simple_dialogs(&self) -> bool {
933 if self
936 .Document()
937 .has_active_sandboxing_flag(SandboxingFlagSet::SANDBOXED_MODALS_FLAG)
938 {
939 return true;
940 }
941
942 false
961 }
962
963 pub(crate) fn perform_a_microtask_checkpoint(&self, cx: &mut JSContext) {
964 self.script_thread().perform_a_microtask_checkpoint(cx);
965 }
966
967 pub(crate) fn web_font_context(&self, no_gc: &NoGC) -> WebFontDocumentContext {
968 let global = self.as_global_scope();
969 let task_source = global
970 .task_manager()
971 .dom_manipulation_task_source()
972 .to_sendable();
973 let target_global = Trusted::new(global);
974 let document = self.document_unrooted(no_gc);
975 WebFontDocumentContext {
976 policy_container: document.policy_container().clone(),
977 request_client: self.request_client(Some(no_gc)),
978 document_url: document.base_url(),
979 csp_handler: Box::new(FontCspHandler {
980 global: target_global.clone(),
981 task_source: task_source.clone(),
982 }),
983 network_timing_handler: Box::new(FontNetworkTimingHandler {
984 global: target_global,
985 task_source,
986 }),
987 }
988 }
989
990 pub(crate) fn request_client(&self, no_gc: Option<&NoGC>) -> RequestClient {
992 let (
995 preloaded_resources,
996 insecure_requests_policy,
997 has_trustworthy_ancestor_origin,
998 policy_container,
999 origin,
1000 ) = if let Some(no_gc) = no_gc {
1001 let document = self.document_unrooted(no_gc);
1002 (
1003 document.preloaded_resources().clone(),
1004 document.insecure_requests_policy(),
1005 document.has_trustworthy_ancestor_or_current_origin(),
1006 document.policy_container().clone(),
1007 document.origin().clone(),
1008 )
1009 } else {
1010 let document = self.Document();
1011 (
1012 document.preloaded_resources().clone(),
1013 document.insecure_requests_policy(),
1014 document.has_trustworthy_ancestor_or_current_origin(),
1015 document.policy_container().clone(),
1016 document.origin().clone(),
1017 )
1018 };
1019 RequestClient {
1020 preloaded_resources,
1021 policy_container,
1022 origin: Origin::Origin(origin.immutable().clone()),
1023 is_nested_browsing_context: !self.is_top_level(),
1024 insecure_requests_policy,
1025 has_trustworthy_ancestor_origin,
1026 }
1027 }
1028
1029 #[expect(unsafe_code)]
1030 pub(crate) fn gc(&self, cx: &mut JSContext) {
1031 unsafe { JS_GC(cx, GCReason::API) };
1032 }
1033
1034 pub(crate) fn with_timers<T>(&self, f: impl FnOnce(&OneshotTimers) -> T) -> T {
1035 let document = self.Document();
1036 f(document.timers())
1037 }
1038}
1039
1040#[derive(Debug, MallocSizeOf)]
1041struct FontCspHandler {
1042 global: Trusted<GlobalScope>,
1043 task_source: SendableTaskSource,
1044}
1045
1046impl CspViolationHandler for FontCspHandler {
1047 fn process_violations(&self, violations: Vec<Violation>) {
1048 let global = self.global.clone();
1049 self.task_source.queue(task!(csp_violation: move |cx| {
1050 global.root().report_csp_violations(cx, violations, None, None);
1051 }));
1052 }
1053
1054 fn clone(&self) -> Box<dyn CspViolationHandler> {
1055 Box::new(Self {
1056 global: self.global.clone(),
1057 task_source: self.task_source.clone(),
1058 })
1059 }
1060}
1061
1062#[derive(Debug, MallocSizeOf)]
1063struct FontNetworkTimingHandler {
1064 global: Trusted<GlobalScope>,
1065 task_source: SendableTaskSource,
1066}
1067
1068impl NetworkTimingHandler for FontNetworkTimingHandler {
1069 fn submit_timing(&self, url: ServoUrl, response: ResourceFetchTiming) {
1070 let global = self.global.clone();
1071 self.task_source.queue(task!(network_timing: move |cx| {
1072 submit_timing(
1073 cx,
1074 &FontFetchListener {
1075 url,
1076 global
1077 },
1078 &Ok(()),
1079 &response,
1080 );
1081 }));
1082 }
1083
1084 fn clone(&self) -> Box<dyn NetworkTimingHandler> {
1085 Box::new(Self {
1086 global: self.global.clone(),
1087 task_source: self.task_source.clone(),
1088 })
1089 }
1090}
1091
1092#[derive(Debug)]
1093struct FontFetchListener {
1094 global: Trusted<GlobalScope>,
1095 url: ServoUrl,
1096}
1097
1098impl ResourceTimingListener for FontFetchListener {
1099 fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
1100 (InitiatorType::Css, self.url.clone())
1101 }
1102
1103 fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
1104 self.global.root()
1105 }
1106}
1107
1108pub(crate) fn base64_btoa(input: DOMString) -> Fallible<DOMString> {
1110 if input.str().chars().any(|c: char| c > '\u{FF}') {
1114 Err(Error::InvalidCharacter(None))
1115 } else {
1116 let octets = input
1121 .str()
1122 .chars()
1123 .map(|c: char| c as u8)
1124 .collect::<Vec<u8>>();
1125
1126 let config =
1129 base64::engine::general_purpose::GeneralPurposeConfig::new().with_encode_padding(true);
1130 let engine = base64::engine::GeneralPurpose::new(&base64::alphabet::STANDARD, config);
1131 Ok(DOMString::from(engine.encode(octets)))
1132 }
1133}
1134
1135pub(crate) fn base64_atob(input: DOMString) -> Fallible<DOMString> {
1137 fn is_html_space(c: char) -> bool {
1139 HTML_SPACE_CHARACTERS.contains(&c)
1140 }
1141 let without_spaces = input
1142 .str()
1143 .chars()
1144 .filter(|&c| !is_html_space(c))
1145 .collect::<String>();
1146 let mut input = &*without_spaces;
1147
1148 if input.len() % 4 == 0 {
1152 if input.ends_with("==") {
1153 input = &input[..input.len() - 2]
1154 } else if input.ends_with('=') {
1155 input = &input[..input.len() - 1]
1156 }
1157 }
1158
1159 if input.len() % 4 == 1 {
1162 return Err(Error::InvalidCharacter(None));
1163 }
1164
1165 if input
1173 .chars()
1174 .any(|c| c != '+' && c != '/' && !c.is_alphanumeric())
1175 {
1176 return Err(Error::InvalidCharacter(None));
1177 }
1178
1179 let config = base64::engine::general_purpose::GeneralPurposeConfig::new()
1180 .with_decode_padding_mode(base64::engine::DecodePaddingMode::RequireNone)
1181 .with_decode_allow_trailing_bits(true);
1182 let engine = base64::engine::GeneralPurpose::new(&base64::alphabet::STANDARD, config);
1183
1184 let data = engine
1185 .decode(input)
1186 .map_err(|_| Error::InvalidCharacter(None))?;
1187 Ok(data.iter().map(|&b| b as char).collect::<String>().into())
1188}
1189
1190impl WindowMethods<crate::DomTypeHolder> for Window {
1191 fn Alert_(&self) {
1193 self.Alert(DOMString::new());
1196 }
1197
1198 fn Alert(&self, mut message: DOMString) {
1200 if self.cannot_show_simple_dialogs() {
1202 return;
1203 }
1204
1205 message.normalize_newlines();
1209
1210 {
1221 let stderr = stderr();
1225 let mut stderr = stderr.lock();
1226 let stdout = stdout();
1227 let mut stdout = stdout.lock();
1228 writeln!(&mut stdout, "\nALERT: {message}").unwrap();
1229 stdout.flush().unwrap();
1230 stderr.flush().unwrap();
1231 }
1232
1233 let (sender, receiver) =
1234 ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1235 let dialog = SimpleDialogRequest::Alert {
1236 id: self.Document().embedder_controls().next_control_id(),
1237 message: String::from(message),
1238 response_sender: sender,
1239 };
1240 self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1241 receiver.recv().unwrap_or_else(|_| {
1242 debug!("Alert dialog was cancelled or failed to show.");
1244 AlertResponse::Ok
1245 });
1246
1247 }
1250
1251 fn Caches(&self, cx: &mut JSContext) -> DomRoot<CacheStorage> {
1253 self.caches
1254 .or_init(|| CacheStorage::new(cx, self.as_global_scope()))
1255 }
1256
1257 fn Confirm(&self, mut message: DOMString) -> bool {
1259 if self.cannot_show_simple_dialogs() {
1261 return false;
1262 }
1263
1264 message.normalize_newlines();
1266
1267 let (sender, receiver) =
1273 ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1274 let dialog = SimpleDialogRequest::Confirm {
1275 id: self.Document().embedder_controls().next_control_id(),
1276 message: String::from(message),
1277 response_sender: sender,
1278 };
1279 self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1280
1281 match receiver.recv() {
1297 Ok(ConfirmResponse::Ok) => true,
1298 Ok(ConfirmResponse::Cancel) => false,
1299 Err(_) => {
1300 warn!("Confirm dialog was cancelled or failed to show.");
1301 false
1302 },
1303 }
1304 }
1305
1306 fn Prompt(&self, mut message: DOMString, default: DOMString) -> Option<DOMString> {
1308 if self.cannot_show_simple_dialogs() {
1310 return None;
1311 }
1312
1313 message.normalize_newlines();
1315
1316 let (sender, receiver) =
1324 ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1325 let dialog = SimpleDialogRequest::Prompt {
1326 id: self.Document().embedder_controls().next_control_id(),
1327 message: String::from(message),
1328 default: String::from(default),
1329 response_sender: sender,
1330 };
1331 self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1332
1333 match receiver.recv() {
1352 Ok(PromptResponse::Ok(input)) => Some(input.into()),
1353 Ok(PromptResponse::Cancel) => None,
1354 Err(_) => {
1355 warn!("Prompt dialog was cancelled or failed to show.");
1356 None
1357 },
1358 }
1359 }
1360
1361 fn Stop(&self, cx: &mut JSContext) {
1363 self.stop_loading(cx);
1368 }
1369
1370 fn Focus(&self, cx: &mut JSContext) {
1372 let document = self.Document();
1380 if !document.is_active() {
1381 return;
1382 }
1383
1384 document.focus_handler().focus(cx, &FocusableArea::Viewport);
1389
1390 }
1395
1396 fn Blur(&self) {
1398 }
1401
1402 fn Open(
1404 &self,
1405 cx: &mut JSContext,
1406 url: USVString,
1407 target: DOMString,
1408 features: DOMString,
1409 ) -> Fallible<Option<DomRoot<WindowProxy>>> {
1410 self.window_proxy().open(cx, url, target, features)
1411 }
1412
1413 fn GetOpener(&self, cx: &mut CurrentRealm, mut retval: MutableHandleValue) -> Fallible<()> {
1415 let current = match self.window_proxy.get() {
1417 Some(proxy) => proxy,
1418 None => {
1420 retval.set(NullValue());
1421 return Ok(());
1422 },
1423 };
1424 if current.is_browsing_context_discarded() {
1429 retval.set(NullValue());
1430 return Ok(());
1431 }
1432 current.opener(cx, retval);
1434 Ok(())
1435 }
1436
1437 fn SetOpener(&self, cx: &mut JSContext, value: HandleValue) -> ErrorResult {
1439 if value.is_null() {
1441 if let Some(proxy) = self.window_proxy.get() {
1442 proxy.disown();
1443 }
1444 return Ok(());
1445 }
1446
1447 let obj = self.reflector().get_jsobject();
1449 let result = JS_DefineProperty(
1450 cx,
1451 obj,
1452 c"opener",
1453 value,
1454 PropertyFlags::ENUMERABLE | PropertyFlags::WRITABLE | PropertyFlags::CONFIGURABLE,
1455 );
1456
1457 if result { Ok(()) } else { Err(Error::JSFailed) }
1458 }
1459
1460 fn Closed(&self) -> bool {
1462 self.window_proxy
1463 .get()
1464 .map(|ref proxy| proxy.is_browsing_context_discarded() || proxy.is_closing())
1465 .unwrap_or(true)
1466 }
1467
1468 fn Close(&self, cx: &mut JSContext) {
1470 let window_proxy = match self.window_proxy.get() {
1472 Some(proxy) => proxy,
1473 None => return,
1475 };
1476 if window_proxy.is_closing() {
1478 return;
1479 }
1480 if let Ok(history_length) = self.History(cx).GetLength() {
1483 let is_auxiliary = window_proxy.is_auxiliary();
1484
1485 let is_script_closable = (self.is_top_level() && history_length == 1) ||
1487 is_auxiliary ||
1488 pref!(dom_allow_scripts_to_close_windows);
1489
1490 if is_script_closable {
1494 window_proxy.close();
1496
1497 let this = Trusted::new(self);
1499 let task = task!(window_close_browsing_context: move |cx| {
1500 let window = this.root();
1501 window.definitely_close(cx);
1502 });
1503 self.as_global_scope()
1504 .task_manager()
1505 .dom_manipulation_task_source()
1506 .queue(task);
1507 }
1508 }
1509 }
1510
1511 fn Document(&self) -> DomRoot<Document> {
1513 self.document
1514 .get()
1515 .expect("Document accessed before initialization.")
1516 }
1517
1518 fn History(&self, cx: &mut JSContext) -> DomRoot<History> {
1520 self.Document().history(cx)
1521 }
1522
1523 fn IndexedDB(&self, cx: &mut JSContext) -> DomRoot<IDBFactory> {
1525 self.upcast::<GlobalScope>().ensure_indexeddb_factory(cx)
1526 }
1527
1528 fn CustomElements(&self, cx: &mut JSContext) -> DomRoot<CustomElementRegistry> {
1530 let document = self.Document();
1533 if let Some(registry) = document.custom_element_registry() {
1534 return registry;
1535 }
1536 let registry = CustomElementRegistry::new(cx, self);
1539 document.set_custom_element_registry(®istry);
1540 registry
1542 }
1543
1544 fn Location(&self, cx: &mut JSContext) -> DomRoot<Location> {
1546 self.location.or_init(|| Location::new(cx, self))
1547 }
1548
1549 fn GetSessionStorage(&self, cx: &mut JSContext) -> Fallible<DomRoot<Storage>> {
1551 if let Some(storage) = self.session_storage.get() {
1554 return Ok(storage);
1555 }
1556
1557 if !self.origin().is_tuple() {
1561 return Err(Error::Security(Some(
1562 "Cannot access sessionStorage from opaque origin.".to_string(),
1563 )));
1564 }
1565
1566 let storage = Storage::new(cx, self, WebStorageType::Session);
1568
1569 self.session_storage.set(Some(&storage));
1571
1572 Ok(storage)
1574 }
1575
1576 fn GetLocalStorage(&self, cx: &mut JSContext) -> Fallible<DomRoot<Storage>> {
1578 if let Some(storage) = self.local_storage.get() {
1581 return Ok(storage);
1582 }
1583
1584 if !self.origin().is_tuple() {
1588 return Err(Error::Security(Some(
1589 "Cannot access localStorage from opaque origin.".to_string(),
1590 )));
1591 }
1592
1593 let storage = Storage::new(cx, self, WebStorageType::Local);
1595
1596 self.local_storage.set(Some(&storage));
1598
1599 Ok(storage)
1601 }
1602
1603 fn CookieStore(&self, cx: &mut JSContext) -> DomRoot<CookieStore> {
1605 self.cookie_store
1606 .or_init(|| CookieStore::new(cx, self.upcast::<GlobalScope>()))
1607 }
1608
1609 #[cfg(feature = "webcrypto")]
1611 fn Crypto(&self, cx: &mut JSContext) -> DomRoot<crate::dom::crypto::Crypto> {
1612 self.crypto
1613 .or_init(|| crate::dom::crypto::Crypto::new(cx, self.as_global_scope()))
1614 }
1615
1616 fn GetFrameElement(&self) -> Option<DomRoot<Element>> {
1618 let window_proxy = self.window_proxy.get()?;
1620
1621 let container = window_proxy.frame_element()?;
1623
1624 let container_doc = container.owner_document();
1626 let current_doc = GlobalScope::current()
1627 .expect("No current global object")
1628 .as_window()
1629 .Document();
1630 if !current_doc
1631 .origin()
1632 .same_origin_domain(&container_doc.origin())
1633 {
1634 return None;
1635 }
1636 Some(DomRoot::from_ref(container))
1638 }
1639
1640 fn ReportError(&self, cx: &mut JSContext, error: HandleValue) {
1642 self.as_global_scope().report_an_exception(cx, error);
1643 }
1644
1645 fn Navigator(&self, cx: &mut JSContext) -> DomRoot<Navigator> {
1647 self.navigator.or_init(|| Navigator::new(cx, self))
1648 }
1649
1650 fn ClientInformation(&self, cx: &mut JSContext) -> DomRoot<Navigator> {
1652 self.Navigator(cx)
1653 }
1654
1655 fn SetTimeout(
1657 &self,
1658 cx: &mut JSContext,
1659 callback: TrustedScriptOrStringOrFunction,
1660 timeout: i32,
1661 args: Vec<HandleValue>,
1662 ) -> Fallible<i32> {
1663 let callback = match callback {
1664 TrustedScriptOrStringOrFunction::String(i) => {
1665 TimerCallback::StringTimerCallback(TrustedScriptOrString::String(i))
1666 },
1667 TrustedScriptOrStringOrFunction::TrustedScript(i) => {
1668 TimerCallback::StringTimerCallback(TrustedScriptOrString::TrustedScript(i))
1669 },
1670 TrustedScriptOrStringOrFunction::Function(i) => TimerCallback::FunctionTimerCallback(i),
1671 };
1672 self.as_global_scope().set_timeout_or_interval(
1673 cx,
1674 callback,
1675 args,
1676 Duration::from_millis(timeout.max(0) as u64),
1677 IsInterval::NonInterval,
1678 )
1679 }
1680
1681 fn ClearTimeout(&self, handle: i32) {
1683 self.as_global_scope().clear_timeout_or_interval(handle);
1684 }
1685
1686 fn SetInterval(
1688 &self,
1689 cx: &mut JSContext,
1690 callback: TrustedScriptOrStringOrFunction,
1691 timeout: i32,
1692 args: Vec<HandleValue>,
1693 ) -> Fallible<i32> {
1694 let callback = match callback {
1695 TrustedScriptOrStringOrFunction::String(i) => {
1696 TimerCallback::StringTimerCallback(TrustedScriptOrString::String(i))
1697 },
1698 TrustedScriptOrStringOrFunction::TrustedScript(i) => {
1699 TimerCallback::StringTimerCallback(TrustedScriptOrString::TrustedScript(i))
1700 },
1701 TrustedScriptOrStringOrFunction::Function(i) => TimerCallback::FunctionTimerCallback(i),
1702 };
1703 self.as_global_scope().set_timeout_or_interval(
1704 cx,
1705 callback,
1706 args,
1707 Duration::from_millis(timeout.max(0) as u64),
1708 IsInterval::Interval,
1709 )
1710 }
1711
1712 fn ClearInterval(&self, handle: i32) {
1714 self.ClearTimeout(handle);
1715 }
1716
1717 fn QueueMicrotask(&self, cx: &JSContext, callback: RootedCallback<VoidFunction>) {
1719 ScriptThread::enqueue_microtask(
1720 cx,
1721 Box::new(UserMicrotask {
1722 callback: callback.to_traced(),
1723 global: Dom::from_ref(&self.globalscope),
1724 }),
1725 );
1726 }
1727
1728 fn CreateImageBitmap(
1730 &self,
1731 realm: &mut CurrentRealm,
1732 image: ImageBitmapSource,
1733 options: &ImageBitmapOptions,
1734 ) -> RootedPromise {
1735 ImageBitmap::create_image_bitmap(
1736 self.as_global_scope(),
1737 image,
1738 0,
1739 0,
1740 None,
1741 None,
1742 options,
1743 realm,
1744 )
1745 }
1746
1747 fn CreateImageBitmap_(
1749 &self,
1750 realm: &mut CurrentRealm,
1751 image: ImageBitmapSource,
1752 sx: i32,
1753 sy: i32,
1754 sw: i32,
1755 sh: i32,
1756 options: &ImageBitmapOptions,
1757 ) -> RootedPromise {
1758 ImageBitmap::create_image_bitmap(
1759 self.as_global_scope(),
1760 image,
1761 sx,
1762 sy,
1763 Some(sw),
1764 Some(sh),
1765 options,
1766 realm,
1767 )
1768 }
1769
1770 fn Window(&self) -> DomRoot<WindowProxy> {
1772 self.window_proxy()
1773 }
1774
1775 fn Self_(&self) -> DomRoot<WindowProxy> {
1777 self.window_proxy()
1778 }
1779
1780 fn Frames(&self) -> DomRoot<WindowProxy> {
1782 self.window_proxy()
1783 }
1784
1785 fn Length(&self) -> u32 {
1787 self.Document().iframes().active_iframe_count() as u32
1788 }
1789
1790 fn GetParent(&self) -> Option<DomRoot<WindowProxy>> {
1792 let window_proxy = self.undiscarded_window_proxy()?;
1794
1795 if let Some(parent) = window_proxy.parent() {
1797 return Some(DomRoot::from_ref(parent));
1798 }
1799 Some(window_proxy)
1801 }
1802
1803 fn GetTop(&self) -> Option<DomRoot<WindowProxy>> {
1805 let window_proxy = self.undiscarded_window_proxy()?;
1807
1808 Some(DomRoot::from_ref(window_proxy.top()))
1810 }
1811
1812 fn Performance(&self, cx: &mut JSContext) -> DomRoot<Performance> {
1815 self.performance
1816 .or_init(|| Performance::new(cx, self.as_global_scope(), self.navigation_start.get()))
1817 }
1818
1819 global_event_handlers!();
1821
1822 window_event_handlers!();
1824
1825 fn Screen(&self, cx: &mut JSContext) -> DomRoot<Screen> {
1827 self.screen.or_init(|| Screen::new(cx, self))
1828 }
1829
1830 fn GetVisualViewport(&self, cx: &mut JSContext) -> Option<DomRoot<VisualViewport>> {
1832 if !self.Document().is_fully_active() {
1836 return None;
1837 }
1838
1839 Some(self.get_or_init_visual_viewport(cx))
1840 }
1841
1842 fn Btoa(&self, btoa: DOMString) -> Fallible<DOMString> {
1844 base64_btoa(btoa)
1845 }
1846
1847 fn Atob(&self, atob: DOMString) -> Fallible<DOMString> {
1849 base64_atob(atob)
1850 }
1851
1852 fn RequestAnimationFrame(
1854 &self,
1855 callback: RootedCallback<FrameRequestCallback>,
1856 ) -> Fallible<u32> {
1857 Ok(self
1858 .Document()
1859 .request_animation_frame(AnimationFrameCallback::FrameRequestCallback {
1860 callback: callback.to_traced(),
1861 }))
1862 }
1863
1864 fn CancelAnimationFrame(&self, ident: u32) -> ErrorResult {
1866 let doc = self.Document();
1867 doc.cancel_animation_frame(ident);
1868 Ok(())
1869 }
1870
1871 fn PostMessage(
1873 &self,
1874 cx: &mut JSContext,
1875 message: HandleValue,
1876 target_origin: USVString,
1877 transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
1878 ) -> ErrorResult {
1879 let incumbent = GlobalScope::incumbent().expect("no incumbent global?");
1880 let source = incumbent.as_window();
1881 let source_origin = source.Document().origin().immutable().clone();
1882
1883 self.post_message_impl(&target_origin, source_origin, source, cx, message, transfer)
1884 }
1885
1886 fn PostMessage_(
1888 &self,
1889 cx: &mut JSContext,
1890 message: HandleValue,
1891 options: &WindowPostMessageOptions,
1892 ) -> ErrorResult {
1893 auto_root!(&in(cx) let transfer =
1894 options
1895 .parent
1896 .transfer
1897 .iter()
1898 .map(|js: &RootedTraceableBox<Heap<*mut JSObject>>| js.get())
1899 .collect::<Vec<_>>());
1900
1901 let incumbent = GlobalScope::incumbent().expect("no incumbent global?");
1902 let source = incumbent.as_window();
1903
1904 let source_origin = source.Document().origin().immutable().clone();
1905
1906 self.post_message_impl(
1907 &options.targetOrigin,
1908 source_origin,
1909 source,
1910 cx,
1911 message,
1912 transfer,
1913 )
1914 }
1915
1916 fn CaptureEvents(&self) {
1918 }
1920
1921 fn ReleaseEvents(&self) {
1923 }
1925
1926 fn WebdriverElement(&self, id: DOMString) -> Option<DomRoot<Element>> {
1927 find_node_by_unique_id_in_document(&self.Document(), id.into()).and_then(Root::downcast)
1928 }
1929
1930 fn WebdriverFrame(&self, browsing_context_id: DOMString) -> Option<DomRoot<WindowProxy>> {
1931 self.Document()
1932 .iframes()
1933 .iter()
1934 .find(|iframe| {
1935 iframe
1936 .browsing_context_id()
1937 .as_ref()
1938 .map(BrowsingContextId::to_string) ==
1939 Some(browsing_context_id.to_string())
1940 })
1941 .and_then(|iframe| iframe.GetContentWindow())
1942 }
1943
1944 fn WebdriverWindow(&self, webview_id: DOMString) -> DomRoot<WindowProxy> {
1945 let window_proxy = &self
1946 .window_proxy
1947 .get()
1948 .expect("Should always have a WindowProxy when calling WebdriverWindow");
1949 assert!(
1950 self.is_top_level(),
1951 "Window must be top level browsing context."
1952 );
1953 assert!(self.webview_id().to_string() == webview_id);
1954 DomRoot::from_ref(window_proxy)
1955 }
1956
1957 fn WebdriverShadowRoot(&self, id: DOMString) -> Option<DomRoot<ShadowRoot>> {
1958 find_node_by_unique_id_in_document(&self.Document(), id.into()).and_then(Root::downcast)
1959 }
1960
1961 fn GetComputedStyle(
1963 &self,
1964 cx: &mut JSContext,
1965 element: &Element,
1966 pseudo: Option<DOMString>,
1967 ) -> DomRoot<CSSStyleDeclaration> {
1968 let mut is_null = false;
1972
1973 let pseudo = pseudo.map(|mut s| {
1979 s.make_ascii_lowercase();
1980 s
1981 });
1982 let pseudo = match pseudo {
1983 Some(ref pseudo) if pseudo == ":before" || pseudo == "::before" => {
1984 Some(PseudoElement::Before)
1985 },
1986 Some(ref pseudo) if pseudo == ":after" || pseudo == "::after" => {
1987 Some(PseudoElement::After)
1988 },
1989 Some(ref pseudo) if pseudo == "::selection" => Some(PseudoElement::Selection),
1990 Some(ref pseudo) if pseudo == "::marker" => Some(PseudoElement::Marker),
1991 Some(ref pseudo) if pseudo == "::placeholder" => Some(PseudoElement::Placeholder),
1992 Some(ref pseudo) if pseudo.starts_with(':') => {
1993 is_null = true;
1996 None
1997 },
1998 _ => None,
1999 };
2000
2001 CSSStyleDeclaration::new(
2017 cx,
2018 self,
2019 if is_null {
2020 CSSStyleOwner::Null
2021 } else {
2022 CSSStyleOwner::Element(Dom::from_ref(element))
2023 },
2024 pseudo,
2025 CSSModificationAccess::Readonly,
2026 )
2027 }
2028
2029 fn InnerHeight(&self) -> i32 {
2032 self.viewport_details
2033 .get()
2034 .size
2035 .height
2036 .to_i32()
2037 .unwrap_or(0)
2038 }
2039
2040 fn InnerWidth(&self) -> i32 {
2043 self.viewport_details.get().size.width.to_i32().unwrap_or(0)
2044 }
2045
2046 fn ScrollX(&self) -> i32 {
2048 self.scroll_offset().x as i32
2049 }
2050
2051 fn PageXOffset(&self) -> i32 {
2053 self.ScrollX()
2054 }
2055
2056 fn ScrollY(&self) -> i32 {
2058 self.scroll_offset().y as i32
2059 }
2060
2061 fn PageYOffset(&self) -> i32 {
2063 self.ScrollY()
2064 }
2065
2066 fn Scroll(&self, cx: &mut JSContext, options: &ScrollToOptions) {
2068 let x = options.left.unwrap_or(0.0) as f32;
2073
2074 let y = options.top.unwrap_or(0.0) as f32;
2077
2078 self.scroll(cx, x, y, options.parent.behavior);
2080 }
2081
2082 fn Scroll_(&self, cx: &mut JSContext, x: f64, y: f64) {
2084 self.scroll(cx, x as f32, y as f32, ScrollBehavior::Auto);
2088 }
2089
2090 fn ScrollTo(&self, cx: &mut JSContext, options: &ScrollToOptions) {
2095 self.Scroll(cx, options);
2096 }
2097
2098 fn ScrollTo_(&self, cx: &mut JSContext, x: f64, y: f64) {
2103 self.Scroll_(cx, x, y)
2104 }
2105
2106 fn ScrollBy(&self, cx: &mut JSContext, options: &ScrollToOptions) {
2108 let mut options = options.clone();
2114 let x = options.left.unwrap_or(0.0);
2115 let x = if x.is_finite() { x } else { 0.0 };
2116 let y = options.top.unwrap_or(0.0);
2117 let y = if y.is_finite() { y } else { 0.0 };
2118
2119 options.left.replace(x + self.ScrollX() as f64);
2121
2122 options.top.replace(y + self.ScrollY() as f64);
2124
2125 self.Scroll(cx, &options)
2127 }
2128
2129 fn ScrollBy_(&self, cx: &mut JSContext, x: f64, y: f64) {
2131 let mut options = ScrollToOptions::empty();
2135
2136 options.left.replace(x);
2139
2140 options.top.replace(y);
2142
2143 self.ScrollBy(cx, &options);
2145 }
2146
2147 fn ResizeTo(&self, width: i32, height: i32) {
2149 let window_proxy = match self.window_proxy.get() {
2151 Some(proxy) => proxy,
2152 None => return,
2153 };
2154
2155 if !window_proxy.is_auxiliary() {
2158 return;
2159 }
2160
2161 let dpr = self.device_pixel_ratio();
2162 let size = Size2D::new(width, height).to_f32() * dpr;
2163 self.send_to_embedder(EmbedderMsg::ResizeTo(self.webview_id(), size.to_i32()));
2164 }
2165
2166 fn ResizeBy(&self, x: i32, y: i32) {
2168 let size = self.client_window().size();
2169 self.ResizeTo(x + size.width, y + size.height)
2171 }
2172
2173 fn MoveTo(&self, x: i32, y: i32) {
2175 let dpr = self.device_pixel_ratio();
2178 let point = Point2D::new(x, y).to_f32() * dpr;
2179 let msg = EmbedderMsg::MoveTo(self.webview_id(), point.to_i32());
2180 self.send_to_embedder(msg);
2181 }
2182
2183 fn MoveBy(&self, x: i32, y: i32) {
2185 let origin = self.client_window().min;
2186 self.MoveTo(x + origin.x, y + origin.y)
2188 }
2189
2190 fn ScreenX(&self) -> i32 {
2192 self.client_window().min.x
2193 }
2194
2195 fn ScreenLeft(&self) -> i32 {
2197 self.client_window().min.x
2198 }
2199
2200 fn ScreenY(&self) -> i32 {
2202 self.client_window().min.y
2203 }
2204
2205 fn ScreenTop(&self) -> i32 {
2207 self.client_window().min.y
2208 }
2209
2210 fn OuterHeight(&self) -> i32 {
2212 self.client_window().height()
2213 }
2214
2215 fn OuterWidth(&self) -> i32 {
2217 self.client_window().width()
2218 }
2219
2220 fn DevicePixelRatio(&self) -> Finite<f64> {
2222 Finite::wrap(self.device_pixel_ratio().get() as f64)
2223 }
2224
2225 fn Status(&self) -> DOMString {
2227 self.status.borrow().clone()
2228 }
2229
2230 fn SetStatus(&self, status: DOMString) {
2232 *self.status.borrow_mut() = status
2233 }
2234
2235 fn MatchMedia(&self, cx: &mut JSContext, query: DOMString) -> DomRoot<MediaQueryList> {
2237 let media_query_list = MediaList::parse_media_list(&query.str(), self);
2238 let document = self.Document();
2239 let mql = MediaQueryList::new(cx, &document, media_query_list);
2240 self.media_query_lists.track(&*mql);
2241 mql
2242 }
2243
2244 fn Fetch(
2246 &self,
2247 realm: &mut CurrentRealm,
2248 input: RequestOrUSVString,
2249 init: &RequestInit,
2250 ) -> RootedPromise {
2251 fetch::Fetch(self.upcast(), input, init, realm)
2252 }
2253
2254 fn FetchLater(
2256 &self,
2257 cx: &mut JSContext,
2258 input: RequestInfo,
2259 init: &DeferredRequestInit,
2260 ) -> Fallible<DomRoot<FetchLaterResult>> {
2261 fetch::FetchLater(cx, self, input, init)
2262 }
2263
2264 #[cfg(feature = "bluetooth")]
2265 fn TestRunner(&self, cx: &mut JSContext) -> DomRoot<TestRunner> {
2266 self.test_runner
2267 .or_init(|| TestRunner::new(cx, self.upcast()))
2268 }
2269
2270 fn RunningAnimationCount(&self) -> u32 {
2271 self.document.get().map_or(0, |document| {
2272 document.animation_manager().running_animation_count() as u32
2273 })
2274 }
2275
2276 fn SetName(&self, name: DOMString) {
2278 if let Some(proxy) = self.undiscarded_window_proxy() {
2279 proxy.set_name(name);
2280 }
2281 }
2282
2283 fn Name(&self) -> DOMString {
2285 match self.undiscarded_window_proxy() {
2286 Some(proxy) => proxy.get_name(),
2287 None => DOMString::new(),
2288 }
2289 }
2290
2291 fn Origin(&self) -> USVString {
2293 USVString(self.origin().immutable().ascii_serialization().into_owned())
2294 }
2295
2296 fn GetSelection(&self, cx: &mut JSContext) -> Option<DomRoot<Selection>> {
2298 self.document.get().and_then(|d| d.GetSelection(cx))
2299 }
2300
2301 fn Event(&self, cx: &mut JSContext, rval: MutableHandleValue) {
2303 if let Some(ref event) = self.current_event.get() {
2304 event.reflector().get_jsobject().to_jsval(cx, rval);
2305 }
2306 }
2307
2308 fn IsSecureContext(&self) -> bool {
2309 self.as_global_scope().is_secure_context()
2310 }
2311
2312 fn NamedGetter(&self, cx: &mut JSContext, name: DOMString) -> Option<NamedPropertyValue> {
2314 if name.is_empty() {
2315 return None;
2316 }
2317 let document = self.Document();
2318
2319 let iframes: Vec<_> = document
2321 .iframes()
2322 .iter()
2323 .filter(|iframe| {
2324 if let Some(window) = iframe.GetContentWindow() {
2325 return window.get_name() == name;
2326 }
2327 false
2328 })
2329 .collect();
2330
2331 let iframe_iter = iframes.iter().map(|iframe| iframe.upcast::<Element>());
2332
2333 let name = Atom::from(name);
2334
2335 let elements_with_name = document.get_elements_with_name(cx, &name);
2337 let name_iter = elements_with_name
2338 .iter()
2339 .map(|element| &**element)
2340 .filter(|elem| is_named_element_with_name_attribute(elem));
2341
2342 let elements_with_id = document.get_elements_with_id(cx, &name);
2343 let id_iter = elements_with_id
2344 .iter()
2345 .map(|element| &**element)
2346 .filter(|elem| is_named_element_with_id_attribute(elem));
2347
2348 for elem in iframe_iter.clone() {
2350 if let Some(nested_window_proxy) = elem
2351 .downcast::<HTMLIFrameElement>()
2352 .and_then(|iframe| iframe.GetContentWindow())
2353 {
2354 return Some(NamedPropertyValue::WindowProxy(nested_window_proxy));
2355 }
2356 }
2357
2358 let mut elements = iframe_iter.chain(name_iter).chain(id_iter);
2359
2360 let first = elements.next()?;
2361
2362 if elements.next().is_none() {
2363 return Some(NamedPropertyValue::Element(DomRoot::from_ref(first)));
2365 }
2366
2367 #[derive(JSTraceable, MallocSizeOf)]
2369 struct WindowNamedGetter {
2370 #[no_trace]
2371 name: Atom,
2372 }
2373 impl CollectionFilter for WindowNamedGetter {
2374 fn filter(&self, elem: &Element, _root: &Node) -> bool {
2375 let type_ = match elem.upcast::<Node>().type_id() {
2376 NodeTypeId::Element(ElementTypeId::HTMLElement(type_)) => type_,
2377 _ => return false,
2378 };
2379 if elem.get_id().as_ref() == Some(&self.name) {
2380 return true;
2381 }
2382 match type_ {
2383 HTMLElementTypeId::HTMLEmbedElement |
2384 HTMLElementTypeId::HTMLFormElement |
2385 HTMLElementTypeId::HTMLImageElement |
2386 HTMLElementTypeId::HTMLObjectElement => {
2387 elem.get_name().as_ref() == Some(&self.name)
2388 },
2389 _ => false,
2390 }
2391 }
2392 }
2393 let collection = HTMLCollection::create(
2394 cx,
2395 self,
2396 document.upcast(),
2397 Box::new(WindowNamedGetter { name }),
2398 );
2399 Some(NamedPropertyValue::HTMLCollection(collection))
2400 }
2401
2402 fn SupportedPropertyNames(&self, no_gc: &NoGC) -> Vec<DOMString> {
2404 self.Document().SupportedPropertyNames(no_gc)
2405 }
2406
2407 fn StructuredClone(
2409 &self,
2410 cx: &mut JSContext,
2411 value: HandleValue,
2412 options: &StructuredSerializeOptions,
2413 retval: MutableHandleValue,
2414 ) -> Fallible<()> {
2415 self.as_global_scope()
2416 .structured_clone(cx, value, options, retval)
2417 }
2418
2419 fn TrustedTypes(&self, cx: &mut JSContext) -> DomRoot<TrustedTypePolicyFactory> {
2420 self.trusted_types
2421 .or_init(|| TrustedTypePolicyFactory::new(cx, self.as_global_scope()))
2422 }
2423}
2424
2425impl Window {
2426 pub(crate) fn scroll_offset(&self) -> Vector2D<f32, LayoutPixel> {
2427 self.scroll_offset_query_with_external_scroll_id(self.pipeline_id().root_scroll_id())
2428 }
2429
2430 pub(crate) fn create_named_properties_object(
2433 cx: &mut JSContext,
2434 proto: HandleObject,
2435 object: MutableHandleObject,
2436 ) {
2437 window_named_properties::create(cx, proto, object)
2438 }
2439
2440 pub(crate) fn current_event(&self) -> Option<DomRoot<Event>> {
2441 self.current_event.get()
2442 }
2443
2444 pub(crate) fn set_current_event(&self, event: Option<&Event>) -> Option<DomRoot<Event>> {
2445 let current = self.current_event();
2446 self.current_event.set(event);
2447 current
2448 }
2449
2450 fn post_message_impl(
2452 &self,
2453 target_origin: &USVString,
2454 source_origin: ImmutableOrigin,
2455 source: &Window,
2456 cx: &mut JSContext,
2457 message: HandleValue,
2458 transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
2459 ) -> ErrorResult {
2460 let data = structuredclone::write(cx, message, Some(transfer))?;
2462
2463 let target_origin = match target_origin.0[..].as_ref() {
2465 "*" => None,
2466 "/" => Some(source_origin.clone()),
2467 url => match ServoUrl::parse(url) {
2468 Ok(url) => Some(url.origin()),
2469 Err(_) => return Err(Error::Syntax(None)),
2470 },
2471 };
2472
2473 self.post_message(target_origin, source_origin, &source.window_proxy(), data);
2475 Ok(())
2476 }
2477
2478 pub(crate) fn paint_worklet(&self, cx: &mut JSContext) -> DomRoot<Worklet> {
2480 self.paint_worklet.or_init(|| self.new_paint_worklet(cx))
2481 }
2482
2483 pub(crate) fn clear_js_runtime(&self) {
2484 self.as_global_scope()
2485 .remove_web_messaging_and_dedicated_workers_infra();
2486
2487 self.Document().teardown_custom_element_registry();
2490
2491 self.current_state.set(WindowState::Zombie);
2492 *self.js_runtime.borrow_mut() = None;
2493
2494 if let Some(performance) = self.performance.get() {
2495 performance.clear_and_disable_performance_entry_buffer();
2496 }
2497
2498 self.as_global_scope()
2499 .task_manager()
2500 .cancel_all_tasks_and_ignore_future_tasks();
2501
2502 if let Some(factory) = self.upcast::<GlobalScope>().indexeddb_factory() {
2507 factory.abort_pending_upgrades_and_close_databases();
2508 }
2509
2510 self.pending_image_callbacks.borrow_mut().clear();
2513 }
2514
2515 pub(crate) fn scroll(&self, cx: &mut JSContext, x: f32, y: f32, behavior: ScrollBehavior) {
2517 let xfinite = if x.is_finite() { x } else { 0.0 };
2519 let yfinite = if y.is_finite() { y } else { 0.0 };
2520
2521 let viewport = self.viewport_details.get().size;
2531
2532 let scrolling_area = self.scrolling_area_query(None).to_f32();
2551 let x = xfinite.clamp(0.0, 0.0f32.max(scrolling_area.width() - viewport.width));
2552 let y = yfinite.clamp(0.0, 0.0f32.max(scrolling_area.height() - viewport.height));
2553
2554 let scroll_offset = self.scroll_offset();
2557 if x == scroll_offset.x && y == scroll_offset.y {
2558 return;
2559 }
2560
2561 self.perform_a_scroll(
2566 cx,
2567 x,
2568 y,
2569 self.pipeline_id().root_scroll_id(),
2570 behavior,
2571 None,
2572 );
2573 }
2574
2575 pub(crate) fn perform_a_scroll(
2577 &self,
2578 cx: &mut JSContext,
2579 x: f32,
2580 y: f32,
2581 scroll_id: ExternalScrollId,
2582 _behavior: ScrollBehavior,
2583 element: Option<&Element>,
2584 ) {
2585 let (reflow_phases_run, _) = self.reflow(
2609 cx,
2610 ReflowGoal::UpdateScrollNode(scroll_id, Vector2D::new(x, y)),
2611 );
2612 if reflow_phases_run.needs_frame() {
2613 self.paint_api()
2614 .generate_frame(vec![self.webview_id().into()]);
2615 }
2616
2617 if reflow_phases_run.contains(ReflowPhasesRun::UpdatedScrollNodeOffset) {
2625 match element {
2626 Some(element) if !scroll_id.is_root() => element.handle_scroll_event(),
2627 _ => self.Document().handle_viewport_scroll_event(),
2628 };
2629 }
2630
2631 }
2634
2635 pub(crate) fn device_pixel_ratio(&self) -> Scale<f32, CSSPixel, DevicePixel> {
2636 self.viewport_details.get().hidpi_scale_factor
2637 }
2638
2639 fn client_window(&self) -> DeviceIndependentIntRect {
2640 let (sender, receiver) = generic_channel::channel().expect("Failed to create IPC channel!");
2641
2642 self.send_to_embedder(EmbedderMsg::GetWindowRect(self.webview_id(), sender));
2643
2644 receiver.recv().unwrap_or_default()
2645 }
2646
2647 pub(crate) fn advance_animation_clock(&self, no_gc: &NoGC, delta: TimeDuration) {
2650 self.Document()
2651 .advance_animation_timeline_for_testing(delta);
2652 ScriptThread::handle_tick_all_animations_for_testing(no_gc, self.pipeline_id());
2653 }
2654
2655 pub(crate) fn reflow(
2663 &self,
2664 cx: &mut JSContext,
2665 reflow_goal: ReflowGoal,
2666 ) -> (ReflowPhasesRun, ReflowStatistics) {
2667 let document = self.Document();
2668
2669 if !document.is_fully_active() {
2671 return Default::default();
2672 }
2673
2674 self.document_unrooted(cx.no_gc())
2675 .ensure_safe_to_run_script_or_layout();
2676
2677 match reflow_goal {
2681 ReflowGoal::LayoutQuery(_) | ReflowGoal::UpdateScrollNode(..) => {
2682 self.flush_ancestor_layouts_if_necessary(cx);
2683 },
2684 ReflowGoal::UpdateTheRendering => { },
2685 }
2686
2687 let pipeline_id = self.pipeline_id();
2691 if reflow_goal == ReflowGoal::UpdateTheRendering &&
2692 self.layout_blocker.get().layout_blocked()
2693 {
2694 debug!("Suppressing pre-load-event reflow pipeline {pipeline_id}");
2695 return Default::default();
2696 }
2697
2698 debug!("script: performing reflow for goal {reflow_goal:?}");
2699 #[cfg(feature = "devtools")]
2700 let marker = if self.need_emit_timeline_marker(devtools_traits::TimelineMarkerType::Reflow)
2701 {
2702 Some(devtools_traits::TimelineMarker::start("Reflow".to_owned()))
2703 } else {
2704 None
2705 };
2706
2707 if let Some(selection) = document.selection() {
2708 selection.update_overlaps_document_selection_flags(cx.no_gc());
2709 }
2710
2711 let restyle_reason = document.restyle_reason(cx.no_gc());
2712 document.clear_restyle_reasons();
2713 let restyle = if restyle_reason.needs_restyle() {
2714 debug!("Invalidating layout cache due to reflow condition {restyle_reason:?}",);
2715 self.layout_marker.borrow().set(false);
2717 *self.layout_marker.borrow_mut() = Rc::new(Cell::new(true));
2719
2720 if restyle_reason.contains(RestyleReason::ViewportChanged) &&
2724 self.layout().device().used_viewport_size()
2725 {
2726 document.dirty_all_nodes(cx.no_gc());
2727 }
2728
2729 let stylesheets_changed = document.flush_stylesheets_for_reflow();
2730 let pending_restyles = document.drain_pending_restyles(cx.no_gc());
2731 let dirty_root = document
2732 .take_dirty_root()
2733 .filter(|_| !stylesheets_changed)
2734 .or_else(|| document.GetDocumentElement())
2735 .map(|root| root.upcast::<Node>().to_trusted_node_address());
2736
2737 Some(ReflowRequestRestyle {
2738 reason: restyle_reason,
2739 dirty_root,
2740 stylesheets_changed,
2741 pending_restyles,
2742 })
2743 } else {
2744 None
2745 };
2746
2747 document.id_map().resolve_all(cx.no_gc(), document.upcast());
2750
2751 let document_context = self.web_font_context(cx.no_gc());
2752 let should_update_accessibility_tree = matches!(
2753 reflow_goal,
2754 ReflowGoal::UpdateTheRendering | ReflowGoal::LayoutQuery(QueryMsg::AccessKitNodeQuery)
2755 );
2756 let accessibility =
2757 if should_update_accessibility_tree && self.layout().accessibility_active() {
2758 let rooted_nodes_for_integrity_check =
2759 document.rooted_nodes_for_accessibility_integrity_check();
2760 let focused_element = document
2761 .focus_handler()
2762 .focused_area()
2763 .element()
2764 .map(|element| element.upcast::<Node>().to_opaque());
2765 let damage = document
2766 .accessibility_data_mut()
2767 .drain_pending_accessibility_damage();
2768 Some(ReflowRequestAccessibility {
2769 damage,
2770 focused_element,
2771 rooted_nodes_for_integrity_check,
2772 })
2773 } else {
2774 None
2775 };
2776
2777 let reflow = ReflowRequest {
2779 document: document.upcast::<Node>().to_trusted_node_address(),
2780 epoch: document.current_rendering_epoch(),
2781 restyle,
2782 viewport_details: self.viewport_details.get(),
2783 origin: self.origin().immutable().clone(),
2784 reflow_goal,
2785 animation_timeline_value: document.current_animation_timeline_value(),
2786 animations: document.animation_manager().sets(),
2787 animating_images: document.animation_manager().animating_images(),
2788 highlighted_dom_node: document.highlighted_dom_node().map(|node| node.to_opaque()),
2789 frame_focused: self.webview_state().has_system_focus.get() &&
2790 document.focus_handler().has_focus(),
2791 halt_lcp: self.has_dispatched_scroll_event.get() ||
2792 self.has_dispatched_input_event.get(),
2793 paint_timing_eligible: document.paint_timing_eligible(),
2794 paint_timing_info: document.paint_timing_info(),
2795 document_context,
2796 accessibility,
2797 };
2798
2799 let Some(reflow_result) = self.layout.borrow_mut().reflow(reflow) else {
2800 return Default::default();
2801 };
2802
2803 self.handle_accessibility_actions(reflow_result.pending_accessibility_actions, cx);
2804
2805 debug!("script: layout complete");
2806 #[cfg(feature = "devtools")]
2807 if let Some(marker) = marker {
2808 self.emit_timeline_marker(marker.end());
2809 }
2810
2811 self.handle_new_or_removed_web_fonts_post_reflow(cx, reflow_result.changed_web_fonts);
2812
2813 self.handle_pending_images_post_reflow(
2814 cx,
2815 reflow_result.pending_images,
2816 reflow_result.pending_rasterization_images,
2817 reflow_result.pending_svg_elements_for_serialization,
2818 );
2819
2820 if let Some(candidate) = reflow_result.lcp_candidate {
2821 self.process_lcp_candidate_post_reflow(candidate, &document);
2822 }
2823
2824 if !reflow_result.container_timing_records.is_empty() {
2825 self.process_container_timing_records_post_reflow(
2826 reflow_result.container_timing_records,
2827 &document,
2828 );
2829 }
2830
2831 if let Some(iframe_sizes) = reflow_result.iframe_sizes {
2832 document
2833 .iframes()
2834 .handle_new_iframe_sizes_after_layout(cx, self, iframe_sizes);
2835 }
2836
2837 document.update_animations_post_reflow();
2838
2839 (
2840 reflow_result.reflow_phases_run,
2841 reflow_result.reflow_statistics,
2842 )
2843 }
2844
2845 pub(crate) fn request_screenshot_readiness(&self, cx: &mut JSContext) {
2846 self.has_pending_screenshot_readiness_request.set(true);
2847 self.maybe_resolve_pending_screenshot_readiness_requests(cx);
2848 }
2849
2850 pub(crate) fn maybe_resolve_pending_screenshot_readiness_requests(&self, cx: &mut JSContext) {
2851 let pending_request = self.has_pending_screenshot_readiness_request.get();
2852 if !pending_request {
2853 return;
2854 }
2855
2856 let document = self.Document();
2857 if document.ReadyState() != DocumentReadyState::Complete {
2858 return;
2859 }
2860
2861 if document.render_blocking_element_count() > 0 {
2862 return;
2863 }
2864
2865 if document.GetDocumentElement().is_some_and(|elem| {
2869 elem.has_class(&atom!("reftest-wait"), CaseSensitivity::CaseSensitive) ||
2870 elem.has_class(&Atom::from("test-wait"), CaseSensitivity::CaseSensitive)
2871 }) {
2872 return;
2873 }
2874
2875 if self.font_context().web_fonts_still_loading() != 0 {
2876 return;
2877 }
2878
2879 if self.Document().Fonts(cx).waiting_to_fullfill_promise() {
2880 return;
2881 }
2882
2883 if !self.pending_layout_images.borrow().is_empty() ||
2884 !self.pending_images_for_rasterization.borrow().is_empty()
2885 {
2886 return;
2887 }
2888
2889 let document = self.Document();
2890 if document.needs_rendering_update(cx.no_gc()) {
2891 return;
2892 }
2893
2894 let epoch = document.current_rendering_epoch();
2897 let pipeline_id = self.pipeline_id();
2898 debug!("Ready to take screenshot of {pipeline_id:?} at epoch={epoch:?}");
2899
2900 self.send_to_constellation(
2901 ScriptToConstellationMessage::RespondToScreenshotReadinessRequest(
2902 ScreenshotReadinessResponse::Ready(epoch),
2903 ),
2904 );
2905 self.has_pending_screenshot_readiness_request.set(false);
2906 }
2907
2908 pub(crate) fn reflow_if_reflow_timer_expired(&self, cx: &mut JSContext) {
2911 if !matches!(
2914 self.layout_blocker.get(),
2915 LayoutBlocker::Parsing(instant) if instant + INITIAL_REFLOW_DELAY < Instant::now()
2916 ) {
2917 return;
2918 }
2919 self.allow_layout_if_necessary(cx);
2920 }
2921
2922 pub(crate) fn prevent_layout_until_load_event(&self) {
2926 if !matches!(self.layout_blocker.get(), LayoutBlocker::WaitingForParse) {
2929 return;
2930 }
2931
2932 self.layout_blocker
2933 .set(LayoutBlocker::Parsing(Instant::now()));
2934 }
2935
2936 pub(crate) fn allow_layout_if_necessary(&self, cx: &mut JSContext) {
2939 if matches!(
2940 self.layout_blocker.get(),
2941 LayoutBlocker::FiredLoadEventOrParsingTimerExpired
2942 ) {
2943 return;
2944 }
2945
2946 self.layout_blocker
2947 .set(LayoutBlocker::FiredLoadEventOrParsingTimerExpired);
2948
2949 let document = self.Document();
2961 if !document.is_render_blocked() && document.update_the_rendering(cx).0.needs_frame() {
2962 self.paint_api()
2963 .generate_frame(vec![self.webview_id().into()]);
2964 }
2965 }
2966
2967 pub(crate) fn layout_blocked(&self) -> bool {
2968 self.layout_blocker.get().layout_blocked()
2969 }
2970
2971 fn flush_ancestor_layouts_if_necessary(&self, cx: &mut JSContext) {
2972 let Some(parent_pipeline_id) = self.parent_info else {
2973 return;
2974 };
2975 let Some(parent_window) = ScriptThread::find_window(parent_pipeline_id) else {
2976 return;
2977 };
2978 if !parent_window.Document().is_safe_to_run_script_or_layout() {
2981 return;
2982 }
2983 if parent_window.Document().is_render_blocked() {
2986 return;
2987 }
2988 parent_window.flush_ancestor_layouts_if_necessary(cx);
2989 if parent_window
2990 .document_unrooted(cx.no_gc())
2991 .restyle_reason(cx.no_gc())
2992 .needs_restyle()
2993 {
2994 parent_window.reflow(
2995 cx,
2996 ReflowGoal::LayoutQuery(QueryMsg::FlushForUpdateTheRenderingQuery),
2997 );
2998 }
2999 }
3000
3001 #[expect(unsafe_code)]
3003 pub(crate) fn layout_reflow(&self, query_msg: QueryMsg) {
3004 let mut cx = unsafe { script_bindings::script_runtime::temp_cx() };
3006
3007 self.reflow(&mut cx, ReflowGoal::LayoutQuery(query_msg));
3008 }
3009
3010 pub(crate) fn reflow_for_non_flushing_update_the_rendering_queries(&self, cx: &mut JSContext) {
3012 self.reflow(
3013 cx,
3014 ReflowGoal::LayoutQuery(QueryMsg::FlushForUpdateTheRenderingQuery),
3015 );
3016 }
3017
3018 pub(crate) fn resolved_font_style_query(
3019 &self,
3020 node: &Node,
3021 value: String,
3022 ) -> Option<ServoArc<Font>> {
3023 self.layout_reflow(QueryMsg::ResolvedFontStyleQuery);
3024
3025 let document = self.Document();
3026 let animations = document.animation_manager().sets();
3027 self.layout.borrow().query_resolved_font_style(
3028 node.to_trusted_node_address(),
3029 &value,
3030 animations,
3031 document.current_animation_timeline_value(),
3032 )
3033 }
3034
3035 #[expect(unsafe_code)]
3038 pub(crate) fn containing_block_node_query_without_reflow(
3039 &self,
3040 node: &Node,
3041 ) -> Option<DomRoot<Node>> {
3042 self.layout
3043 .borrow()
3044 .query_containing_block(node.to_trusted_node_address())
3045 .map(|address| unsafe { from_untrusted_node_address(address) })
3046 }
3047
3048 pub(crate) fn is_containing_block_descendant_query_without_reflow(
3051 &self,
3052 possible_ancestor: &Node,
3053 possible_descendant: &Node,
3054 ) -> bool {
3055 self.layout.borrow().query_containing_block_is_descendant(
3056 possible_ancestor.to_trusted_node_address(),
3057 possible_descendant.to_trusted_node_address(),
3058 )
3059 }
3060
3061 pub(crate) fn padding_query_without_reflow(&self, node: &Node) -> Option<PhysicalSides> {
3066 let layout = self.layout.borrow();
3067 layout.query_padding(node.to_trusted_node_address())
3068 }
3069
3070 pub(crate) fn box_area_query_without_reflow(
3075 &self,
3076 node: &Node,
3077 area: BoxAreaType,
3078 exclude_transform_and_inline: bool,
3079 ) -> Option<Rect<Au, CSSPixel>> {
3080 let layout = self.layout.borrow();
3081 layout.ensure_stacking_context_tree(self.viewport_details.get());
3082 layout.query_box_area(
3083 node.to_trusted_node_address(),
3084 area,
3085 exclude_transform_and_inline,
3086 )
3087 }
3088
3089 pub(crate) fn box_area_query(
3090 &self,
3091 node: &Node,
3092 area: BoxAreaType,
3093 exclude_transform_and_inline: bool,
3094 ) -> Option<Rect<Au, CSSPixel>> {
3095 self.layout_reflow(QueryMsg::BoxArea);
3096 self.box_area_query_without_reflow(node, area, exclude_transform_and_inline)
3097 }
3098
3099 pub(crate) fn box_areas_query(&self, node: &Node, area: BoxAreaType) -> CSSPixelRectVec {
3100 self.layout_reflow(QueryMsg::BoxAreas);
3101 self.layout
3102 .borrow()
3103 .query_box_areas(node.to_trusted_node_address(), area)
3104 }
3105
3106 pub(crate) fn client_rect_query(&self, node: &Node) -> Rect<i32, CSSPixel> {
3107 self.layout_reflow(QueryMsg::ClientRectQuery);
3108 self.layout
3109 .borrow()
3110 .query_client_rect(node.to_trusted_node_address())
3111 }
3112
3113 pub(crate) fn current_css_zoom_query(&self, node: &Node) -> f32 {
3114 self.layout_reflow(QueryMsg::CurrentCSSZoomQuery);
3115 self.layout
3116 .borrow()
3117 .query_current_css_zoom(node.to_trusted_node_address())
3118 }
3119
3120 pub(crate) fn document_unrooted<'a>(&self, no_gc: &'a NoGC) -> UnrootedDom<'a, Document> {
3122 self.document
3123 .get_unrooted(no_gc)
3124 .expect("Document accessed before initialization.")
3125 }
3126
3127 pub(crate) fn scrolling_area_query(&self, node: Option<&Node>) -> Rect<i32, CSSPixel> {
3130 self.layout_reflow(QueryMsg::ScrollingAreaOrOffsetQuery);
3131 self.layout
3132 .borrow()
3133 .query_scrolling_area(node.map(Node::to_trusted_node_address))
3134 }
3135
3136 pub(crate) fn scroll_offset_query(&self, node: &Node) -> Vector2D<f32, LayoutPixel> {
3137 let external_scroll_id = ExternalScrollId(
3138 combine_id_with_fragment_type(node.to_opaque().id(), FragmentType::FragmentBody),
3139 self.pipeline_id().into(),
3140 );
3141 self.scroll_offset_query_with_external_scroll_id(external_scroll_id)
3142 }
3143
3144 fn scroll_offset_query_with_external_scroll_id(
3145 &self,
3146 external_scroll_id: ExternalScrollId,
3147 ) -> Vector2D<f32, LayoutPixel> {
3148 self.layout_reflow(QueryMsg::ScrollingAreaOrOffsetQuery);
3149 self.scroll_offset_query_with_external_scroll_id_no_reflow(external_scroll_id)
3150 }
3151
3152 fn scroll_offset_query_with_external_scroll_id_no_reflow(
3153 &self,
3154 external_scroll_id: ExternalScrollId,
3155 ) -> Vector2D<f32, LayoutPixel> {
3156 self.layout
3157 .borrow()
3158 .scroll_offset(external_scroll_id)
3159 .unwrap_or_default()
3160 }
3161
3162 pub(crate) fn scroll_an_element(
3165 &self,
3166 cx: &mut JSContext,
3167 element: &Element,
3168 x: f32,
3169 y: f32,
3170 behavior: ScrollBehavior,
3171 ) {
3172 let scroll_id = ExternalScrollId(
3173 combine_id_with_fragment_type(
3174 element.upcast::<Node>().to_opaque().id(),
3175 FragmentType::FragmentBody,
3176 ),
3177 self.pipeline_id().into(),
3178 );
3179
3180 self.perform_a_scroll(cx, x, y, scroll_id, behavior, Some(element));
3184 }
3185
3186 pub(crate) fn resolved_style_query(
3187 &self,
3188 element: TrustedNodeAddress,
3189 pseudo: Option<PseudoElement>,
3190 property: PropertyId,
3191 ) -> DOMString {
3192 self.layout_reflow(QueryMsg::ResolvedStyleQuery(property.clone()));
3193
3194 let document = self.Document();
3195 let animations = document.animation_manager().sets();
3196 DOMString::from(self.layout.borrow().query_resolved_style(
3197 element,
3198 pseudo,
3199 property,
3200 animations,
3201 document.current_animation_timeline_value(),
3202 ))
3203 }
3204
3205 pub(crate) fn accesskit_node_query(
3206 &self,
3207 element: TrustedNodeAddress,
3208 ) -> Option<accesskit::Node> {
3209 self.layout_reflow(QueryMsg::AccessKitNodeQuery);
3210 self.layout.borrow().query_accesskit_node(element)
3211 }
3212
3213 pub(crate) fn get_iframe_viewport_details_if_known(
3217 &self,
3218 browsing_context_id: BrowsingContextId,
3219 ) -> Option<ViewportDetails> {
3220 self.layout_reflow(QueryMsg::InnerWindowDimensionsQuery);
3222 self.Document()
3223 .iframes()
3224 .viewport_details(browsing_context_id)
3225 }
3226
3227 #[expect(unsafe_code)]
3228 pub(crate) fn offset_parent_query(
3229 &self,
3230 node: &Node,
3231 ) -> (Option<DomRoot<Element>>, Rect<Au, CSSPixel>) {
3232 self.layout_reflow(QueryMsg::OffsetParentQuery);
3233 let response = self
3234 .layout
3235 .borrow()
3236 .query_offset_parent(node.to_trusted_node_address());
3237 let element = response.node_address.and_then(|parent_node_address| {
3238 let node = unsafe { from_untrusted_node_address(parent_node_address) };
3239 DomRoot::downcast(node)
3240 });
3241 (element, response.rect)
3242 }
3243
3244 pub(crate) fn scroll_container_query(
3245 &self,
3246 node: Option<&Node>,
3247 flags: ScrollContainerQueryFlags,
3248 ) -> Option<ScrollContainerResponse> {
3249 self.layout_reflow(QueryMsg::ScrollParentQuery);
3250 self.layout
3251 .borrow()
3252 .query_scroll_container(node.map(Node::to_trusted_node_address), flags)
3253 }
3254
3255 #[expect(unsafe_code)]
3256 pub(crate) fn scrolling_box_query(
3257 &self,
3258 node: Option<&Node>,
3259 flags: ScrollContainerQueryFlags,
3260 ) -> Option<ScrollingBox> {
3261 self.scroll_container_query(node, flags)
3262 .and_then(|response| {
3263 Some(match response {
3264 ScrollContainerResponse::Viewport(overflow) => {
3265 (ScrollingBoxSource::Viewport(self.Document()), overflow)
3266 },
3267 ScrollContainerResponse::Element(parent_node_address, overflow) => {
3268 let node = unsafe { from_untrusted_node_address(parent_node_address) };
3269 (
3270 ScrollingBoxSource::Element(DomRoot::downcast(node)?),
3271 overflow,
3272 )
3273 },
3274 })
3275 })
3276 .map(|(source, overflow)| ScrollingBox::new(source, overflow))
3277 }
3278
3279 #[expect(unsafe_code)]
3280 pub(crate) fn text_index_query_on_node_for_event(
3281 &self,
3282 node: &Node,
3283 point_in_viewport: Point2D<Au, CSSPixel>,
3284 ) -> Option<(DomRoot<Node>, Utf32CodeUnits)> {
3285 self.layout_reflow(QueryMsg::TextIndexOrSegmentQuery);
3286 let result = self
3287 .layout
3288 .borrow()
3289 .query_text_index(node.to_trusted_node_address(), point_in_viewport)?;
3290 let node = unsafe { from_untrusted_node_address(result.0.into()) };
3291 Some((node, result.1))
3292 }
3293
3294 #[expect(unsafe_code)]
3299 pub(crate) fn query_text_segment(
3300 &self,
3301 node: &Node,
3302 offset: Utf32CodeUnitsOrNodeOffset,
3303 granularity: SegmentGranularity,
3304 ) -> Option<(RootedSelectionBoundary, RootedSelectionBoundary)> {
3305 self.layout_reflow(QueryMsg::TextIndexOrSegmentQuery);
3306 let ((start_node, start_offset), (end_node, end_offset)) = self
3307 .layout()
3308 .query_text_segment(node.to_trusted_node_address(), offset, granularity)?;
3309 let start = RootedSelectionBoundary::new_with_utf32_offset(
3310 unsafe { from_untrusted_node_address(start_node.into()) },
3311 start_offset,
3312 );
3313 let end = RootedSelectionBoundary::new_with_utf32_offset(
3314 unsafe { from_untrusted_node_address(end_node.into()) },
3315 end_offset,
3316 );
3317 Some((start, end))
3318 }
3319
3320 pub(crate) fn elements_from_point_query(
3321 &self,
3322 flags: HitTestFlags,
3323 point: LayoutPoint,
3324 ) -> layout_api::HitTestResult {
3325 self.layout_reflow(QueryMsg::ElementsFromPoint);
3326 self.layout().hit_test(flags, point)
3327 }
3328
3329 pub(crate) fn query_effective_overflow(&self, node: &Node) -> Option<AxesOverflow> {
3330 self.layout_reflow(QueryMsg::EffectiveOverflow);
3331 self.query_effective_overflow_without_reflow(node)
3332 }
3333
3334 pub(crate) fn query_effective_overflow_without_reflow(
3335 &self,
3336 node: &Node,
3337 ) -> Option<AxesOverflow> {
3338 self.layout
3339 .borrow()
3340 .query_effective_overflow(node.to_trusted_node_address())
3341 }
3342
3343 pub(crate) fn hit_test_from_input_event(
3344 &self,
3345 flags: HitTestFlags,
3346 input_event: &ConstellationInputEvent,
3347 ) -> Option<HitTestResult> {
3348 self.hit_test_from_point_in_viewport(
3349 flags,
3350 input_event.hit_test_result.as_ref()?.point_in_viewport,
3351 )
3352 }
3353
3354 #[expect(unsafe_code)]
3355 pub(crate) fn hit_test_from_point_in_viewport(
3356 &self,
3357 flags: HitTestFlags,
3358 point_in_frame: Point2D<f32, CSSPixel>,
3359 ) -> Option<HitTestResult> {
3360 let result = self.elements_from_point_query(flags, point_in_frame.cast_unit());
3361 let item = result.items.into_iter().next()?;
3362
3363 let point_relative_to_initial_containing_block =
3364 point_in_frame + self.scroll_offset().cast_unit();
3365
3366 let from_opaque_node = |node: OpaqueNode| {
3369 let address = UntrustedNodeAddress(node.0 as *const c_void);
3370 unsafe { from_untrusted_node_address(address) }
3371 };
3372 Some(HitTestResult {
3373 node: from_opaque_node(item.node),
3374 dom_position_for_selection: result.dom_position_for_selection.map(|(node, offset)| {
3375 RootedSelectionBoundary::new_with_utf32_offset(from_opaque_node(node), offset)
3376 }),
3377 cursor: item.cursor,
3378 point_in_node: item.point_in_target,
3379 point_in_frame,
3380 point_relative_to_initial_containing_block,
3381 })
3382 }
3383
3384 pub(crate) fn init_window_proxy(&self, window_proxy: &WindowProxy) {
3385 assert!(
3386 self.window_proxy
3387 .get()
3388 .is_none_or(|current_proxy| &*current_proxy as *const WindowProxy == window_proxy)
3389 );
3390 self.window_proxy.set(Some(window_proxy));
3391 }
3392
3393 pub(crate) fn init_document(&self, document: &Document) {
3394 assert!(
3395 self.document
3396 .get()
3397 .is_none_or(|document| document.is_initial_about_blank())
3398 );
3399 assert!(document.window() == self);
3400 self.document.set(Some(document));
3401 self.update_jsprincipals_from_document(document);
3402 }
3403
3404 #[expect(unsafe_code)]
3411 pub(crate) fn update_jsprincipals_from_document(&self, document: &Document) {
3412 let realm = unsafe { GetObjectRealmOrNull(self.reflector().get_jsobject().get()) };
3413 let new_principals = ServoJSPrincipals::new::<crate::DomTypeHolder>(&document.origin());
3414 unsafe { SetRealmPrincipals(realm, new_principals.as_raw()) };
3415 }
3416
3417 pub(crate) fn load_data_for_document(
3418 &self,
3419 url: ServoUrl,
3420 pipeline_id: PipelineId,
3421 ) -> LoadData {
3422 let source_document = self.Document();
3423 let secure_context = if self.is_top_level() {
3424 None
3425 } else {
3426 Some(self.IsSecureContext())
3427 };
3428 LoadData::new(
3429 LoadOrigin::Script(self.origin().snapshot()),
3430 url,
3431 source_document.about_base_url(),
3432 Some(pipeline_id),
3433 Referrer::ReferrerUrl(source_document.url()),
3434 source_document.get_referrer_policy(),
3435 secure_context,
3436 Some(source_document.insecure_requests_policy()),
3437 source_document.has_trustworthy_ancestor_origin(),
3438 source_document.creation_sandboxing_flag_set_considering_parent_iframe(),
3439 )
3440 }
3441
3442 pub(crate) fn set_viewport_details(&self, viewport_details: ViewportDetails) {
3445 self.viewport_details.set(viewport_details);
3446 if !self.layout_mut().set_viewport_details(viewport_details) {
3447 return;
3448 }
3449 self.Document()
3450 .add_restyle_reason(RestyleReason::ViewportChanged);
3451 }
3452
3453 pub(crate) fn viewport_details(&self) -> ViewportDetails {
3454 self.viewport_details.get()
3455 }
3456
3457 pub(crate) fn get_or_init_visual_viewport(
3458 &self,
3459 cx: &mut JSContext,
3460 ) -> DomRoot<VisualViewport> {
3461 self.visual_viewport.or_init(|| {
3462 VisualViewport::new_from_layout_viewport(cx, self, self.viewport_details().size)
3463 })
3464 }
3465
3466 pub(crate) fn maybe_update_visual_viewport(
3468 &self,
3469 cx: &mut JSContext,
3470 pinch_zoom_infos: PinchZoomInfos,
3471 ) {
3472 if pinch_zoom_infos.rect == Rect::from_size(self.viewport_details().size) &&
3475 self.visual_viewport.get().is_none()
3476 {
3477 return;
3478 }
3479
3480 let visual_viewport = self.get_or_init_visual_viewport(cx);
3481 let changes = visual_viewport.update_from_pinch_zoom_infos(pinch_zoom_infos);
3482
3483 if changes.intersects(VisualViewportChanges::DimensionChanged) {
3484 self.has_changed_visual_viewport_dimension.set(true);
3485 }
3486 if changes.intersects(VisualViewportChanges::OffsetChanged) {
3487 visual_viewport.handle_scroll_event();
3488 }
3489 }
3490
3491 pub(crate) fn webview_theme(&self) -> Theme {
3492 self.webview_state.theme.get()
3493 }
3494
3495 pub(crate) fn refresh_theme(&self) {
3496 let document = self.Document();
3501 let new_theme = document
3502 .theme_override()
3503 .or(document.theme())
3504 .unwrap_or(self.webview_theme());
3505 if !self.layout_mut().set_theme(new_theme) {
3506 return;
3507 }
3508 document.add_restyle_reason(RestyleReason::ThemeChanged);
3509 self.pending_media_query_evaluation.set(true);
3512 }
3513
3514 pub(crate) fn take_pending_media_query_evaluation(&self) -> bool {
3517 self.pending_media_query_evaluation.replace(false)
3518 }
3519
3520 pub(crate) fn has_pending_media_query_evaluation(&self) -> bool {
3521 self.pending_media_query_evaluation.get()
3522 }
3523
3524 pub(crate) fn get_url(&self) -> ServoUrl {
3525 self.Document().url()
3526 }
3527
3528 pub(crate) fn windowproxy_handler(&self) -> &'static WindowProxyHandler {
3529 self.dom_static.windowproxy_handler
3530 }
3531
3532 pub(crate) fn add_resize_event(&self, event: ViewportDetails, event_type: WindowSizeType) {
3533 if self.viewport_details() == event {
3534 return;
3535 }
3536
3537 self.set_viewport_details(event);
3539
3540 *self.unhandled_resize_event.borrow_mut() = Some((event, event_type))
3543 }
3544
3545 pub(crate) fn take_unhandled_resize_event(&self) -> Option<(ViewportDetails, WindowSizeType)> {
3546 self.unhandled_resize_event.borrow_mut().take()
3547 }
3548
3549 pub(crate) fn has_unhandled_resize_event(&self) -> bool {
3551 self.unhandled_resize_event.borrow().is_some()
3552 }
3553
3554 pub(crate) fn suspend(&self, cx: &mut JSContext) {
3555 self.as_global_scope().suspend();
3557
3558 if self.window_proxy().currently_active() == Some(self.global().pipeline_id()) {
3560 self.window_proxy().unset_currently_active(cx);
3561 }
3562
3563 self.gc(cx);
3568 }
3569
3570 pub(crate) fn resume(&self, cx: &mut JSContext) {
3571 self.as_global_scope().resume();
3573
3574 self.window_proxy().set_currently_active(cx, self);
3576
3577 self.Document().title_changed();
3580 }
3581 pub(crate) fn set_webdriver_load_status_sender(
3582 &self,
3583 sender: Option<GenericSender<WebDriverLoadStatus>>,
3584 ) {
3585 *self.webdriver_load_status_sender.borrow_mut() = sender;
3586 }
3587
3588 pub(crate) fn webdriver_load_status_sender(
3589 &self,
3590 ) -> Option<GenericSender<WebDriverLoadStatus>> {
3591 self.webdriver_load_status_sender.borrow().clone()
3592 }
3593
3594 pub(crate) fn is_alive(&self) -> bool {
3595 self.current_state.get() == WindowState::Alive
3596 }
3597
3598 pub(crate) fn is_top_level(&self) -> bool {
3600 self.parent_info.is_none()
3601 }
3602
3603 fn run_resize_steps_for_layout_viewport(&self, cx: &mut JSContext) -> bool {
3608 let Some((new_size, size_type)) = self.take_unhandled_resize_event() else {
3609 return false;
3610 };
3611
3612 let current_viewport = self.viewport_details();
3615 if current_viewport == self.viewport_details_at_last_resize_steps.get() {
3616 return false;
3617 }
3618 self.viewport_details_at_last_resize_steps
3619 .set(current_viewport);
3620
3621 debug!(
3622 "Running resize steps for pipeline {:?} with viewport {new_size:?}",
3623 self.pipeline_id(),
3624 );
3625
3626 if size_type == WindowSizeType::Resize {
3628 let mut realm = enter_auto_realm(cx, self);
3629 let cx = &mut realm.current_realm();
3630 let uievent = UIEvent::new(
3631 cx,
3632 self,
3633 atom!("resize"),
3634 EventBubbles::DoesNotBubble,
3635 EventCancelable::NotCancelable,
3636 Some(self),
3637 0i32,
3638 0u32,
3639 );
3640 uievent.upcast::<Event>().fire(cx, self.upcast());
3641 }
3642
3643 true
3644 }
3645
3646 pub(crate) fn run_the_resize_steps(&self, cx: &mut JSContext) -> bool {
3651 let layout_viewport_resized = self.run_resize_steps_for_layout_viewport(cx);
3652
3653 if self.has_changed_visual_viewport_dimension.get() {
3654 let visual_viewport = self.get_or_init_visual_viewport(cx);
3655
3656 let uievent = UIEvent::new(
3657 cx,
3658 self,
3659 atom!("resize"),
3660 EventBubbles::DoesNotBubble,
3661 EventCancelable::NotCancelable,
3662 Some(self),
3663 0i32,
3664 0u32,
3665 );
3666 uievent.upcast::<Event>().fire(cx, visual_viewport.upcast());
3667
3668 self.has_changed_visual_viewport_dimension.set(false);
3669 }
3670
3671 layout_viewport_resized
3672 }
3673
3674 pub(crate) fn evaluate_media_queries_and_report_changes(&self, cx: &mut JSContext) {
3677 let mut realm = enter_auto_realm(cx, self);
3678 let cx = &mut realm.current_realm();
3679 rooted_vec!(let mut mql_list);
3680
3681 self.media_query_lists.for_each(|mql| {
3682 if let MediaQueryListMatchState::Changed = mql.evaluate_changes() {
3683 mql_list.push(Dom::from_ref(&*mql));
3685 }
3686 });
3687 for mql in mql_list.iter() {
3689 let event = MediaQueryListEvent::new(
3690 cx,
3691 &mql.global(),
3692 atom!("change"),
3693 false,
3694 false,
3695 mql.Media(),
3696 mql.Matches(),
3697 );
3698 event
3699 .upcast::<Event>()
3700 .fire(cx, mql.upcast::<EventTarget>());
3701 }
3702 }
3703
3704 pub(crate) fn set_throttled(&self, throttled: bool) {
3706 self.throttled.set(throttled);
3707 if throttled {
3708 self.as_global_scope().slow_down_timers();
3709 } else {
3710 self.as_global_scope().speed_up_timers();
3711 }
3712 }
3713
3714 pub(crate) fn throttled(&self) -> bool {
3715 self.throttled.get()
3716 }
3717
3718 pub(crate) fn unminified_css_dir(&self) -> Option<String> {
3719 self.unminified_css_dir.borrow().clone()
3720 }
3721
3722 pub(crate) fn local_script_source(&self) -> &Option<String> {
3723 &self.local_script_source
3724 }
3725
3726 pub(crate) fn set_navigation_start(&self) {
3727 self.navigation_start.set(CrossProcessInstant::now());
3728 }
3729
3730 pub(crate) fn navigation_start(&self) -> CrossProcessInstant {
3731 self.navigation_start.get()
3732 }
3733
3734 pub(crate) fn set_last_activation_timestamp(&self, time: UserActivationTimestamp) {
3735 self.last_activation_timestamp.set(time);
3736 }
3737
3738 pub(crate) fn send_to_embedder(&self, msg: EmbedderMsg) {
3739 self.as_global_scope()
3740 .script_to_embedder_chan()
3741 .send(msg)
3742 .unwrap();
3743 }
3744
3745 pub(crate) fn send_to_constellation(&self, msg: ScriptToConstellationMessage) {
3746 self.as_global_scope()
3747 .script_to_constellation_chan()
3748 .send(msg)
3749 .unwrap();
3750 }
3751
3752 #[cfg(feature = "webxr")]
3753 pub(crate) fn in_immersive_xr_session(&self) -> bool {
3754 self.navigator
3755 .get()
3756 .as_ref()
3757 .and_then(|nav| nav.xr())
3758 .is_some_and(|xr| xr.pending_or_active_session())
3759 }
3760
3761 #[cfg(all(feature = "webgl", not(feature = "webxr")))]
3762 pub(crate) fn in_immersive_xr_session(&self) -> bool {
3763 false
3764 }
3765
3766 fn handle_new_or_removed_web_fonts_post_reflow(
3768 &self,
3769 cx: &mut JSContext,
3770 changed_web_fonts: WebFontSetDifference,
3771 ) {
3772 if changed_web_fonts.is_empty() {
3773 return;
3774 }
3775
3776 let document = self.Document();
3777 let fonts = document.Fonts(cx);
3778 if !changed_web_fonts.removed_font_faces.is_empty() {
3779 fonts.notify_font_face_rules_removed(&changed_web_fonts.removed_font_faces);
3780 }
3781
3782 if !changed_web_fonts.removed_font_faces.is_empty() ||
3783 changed_web_fonts.cascade_index_of_any_rule_changed
3784 {
3785 document.dirty_all_nodes(cx.no_gc());
3788 }
3789
3790 if !changed_web_fonts.added_font_faces.is_empty() {
3791 fonts.switch_to_loading(cx);
3792
3793 for new_web_font in changed_web_fonts.added_font_faces {
3794 if let Some(font_face) = FontFace::new_for_web_font(cx, self.upcast(), new_web_font)
3795 {
3796 fonts.add(cx, font_face);
3797 }
3798 }
3799 }
3800 }
3801
3802 #[expect(unsafe_code)]
3804 fn process_lcp_candidate_post_reflow(&self, candidate: LCPCandidate, document: &Document) {
3805 let element = candidate.node.and_then(|node| {
3806 let node_address = UntrustedNodeAddress(node.id() as *const c_void);
3807 let node = unsafe { from_untrusted_node_address(node_address) };
3808 DomRoot::downcast::<Element>(node)
3809 });
3810 document.store_lcp_candidate(candidate, element.as_deref());
3811 }
3812
3813 #[expect(unsafe_code)]
3819 fn process_container_timing_records_post_reflow(
3820 &self,
3821 records: Vec<ContainerTimingRecord>,
3822 document: &Document,
3823 ) {
3824 let resolve = |node: OpaqueNode| unsafe {
3828 let node_address = UntrustedNodeAddress(node.id() as *const c_void);
3829 DomRoot::downcast::<Element>(from_untrusted_node_address(node_address))
3830 };
3831
3832 for record in records {
3833 let Some(root_element) = resolve(record.root_element) else {
3834 continue;
3835 };
3836 let Some(identifier) =
3840 root_element.get_attribute_string_value(&LocalName::from("containertiming"))
3841 else {
3842 continue;
3843 };
3844 let last_painted_element = record.last_painted_element.and_then(resolve);
3845 document.store_container_timing_record(
3846 record,
3847 identifier.into(),
3848 &root_element,
3849 last_painted_element.as_deref(),
3850 );
3851 }
3852 }
3853
3854 #[expect(unsafe_code)]
3855 fn handle_pending_images_post_reflow(
3856 &self,
3857 cx: &mut JSContext,
3858 pending_images: Vec<PendingImage>,
3859 pending_rasterization_images: Vec<PendingRasterizationImage>,
3860 pending_svg_element_for_serialization: Vec<UntrustedNodeAddress>,
3861 ) {
3862 let pipeline_id = self.pipeline_id();
3863 let image_cache = self.image_cache();
3864 for image in pending_images {
3865 let id = image.id;
3866 let node = unsafe { from_untrusted_node_address(image.node) };
3867
3868 if let PendingImageState::Unrequested(ref url) = image.state {
3869 fetch_image_for_layout(
3870 url.clone(),
3871 &node,
3872 id,
3873 image.is_internal_request,
3874 image_cache.clone(),
3875 );
3876 }
3877
3878 let mut images = self.pending_layout_images.borrow_mut();
3879 if !images.contains_key(&id) {
3880 let trusted_node = Trusted::new(&*node);
3881 let sender = self.register_image_cache_listener(id, move |response, cx| {
3882 trusted_node
3883 .root()
3884 .owner_window()
3885 .pending_layout_image_notification(cx.no_gc(), response);
3886 });
3887
3888 image_cache.add_listener(ImageLoadListener::new(sender, pipeline_id, id));
3889 }
3890
3891 let nodes = images.entry(id).or_default();
3892 if !nodes.iter().any(|n| *n.node == *node) {
3893 nodes.push(PendingLayoutImageAncillaryData {
3894 node: Dom::from_ref(&*node),
3895 destination: image.destination,
3896 });
3897 }
3898 }
3899
3900 for image in pending_rasterization_images {
3901 let node = unsafe { from_untrusted_node_address(image.node) };
3902
3903 let mut images = self.pending_images_for_rasterization.borrow_mut();
3904 if !images.contains_key(&(image.id, image.size)) {
3905 let image_cache_sender = self.image_cache_sender.clone();
3906 image_cache.add_rasterization_complete_listener(
3907 pipeline_id,
3908 image.id,
3909 image.size,
3910 Box::new(move |response| {
3911 let _ = image_cache_sender.send(response);
3912 }),
3913 );
3914 }
3915
3916 let nodes = images.entry((image.id, image.size)).or_default();
3917 if !nodes.iter().any(|n| **n == *node) {
3918 nodes.push(Dom::from_ref(&*node));
3919 }
3920 }
3921
3922 for node in pending_svg_element_for_serialization.into_iter() {
3923 let node = unsafe { from_untrusted_node_address(node) };
3924 let svg = node.downcast::<SVGSVGElement>().unwrap();
3925 svg.serialize_and_cache_subtree(cx);
3926 node.dirty(cx.no_gc(), NodeDamage::Other);
3927 }
3928 }
3929
3930 #[expect(unsafe_code)]
3931 fn handle_accessibility_actions(
3932 &self,
3933 actions: Vec<AccessibilityActionRequest>,
3934 cx: &mut JSContext,
3935 ) {
3936 for action_request in actions {
3937 let target_opaque = action_request.target;
3938 let target = unsafe { from_untrusted_node_address(target_opaque.into()) };
3939 if action_request.action == Action::Click {
3940 target.fire_synthetic_pointer_event_not_trusted(cx, atom!("click"));
3941 }
3942 }
3943 }
3944
3945 pub(crate) fn has_sticky_activation(&self) -> bool {
3947 UserActivationTimestamp::TimeStamp(CrossProcessInstant::now()) >=
3949 self.last_activation_timestamp.get()
3950 }
3951
3952 pub(crate) fn has_transient_activation(&self) -> bool {
3954 let current_time = CrossProcessInstant::now();
3957 UserActivationTimestamp::TimeStamp(current_time) >= self.last_activation_timestamp.get() &&
3958 UserActivationTimestamp::TimeStamp(current_time) <
3959 self.last_activation_timestamp.get() +
3960 pref!(dom_transient_activation_duration_ms)
3961 }
3962
3963 pub(crate) fn consume_last_activation_timestamp(&self) {
3964 if self.last_activation_timestamp.get() != UserActivationTimestamp::PositiveInfinity {
3965 self.set_last_activation_timestamp(UserActivationTimestamp::NegativeInfinity);
3966 }
3967 }
3968
3969 pub(crate) fn consume_user_activation(&self) {
3971 if self.undiscarded_window_proxy().is_none() {
3974 return;
3975 }
3976
3977 let Some(top_level_document) = self.top_level_document_if_local() else {
3981 return;
3982 };
3983
3984 top_level_document
3992 .window()
3993 .consume_last_activation_timestamp();
3994 for document in SameOriginDescendantNavigablesIterator::new(&top_level_document) {
3995 document.window().consume_last_activation_timestamp();
3996 }
3997 }
3998
3999 #[allow(clippy::too_many_arguments)]
4000 pub(crate) fn new(
4001 cx: &mut JSContext,
4002 webview_state: Rc<WebViewState>,
4003 runtime: Rc<Runtime>,
4004 script_chan: Sender<MainThreadScriptMsg>,
4005 layout: Box<dyn Layout>,
4006 image_cache_sender: Sender<ImageCacheResponseMessage>,
4007 resource_threads: ResourceThreads,
4008 storage_threads: StorageThreads,
4009 #[cfg(feature = "bluetooth")] bluetooth_thread: GenericSender<BluetoothRequest>,
4010 mem_profiler_chan: MemProfilerChan,
4011 time_profiler_chan: TimeProfilerChan,
4012 #[cfg(feature = "devtools")] devtools_chan: Option<
4013 GenericCallback<devtools_traits::ScriptToDevtoolsControlMsg>,
4014 >,
4015 script_to_constellation_sender: ScriptToConstellationSender,
4016 embedder_chan: ScriptToEmbedderChan,
4017 control_chan: GenericSender<ScriptThreadMessage>,
4018 pipeline_id: PipelineId,
4019 parent_info: Option<PipelineId>,
4020 viewport_details: ViewportDetails,
4021 origin: MutableOrigin,
4022 creation_url: ServoUrl,
4023 top_level_creation_url: ServoUrl,
4024 navigation_start: CrossProcessInstant,
4025 #[cfg(feature = "webgl")] webgl_chan: Option<WebGLChan>,
4026 #[cfg(feature = "webxr")] webxr_registry: Option<webxr_api::Registry>,
4027 paint_api: CrossProcessPaintApi,
4028 unminify_js: bool,
4029 unminify_css: bool,
4030 local_script_source: Option<String>,
4031 user_scripts: Rc<Vec<UserScript>>,
4032 player_context: WindowGLContext,
4033 #[cfg(feature = "webgpu")] gpu_id_hub: Arc<IdentityHub>,
4034 inherited_secure_context: Option<bool>,
4035 weak_script_thread: Weak<ScriptThread>,
4036 ) -> DomRoot<Self> {
4037 let error_reporter = CSSErrorReporter {
4038 pipelineid: pipeline_id,
4039 script_chan: control_chan,
4040 };
4041
4042 let win = Box::new(Self {
4043 webview_state,
4044 globalscope: GlobalScope::new_inherited(
4045 #[cfg(feature = "devtools")]
4046 devtools_chan,
4047 mem_profiler_chan,
4048 time_profiler_chan,
4049 script_to_constellation_sender,
4050 embedder_chan,
4051 resource_threads,
4052 storage_threads,
4053 creation_url,
4054 Some(top_level_creation_url),
4055 #[cfg(feature = "webgpu")]
4056 gpu_id_hub,
4057 inherited_secure_context,
4058 unminify_js,
4059 ),
4060 caches: Default::default(),
4061 ongoing_navigation: Default::default(),
4062 script_chan,
4063 layout: RefCell::new(layout),
4064 image_cache_sender,
4065 navigator: Default::default(),
4066 #[cfg(feature = "webcrypto")]
4067 crypto: Default::default(),
4068 location: Default::default(),
4069 window_proxy: Default::default(),
4070 document: Default::default(),
4071 performance: Default::default(),
4072 navigation_start: Cell::new(navigation_start),
4073 screen: Default::default(),
4074 session_storage: Default::default(),
4075 local_storage: Default::default(),
4076 cookie_store: Default::default(),
4077 status: DomRefCell::new(DOMString::new()),
4078 parent_info,
4079 dom_static: GlobalStaticData::new(),
4080 js_runtime: DomRefCell::new(Some(runtime)),
4081 #[cfg(feature = "bluetooth")]
4082 bluetooth_thread,
4083 #[cfg(feature = "bluetooth")]
4084 bluetooth_extra_permission_data: BluetoothExtraPermissionData::new(),
4085 unhandled_resize_event: Default::default(),
4086 viewport_details_at_last_resize_steps: Cell::new(viewport_details),
4087 viewport_details: Cell::new(viewport_details),
4088 layout_blocker: Cell::new(LayoutBlocker::WaitingForParse),
4089 current_state: Cell::new(WindowState::Alive),
4090 #[cfg(feature = "devtools")]
4091 devtools_marker_sender: Default::default(),
4092 #[cfg(feature = "devtools")]
4093 devtools_markers: Default::default(),
4094 webdriver_load_status_sender: Default::default(),
4095 error_reporter,
4096 media_query_lists: DOMTracker::new(),
4097 #[cfg(feature = "bluetooth")]
4098 test_runner: Default::default(),
4099 #[cfg(feature = "webgl")]
4100 webgl_chan,
4101 #[cfg(feature = "webxr")]
4102 webxr_registry,
4103 pending_image_callbacks: Default::default(),
4104 pending_layout_images: Default::default(),
4105 pending_images_for_rasterization: Default::default(),
4106 unminified_css_dir: DomRefCell::new(if unminify_css {
4107 Some(unminified_path("unminified-css"))
4108 } else {
4109 None
4110 }),
4111 local_script_source,
4112 test_worklet: Default::default(),
4113 paint_worklet: Default::default(),
4114 exists_mut_observer: Cell::new(false),
4115 paint_api,
4116 user_scripts,
4117 player_context,
4118 throttled: Cell::new(false),
4119 layout_marker: DomRefCell::new(Rc::new(Cell::new(true))),
4120 current_event: MutNullableDom::new(None),
4121 trusted_types: Default::default(),
4122 reporting_observer_list: Default::default(),
4123 report_list: Default::default(),
4124 endpoints_list: Default::default(),
4125 script_window_proxies: ScriptThread::window_proxies(),
4126 has_pending_screenshot_readiness_request: Default::default(),
4127 visual_viewport: Default::default(),
4128 weak_script_thread,
4129 has_changed_visual_viewport_dimension: Default::default(),
4130 pending_media_query_evaluation: Default::default(),
4131 last_activation_timestamp: Cell::new(UserActivationTimestamp::PositiveInfinity),
4132 devtools_wants_updates: Default::default(),
4133 has_dispatched_scroll_event: Cell::new(false),
4134 has_dispatched_input_event: Cell::new(false),
4135 });
4136
4137 WindowBinding::Wrap::<crate::DomTypeHolder>(cx, &origin, win)
4138 }
4139
4140 pub(crate) fn task_manager(&self) -> Rc<TaskManager> {
4141 self.Document().task_manager()
4142 }
4143
4144 pub(crate) fn pipeline_id(&self) -> PipelineId {
4145 self.Document().pipeline_id()
4146 }
4147
4148 pub(crate) fn live_devtools_updates(&self) -> bool {
4149 self.devtools_wants_updates.get()
4150 }
4151
4152 pub(crate) fn set_devtools_wants_updates(&self, value: bool) {
4153 self.devtools_wants_updates.set(value);
4154 }
4155
4156 pub(crate) fn cache_layout_value<T>(&self, value: T) -> LayoutValue<T>
4158 where
4159 T: Copy + MallocSizeOf,
4160 {
4161 LayoutValue::new(self.layout_marker.borrow().clone(), value)
4162 }
4163
4164 pub(crate) fn set_up_a_window_environment_settings_object(
4173 &self,
4174 layout: Box<dyn Layout>,
4175 creation_url: ServoUrl,
4176 top_level_creation_url: ServoUrl,
4177 navigation_start: CrossProcessInstant,
4178 viewport_details: ViewportDetails,
4179 ) {
4180 *self.layout.borrow_mut() = layout;
4181 self.set_viewport_details(viewport_details);
4182 self.navigation_start.set(navigation_start);
4183
4184 let global = self.upcast::<GlobalScope>();
4187 global.set_creation_url(creation_url);
4188 global.set_top_level_creation_url(top_level_creation_url);
4189
4190 self.Document().detach_window();
4191 }
4192}
4193
4194#[cfg(feature = "devtools")]
4195impl Window {
4196 pub(crate) fn need_emit_timeline_marker(
4197 &self,
4198 timeline_type: devtools_traits::TimelineMarkerType,
4199 ) -> bool {
4200 let markers = self.devtools_markers.borrow();
4201 markers.contains(&timeline_type)
4202 }
4203
4204 pub(crate) fn emit_timeline_marker(&self, marker: devtools_traits::TimelineMarker) {
4205 let sender = self.devtools_marker_sender.borrow();
4206 let sender = sender.as_ref().expect("There is no marker sender");
4207 sender.send(Some(marker)).unwrap();
4208 }
4209
4210 pub(crate) fn set_devtools_timeline_markers(
4211 &self,
4212 markers: Vec<devtools_traits::TimelineMarkerType>,
4213 reply: GenericSender<Option<devtools_traits::TimelineMarker>>,
4214 ) {
4215 *self.devtools_marker_sender.borrow_mut() = Some(reply);
4216 self.devtools_markers.borrow_mut().extend(markers);
4217 }
4218
4219 pub(crate) fn drop_devtools_timeline_markers(
4220 &self,
4221 markers: Vec<devtools_traits::TimelineMarkerType>,
4222 ) {
4223 let mut devtools_markers = self.devtools_markers.borrow_mut();
4224 for marker in markers {
4225 devtools_markers.remove(&marker);
4226 }
4227 if devtools_markers.is_empty() {
4228 *self.devtools_marker_sender.borrow_mut() = None;
4229 }
4230 }
4231}
4232#[derive(MallocSizeOf)]
4237pub(crate) struct LayoutValue<T: MallocSizeOf> {
4238 #[conditional_malloc_size_of]
4239 is_valid: Rc<Cell<bool>>,
4240 value: T,
4241}
4242
4243#[expect(unsafe_code)]
4244unsafe impl<T: JSTraceable + MallocSizeOf> JSTraceable for LayoutValue<T> {
4245 unsafe fn trace(&self, trc: *mut js::jsapi::JSTracer) {
4246 unsafe { self.value.trace(trc) };
4247 }
4248}
4249
4250impl<T: Copy + MallocSizeOf> LayoutValue<T> {
4251 fn new(marker: Rc<Cell<bool>>, value: T) -> Self {
4252 LayoutValue {
4253 is_valid: marker,
4254 value,
4255 }
4256 }
4257
4258 pub(crate) fn get(&self) -> Result<T, ()> {
4260 if self.is_valid.get() {
4261 return Ok(self.value);
4262 }
4263 Err(())
4264 }
4265}
4266
4267impl Window {
4268 pub(crate) fn post_message(
4270 &self,
4271 target_origin: Option<ImmutableOrigin>,
4272 source_origin: ImmutableOrigin,
4273 source: &WindowProxy,
4274 data: StructuredSerializedData,
4275 ) {
4276 let this = Trusted::new(self);
4277 let source = Trusted::new(source);
4278 let task = task!(post_serialised_message: move |cx| {
4279 let this = this.root();
4280 let source = source.root();
4281 let document = this.Document();
4282
4283 if let Some(ref target_origin) = target_origin
4285 && !target_origin.same_origin(&*document.origin()) {
4286 return;
4287 }
4288
4289 let obj = this.reflector().get_jsobject();
4291 let mut realm = AutoRealm::new(cx, NonNull::new(obj.get()).unwrap());
4292 let cx = &mut *realm;
4293 rooted!(&in(cx) let mut message_clone = UndefinedValue());
4294 if let Ok(ports) = structuredclone::read(cx, this.upcast(), data, message_clone.handle_mut()) {
4295 MessageEvent::dispatch_jsval(
4297 cx,
4298 this.upcast(),
4299 this.upcast(),
4300 message_clone.handle(),
4301 Some(source_origin.ascii_serialization().as_ref()),
4302 Some(&*source),
4303 ports,
4304 );
4305 } else {
4306 MessageEvent::dispatch_error(
4308 cx,
4309 this.upcast(),
4310 this.upcast(),
4311 );
4312 }
4313 });
4314 self.as_global_scope()
4316 .task_manager()
4317 .dom_manipulation_task_source()
4318 .queue(task);
4319 }
4320}
4321
4322#[derive(Clone, MallocSizeOf)]
4323pub(crate) struct CSSErrorReporter {
4324 pub(crate) pipelineid: PipelineId,
4325 pub(crate) script_chan: GenericSender<ScriptThreadMessage>,
4326}
4327unsafe_no_jsmanaged_fields!(CSSErrorReporter);
4328
4329impl ParseErrorReporter for CSSErrorReporter {
4330 fn report_error(
4331 &self,
4332 url: &UrlExtraData,
4333 location: SourceLocation,
4334 error: ContextualParseError,
4335 ) {
4336 if log_enabled!(log::Level::Info) {
4337 info!(
4338 "Url:\t{}\n{}:{} {}",
4339 url.0.as_str(),
4340 location.line,
4341 location.column,
4342 error
4343 )
4344 }
4345
4346 #[cfg(feature = "devtools")]
4348 let _ = self.script_chan.send(ScriptThreadMessage::ReportCSSError(
4349 self.pipelineid,
4350 url.0.to_string(),
4351 location.line,
4352 location.column,
4353 error.to_string(),
4354 ));
4355 }
4356}
4357
4358fn is_named_element_with_name_attribute(elem: &Element) -> bool {
4359 let type_ = match elem.upcast::<Node>().type_id() {
4360 NodeTypeId::Element(ElementTypeId::HTMLElement(type_)) => type_,
4361 _ => return false,
4362 };
4363 matches!(
4364 type_,
4365 HTMLElementTypeId::HTMLEmbedElement |
4366 HTMLElementTypeId::HTMLFormElement |
4367 HTMLElementTypeId::HTMLImageElement |
4368 HTMLElementTypeId::HTMLObjectElement
4369 )
4370}
4371
4372fn is_named_element_with_id_attribute(elem: &Element) -> bool {
4373 elem.is_html_element() || elem.is_svg_element()
4374}
4375
4376#[expect(unsafe_code)]
4377#[unsafe(no_mangle)]
4378unsafe extern "C" fn dump_js_stack(cx: *mut RawJSContext) {
4380 unsafe {
4381 DumpJSStack(cx, true, false, false);
4382 }
4383}
4384
4385impl WindowHelpers for Window {
4386 fn create_named_properties_object(
4387 cx: &mut JSContext,
4388 proto: HandleObject,
4389 object: MutableHandleObject,
4390 ) {
4391 Self::create_named_properties_object(cx, proto, object)
4392 }
4393}
4394
4395impl HasOrigin for Window {
4396 fn origin(&self) -> MutableOrigin {
4397 Window::origin(self)
4398 }
4399}