1#![cfg_attr(crown, allow(crown::jscontext_first_arg))]
6
7use std::borrow::ToOwned;
8use std::cell::{Cell, RefCell, RefMut};
9use std::collections::HashSet;
10use std::collections::hash_map::Entry;
11use std::default::Default;
12use std::ffi::c_void;
13use std::io::{Write, stderr, stdout};
14use std::ptr::NonNull;
15use std::rc::{Rc, Weak};
16use std::sync::Arc;
17use std::time::{Duration, Instant};
18
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 devtools_traits::{ScriptToDevtoolsControlMsg, TimelineMarker, TimelineMarkerType};
26use dom_struct::dom_struct;
27use embedder_traits::user_contents::UserScript;
28use embedder_traits::{
29 AlertResponse, ConfirmResponse, EmbedderMsg, PromptResponse, ScriptToEmbedderChan,
30 SimpleDialogRequest, Theme, UntrustedNodeAddress, ViewportDetails, WebDriverLoadStatus,
31};
32use euclid::{Point2D, Rect, Scale, Size2D, Vector2D};
33use fonts::{
34 CspViolationHandler, FontContext, NetworkTimingHandler, WebFontDocumentContext,
35 WebFontSetDifference,
36};
37use js::context::{JSContext, NoGC};
38use js::conversions::ToJSValConvertible;
39use js::glue::DumpJSStack;
40use js::jsapi::{
41 GCReason, GetObjectRealmOrNull, Heap, JSContext as RawJSContext, JSObject, JSPROP_ENUMERATE,
42 SetRealmPrincipals,
43};
44use js::jsval::{NullValue, UndefinedValue};
45use js::realm::{AutoRealm, CurrentRealm};
46use js::rust::wrappers2::{JS_DefineProperty, JS_GC};
47use js::rust::{
48 CustomAutoRooterGuard, HandleObject, HandleValue, MutableHandleObject, MutableHandleValue,
49};
50use layout_api::{
51 AxesOverflow, BoxAreaType, CSSPixelRectVec, FragmentType, HitTestFlags, LCPCandidate, Layout,
52 LayoutImageDestination, PendingImage, PendingImageState, PendingRasterizationImage,
53 PhysicalSides, QueryMsg, ReflowGoal, ReflowPhasesRun, ReflowRequest, ReflowRequestRestyle,
54 ReflowStatistics, RestyleReason, ScrollContainerQueryFlags, ScrollContainerResponse,
55 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};
71use script_bindings::cell::{DomRefCell, Ref};
72use script_bindings::codegen::GenericBindings::WindowBinding::ScrollToOptions;
73use script_bindings::dom::UnrootedDom;
74use script_bindings::interfaces::{HasOrigin, WindowHelpers};
75use script_bindings::like::Setlike;
76use script_bindings::principals::ServoJSPrincipals;
77use script_bindings::reflector::DomObject;
78use script_bindings::root::Root;
79use script_traits::{ConstellationInputEvent, ScriptThreadMessage};
80use selectors::attr::CaseSensitivity;
81use servo_arc::Arc as ServoArc;
82use servo_base::cross_process_instant::CrossProcessInstant;
83use servo_base::generic_channel::{self, GenericCallback, GenericSender};
84use servo_base::id::{BrowsingContextId, PipelineId, WebViewId};
85use servo_base::text::Utf32CodeUnits;
86#[cfg(feature = "bluetooth")]
87use servo_bluetooth_traits::BluetoothRequest;
88#[cfg(feature = "webgl")]
89use servo_canvas_traits::webgl::WebGLChan;
90use servo_config::pref;
91use servo_constellation_traits::{
92 LoadData, LoadOrigin, ScreenshotReadinessResponse, ScriptToConstellationMessage,
93 ScriptToConstellationSender, StructuredSerializedData, WindowSizeType,
94};
95use servo_geometry::DeviceIndependentIntRect;
96use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
97use storage_traits::StorageThreads;
98use storage_traits::webstorage_thread::WebStorageType;
99use style::dom::OpaqueNode;
100use style::error_reporting::{ContextualParseError, ParseErrorReporter};
101use style::properties::PropertyId;
102use style::properties::style_structs::Font;
103use style::selector_parser::PseudoElement;
104use style::str::HTML_SPACE_CHARACTERS;
105use style::stylesheets::UrlExtraData;
106use style_traits::CSSPixel;
107use stylo_atoms::Atom;
108use time::Duration as TimeDuration;
109use webrender_api::ExternalScrollId;
110use webrender_api::units::{DeviceIntSize, DevicePixel, LayoutPixel, LayoutPoint};
111
112use crate::dom::StatelessWorkletThreadPool;
113use crate::dom::bindings::codegen::Bindings::AnimationFrameProviderBinding::FrameRequestCallback;
114use crate::dom::bindings::codegen::Bindings::DocumentBinding::{
115 DocumentMethods, DocumentReadyState, NamedPropertyValue,
116};
117use crate::dom::bindings::codegen::Bindings::HTMLIFrameElementBinding::HTMLIFrameElementMethods;
118use crate::dom::bindings::codegen::Bindings::HistoryBinding::History_Binding::HistoryMethods;
119use crate::dom::bindings::codegen::Bindings::ImageBitmapBinding::{
120 ImageBitmapOptions, ImageBitmapSource,
121};
122use crate::dom::bindings::codegen::Bindings::MediaQueryListBinding::MediaQueryList_Binding::MediaQueryListMethods;
123use crate::dom::bindings::codegen::Bindings::MessagePortBinding::StructuredSerializeOptions;
124use crate::dom::bindings::codegen::Bindings::ReportingObserverBinding::Report;
125use crate::dom::bindings::codegen::Bindings::RequestBinding::{RequestInfo, RequestInit};
126use crate::dom::bindings::codegen::Bindings::VoidFunctionBinding::VoidFunction;
127use crate::dom::bindings::codegen::Bindings::WindowBinding::{
128 self, DeferredRequestInit, ScrollBehavior, WindowMethods, WindowPostMessageOptions,
129};
130use crate::dom::bindings::codegen::UnionTypes::{
131 RequestOrUSVString, TrustedScriptOrString, TrustedScriptOrStringOrFunction,
132};
133use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
134use crate::dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
135use crate::dom::bindings::num::Finite;
136use crate::dom::bindings::refcounted::Trusted;
137use crate::dom::bindings::reflector::DomGlobal;
138use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
139use crate::dom::bindings::str::{DOMString, USVString};
140use crate::dom::bindings::structuredclone;
141use crate::dom::bindings::trace::{
142 CustomTraceable, HashMapTracedValues, JSTraceable, RootedTraceableBox,
143};
144use crate::dom::bindings::utils::GlobalStaticData;
145use crate::dom::bindings::weakref::DOMTracker;
146#[cfg(feature = "bluetooth")]
147use crate::dom::bluetooth::BluetoothExtraPermissionData;
148use crate::dom::cookiestore::cookiestore::CookieStore;
149use crate::dom::csp::GlobalCspReporting;
150use crate::dom::css::cssstyledeclaration::{
151 CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner,
152};
153use crate::dom::customelementregistry::CustomElementRegistry;
154use crate::dom::document::focus::FocusableArea;
155use crate::dom::document::{
156 AnimationFrameCallback, Document, SameOriginDescendantNavigablesIterator,
157};
158use crate::dom::element::Element;
159use crate::dom::event::{Event, EventBubbles, EventCancelable};
160use crate::dom::eventtarget::EventTarget;
161use crate::dom::fetchlaterresult::FetchLaterResult;
162use crate::dom::globalscope::GlobalScope;
163use crate::dom::history::History;
164use crate::dom::html::htmlcollection::{CollectionFilter, HTMLCollection};
165use crate::dom::html::htmliframeelement::HTMLIFrameElement;
166use crate::dom::idbfactory::IDBFactory;
167use crate::dom::inputevent::HitTestResult;
168use crate::dom::location::Location;
169use crate::dom::medialist::MediaList;
170use crate::dom::mediaquerylist::{MediaQueryList, MediaQueryListMatchState};
171use crate::dom::mediaquerylistevent::MediaQueryListEvent;
172use crate::dom::messageevent::MessageEvent;
173use crate::dom::navigator::Navigator;
174use crate::dom::node::{Node, NodeDamage, NodeTraits, from_untrusted_node_address};
175use crate::dom::performance::performance::Performance;
176use crate::dom::performanceresourcetiming::InitiatorType;
177use crate::dom::promise::RootedPromise;
178use crate::dom::reporting::reportingendpoint::{ReportingEndpoint, SendReportsToEndpoints};
179use crate::dom::reporting::reportingobserver::ReportingObserver;
180use crate::dom::selection::Selection;
181use crate::dom::serviceworker::cachestorage::CacheStorage;
182use crate::dom::shadowroot::ShadowRoot;
183use crate::dom::storage::Storage;
184#[cfg(feature = "bluetooth")]
185use crate::dom::testrunner::TestRunner;
186use crate::dom::trustedtypes::trustedtypepolicyfactory::TrustedTypePolicyFactory;
187use crate::dom::types::{FontFace, ImageBitmap, SVGSVGElement, UIEvent};
188use crate::dom::visualviewport::{VisualViewport, VisualViewportChanges};
189#[cfg(feature = "webgpu")]
190use crate::dom::webgpu::identityhub::IdentityHub;
191use crate::dom::window::layout_image::fetch_image_for_layout;
192use crate::dom::window::screen::Screen;
193use crate::dom::window::scrolling_box::{ScrollingBox, ScrollingBoxSource};
194use crate::dom::window::useractivation::UserActivationTimestamp;
195use crate::dom::windowproxy::{WindowProxy, WindowProxyHandler};
196use crate::dom::worklet::Worklet;
197use crate::dom::workletglobalscope::WorkletGlobalScopeType;
198use crate::event_loop::script_thread::ScriptThread;
199use crate::event_loop::script_window_proxies::ScriptWindowProxies;
200use crate::event_loop::timers::{IsInterval, OneshotTimers, TimerCallback};
201use crate::event_loop::webdriver_handlers::find_node_by_unique_id_in_document;
202use crate::fetch::fetch;
203use crate::fetch::network_listener::{ResourceTimingListener, submit_timing};
204use crate::messaging::{MainThreadScriptMsg, ScriptEventLoopReceiver, ScriptEventLoopSender};
205use crate::realms::enter_auto_realm;
206use crate::runtime::job_queue::UserMicrotask;
207use crate::runtime::script_runtime::Runtime;
208use crate::tasks::task_manager::TaskManager;
209use crate::tasks::task_source::SendableTaskSource;
210use crate::unminify::unminified_path;
211use crate::window_named_properties;
212
213#[derive(MallocSizeOf)]
218pub struct PendingImageCallback(
219 #[ignore_malloc_size_of = "dyn Fn is currently impossible to measure"]
220 #[expect(clippy::type_complexity)]
221 Box<dyn Fn(PendingImageResponse, &mut JSContext) + 'static>,
222);
223
224#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
226enum WindowState {
227 Alive,
228 Zombie, }
230
231const INITIAL_REFLOW_DELAY: Duration = Duration::from_millis(200);
234
235#[derive(Clone, Copy, MallocSizeOf)]
246enum LayoutBlocker {
247 WaitingForParse,
249 Parsing(Instant),
251 FiredLoadEventOrParsingTimerExpired,
255}
256
257impl LayoutBlocker {
258 fn layout_blocked(&self) -> bool {
259 !matches!(self, Self::FiredLoadEventOrParsingTimerExpired)
260 }
261}
262
263#[derive(Clone, Copy, Debug, Default, JSTraceable, MallocSizeOf, PartialEq)]
266pub(crate) struct OngoingNavigation(u32);
267
268type PendingImageRasterizationKey = (PendingImageId, DeviceIntSize);
269
270#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
274#[derive(JSTraceable, MallocSizeOf)]
275struct PendingLayoutImageAncillaryData {
276 node: Dom<Node>,
277 #[no_trace]
278 destination: LayoutImageDestination,
279}
280
281#[dom_struct]
282pub(crate) struct Window {
283 globalscope: GlobalScope,
284
285 #[ignore_malloc_size_of = "Weak does not need to be accounted"]
289 #[no_trace]
290 weak_script_thread: Weak<ScriptThread>,
291
292 #[no_trace]
296 webview_id: WebViewId,
297 script_chan: Sender<MainThreadScriptMsg>,
298 #[no_trace]
299 #[ignore_malloc_size_of = "TODO: Add MallocSizeOf support to layout"]
300 layout: RefCell<Box<dyn Layout>>,
301 navigator: MutNullableDom<Navigator>,
302 #[cfg(feature = "webcrypto")]
303 crypto: MutNullableDom<crate::dom::crypto::Crypto>,
304 #[no_trace]
305 image_cache_sender: Sender<ImageCacheResponseMessage>,
306 window_proxy: MutNullableDom<WindowProxy>,
307 document: MutNullableDom<Document>,
308 location: MutNullableDom<Location>,
309 performance: MutNullableDom<Performance>,
310 #[no_trace]
311 navigation_start: Cell<CrossProcessInstant>,
312 screen: MutNullableDom<Screen>,
313 session_storage: MutNullableDom<Storage>,
314 local_storage: MutNullableDom<Storage>,
315 cookie_store: MutNullableDom<CookieStore>,
317 status: DomRefCell<DOMString>,
318 trusted_types: MutNullableDom<TrustedTypePolicyFactory>,
319
320 ongoing_navigation: Cell<OngoingNavigation>,
323
324 caches: MutNullableDom<CacheStorage>,
326
327 #[no_trace]
330 devtools_markers: DomRefCell<HashSet<TimelineMarkerType>>,
331 #[no_trace]
332 devtools_marker_sender: DomRefCell<Option<GenericSender<Option<TimelineMarker>>>>,
333
334 #[no_trace]
336 unhandled_resize_event: DomRefCell<Option<(ViewportDetails, WindowSizeType)>>,
337
338 #[no_trace]
342 viewport_details_at_last_resize_steps: Cell<ViewportDetails>,
343
344 #[no_trace]
346 embedder_theme: Cell<Theme>,
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: DomRefCell<Option<Dom<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_id
519 }
520
521 pub(crate) fn as_global_scope(&self) -> &GlobalScope {
522 self.upcast::<GlobalScope>()
523 }
524
525 pub(crate) fn mark_has_dispatched_scroll_event(&self) {
527 self.has_dispatched_scroll_event.set(true);
528 }
529
530 pub(crate) fn mark_has_dispatched_input_event(&self) {
532 self.has_dispatched_input_event.set(true);
533 }
534
535 pub(crate) fn layout(&self) -> Ref<'_, Box<dyn Layout>> {
536 self.layout.borrow()
537 }
538
539 pub(crate) fn layout_mut(&self) -> RefMut<'_, Box<dyn Layout>> {
540 self.layout.borrow_mut()
541 }
542
543 pub(crate) fn get_exists_mut_observer(&self) -> bool {
544 self.exists_mut_observer.get()
545 }
546
547 pub(crate) fn set_exists_mut_observer(&self) {
548 self.exists_mut_observer.set(true);
549 }
550
551 #[expect(unsafe_code)]
552 pub(crate) fn clear_js_runtime_for_script_deallocation(&self) {
553 self.as_global_scope()
554 .remove_web_messaging_and_dedicated_workers_infra();
555 unsafe {
556 *self.js_runtime.borrow_for_script_deallocation() = None;
557 self.window_proxy.set(None);
558 self.current_state.set(WindowState::Zombie);
559 self.as_global_scope()
560 .task_manager()
561 .cancel_all_tasks_and_ignore_future_tasks();
562 }
563 }
564
565 pub(crate) fn discard_browsing_context(&self) {
568 let proxy = self
569 .window_proxy
570 .get()
571 .expect("Discarding a BC from a window that has none");
572 proxy.discard_browsing_context();
573
574 self.as_global_scope()
578 .task_manager()
579 .cancel_all_tasks_and_ignore_future_tasks();
580 }
581
582 pub(crate) fn time_profiler_chan(&self) -> &TimeProfilerChan {
584 self.globalscope.time_profiler_chan()
585 }
586
587 pub(crate) fn origin(&self) -> MutableOrigin {
589 self.Document().origin().clone()
591 }
592
593 pub(crate) fn main_thread_script_chan(&self) -> &Sender<MainThreadScriptMsg> {
594 &self.script_chan
595 }
596
597 pub(crate) fn parent_info(&self) -> Option<PipelineId> {
598 self.parent_info
599 }
600
601 pub(crate) fn new_script_pair(&self) -> (ScriptEventLoopSender, ScriptEventLoopReceiver) {
602 let (sender, receiver) = unbounded();
603 (
604 ScriptEventLoopSender::MainThread(sender),
605 ScriptEventLoopReceiver::MainThread(receiver),
606 )
607 }
608
609 pub(crate) fn event_loop_sender(&self) -> ScriptEventLoopSender {
610 ScriptEventLoopSender::MainThread(self.script_chan.clone())
611 }
612
613 pub(crate) fn image_cache(&self) -> Arc<dyn ImageCache> {
614 self.Document().image_cache()
615 }
616
617 pub(crate) fn window_proxy(&self) -> DomRoot<WindowProxy> {
619 self.window_proxy.get().unwrap()
620 }
621
622 pub(crate) fn append_reporting_observer(&self, reporting_observer: &ReportingObserver) {
623 self.reporting_observer_list
624 .borrow_mut()
625 .push(Dom::from_ref(reporting_observer));
626 }
627
628 pub(crate) fn remove_reporting_observer(&self, reporting_observer: &ReportingObserver) {
629 let index = {
630 let list = self.reporting_observer_list.borrow();
631 list.iter()
632 .position(|observer| &**observer == reporting_observer)
633 };
634
635 if let Some(index) = index {
636 self.reporting_observer_list.borrow_mut().remove(index);
637 }
638 }
639
640 pub(crate) fn registered_reporting_observers(&self) -> Vec<DomRoot<ReportingObserver>> {
641 self.reporting_observer_list
642 .borrow()
643 .iter()
644 .map(|observer| DomRoot::from_ref(&**observer))
645 .collect()
646 }
647
648 pub(crate) fn append_report(&self, report: Report) {
649 self.report_list.borrow_mut().push(report);
650 let trusted_window = Trusted::new(self);
651 self.upcast::<GlobalScope>()
652 .task_manager()
653 .dom_manipulation_task_source()
654 .queue(task!(send_to_reporting_endpoints: move || {
655 let window = trusted_window.root();
656 let reports = std::mem::take(&mut *window.report_list.borrow_mut());
657 window.upcast::<GlobalScope>().send_reports_to_endpoints(
658 reports,
659 window.endpoints_list.borrow().clone(),
660 );
661 }));
662 }
663
664 pub(crate) fn buffered_reports(&self) -> Vec<Report> {
665 self.report_list.borrow().clone()
666 }
667
668 pub(crate) fn set_endpoints_list(&self, endpoints: Vec<ReportingEndpoint>) {
669 *self.endpoints_list.borrow_mut() = endpoints;
670 }
671
672 pub(crate) fn undiscarded_window_proxy(&self) -> Option<DomRoot<WindowProxy>> {
675 self.window_proxy
676 .get()
677 .filter(|window_proxy| !window_proxy.is_browsing_context_discarded())
678 }
679
680 pub(crate) fn top_level_document_if_local(&self) -> Option<DomRoot<Document>> {
685 if self.is_top_level() {
686 return Some(self.Document());
687 }
688
689 let window_proxy = self.undiscarded_window_proxy()?;
690 self.script_window_proxies
691 .find_window_proxy(window_proxy.webview_id().into())?
692 .document()
693 }
694
695 #[cfg(feature = "bluetooth")]
696 pub(crate) fn bluetooth_thread(&self) -> GenericSender<BluetoothRequest> {
697 self.bluetooth_thread.clone()
698 }
699
700 #[cfg(feature = "bluetooth")]
701 pub(crate) fn bluetooth_extra_permission_data(&self) -> &BluetoothExtraPermissionData {
702 &self.bluetooth_extra_permission_data
703 }
704
705 pub(crate) fn css_error_reporter(&self) -> &CSSErrorReporter {
706 &self.error_reporter
707 }
708
709 #[cfg(feature = "webgl")]
710 pub(crate) fn webgl_chan(&self) -> Option<WebGLChan> {
711 self.webgl_chan.clone()
712 }
713
714 #[cfg(feature = "webgl")]
716 pub(crate) fn webgl_chan_value(&self) -> Option<WebGLChan> {
717 self.webgl_chan.clone()
718 }
719
720 #[cfg(feature = "webxr")]
721 pub(crate) fn webxr_registry(&self) -> Option<webxr_api::Registry> {
722 self.webxr_registry.clone()
723 }
724
725 fn new_paint_worklet(&self, cx: &mut JSContext) -> DomRoot<Worklet> {
726 debug!("Creating new paint worklet.");
727
728 let worklet_global_scope_init = self.into();
729 Worklet::new(
730 cx,
731 self,
732 WorkletGlobalScopeType::Paint,
733 Box::new(|| Rc::new(StatelessWorkletThreadPool::spawn(worklet_global_scope_init))),
734 )
735 }
736
737 pub(crate) fn register_image_cache_listener(
738 &self,
739 id: PendingImageId,
740 callback: impl Fn(PendingImageResponse, &mut JSContext) + 'static,
741 ) -> ImageCacheResponseCallback {
742 self.pending_image_callbacks
743 .borrow_mut()
744 .entry(id)
745 .or_default()
746 .push(PendingImageCallback(Box::new(callback)));
747
748 let image_cache_sender = self.image_cache_sender.clone();
749 Box::new(move |message| {
750 let _ = image_cache_sender.send(message);
751 })
752 }
753
754 fn pending_layout_image_notification(&self, no_gc: &NoGC, response: PendingImageResponse) {
755 let mut images = self.pending_layout_images.borrow_mut();
756 let nodes = images.entry(response.id);
757 let nodes = match nodes {
758 Entry::Occupied(nodes) => nodes,
759 Entry::Vacant(_) => return,
760 };
761 if matches!(
762 response.response,
763 ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode
764 ) {
765 for ancillary_data in nodes.get() {
766 match ancillary_data.destination {
767 LayoutImageDestination::BoxTreeConstruction => {
768 ancillary_data.node.dirty(no_gc, NodeDamage::Other);
769 },
770 LayoutImageDestination::DisplayListBuilding => {
771 self.layout().set_needs_new_display_list();
772 },
773 }
774 }
775 }
776
777 match response.response {
778 ImageResponse::MetadataLoaded(_) => {},
779 ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode => {
780 nodes.remove();
781 },
782 }
783 }
784
785 pub(crate) fn handle_image_rasterization_complete_notification(
786 &self,
787 no_gc: &NoGC,
788 response: RasterizationCompleteResponse,
789 ) {
790 let mut images = self.pending_images_for_rasterization.borrow_mut();
791 let nodes = images.entry((response.image_id, response.requested_size));
792 let nodes = match nodes {
793 Entry::Occupied(nodes) => nodes,
794 Entry::Vacant(_) => return,
795 };
796 for node in nodes.get() {
797 node.dirty(no_gc, NodeDamage::Other);
798 }
799 nodes.remove();
800 }
801
802 pub(crate) fn pending_image_notification(
803 &self,
804 response: PendingImageResponse,
805 cx: &mut JSContext,
806 ) {
807 let mut images = std::mem::take(&mut *self.pending_image_callbacks.borrow_mut());
812 let Entry::Occupied(callbacks) = images.entry(response.id) else {
813 let _ = std::mem::replace(&mut *self.pending_image_callbacks.borrow_mut(), images);
814 return;
815 };
816
817 for callback in callbacks.get() {
818 callback.0(response.clone(), cx);
819 }
820
821 match response.response {
822 ImageResponse::MetadataLoaded(_) => {},
823 ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode => {
824 callbacks.remove();
825 },
826 }
827
828 let _ = std::mem::replace(&mut *self.pending_image_callbacks.borrow_mut(), images);
829 }
830
831 pub(crate) fn paint_api(&self) -> &CrossProcessPaintApi {
832 &self.paint_api
833 }
834
835 pub(crate) fn userscripts(&self) -> &[UserScript] {
836 &self.user_scripts
837 }
838
839 pub(crate) fn get_player_context(&self) -> WindowGLContext {
840 self.player_context.clone()
841 }
842
843 pub(crate) fn dispatch_event_with_target_override(&self, cx: &mut JSContext, event: &Event) {
845 event.dispatch(cx, self.upcast(), true);
846 }
847
848 pub(crate) fn font_context(&self) -> Arc<FontContext> {
849 self.layout().font_context().clone()
850 }
851
852 pub(crate) fn ongoing_navigation(&self) -> OngoingNavigation {
853 self.ongoing_navigation.get()
854 }
855
856 pub(crate) fn set_ongoing_navigation(&self) -> OngoingNavigation {
858 let new_value = self.ongoing_navigation.get().0.wrapping_add(1);
862
863 self.ongoing_navigation.set(OngoingNavigation(new_value));
870
871 OngoingNavigation(new_value)
873 }
874
875 fn stop_loading(&self, cx: &mut JSContext) {
877 let doc = self.Document();
879
880 self.set_ongoing_navigation();
890
891 doc.abort_a_document_and_its_descendants(cx);
893 }
894
895 fn destroy_top_level_traversable(&self, cx: &mut JSContext) {
897 let document = self.Document();
903 document.destroy_document_and_its_descendants(cx);
905 self.send_to_constellation(ScriptToConstellationMessage::DiscardTopLevelBrowsingContext);
907 }
908
909 fn definitely_close(&self, cx: &mut JSContext) {
911 let document = self.Document();
912 if !document.check_if_unloading_is_cancelled(cx, false) {
917 return;
918 }
919 document.unload(cx, false);
923 self.destroy_top_level_traversable(cx);
925 }
926
927 fn cannot_show_simple_dialogs(&self) -> bool {
929 if self
932 .Document()
933 .has_active_sandboxing_flag(SandboxingFlagSet::SANDBOXED_MODALS_FLAG)
934 {
935 return true;
936 }
937
938 false
957 }
958
959 pub(crate) fn perform_a_microtask_checkpoint(&self, cx: &mut JSContext) {
960 self.script_thread().perform_a_microtask_checkpoint(cx);
961 }
962
963 pub(crate) fn web_font_context(&self, no_gc: &NoGC) -> WebFontDocumentContext {
964 let global = self.as_global_scope();
965 let task_source = global
966 .task_manager()
967 .dom_manipulation_task_source()
968 .to_sendable();
969 let target_global = Trusted::new(global);
970 let document = self.document_unrooted(no_gc);
971 WebFontDocumentContext {
972 policy_container: document.policy_container().clone(),
973 request_client: self.request_client(Some(no_gc)),
974 document_url: document.base_url(),
975 csp_handler: Box::new(FontCspHandler {
976 global: target_global.clone(),
977 task_source: task_source.clone(),
978 }),
979 network_timing_handler: Box::new(FontNetworkTimingHandler {
980 global: target_global,
981 task_source,
982 }),
983 }
984 }
985
986 pub(crate) fn request_client(&self, no_gc: Option<&NoGC>) -> RequestClient {
988 let (
991 preloaded_resources,
992 insecure_requests_policy,
993 has_trustworthy_ancestor_origin,
994 policy_container,
995 origin,
996 ) = if let Some(no_gc) = no_gc {
997 let document = self.document_unrooted(no_gc);
998 (
999 document.preloaded_resources().clone(),
1000 document.insecure_requests_policy(),
1001 document.has_trustworthy_ancestor_or_current_origin(),
1002 document.policy_container().clone(),
1003 document.origin().clone(),
1004 )
1005 } else {
1006 let document = self.Document();
1007 (
1008 document.preloaded_resources().clone(),
1009 document.insecure_requests_policy(),
1010 document.has_trustworthy_ancestor_or_current_origin(),
1011 document.policy_container().clone(),
1012 document.origin().clone(),
1013 )
1014 };
1015 RequestClient {
1016 preloaded_resources,
1017 policy_container,
1018 origin: Origin::Origin(origin.immutable().clone()),
1019 is_nested_browsing_context: !self.is_top_level(),
1020 insecure_requests_policy,
1021 has_trustworthy_ancestor_origin,
1022 }
1023 }
1024
1025 #[expect(unsafe_code)]
1026 pub(crate) fn gc(&self, cx: &mut JSContext) {
1027 unsafe { JS_GC(cx, GCReason::API) };
1028 }
1029
1030 pub(crate) fn with_timers<T>(&self, f: impl FnOnce(&OneshotTimers) -> T) -> T {
1031 let document = self.Document();
1032 f(document.timers())
1033 }
1034}
1035
1036#[derive(Debug, MallocSizeOf)]
1037struct FontCspHandler {
1038 global: Trusted<GlobalScope>,
1039 task_source: SendableTaskSource,
1040}
1041
1042impl CspViolationHandler for FontCspHandler {
1043 fn process_violations(&self, violations: Vec<Violation>) {
1044 let global = self.global.clone();
1045 self.task_source.queue(task!(csp_violation: move |cx| {
1046 global.root().report_csp_violations(cx, violations, None, None);
1047 }));
1048 }
1049
1050 fn clone(&self) -> Box<dyn CspViolationHandler> {
1051 Box::new(Self {
1052 global: self.global.clone(),
1053 task_source: self.task_source.clone(),
1054 })
1055 }
1056}
1057
1058#[derive(Debug, MallocSizeOf)]
1059struct FontNetworkTimingHandler {
1060 global: Trusted<GlobalScope>,
1061 task_source: SendableTaskSource,
1062}
1063
1064impl NetworkTimingHandler for FontNetworkTimingHandler {
1065 fn submit_timing(&self, url: ServoUrl, response: ResourceFetchTiming) {
1066 let global = self.global.clone();
1067 self.task_source.queue(task!(network_timing: move |cx| {
1068 submit_timing(
1069 cx,
1070 &FontFetchListener {
1071 url,
1072 global
1073 },
1074 &Ok(()),
1075 &response,
1076 );
1077 }));
1078 }
1079
1080 fn clone(&self) -> Box<dyn NetworkTimingHandler> {
1081 Box::new(Self {
1082 global: self.global.clone(),
1083 task_source: self.task_source.clone(),
1084 })
1085 }
1086}
1087
1088#[derive(Debug)]
1089struct FontFetchListener {
1090 global: Trusted<GlobalScope>,
1091 url: ServoUrl,
1092}
1093
1094impl ResourceTimingListener for FontFetchListener {
1095 fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
1096 (InitiatorType::Css, self.url.clone())
1097 }
1098
1099 fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
1100 self.global.root()
1101 }
1102}
1103
1104pub(crate) fn base64_btoa(input: DOMString) -> Fallible<DOMString> {
1106 if input.str().chars().any(|c: char| c > '\u{FF}') {
1110 Err(Error::InvalidCharacter(None))
1111 } else {
1112 let octets = input
1117 .str()
1118 .chars()
1119 .map(|c: char| c as u8)
1120 .collect::<Vec<u8>>();
1121
1122 let config =
1125 base64::engine::general_purpose::GeneralPurposeConfig::new().with_encode_padding(true);
1126 let engine = base64::engine::GeneralPurpose::new(&base64::alphabet::STANDARD, config);
1127 Ok(DOMString::from(engine.encode(octets)))
1128 }
1129}
1130
1131pub(crate) fn base64_atob(input: DOMString) -> Fallible<DOMString> {
1133 fn is_html_space(c: char) -> bool {
1135 HTML_SPACE_CHARACTERS.contains(&c)
1136 }
1137 let without_spaces = input
1138 .str()
1139 .chars()
1140 .filter(|&c| !is_html_space(c))
1141 .collect::<String>();
1142 let mut input = &*without_spaces;
1143
1144 if input.len() % 4 == 0 {
1148 if input.ends_with("==") {
1149 input = &input[..input.len() - 2]
1150 } else if input.ends_with('=') {
1151 input = &input[..input.len() - 1]
1152 }
1153 }
1154
1155 if input.len() % 4 == 1 {
1158 return Err(Error::InvalidCharacter(None));
1159 }
1160
1161 if input
1169 .chars()
1170 .any(|c| c != '+' && c != '/' && !c.is_alphanumeric())
1171 {
1172 return Err(Error::InvalidCharacter(None));
1173 }
1174
1175 let config = base64::engine::general_purpose::GeneralPurposeConfig::new()
1176 .with_decode_padding_mode(base64::engine::DecodePaddingMode::RequireNone)
1177 .with_decode_allow_trailing_bits(true);
1178 let engine = base64::engine::GeneralPurpose::new(&base64::alphabet::STANDARD, config);
1179
1180 let data = engine
1181 .decode(input)
1182 .map_err(|_| Error::InvalidCharacter(None))?;
1183 Ok(data.iter().map(|&b| b as char).collect::<String>().into())
1184}
1185
1186impl WindowMethods<crate::DomTypeHolder> for Window {
1187 fn Alert_(&self) {
1189 self.Alert(DOMString::new());
1192 }
1193
1194 fn Alert(&self, mut message: DOMString) {
1196 if self.cannot_show_simple_dialogs() {
1198 return;
1199 }
1200
1201 message.normalize_newlines();
1205
1206 {
1217 let stderr = stderr();
1221 let mut stderr = stderr.lock();
1222 let stdout = stdout();
1223 let mut stdout = stdout.lock();
1224 writeln!(&mut stdout, "\nALERT: {message}").unwrap();
1225 stdout.flush().unwrap();
1226 stderr.flush().unwrap();
1227 }
1228
1229 let (sender, receiver) =
1230 ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1231 let dialog = SimpleDialogRequest::Alert {
1232 id: self.Document().embedder_controls().next_control_id(),
1233 message: String::from(message),
1234 response_sender: sender,
1235 };
1236 self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1237 receiver.recv().unwrap_or_else(|_| {
1238 debug!("Alert dialog was cancelled or failed to show.");
1240 AlertResponse::Ok
1241 });
1242
1243 }
1246
1247 fn Caches(&self, cx: &mut JSContext) -> DomRoot<CacheStorage> {
1249 self.caches
1250 .or_init(|| CacheStorage::new(cx, self.as_global_scope()))
1251 }
1252
1253 fn Confirm(&self, mut message: DOMString) -> bool {
1255 if self.cannot_show_simple_dialogs() {
1257 return false;
1258 }
1259
1260 message.normalize_newlines();
1262
1263 let (sender, receiver) =
1269 ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1270 let dialog = SimpleDialogRequest::Confirm {
1271 id: self.Document().embedder_controls().next_control_id(),
1272 message: String::from(message),
1273 response_sender: sender,
1274 };
1275 self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1276
1277 match receiver.recv() {
1293 Ok(ConfirmResponse::Ok) => true,
1294 Ok(ConfirmResponse::Cancel) => false,
1295 Err(_) => {
1296 warn!("Confirm dialog was cancelled or failed to show.");
1297 false
1298 },
1299 }
1300 }
1301
1302 fn Prompt(&self, mut message: DOMString, default: DOMString) -> Option<DOMString> {
1304 if self.cannot_show_simple_dialogs() {
1306 return None;
1307 }
1308
1309 message.normalize_newlines();
1311
1312 let (sender, receiver) =
1320 ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1321 let dialog = SimpleDialogRequest::Prompt {
1322 id: self.Document().embedder_controls().next_control_id(),
1323 message: String::from(message),
1324 default: String::from(default),
1325 response_sender: sender,
1326 };
1327 self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1328
1329 match receiver.recv() {
1348 Ok(PromptResponse::Ok(input)) => Some(input.into()),
1349 Ok(PromptResponse::Cancel) => None,
1350 Err(_) => {
1351 warn!("Prompt dialog was cancelled or failed to show.");
1352 None
1353 },
1354 }
1355 }
1356
1357 fn Stop(&self, cx: &mut JSContext) {
1359 self.stop_loading(cx);
1364 }
1365
1366 fn Focus(&self, cx: &mut JSContext) {
1368 let document = self.Document();
1376 if !document.is_active() {
1377 return;
1378 }
1379
1380 document.focus_handler().focus(cx, &FocusableArea::Viewport);
1385
1386 }
1391
1392 fn Blur(&self) {
1394 }
1397
1398 fn Open(
1400 &self,
1401 cx: &mut JSContext,
1402 url: USVString,
1403 target: DOMString,
1404 features: DOMString,
1405 ) -> Fallible<Option<DomRoot<WindowProxy>>> {
1406 self.window_proxy().open(cx, url, target, features)
1407 }
1408
1409 fn GetOpener(&self, cx: &mut CurrentRealm, mut retval: MutableHandleValue) -> Fallible<()> {
1411 let current = match self.window_proxy.get() {
1413 Some(proxy) => proxy,
1414 None => {
1416 retval.set(NullValue());
1417 return Ok(());
1418 },
1419 };
1420 if current.is_browsing_context_discarded() {
1425 retval.set(NullValue());
1426 return Ok(());
1427 }
1428 current.opener(cx, retval);
1430 Ok(())
1431 }
1432
1433 #[expect(unsafe_code)]
1434 fn SetOpener(&self, cx: &mut JSContext, value: HandleValue) -> ErrorResult {
1436 if value.is_null() {
1438 if let Some(proxy) = self.window_proxy.get() {
1439 proxy.disown();
1440 }
1441 return Ok(());
1442 }
1443
1444 let obj = self.reflector().get_jsobject();
1446 let result = unsafe {
1447 JS_DefineProperty(cx, obj, c"opener".as_ptr(), value, JSPROP_ENUMERATE as u32)
1448 };
1449
1450 if result { Ok(()) } else { Err(Error::JSFailed) }
1451 }
1452
1453 fn Closed(&self) -> bool {
1455 self.window_proxy
1456 .get()
1457 .map(|ref proxy| proxy.is_browsing_context_discarded() || proxy.is_closing())
1458 .unwrap_or(true)
1459 }
1460
1461 fn Close(&self, cx: &mut JSContext) {
1463 let window_proxy = match self.window_proxy.get() {
1465 Some(proxy) => proxy,
1466 None => return,
1468 };
1469 if window_proxy.is_closing() {
1471 return;
1472 }
1473 if let Ok(history_length) = self.History(cx).GetLength() {
1476 let is_auxiliary = window_proxy.is_auxiliary();
1477
1478 let is_script_closable = (self.is_top_level() && history_length == 1) ||
1480 is_auxiliary ||
1481 pref!(dom_allow_scripts_to_close_windows);
1482
1483 if is_script_closable {
1487 window_proxy.close();
1489
1490 let this = Trusted::new(self);
1492 let task = task!(window_close_browsing_context: move |cx| {
1493 let window = this.root();
1494 window.definitely_close(cx);
1495 });
1496 self.as_global_scope()
1497 .task_manager()
1498 .dom_manipulation_task_source()
1499 .queue(task);
1500 }
1501 }
1502 }
1503
1504 fn Document(&self) -> DomRoot<Document> {
1506 self.document
1507 .get()
1508 .expect("Document accessed before initialization.")
1509 }
1510
1511 fn History(&self, cx: &mut JSContext) -> DomRoot<History> {
1513 self.Document().history(cx)
1514 }
1515
1516 fn IndexedDB(&self, cx: &mut JSContext) -> DomRoot<IDBFactory> {
1518 self.upcast::<GlobalScope>().ensure_indexeddb_factory(cx)
1519 }
1520
1521 fn CustomElements(&self, cx: &mut JSContext) -> DomRoot<CustomElementRegistry> {
1523 let document = self.Document();
1526 if let Some(registry) = document.custom_element_registry() {
1527 return registry;
1528 }
1529 let registry = CustomElementRegistry::new(cx, self);
1532 document.set_custom_element_registry(®istry);
1533 registry
1535 }
1536
1537 fn Location(&self, cx: &mut JSContext) -> DomRoot<Location> {
1539 self.location.or_init(|| Location::new(cx, self))
1540 }
1541
1542 fn GetSessionStorage(&self, cx: &mut JSContext) -> Fallible<DomRoot<Storage>> {
1544 if let Some(storage) = self.session_storage.get() {
1547 return Ok(storage);
1548 }
1549
1550 if !self.origin().is_tuple() {
1554 return Err(Error::Security(Some(
1555 "Cannot access sessionStorage from opaque origin.".to_string(),
1556 )));
1557 }
1558
1559 let storage = Storage::new(cx, self, WebStorageType::Session);
1561
1562 self.session_storage.set(Some(&storage));
1564
1565 Ok(storage)
1567 }
1568
1569 fn GetLocalStorage(&self, cx: &mut JSContext) -> Fallible<DomRoot<Storage>> {
1571 if let Some(storage) = self.local_storage.get() {
1574 return Ok(storage);
1575 }
1576
1577 if !self.origin().is_tuple() {
1581 return Err(Error::Security(Some(
1582 "Cannot access localStorage from opaque origin.".to_string(),
1583 )));
1584 }
1585
1586 let storage = Storage::new(cx, self, WebStorageType::Local);
1588
1589 self.local_storage.set(Some(&storage));
1591
1592 Ok(storage)
1594 }
1595
1596 fn CookieStore(&self, cx: &mut JSContext) -> DomRoot<CookieStore> {
1598 self.cookie_store
1599 .or_init(|| CookieStore::new(cx, self.upcast::<GlobalScope>()))
1600 }
1601
1602 #[cfg(feature = "webcrypto")]
1604 fn Crypto(&self, cx: &mut JSContext) -> DomRoot<crate::dom::crypto::Crypto> {
1605 self.crypto
1606 .or_init(|| crate::dom::crypto::Crypto::new(cx, self.as_global_scope()))
1607 }
1608
1609 fn GetFrameElement(&self) -> Option<DomRoot<Element>> {
1611 let window_proxy = self.window_proxy.get()?;
1613
1614 let container = window_proxy.frame_element()?;
1616
1617 let container_doc = container.owner_document();
1619 let current_doc = GlobalScope::current()
1620 .expect("No current global object")
1621 .as_window()
1622 .Document();
1623 if !current_doc
1624 .origin()
1625 .same_origin_domain(&container_doc.origin())
1626 {
1627 return None;
1628 }
1629 Some(DomRoot::from_ref(container))
1631 }
1632
1633 fn ReportError(&self, cx: &mut JSContext, error: HandleValue) {
1635 self.as_global_scope().report_an_exception(cx, error);
1636 }
1637
1638 fn Navigator(&self, cx: &mut JSContext) -> DomRoot<Navigator> {
1640 self.navigator.or_init(|| Navigator::new(cx, self))
1641 }
1642
1643 fn ClientInformation(&self, cx: &mut JSContext) -> DomRoot<Navigator> {
1645 self.Navigator(cx)
1646 }
1647
1648 fn SetTimeout(
1650 &self,
1651 cx: &mut JSContext,
1652 callback: TrustedScriptOrStringOrFunction,
1653 timeout: i32,
1654 args: Vec<HandleValue>,
1655 ) -> Fallible<i32> {
1656 let callback = match callback {
1657 TrustedScriptOrStringOrFunction::String(i) => {
1658 TimerCallback::StringTimerCallback(TrustedScriptOrString::String(i))
1659 },
1660 TrustedScriptOrStringOrFunction::TrustedScript(i) => {
1661 TimerCallback::StringTimerCallback(TrustedScriptOrString::TrustedScript(i))
1662 },
1663 TrustedScriptOrStringOrFunction::Function(i) => TimerCallback::FunctionTimerCallback(i),
1664 };
1665 self.as_global_scope().set_timeout_or_interval(
1666 cx,
1667 callback,
1668 args,
1669 Duration::from_millis(timeout.max(0) as u64),
1670 IsInterval::NonInterval,
1671 )
1672 }
1673
1674 fn ClearTimeout(&self, handle: i32) {
1676 self.as_global_scope().clear_timeout_or_interval(handle);
1677 }
1678
1679 fn SetInterval(
1681 &self,
1682 cx: &mut JSContext,
1683 callback: TrustedScriptOrStringOrFunction,
1684 timeout: i32,
1685 args: Vec<HandleValue>,
1686 ) -> Fallible<i32> {
1687 let callback = match callback {
1688 TrustedScriptOrStringOrFunction::String(i) => {
1689 TimerCallback::StringTimerCallback(TrustedScriptOrString::String(i))
1690 },
1691 TrustedScriptOrStringOrFunction::TrustedScript(i) => {
1692 TimerCallback::StringTimerCallback(TrustedScriptOrString::TrustedScript(i))
1693 },
1694 TrustedScriptOrStringOrFunction::Function(i) => TimerCallback::FunctionTimerCallback(i),
1695 };
1696 self.as_global_scope().set_timeout_or_interval(
1697 cx,
1698 callback,
1699 args,
1700 Duration::from_millis(timeout.max(0) as u64),
1701 IsInterval::Interval,
1702 )
1703 }
1704
1705 fn ClearInterval(&self, handle: i32) {
1707 self.ClearTimeout(handle);
1708 }
1709
1710 fn QueueMicrotask(&self, cx: &JSContext, callback: Rc<VoidFunction>) {
1712 ScriptThread::enqueue_microtask(
1713 cx,
1714 Box::new(UserMicrotask {
1715 callback,
1716 global: Dom::from_ref(&self.globalscope),
1717 }),
1718 );
1719 }
1720
1721 fn CreateImageBitmap(
1723 &self,
1724 realm: &mut CurrentRealm,
1725 image: ImageBitmapSource,
1726 options: &ImageBitmapOptions,
1727 ) -> RootedPromise {
1728 ImageBitmap::create_image_bitmap(
1729 self.as_global_scope(),
1730 image,
1731 0,
1732 0,
1733 None,
1734 None,
1735 options,
1736 realm,
1737 )
1738 }
1739
1740 fn CreateImageBitmap_(
1742 &self,
1743 realm: &mut CurrentRealm,
1744 image: ImageBitmapSource,
1745 sx: i32,
1746 sy: i32,
1747 sw: i32,
1748 sh: i32,
1749 options: &ImageBitmapOptions,
1750 ) -> RootedPromise {
1751 ImageBitmap::create_image_bitmap(
1752 self.as_global_scope(),
1753 image,
1754 sx,
1755 sy,
1756 Some(sw),
1757 Some(sh),
1758 options,
1759 realm,
1760 )
1761 }
1762
1763 fn Window(&self) -> DomRoot<WindowProxy> {
1765 self.window_proxy()
1766 }
1767
1768 fn Self_(&self) -> DomRoot<WindowProxy> {
1770 self.window_proxy()
1771 }
1772
1773 fn Frames(&self) -> DomRoot<WindowProxy> {
1775 self.window_proxy()
1776 }
1777
1778 fn Length(&self) -> u32 {
1780 self.Document().iframes().iter().count() as u32
1781 }
1782
1783 fn GetParent(&self) -> Option<DomRoot<WindowProxy>> {
1785 let window_proxy = self.undiscarded_window_proxy()?;
1787
1788 if let Some(parent) = window_proxy.parent() {
1790 return Some(DomRoot::from_ref(parent));
1791 }
1792 Some(window_proxy)
1794 }
1795
1796 fn GetTop(&self) -> Option<DomRoot<WindowProxy>> {
1798 let window_proxy = self.undiscarded_window_proxy()?;
1800
1801 Some(DomRoot::from_ref(window_proxy.top()))
1803 }
1804
1805 fn Performance(&self, cx: &mut JSContext) -> DomRoot<Performance> {
1808 self.performance
1809 .or_init(|| Performance::new(cx, self.as_global_scope(), self.navigation_start.get()))
1810 }
1811
1812 global_event_handlers!();
1814
1815 window_event_handlers!();
1817
1818 fn Screen(&self, cx: &mut JSContext) -> DomRoot<Screen> {
1820 self.screen.or_init(|| Screen::new(cx, self))
1821 }
1822
1823 fn GetVisualViewport(&self, cx: &mut JSContext) -> Option<DomRoot<VisualViewport>> {
1825 if !self.Document().is_fully_active() {
1829 return None;
1830 }
1831
1832 Some(self.get_or_init_visual_viewport(cx))
1833 }
1834
1835 fn Btoa(&self, btoa: DOMString) -> Fallible<DOMString> {
1837 base64_btoa(btoa)
1838 }
1839
1840 fn Atob(&self, atob: DOMString) -> Fallible<DOMString> {
1842 base64_atob(atob)
1843 }
1844
1845 fn RequestAnimationFrame(&self, callback: Rc<FrameRequestCallback>) -> Fallible<u32> {
1847 Ok(self
1848 .Document()
1849 .request_animation_frame(AnimationFrameCallback::FrameRequestCallback { callback }))
1850 }
1851
1852 fn CancelAnimationFrame(&self, ident: u32) -> ErrorResult {
1854 let doc = self.Document();
1855 doc.cancel_animation_frame(ident);
1856 Ok(())
1857 }
1858
1859 fn PostMessage(
1861 &self,
1862 cx: &mut JSContext,
1863 message: HandleValue,
1864 target_origin: USVString,
1865 transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
1866 ) -> ErrorResult {
1867 let incumbent = GlobalScope::incumbent().expect("no incumbent global?");
1868 let source = incumbent.as_window();
1869 let source_origin = source.Document().origin().immutable().clone();
1870
1871 self.post_message_impl(&target_origin, source_origin, source, cx, message, transfer)
1872 }
1873
1874 fn PostMessage_(
1876 &self,
1877 cx: &mut JSContext,
1878 message: HandleValue,
1879 options: RootedTraceableBox<WindowPostMessageOptions>,
1880 ) -> ErrorResult {
1881 auto_root!(&in(cx) let transfer =
1882 options
1883 .parent
1884 .transfer
1885 .iter()
1886 .map(|js: &RootedTraceableBox<Heap<*mut JSObject>>| js.get())
1887 .collect::<Vec<_>>());
1888
1889 let incumbent = GlobalScope::incumbent().expect("no incumbent global?");
1890 let source = incumbent.as_window();
1891
1892 let source_origin = source.Document().origin().immutable().clone();
1893
1894 self.post_message_impl(
1895 &options.targetOrigin,
1896 source_origin,
1897 source,
1898 cx,
1899 message,
1900 transfer,
1901 )
1902 }
1903
1904 fn CaptureEvents(&self) {
1906 }
1908
1909 fn ReleaseEvents(&self) {
1911 }
1913
1914 fn WebdriverElement(&self, id: DOMString) -> Option<DomRoot<Element>> {
1915 find_node_by_unique_id_in_document(&self.Document(), id.into()).and_then(Root::downcast)
1916 }
1917
1918 fn WebdriverFrame(&self, browsing_context_id: DOMString) -> Option<DomRoot<WindowProxy>> {
1919 self.Document()
1920 .iframes()
1921 .iter()
1922 .find(|iframe| {
1923 iframe
1924 .browsing_context_id()
1925 .as_ref()
1926 .map(BrowsingContextId::to_string) ==
1927 Some(browsing_context_id.to_string())
1928 })
1929 .and_then(|iframe| iframe.GetContentWindow())
1930 }
1931
1932 fn WebdriverWindow(&self, webview_id: DOMString) -> DomRoot<WindowProxy> {
1933 let window_proxy = &self
1934 .window_proxy
1935 .get()
1936 .expect("Should always have a WindowProxy when calling WebdriverWindow");
1937 assert!(
1938 self.is_top_level(),
1939 "Window must be top level browsing context."
1940 );
1941 assert!(self.webview_id().to_string() == webview_id);
1942 DomRoot::from_ref(window_proxy)
1943 }
1944
1945 fn WebdriverShadowRoot(&self, id: DOMString) -> Option<DomRoot<ShadowRoot>> {
1946 find_node_by_unique_id_in_document(&self.Document(), id.into()).and_then(Root::downcast)
1947 }
1948
1949 fn GetComputedStyle(
1951 &self,
1952 cx: &mut JSContext,
1953 element: &Element,
1954 pseudo: Option<DOMString>,
1955 ) -> DomRoot<CSSStyleDeclaration> {
1956 let mut is_null = false;
1960
1961 let pseudo = pseudo.map(|mut s| {
1967 s.make_ascii_lowercase();
1968 s
1969 });
1970 let pseudo = match pseudo {
1971 Some(ref pseudo) if pseudo == ":before" || pseudo == "::before" => {
1972 Some(PseudoElement::Before)
1973 },
1974 Some(ref pseudo) if pseudo == ":after" || pseudo == "::after" => {
1975 Some(PseudoElement::After)
1976 },
1977 Some(ref pseudo) if pseudo == "::selection" => Some(PseudoElement::Selection),
1978 Some(ref pseudo) if pseudo == "::marker" => Some(PseudoElement::Marker),
1979 Some(ref pseudo) if pseudo == "::placeholder" => Some(PseudoElement::Placeholder),
1980 Some(ref pseudo) if pseudo.starts_with(':') => {
1981 is_null = true;
1984 None
1985 },
1986 _ => None,
1987 };
1988
1989 CSSStyleDeclaration::new(
2005 cx,
2006 self,
2007 if is_null {
2008 CSSStyleOwner::Null
2009 } else {
2010 CSSStyleOwner::Element(Dom::from_ref(element))
2011 },
2012 pseudo,
2013 CSSModificationAccess::Readonly,
2014 )
2015 }
2016
2017 fn InnerHeight(&self) -> i32 {
2020 self.viewport_details
2021 .get()
2022 .size
2023 .height
2024 .to_i32()
2025 .unwrap_or(0)
2026 }
2027
2028 fn InnerWidth(&self) -> i32 {
2031 self.viewport_details.get().size.width.to_i32().unwrap_or(0)
2032 }
2033
2034 fn ScrollX(&self) -> i32 {
2036 self.scroll_offset().x as i32
2037 }
2038
2039 fn PageXOffset(&self) -> i32 {
2041 self.ScrollX()
2042 }
2043
2044 fn ScrollY(&self) -> i32 {
2046 self.scroll_offset().y as i32
2047 }
2048
2049 fn PageYOffset(&self) -> i32 {
2051 self.ScrollY()
2052 }
2053
2054 fn Scroll(&self, cx: &mut JSContext, options: &ScrollToOptions) {
2056 let x = options.left.unwrap_or(0.0) as f32;
2061
2062 let y = options.top.unwrap_or(0.0) as f32;
2065
2066 self.scroll(cx, x, y, options.parent.behavior);
2068 }
2069
2070 fn Scroll_(&self, cx: &mut JSContext, x: f64, y: f64) {
2072 self.scroll(cx, x as f32, y as f32, ScrollBehavior::Auto);
2076 }
2077
2078 fn ScrollTo(&self, cx: &mut JSContext, options: &ScrollToOptions) {
2083 self.Scroll(cx, options);
2084 }
2085
2086 fn ScrollTo_(&self, cx: &mut JSContext, x: f64, y: f64) {
2091 self.Scroll_(cx, x, y)
2092 }
2093
2094 fn ScrollBy(&self, cx: &mut JSContext, options: &ScrollToOptions) {
2096 let mut options = options.clone();
2102 let x = options.left.unwrap_or(0.0);
2103 let x = if x.is_finite() { x } else { 0.0 };
2104 let y = options.top.unwrap_or(0.0);
2105 let y = if y.is_finite() { y } else { 0.0 };
2106
2107 options.left.replace(x + self.ScrollX() as f64);
2109
2110 options.top.replace(y + self.ScrollY() as f64);
2112
2113 self.Scroll(cx, &options)
2115 }
2116
2117 fn ScrollBy_(&self, cx: &mut JSContext, x: f64, y: f64) {
2119 let mut options = ScrollToOptions::empty();
2123
2124 options.left.replace(x);
2127
2128 options.top.replace(y);
2130
2131 self.ScrollBy(cx, &options);
2133 }
2134
2135 fn ResizeTo(&self, width: i32, height: i32) {
2137 let window_proxy = match self.window_proxy.get() {
2139 Some(proxy) => proxy,
2140 None => return,
2141 };
2142
2143 if !window_proxy.is_auxiliary() {
2146 return;
2147 }
2148
2149 let dpr = self.device_pixel_ratio();
2150 let size = Size2D::new(width, height).to_f32() * dpr;
2151 self.send_to_embedder(EmbedderMsg::ResizeTo(self.webview_id(), size.to_i32()));
2152 }
2153
2154 fn ResizeBy(&self, x: i32, y: i32) {
2156 let size = self.client_window().size();
2157 self.ResizeTo(x + size.width, y + size.height)
2159 }
2160
2161 fn MoveTo(&self, x: i32, y: i32) {
2163 let dpr = self.device_pixel_ratio();
2166 let point = Point2D::new(x, y).to_f32() * dpr;
2167 let msg = EmbedderMsg::MoveTo(self.webview_id(), point.to_i32());
2168 self.send_to_embedder(msg);
2169 }
2170
2171 fn MoveBy(&self, x: i32, y: i32) {
2173 let origin = self.client_window().min;
2174 self.MoveTo(x + origin.x, y + origin.y)
2176 }
2177
2178 fn ScreenX(&self) -> i32 {
2180 self.client_window().min.x
2181 }
2182
2183 fn ScreenLeft(&self) -> i32 {
2185 self.client_window().min.x
2186 }
2187
2188 fn ScreenY(&self) -> i32 {
2190 self.client_window().min.y
2191 }
2192
2193 fn ScreenTop(&self) -> i32 {
2195 self.client_window().min.y
2196 }
2197
2198 fn OuterHeight(&self) -> i32 {
2200 self.client_window().height()
2201 }
2202
2203 fn OuterWidth(&self) -> i32 {
2205 self.client_window().width()
2206 }
2207
2208 fn DevicePixelRatio(&self) -> Finite<f64> {
2210 Finite::wrap(self.device_pixel_ratio().get() as f64)
2211 }
2212
2213 fn Status(&self) -> DOMString {
2215 self.status.borrow().clone()
2216 }
2217
2218 fn SetStatus(&self, status: DOMString) {
2220 *self.status.borrow_mut() = status
2221 }
2222
2223 fn MatchMedia(&self, cx: &mut JSContext, query: DOMString) -> DomRoot<MediaQueryList> {
2225 let media_query_list = MediaList::parse_media_list(&query.str(), self);
2226 let document = self.Document();
2227 let mql = MediaQueryList::new(cx, &document, media_query_list);
2228 self.media_query_lists.track(&*mql);
2229 mql
2230 }
2231
2232 fn Fetch(
2234 &self,
2235 realm: &mut CurrentRealm,
2236 input: RequestOrUSVString,
2237 init: RootedTraceableBox<RequestInit>,
2238 ) -> RootedPromise {
2239 fetch::Fetch(self.upcast(), input, init, realm)
2240 }
2241
2242 fn FetchLater(
2244 &self,
2245 cx: &mut JSContext,
2246 input: RequestInfo,
2247 init: RootedTraceableBox<DeferredRequestInit>,
2248 ) -> Fallible<DomRoot<FetchLaterResult>> {
2249 fetch::FetchLater(cx, self, input, init)
2250 }
2251
2252 #[cfg(feature = "bluetooth")]
2253 fn TestRunner(&self, cx: &mut JSContext) -> DomRoot<TestRunner> {
2254 self.test_runner
2255 .or_init(|| TestRunner::new(cx, self.upcast()))
2256 }
2257
2258 fn RunningAnimationCount(&self) -> u32 {
2259 self.document.get().map_or(0, |document| {
2260 document.animation_manager().running_animation_count() as u32
2261 })
2262 }
2263
2264 fn SetName(&self, name: DOMString) {
2266 if let Some(proxy) = self.undiscarded_window_proxy() {
2267 proxy.set_name(name);
2268 }
2269 }
2270
2271 fn Name(&self) -> DOMString {
2273 match self.undiscarded_window_proxy() {
2274 Some(proxy) => proxy.get_name(),
2275 None => DOMString::new(),
2276 }
2277 }
2278
2279 fn Origin(&self) -> USVString {
2281 USVString(self.origin().immutable().ascii_serialization().into_owned())
2282 }
2283
2284 fn GetSelection(&self, cx: &mut JSContext) -> Option<DomRoot<Selection>> {
2286 self.document.get().and_then(|d| d.GetSelection(cx))
2287 }
2288
2289 fn Event(&self, cx: &mut JSContext, rval: MutableHandleValue) {
2291 if let Some(ref event) = *self.current_event.borrow() {
2292 event.reflector().get_jsobject().to_jsval(cx, rval);
2293 }
2294 }
2295
2296 fn IsSecureContext(&self) -> bool {
2297 self.as_global_scope().is_secure_context()
2298 }
2299
2300 fn NamedGetter(&self, cx: &mut JSContext, name: DOMString) -> Option<NamedPropertyValue> {
2302 if name.is_empty() {
2303 return None;
2304 }
2305 let document = self.Document();
2306
2307 let iframes: Vec<_> = document
2309 .iframes()
2310 .iter()
2311 .filter(|iframe| {
2312 if let Some(window) = iframe.GetContentWindow() {
2313 return window.get_name() == name;
2314 }
2315 false
2316 })
2317 .collect();
2318
2319 let iframe_iter = iframes.iter().map(|iframe| iframe.upcast::<Element>());
2320
2321 let name = Atom::from(name);
2322
2323 let elements_with_name = document.get_elements_with_name(cx, &name);
2325 let name_iter = elements_with_name
2326 .iter()
2327 .map(|element| &**element)
2328 .filter(|elem| is_named_element_with_name_attribute(elem));
2329
2330 let elements_with_id = document.get_elements_with_id(cx, &name);
2331 let id_iter = elements_with_id
2332 .iter()
2333 .map(|element| &**element)
2334 .filter(|elem| is_named_element_with_id_attribute(elem));
2335
2336 for elem in iframe_iter.clone() {
2338 if let Some(nested_window_proxy) = elem
2339 .downcast::<HTMLIFrameElement>()
2340 .and_then(|iframe| iframe.GetContentWindow())
2341 {
2342 return Some(NamedPropertyValue::WindowProxy(nested_window_proxy));
2343 }
2344 }
2345
2346 let mut elements = iframe_iter.chain(name_iter).chain(id_iter);
2347
2348 let first = elements.next()?;
2349
2350 if elements.next().is_none() {
2351 return Some(NamedPropertyValue::Element(DomRoot::from_ref(first)));
2353 }
2354
2355 #[derive(JSTraceable, MallocSizeOf)]
2357 struct WindowNamedGetter {
2358 #[no_trace]
2359 name: Atom,
2360 }
2361 impl CollectionFilter for WindowNamedGetter {
2362 fn filter(&self, elem: &Element, _root: &Node) -> bool {
2363 let type_ = match elem.upcast::<Node>().type_id() {
2364 NodeTypeId::Element(ElementTypeId::HTMLElement(type_)) => type_,
2365 _ => return false,
2366 };
2367 if elem.get_id().as_ref() == Some(&self.name) {
2368 return true;
2369 }
2370 match type_ {
2371 HTMLElementTypeId::HTMLEmbedElement |
2372 HTMLElementTypeId::HTMLFormElement |
2373 HTMLElementTypeId::HTMLImageElement |
2374 HTMLElementTypeId::HTMLObjectElement => {
2375 elem.get_name().as_ref() == Some(&self.name)
2376 },
2377 _ => false,
2378 }
2379 }
2380 }
2381 let collection = HTMLCollection::create(
2382 cx,
2383 self,
2384 document.upcast(),
2385 Box::new(WindowNamedGetter { name }),
2386 );
2387 Some(NamedPropertyValue::HTMLCollection(collection))
2388 }
2389
2390 fn SupportedPropertyNames(&self, no_gc: &NoGC) -> Vec<DOMString> {
2392 self.Document().SupportedPropertyNames(no_gc)
2393 }
2394
2395 fn StructuredClone(
2397 &self,
2398 cx: &mut JSContext,
2399 value: HandleValue,
2400 options: RootedTraceableBox<StructuredSerializeOptions>,
2401 retval: MutableHandleValue,
2402 ) -> Fallible<()> {
2403 self.as_global_scope()
2404 .structured_clone(cx, value, options, retval)
2405 }
2406
2407 fn TrustedTypes(&self, cx: &mut JSContext) -> DomRoot<TrustedTypePolicyFactory> {
2408 self.trusted_types
2409 .or_init(|| TrustedTypePolicyFactory::new(cx, self.as_global_scope()))
2410 }
2411}
2412
2413impl Window {
2414 pub(crate) fn scroll_offset(&self) -> Vector2D<f32, LayoutPixel> {
2415 self.scroll_offset_query_with_external_scroll_id(self.pipeline_id().root_scroll_id())
2416 }
2417
2418 pub(crate) fn create_named_properties_object(
2421 cx: &mut JSContext,
2422 proto: HandleObject,
2423 object: MutableHandleObject,
2424 ) {
2425 window_named_properties::create(cx, proto, object)
2426 }
2427
2428 pub(crate) fn current_event(&self) -> Option<DomRoot<Event>> {
2429 self.current_event
2430 .borrow()
2431 .as_ref()
2432 .map(|e| DomRoot::from_ref(&**e))
2433 }
2434
2435 pub(crate) fn set_current_event(&self, event: Option<&Event>) -> Option<DomRoot<Event>> {
2436 let current = self.current_event();
2437 *self.current_event.borrow_mut() = event.map(Dom::from_ref);
2438 current
2439 }
2440
2441 fn post_message_impl(
2443 &self,
2444 target_origin: &USVString,
2445 source_origin: ImmutableOrigin,
2446 source: &Window,
2447 cx: &mut JSContext,
2448 message: HandleValue,
2449 transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
2450 ) -> ErrorResult {
2451 let data = structuredclone::write(cx, message, Some(transfer))?;
2453
2454 let target_origin = match target_origin.0[..].as_ref() {
2456 "*" => None,
2457 "/" => Some(source_origin.clone()),
2458 url => match ServoUrl::parse(url) {
2459 Ok(url) => Some(url.origin()),
2460 Err(_) => return Err(Error::Syntax(None)),
2461 },
2462 };
2463
2464 self.post_message(target_origin, source_origin, &source.window_proxy(), data);
2466 Ok(())
2467 }
2468
2469 pub(crate) fn paint_worklet(&self, cx: &mut JSContext) -> DomRoot<Worklet> {
2471 self.paint_worklet.or_init(|| self.new_paint_worklet(cx))
2472 }
2473
2474 pub(crate) fn clear_js_runtime(&self) {
2475 self.as_global_scope()
2476 .remove_web_messaging_and_dedicated_workers_infra();
2477
2478 self.Document().teardown_custom_element_registry();
2481
2482 self.current_state.set(WindowState::Zombie);
2483 *self.js_runtime.borrow_mut() = None;
2484
2485 if let Some(performance) = self.performance.get() {
2486 performance.clear_and_disable_performance_entry_buffer();
2487 }
2488
2489 self.as_global_scope()
2490 .task_manager()
2491 .cancel_all_tasks_and_ignore_future_tasks();
2492
2493 if let Some(factory) = self.upcast::<GlobalScope>().indexeddb_factory() {
2498 factory.abort_pending_upgrades_and_close_databases();
2499 }
2500
2501 self.pending_image_callbacks.borrow_mut().clear();
2504 }
2505
2506 pub(crate) fn scroll(&self, cx: &mut JSContext, x: f32, y: f32, behavior: ScrollBehavior) {
2508 let xfinite = if x.is_finite() { x } else { 0.0 };
2510 let yfinite = if y.is_finite() { y } else { 0.0 };
2511
2512 let viewport = self.viewport_details.get().size;
2522
2523 let scrolling_area = self.scrolling_area_query(None).to_f32();
2542 let x = xfinite.clamp(0.0, 0.0f32.max(scrolling_area.width() - viewport.width));
2543 let y = yfinite.clamp(0.0, 0.0f32.max(scrolling_area.height() - viewport.height));
2544
2545 let scroll_offset = self.scroll_offset();
2548 if x == scroll_offset.x && y == scroll_offset.y {
2549 return;
2550 }
2551
2552 self.perform_a_scroll(
2557 cx,
2558 x,
2559 y,
2560 self.pipeline_id().root_scroll_id(),
2561 behavior,
2562 None,
2563 );
2564 }
2565
2566 pub(crate) fn perform_a_scroll(
2568 &self,
2569 cx: &mut JSContext,
2570 x: f32,
2571 y: f32,
2572 scroll_id: ExternalScrollId,
2573 _behavior: ScrollBehavior,
2574 element: Option<&Element>,
2575 ) {
2576 let (reflow_phases_run, _) = self.reflow(
2580 cx,
2581 ReflowGoal::UpdateScrollNode(scroll_id, Vector2D::new(x, y)),
2582 );
2583 if reflow_phases_run.needs_frame() {
2584 self.paint_api()
2585 .generate_frame(vec![self.webview_id().into()]);
2586 }
2587
2588 if reflow_phases_run.contains(ReflowPhasesRun::UpdatedScrollNodeOffset) {
2593 match element {
2594 Some(element) if !scroll_id.is_root() => element.handle_scroll_event(),
2595 _ => self.Document().handle_viewport_scroll_event(),
2596 };
2597 }
2598 }
2599
2600 pub(crate) fn device_pixel_ratio(&self) -> Scale<f32, CSSPixel, DevicePixel> {
2601 self.viewport_details.get().hidpi_scale_factor
2602 }
2603
2604 fn client_window(&self) -> DeviceIndependentIntRect {
2605 let (sender, receiver) = generic_channel::channel().expect("Failed to create IPC channel!");
2606
2607 self.send_to_embedder(EmbedderMsg::GetWindowRect(self.webview_id(), sender));
2608
2609 receiver.recv().unwrap_or_default()
2610 }
2611
2612 pub(crate) fn advance_animation_clock(&self, no_gc: &NoGC, delta: TimeDuration) {
2615 self.Document()
2616 .advance_animation_timeline_for_testing(delta);
2617 ScriptThread::handle_tick_all_animations_for_testing(no_gc, self.pipeline_id());
2618 }
2619
2620 pub(crate) fn reflow(
2628 &self,
2629 cx: &mut JSContext,
2630 reflow_goal: ReflowGoal,
2631 ) -> (ReflowPhasesRun, ReflowStatistics) {
2632 let document = self.Document();
2633
2634 if !document.is_fully_active() {
2636 return Default::default();
2637 }
2638
2639 self.document_unrooted(cx.no_gc())
2640 .ensure_safe_to_run_script_or_layout();
2641
2642 match reflow_goal {
2646 ReflowGoal::LayoutQuery(_) | ReflowGoal::UpdateScrollNode(..) => {
2647 self.flush_ancestor_layouts_if_necessary(cx);
2648 },
2649 ReflowGoal::UpdateTheRendering => { },
2650 }
2651
2652 let pipeline_id = self.pipeline_id();
2656 if reflow_goal == ReflowGoal::UpdateTheRendering &&
2657 self.layout_blocker.get().layout_blocked()
2658 {
2659 debug!("Suppressing pre-load-event reflow pipeline {pipeline_id}");
2660 return Default::default();
2661 }
2662
2663 debug!("script: performing reflow for goal {reflow_goal:?}");
2664 let marker = if self.need_emit_timeline_marker(TimelineMarkerType::Reflow) {
2665 Some(TimelineMarker::start("Reflow".to_owned()))
2666 } else {
2667 None
2668 };
2669
2670 if let Some(selection) = document.selection() {
2671 selection.update_overlaps_document_selection_flags(cx.no_gc());
2672 }
2673
2674 let restyle_reason = document.restyle_reason(cx.no_gc());
2675 document.clear_restyle_reasons();
2676 let restyle = if restyle_reason.needs_restyle() {
2677 debug!("Invalidating layout cache due to reflow condition {restyle_reason:?}",);
2678 self.layout_marker.borrow().set(false);
2680 *self.layout_marker.borrow_mut() = Rc::new(Cell::new(true));
2682
2683 if restyle_reason.contains(RestyleReason::ViewportChanged) &&
2687 self.layout().device().used_viewport_size()
2688 {
2689 document.dirty_all_nodes(cx.no_gc());
2690 }
2691
2692 let stylesheets_changed = document.flush_stylesheets_for_reflow();
2693 let pending_restyles = document.drain_pending_restyles(cx.no_gc());
2694 let dirty_root = document
2695 .take_dirty_root()
2696 .filter(|_| !stylesheets_changed)
2697 .or_else(|| document.GetDocumentElement())
2698 .map(|root| root.upcast::<Node>().to_trusted_node_address());
2699
2700 Some(ReflowRequestRestyle {
2701 reason: restyle_reason,
2702 dirty_root,
2703 stylesheets_changed,
2704 pending_restyles,
2705 })
2706 } else {
2707 None
2708 };
2709
2710 document.id_map().resolve_all(cx.no_gc(), document.upcast());
2713
2714 let document_context = self.web_font_context(cx.no_gc());
2715
2716 let mut rooted_nodes_for_accessibility_integrity_check = None;
2717 let mut accessibility_damage = None;
2718 if reflow_goal == ReflowGoal::UpdateTheRendering && self.layout().accessibility_active() {
2719 rooted_nodes_for_accessibility_integrity_check =
2720 document.rooted_nodes_for_accessibility_integrity_check();
2721 let mut accessibility_data = document.accessibility_data_mut();
2722 accessibility_damage = Some(accessibility_data.drain_pending_accessibility_damage());
2723 }
2724
2725 let reflow = ReflowRequest {
2727 document: document.upcast::<Node>().to_trusted_node_address(),
2728 epoch: document.current_rendering_epoch(),
2729 restyle,
2730 viewport_details: self.viewport_details.get(),
2731 origin: self.origin().immutable().clone(),
2732 reflow_goal,
2733 animation_timeline_value: document.current_animation_timeline_value(),
2734 animations: document.animation_manager().sets(),
2735 animating_images: document.animation_manager().animating_images(),
2736 highlighted_dom_node: document.highlighted_dom_node().map(|node| node.to_opaque()),
2737 halt_lcp: self.has_dispatched_scroll_event.get() ||
2738 self.has_dispatched_input_event.get(),
2739 paint_timing_eligible: document.paint_timing_eligible(),
2740 paint_timing_info: document.paint_timing_info(),
2741 document_context,
2742 accessibility_damage,
2743 rooted_nodes_for_accessibility_integrity_check,
2744 };
2745
2746 let Some(reflow_result) = self.layout.borrow_mut().reflow(reflow) else {
2747 return Default::default();
2748 };
2749
2750 debug!("script: layout complete");
2751 if let Some(marker) = marker {
2752 self.emit_timeline_marker(marker.end());
2753 }
2754
2755 self.handle_new_or_removed_web_fonts_post_reflow(cx, reflow_result.changed_web_fonts);
2756
2757 self.handle_pending_images_post_reflow(
2758 cx,
2759 reflow_result.pending_images,
2760 reflow_result.pending_rasterization_images,
2761 reflow_result.pending_svg_elements_for_serialization,
2762 );
2763
2764 if let Some(candidate) = reflow_result.lcp_candidate {
2765 self.process_lcp_candidate_post_reflow(candidate, &document);
2766 }
2767
2768 if let Some(iframe_sizes) = reflow_result.iframe_sizes {
2769 document
2770 .iframes_mut()
2771 .handle_new_iframe_sizes_after_layout(cx, self, iframe_sizes);
2772 }
2773
2774 document.update_animations_post_reflow();
2775
2776 (
2777 reflow_result.reflow_phases_run,
2778 reflow_result.reflow_statistics,
2779 )
2780 }
2781
2782 pub(crate) fn request_screenshot_readiness(&self, cx: &mut JSContext) {
2783 self.has_pending_screenshot_readiness_request.set(true);
2784 self.maybe_resolve_pending_screenshot_readiness_requests(cx);
2785 }
2786
2787 pub(crate) fn maybe_resolve_pending_screenshot_readiness_requests(&self, cx: &mut JSContext) {
2788 let pending_request = self.has_pending_screenshot_readiness_request.get();
2789 if !pending_request {
2790 return;
2791 }
2792
2793 let document = self.Document();
2794 if document.ReadyState() != DocumentReadyState::Complete {
2795 return;
2796 }
2797
2798 if document.render_blocking_element_count() > 0 {
2799 return;
2800 }
2801
2802 if document.GetDocumentElement().is_some_and(|elem| {
2806 elem.has_class(&atom!("reftest-wait"), CaseSensitivity::CaseSensitive) ||
2807 elem.has_class(&Atom::from("test-wait"), CaseSensitivity::CaseSensitive)
2808 }) {
2809 return;
2810 }
2811
2812 if self.font_context().web_fonts_still_loading() != 0 {
2813 return;
2814 }
2815
2816 if self.Document().Fonts(cx).waiting_to_fullfill_promise() {
2817 return;
2818 }
2819
2820 if !self.pending_layout_images.borrow().is_empty() ||
2821 !self.pending_images_for_rasterization.borrow().is_empty()
2822 {
2823 return;
2824 }
2825
2826 let document = self.Document();
2827 if document.needs_rendering_update(cx.no_gc()) {
2828 return;
2829 }
2830
2831 let epoch = document.current_rendering_epoch();
2834 let pipeline_id = self.pipeline_id();
2835 debug!("Ready to take screenshot of {pipeline_id:?} at epoch={epoch:?}");
2836
2837 self.send_to_constellation(
2838 ScriptToConstellationMessage::RespondToScreenshotReadinessRequest(
2839 ScreenshotReadinessResponse::Ready(epoch),
2840 ),
2841 );
2842 self.has_pending_screenshot_readiness_request.set(false);
2843 }
2844
2845 pub(crate) fn reflow_if_reflow_timer_expired(&self, cx: &mut JSContext) {
2848 if !matches!(
2851 self.layout_blocker.get(),
2852 LayoutBlocker::Parsing(instant) if instant + INITIAL_REFLOW_DELAY < Instant::now()
2853 ) {
2854 return;
2855 }
2856 self.allow_layout_if_necessary(cx);
2857 }
2858
2859 pub(crate) fn prevent_layout_until_load_event(&self) {
2863 if !matches!(self.layout_blocker.get(), LayoutBlocker::WaitingForParse) {
2866 return;
2867 }
2868
2869 self.layout_blocker
2870 .set(LayoutBlocker::Parsing(Instant::now()));
2871 }
2872
2873 pub(crate) fn allow_layout_if_necessary(&self, cx: &mut JSContext) {
2876 if matches!(
2877 self.layout_blocker.get(),
2878 LayoutBlocker::FiredLoadEventOrParsingTimerExpired
2879 ) {
2880 return;
2881 }
2882
2883 self.layout_blocker
2884 .set(LayoutBlocker::FiredLoadEventOrParsingTimerExpired);
2885
2886 let document = self.Document();
2898 if !document.is_render_blocked() && document.update_the_rendering(cx).0.needs_frame() {
2899 self.paint_api()
2900 .generate_frame(vec![self.webview_id().into()]);
2901 }
2902 }
2903
2904 pub(crate) fn layout_blocked(&self) -> bool {
2905 self.layout_blocker.get().layout_blocked()
2906 }
2907
2908 fn flush_ancestor_layouts_if_necessary(&self, cx: &mut JSContext) {
2909 let Some(parent_pipeline_id) = self.parent_info else {
2910 return;
2911 };
2912 let Some(parent_window) = ScriptThread::find_window(parent_pipeline_id) else {
2913 return;
2914 };
2915 if !parent_window.Document().is_safe_to_run_script_or_layout() {
2918 return;
2919 }
2920 if parent_window.Document().is_render_blocked() {
2923 return;
2924 }
2925 parent_window.flush_ancestor_layouts_if_necessary(cx);
2926 if parent_window
2927 .document_unrooted(cx.no_gc())
2928 .restyle_reason(cx.no_gc())
2929 .needs_restyle()
2930 {
2931 parent_window.reflow(
2932 cx,
2933 ReflowGoal::LayoutQuery(QueryMsg::FlushForUpdateTheRenderingQuery),
2934 );
2935 }
2936 }
2937
2938 #[expect(unsafe_code)]
2940 pub(crate) fn layout_reflow(&self, query_msg: QueryMsg) {
2941 let mut cx = unsafe { script_bindings::script_runtime::temp_cx() };
2943
2944 self.reflow(&mut cx, ReflowGoal::LayoutQuery(query_msg));
2945 }
2946
2947 pub(crate) fn reflow_for_non_flushing_update_the_rendering_queries(&self, cx: &mut JSContext) {
2949 self.reflow(
2950 cx,
2951 ReflowGoal::LayoutQuery(QueryMsg::FlushForUpdateTheRenderingQuery),
2952 );
2953 }
2954
2955 pub(crate) fn resolved_font_style_query(
2956 &self,
2957 node: &Node,
2958 value: String,
2959 ) -> Option<ServoArc<Font>> {
2960 self.layout_reflow(QueryMsg::ResolvedFontStyleQuery);
2961
2962 let document = self.Document();
2963 let animations = document.animation_manager().sets();
2964 self.layout.borrow().query_resolved_font_style(
2965 node.to_trusted_node_address(),
2966 &value,
2967 animations,
2968 document.current_animation_timeline_value(),
2969 )
2970 }
2971
2972 #[expect(unsafe_code)]
2975 pub(crate) fn containing_block_node_query_without_reflow(
2976 &self,
2977 node: &Node,
2978 ) -> Option<DomRoot<Node>> {
2979 self.layout
2980 .borrow()
2981 .query_containing_block(node.to_trusted_node_address())
2982 .map(|address| unsafe { from_untrusted_node_address(address) })
2983 }
2984
2985 pub(crate) fn is_containing_block_descendant_query_without_reflow(
2988 &self,
2989 possible_ancestor: &Node,
2990 possible_descendant: &Node,
2991 ) -> bool {
2992 self.layout.borrow().query_containing_block_is_descendant(
2993 possible_ancestor.to_trusted_node_address(),
2994 possible_descendant.to_trusted_node_address(),
2995 )
2996 }
2997
2998 pub(crate) fn padding_query_without_reflow(&self, node: &Node) -> Option<PhysicalSides> {
3003 let layout = self.layout.borrow();
3004 layout.query_padding(node.to_trusted_node_address())
3005 }
3006
3007 pub(crate) fn box_area_query_without_reflow(
3012 &self,
3013 node: &Node,
3014 area: BoxAreaType,
3015 exclude_transform_and_inline: bool,
3016 ) -> Option<Rect<Au, CSSPixel>> {
3017 let layout = self.layout.borrow();
3018 layout.ensure_stacking_context_tree(self.viewport_details.get());
3019 layout.query_box_area(
3020 node.to_trusted_node_address(),
3021 area,
3022 exclude_transform_and_inline,
3023 )
3024 }
3025
3026 pub(crate) fn box_area_query(
3027 &self,
3028 node: &Node,
3029 area: BoxAreaType,
3030 exclude_transform_and_inline: bool,
3031 ) -> Option<Rect<Au, CSSPixel>> {
3032 self.layout_reflow(QueryMsg::BoxArea);
3033 self.box_area_query_without_reflow(node, area, exclude_transform_and_inline)
3034 }
3035
3036 pub(crate) fn box_areas_query(&self, node: &Node, area: BoxAreaType) -> CSSPixelRectVec {
3037 self.layout_reflow(QueryMsg::BoxAreas);
3038 self.layout
3039 .borrow()
3040 .query_box_areas(node.to_trusted_node_address(), area)
3041 }
3042
3043 pub(crate) fn client_rect_query(&self, node: &Node) -> Rect<i32, CSSPixel> {
3044 self.layout_reflow(QueryMsg::ClientRectQuery);
3045 self.layout
3046 .borrow()
3047 .query_client_rect(node.to_trusted_node_address())
3048 }
3049
3050 pub(crate) fn current_css_zoom_query(&self, node: &Node) -> f32 {
3051 self.layout_reflow(QueryMsg::CurrentCSSZoomQuery);
3052 self.layout
3053 .borrow()
3054 .query_current_css_zoom(node.to_trusted_node_address())
3055 }
3056
3057 pub(crate) fn document_unrooted<'a>(&self, no_gc: &'a NoGC) -> UnrootedDom<'a, Document> {
3059 self.document
3060 .get_unrooted(no_gc)
3061 .expect("Document accessed before initialization.")
3062 }
3063
3064 pub(crate) fn scrolling_area_query(&self, node: Option<&Node>) -> Rect<i32, CSSPixel> {
3067 self.layout_reflow(QueryMsg::ScrollingAreaOrOffsetQuery);
3068 self.layout
3069 .borrow()
3070 .query_scrolling_area(node.map(Node::to_trusted_node_address))
3071 }
3072
3073 pub(crate) fn scroll_offset_query(&self, node: &Node) -> Vector2D<f32, LayoutPixel> {
3074 let external_scroll_id = ExternalScrollId(
3075 combine_id_with_fragment_type(node.to_opaque().id(), FragmentType::FragmentBody),
3076 self.pipeline_id().into(),
3077 );
3078 self.scroll_offset_query_with_external_scroll_id(external_scroll_id)
3079 }
3080
3081 fn scroll_offset_query_with_external_scroll_id(
3082 &self,
3083 external_scroll_id: ExternalScrollId,
3084 ) -> Vector2D<f32, LayoutPixel> {
3085 self.layout_reflow(QueryMsg::ScrollingAreaOrOffsetQuery);
3086 self.scroll_offset_query_with_external_scroll_id_no_reflow(external_scroll_id)
3087 }
3088
3089 fn scroll_offset_query_with_external_scroll_id_no_reflow(
3090 &self,
3091 external_scroll_id: ExternalScrollId,
3092 ) -> Vector2D<f32, LayoutPixel> {
3093 self.layout
3094 .borrow()
3095 .scroll_offset(external_scroll_id)
3096 .unwrap_or_default()
3097 }
3098
3099 pub(crate) fn scroll_an_element(
3102 &self,
3103 cx: &mut JSContext,
3104 element: &Element,
3105 x: f32,
3106 y: f32,
3107 behavior: ScrollBehavior,
3108 ) {
3109 let scroll_id = ExternalScrollId(
3110 combine_id_with_fragment_type(
3111 element.upcast::<Node>().to_opaque().id(),
3112 FragmentType::FragmentBody,
3113 ),
3114 self.pipeline_id().into(),
3115 );
3116
3117 self.perform_a_scroll(cx, x, y, scroll_id, behavior, Some(element));
3121 }
3122
3123 pub(crate) fn resolved_style_query(
3124 &self,
3125 element: TrustedNodeAddress,
3126 pseudo: Option<PseudoElement>,
3127 property: PropertyId,
3128 ) -> DOMString {
3129 self.layout_reflow(QueryMsg::ResolvedStyleQuery(property.clone()));
3130
3131 let document = self.Document();
3132 let animations = document.animation_manager().sets();
3133 DOMString::from(self.layout.borrow().query_resolved_style(
3134 element,
3135 pseudo,
3136 property,
3137 animations,
3138 document.current_animation_timeline_value(),
3139 ))
3140 }
3141
3142 pub(crate) fn get_iframe_viewport_details_if_known(
3146 &self,
3147 browsing_context_id: BrowsingContextId,
3148 ) -> Option<ViewportDetails> {
3149 self.layout_reflow(QueryMsg::InnerWindowDimensionsQuery);
3151 self.Document()
3152 .iframes()
3153 .get(browsing_context_id)
3154 .and_then(|iframe| iframe.size)
3155 }
3156
3157 #[expect(unsafe_code)]
3158 pub(crate) fn offset_parent_query(
3159 &self,
3160 node: &Node,
3161 ) -> (Option<DomRoot<Element>>, Rect<Au, CSSPixel>) {
3162 self.layout_reflow(QueryMsg::OffsetParentQuery);
3163 let response = self
3164 .layout
3165 .borrow()
3166 .query_offset_parent(node.to_trusted_node_address());
3167 let element = response.node_address.and_then(|parent_node_address| {
3168 let node = unsafe { from_untrusted_node_address(parent_node_address) };
3169 DomRoot::downcast(node)
3170 });
3171 (element, response.rect)
3172 }
3173
3174 pub(crate) fn scroll_container_query(
3175 &self,
3176 node: Option<&Node>,
3177 flags: ScrollContainerQueryFlags,
3178 ) -> Option<ScrollContainerResponse> {
3179 self.layout_reflow(QueryMsg::ScrollParentQuery);
3180 self.layout
3181 .borrow()
3182 .query_scroll_container(node.map(Node::to_trusted_node_address), flags)
3183 }
3184
3185 #[expect(unsafe_code)]
3186 pub(crate) fn scrolling_box_query(
3187 &self,
3188 node: Option<&Node>,
3189 flags: ScrollContainerQueryFlags,
3190 ) -> Option<ScrollingBox> {
3191 self.scroll_container_query(node, flags)
3192 .and_then(|response| {
3193 Some(match response {
3194 ScrollContainerResponse::Viewport(overflow) => {
3195 (ScrollingBoxSource::Viewport(self.Document()), overflow)
3196 },
3197 ScrollContainerResponse::Element(parent_node_address, overflow) => {
3198 let node = unsafe { from_untrusted_node_address(parent_node_address) };
3199 (
3200 ScrollingBoxSource::Element(DomRoot::downcast(node)?),
3201 overflow,
3202 )
3203 },
3204 })
3205 })
3206 .map(|(source, overflow)| ScrollingBox::new(source, overflow))
3207 }
3208
3209 #[expect(unsafe_code)]
3210 pub(crate) fn text_index_query_on_node_for_event(
3211 &self,
3212 node: &Node,
3213 point_in_viewport: Point2D<Au, CSSPixel>,
3214 ) -> Option<(DomRoot<Node>, Utf32CodeUnits)> {
3215 self.layout_reflow(QueryMsg::TextIndexQuery);
3216 let result = self
3217 .layout
3218 .borrow()
3219 .query_text_index(node.to_trusted_node_address(), point_in_viewport)?;
3220 let node = unsafe { from_untrusted_node_address(result.0.into()) };
3221 Some((node, result.1))
3222 }
3223
3224 pub(crate) fn elements_from_point_query(
3225 &self,
3226 flags: HitTestFlags,
3227 point: LayoutPoint,
3228 ) -> layout_api::HitTestResult {
3229 self.layout_reflow(QueryMsg::ElementsFromPoint);
3230 self.layout().hit_test(flags, point)
3231 }
3232
3233 pub(crate) fn query_effective_overflow(&self, node: &Node) -> Option<AxesOverflow> {
3234 self.layout_reflow(QueryMsg::EffectiveOverflow);
3235 self.query_effective_overflow_without_reflow(node)
3236 }
3237
3238 pub(crate) fn query_effective_overflow_without_reflow(
3239 &self,
3240 node: &Node,
3241 ) -> Option<AxesOverflow> {
3242 self.layout
3243 .borrow()
3244 .query_effective_overflow(node.to_trusted_node_address())
3245 }
3246
3247 pub(crate) fn hit_test_from_input_event(
3248 &self,
3249 flags: HitTestFlags,
3250 input_event: &ConstellationInputEvent,
3251 ) -> Option<HitTestResult> {
3252 self.hit_test_from_point_in_viewport(
3253 flags,
3254 input_event.hit_test_result.as_ref()?.point_in_viewport,
3255 )
3256 }
3257
3258 #[expect(unsafe_code)]
3259 pub(crate) fn hit_test_from_point_in_viewport(
3260 &self,
3261 flags: HitTestFlags,
3262 point_in_frame: Point2D<f32, CSSPixel>,
3263 ) -> Option<HitTestResult> {
3264 let result = self.elements_from_point_query(flags, point_in_frame.cast_unit());
3265 let item = result.items.into_iter().next()?;
3266
3267 let point_relative_to_initial_containing_block =
3268 point_in_frame + self.scroll_offset().cast_unit();
3269
3270 let from_opaque_node = |node: OpaqueNode| {
3273 let address = UntrustedNodeAddress(node.0 as *const c_void);
3274 unsafe { from_untrusted_node_address(address) }
3275 };
3276 Some(HitTestResult {
3277 node: from_opaque_node(item.node),
3278 dom_position_for_selection: result
3279 .dom_position_for_selection
3280 .map(|(node, offset)| (from_opaque_node(node), offset)),
3281 cursor: item.cursor,
3282 point_in_node: item.point_in_target,
3283 point_in_frame,
3284 point_relative_to_initial_containing_block,
3285 })
3286 }
3287
3288 pub(crate) fn init_window_proxy(&self, window_proxy: &WindowProxy) {
3289 assert!(
3290 self.window_proxy
3291 .get()
3292 .is_none_or(|current_proxy| &*current_proxy as *const WindowProxy == window_proxy)
3293 );
3294 self.window_proxy.set(Some(window_proxy));
3295 }
3296
3297 pub(crate) fn init_document(&self, document: &Document) {
3298 assert!(
3299 self.document
3300 .get()
3301 .is_none_or(|document| document.is_initial_about_blank())
3302 );
3303 assert!(document.window() == self);
3304 self.document.set(Some(document));
3305 self.update_jsprincipals_from_document(document);
3306 }
3307
3308 #[expect(unsafe_code)]
3315 pub(crate) fn update_jsprincipals_from_document(&self, document: &Document) {
3316 let realm = unsafe { GetObjectRealmOrNull(self.reflector().get_jsobject().get()) };
3317 let new_principals = ServoJSPrincipals::new::<crate::DomTypeHolder>(&document.origin());
3318 unsafe { SetRealmPrincipals(realm, new_principals.as_raw()) };
3319 }
3320
3321 pub(crate) fn load_data_for_document(
3322 &self,
3323 url: ServoUrl,
3324 pipeline_id: PipelineId,
3325 ) -> LoadData {
3326 let source_document = self.Document();
3327 let secure_context = if self.is_top_level() {
3328 None
3329 } else {
3330 Some(self.IsSecureContext())
3331 };
3332 LoadData::new(
3333 LoadOrigin::Script(self.origin().snapshot()),
3334 url,
3335 source_document.about_base_url(),
3336 Some(pipeline_id),
3337 Referrer::ReferrerUrl(source_document.url()),
3338 source_document.get_referrer_policy(),
3339 secure_context,
3340 Some(source_document.insecure_requests_policy()),
3341 source_document.has_trustworthy_ancestor_origin(),
3342 source_document.creation_sandboxing_flag_set_considering_parent_iframe(),
3343 )
3344 }
3345
3346 pub(crate) fn set_viewport_details(&self, viewport_details: ViewportDetails) {
3349 self.viewport_details.set(viewport_details);
3350 if !self.layout_mut().set_viewport_details(viewport_details) {
3351 return;
3352 }
3353 self.Document()
3354 .add_restyle_reason(RestyleReason::ViewportChanged);
3355 }
3356
3357 pub(crate) fn viewport_details(&self) -> ViewportDetails {
3358 self.viewport_details.get()
3359 }
3360
3361 pub(crate) fn get_or_init_visual_viewport(
3362 &self,
3363 cx: &mut JSContext,
3364 ) -> DomRoot<VisualViewport> {
3365 self.visual_viewport.or_init(|| {
3366 VisualViewport::new_from_layout_viewport(cx, self, self.viewport_details().size)
3367 })
3368 }
3369
3370 pub(crate) fn maybe_update_visual_viewport(
3372 &self,
3373 cx: &mut JSContext,
3374 pinch_zoom_infos: PinchZoomInfos,
3375 ) {
3376 if pinch_zoom_infos.rect == Rect::from_size(self.viewport_details().size) &&
3379 self.visual_viewport.get().is_none()
3380 {
3381 return;
3382 }
3383
3384 let visual_viewport = self.get_or_init_visual_viewport(cx);
3385 let changes = visual_viewport.update_from_pinch_zoom_infos(pinch_zoom_infos);
3386
3387 if changes.intersects(VisualViewportChanges::DimensionChanged) {
3388 self.has_changed_visual_viewport_dimension.set(true);
3389 }
3390 if changes.intersects(VisualViewportChanges::OffsetChanged) {
3391 visual_viewport.handle_scroll_event();
3392 }
3393 }
3394
3395 pub(crate) fn embedder_theme(&self) -> Theme {
3397 self.embedder_theme.get()
3398 }
3399
3400 pub(crate) fn set_embedder_theme(&self, new_theme: Theme) {
3402 self.embedder_theme.set(new_theme);
3403 self.refresh_theme();
3404 }
3405
3406 pub(crate) fn refresh_theme(&self) {
3407 let document = self.Document();
3408 let new_theme = document.theme().unwrap_or(self.embedder_theme.get());
3410 if !self.layout_mut().set_theme(new_theme) {
3411 return;
3412 }
3413 document.add_restyle_reason(RestyleReason::ThemeChanged);
3414 self.pending_media_query_evaluation.set(true);
3417 }
3418
3419 pub(crate) fn take_pending_media_query_evaluation(&self) -> bool {
3422 self.pending_media_query_evaluation.replace(false)
3423 }
3424
3425 pub(crate) fn has_pending_media_query_evaluation(&self) -> bool {
3426 self.pending_media_query_evaluation.get()
3427 }
3428
3429 pub(crate) fn get_url(&self) -> ServoUrl {
3430 self.Document().url()
3431 }
3432
3433 pub(crate) fn windowproxy_handler(&self) -> &'static WindowProxyHandler {
3434 self.dom_static.windowproxy_handler
3435 }
3436
3437 pub(crate) fn add_resize_event(&self, event: ViewportDetails, event_type: WindowSizeType) {
3438 if self.viewport_details() == event {
3439 return;
3440 }
3441
3442 self.set_viewport_details(event);
3444
3445 *self.unhandled_resize_event.borrow_mut() = Some((event, event_type))
3448 }
3449
3450 pub(crate) fn take_unhandled_resize_event(&self) -> Option<(ViewportDetails, WindowSizeType)> {
3451 self.unhandled_resize_event.borrow_mut().take()
3452 }
3453
3454 pub(crate) fn has_unhandled_resize_event(&self) -> bool {
3456 self.unhandled_resize_event.borrow().is_some()
3457 }
3458
3459 pub(crate) fn suspend(&self, cx: &mut JSContext) {
3460 self.as_global_scope().suspend();
3462
3463 if self.window_proxy().currently_active() == Some(self.global().pipeline_id()) {
3465 self.window_proxy().unset_currently_active(cx);
3466 }
3467
3468 self.gc(cx);
3473 }
3474
3475 pub(crate) fn resume(&self, cx: &mut JSContext) {
3476 self.as_global_scope().resume();
3478
3479 self.window_proxy().set_currently_active(cx, self);
3481
3482 self.Document().title_changed();
3485 }
3486
3487 pub(crate) fn need_emit_timeline_marker(&self, timeline_type: TimelineMarkerType) -> bool {
3488 let markers = self.devtools_markers.borrow();
3489 markers.contains(&timeline_type)
3490 }
3491
3492 pub(crate) fn emit_timeline_marker(&self, marker: TimelineMarker) {
3493 let sender = self.devtools_marker_sender.borrow();
3494 let sender = sender.as_ref().expect("There is no marker sender");
3495 sender.send(Some(marker)).unwrap();
3496 }
3497
3498 pub(crate) fn set_devtools_timeline_markers(
3499 &self,
3500 markers: Vec<TimelineMarkerType>,
3501 reply: GenericSender<Option<TimelineMarker>>,
3502 ) {
3503 *self.devtools_marker_sender.borrow_mut() = Some(reply);
3504 self.devtools_markers.borrow_mut().extend(markers);
3505 }
3506
3507 pub(crate) fn drop_devtools_timeline_markers(&self, markers: Vec<TimelineMarkerType>) {
3508 let mut devtools_markers = self.devtools_markers.borrow_mut();
3509 for marker in markers {
3510 devtools_markers.remove(&marker);
3511 }
3512 if devtools_markers.is_empty() {
3513 *self.devtools_marker_sender.borrow_mut() = None;
3514 }
3515 }
3516
3517 pub(crate) fn set_webdriver_load_status_sender(
3518 &self,
3519 sender: Option<GenericSender<WebDriverLoadStatus>>,
3520 ) {
3521 *self.webdriver_load_status_sender.borrow_mut() = sender;
3522 }
3523
3524 pub(crate) fn webdriver_load_status_sender(
3525 &self,
3526 ) -> Option<GenericSender<WebDriverLoadStatus>> {
3527 self.webdriver_load_status_sender.borrow().clone()
3528 }
3529
3530 pub(crate) fn is_alive(&self) -> bool {
3531 self.current_state.get() == WindowState::Alive
3532 }
3533
3534 pub(crate) fn is_top_level(&self) -> bool {
3536 self.parent_info.is_none()
3537 }
3538
3539 fn run_resize_steps_for_layout_viewport(&self, cx: &mut JSContext) -> bool {
3544 let Some((new_size, size_type)) = self.take_unhandled_resize_event() else {
3545 return false;
3546 };
3547
3548 let current_viewport = self.viewport_details();
3551 if current_viewport == self.viewport_details_at_last_resize_steps.get() {
3552 return false;
3553 }
3554 self.viewport_details_at_last_resize_steps
3555 .set(current_viewport);
3556
3557 debug!(
3558 "Running resize steps for pipeline {:?} with viewport {new_size:?}",
3559 self.pipeline_id(),
3560 );
3561
3562 if size_type == WindowSizeType::Resize {
3564 let mut realm = enter_auto_realm(cx, self);
3565 let cx = &mut realm.current_realm();
3566 let uievent = UIEvent::new(
3567 cx,
3568 self,
3569 atom!("resize"),
3570 EventBubbles::DoesNotBubble,
3571 EventCancelable::NotCancelable,
3572 Some(self),
3573 0i32,
3574 0u32,
3575 );
3576 uievent.upcast::<Event>().fire(cx, self.upcast());
3577 }
3578
3579 true
3580 }
3581
3582 pub(crate) fn run_the_resize_steps(&self, cx: &mut JSContext) -> bool {
3587 let layout_viewport_resized = self.run_resize_steps_for_layout_viewport(cx);
3588
3589 if self.has_changed_visual_viewport_dimension.get() {
3590 let visual_viewport = self.get_or_init_visual_viewport(cx);
3591
3592 let uievent = UIEvent::new(
3593 cx,
3594 self,
3595 atom!("resize"),
3596 EventBubbles::DoesNotBubble,
3597 EventCancelable::NotCancelable,
3598 Some(self),
3599 0i32,
3600 0u32,
3601 );
3602 uievent.upcast::<Event>().fire(cx, visual_viewport.upcast());
3603
3604 self.has_changed_visual_viewport_dimension.set(false);
3605 }
3606
3607 layout_viewport_resized
3608 }
3609
3610 pub(crate) fn evaluate_media_queries_and_report_changes(&self, cx: &mut JSContext) {
3613 let mut realm = enter_auto_realm(cx, self);
3614 let cx = &mut realm.current_realm();
3615 rooted_vec!(let mut mql_list);
3616
3617 self.media_query_lists.for_each(|mql| {
3618 if let MediaQueryListMatchState::Changed = mql.evaluate_changes() {
3619 mql_list.push(Dom::from_ref(&*mql));
3621 }
3622 });
3623 for mql in mql_list.iter() {
3625 let event = MediaQueryListEvent::new(
3626 cx,
3627 &mql.global(),
3628 atom!("change"),
3629 false,
3630 false,
3631 mql.Media(),
3632 mql.Matches(),
3633 );
3634 event
3635 .upcast::<Event>()
3636 .fire(cx, mql.upcast::<EventTarget>());
3637 }
3638 }
3639
3640 pub(crate) fn set_throttled(&self, throttled: bool) {
3642 self.throttled.set(throttled);
3643 if throttled {
3644 self.as_global_scope().slow_down_timers();
3645 } else {
3646 self.as_global_scope().speed_up_timers();
3647 }
3648 }
3649
3650 pub(crate) fn throttled(&self) -> bool {
3651 self.throttled.get()
3652 }
3653
3654 pub(crate) fn unminified_css_dir(&self) -> Option<String> {
3655 self.unminified_css_dir.borrow().clone()
3656 }
3657
3658 pub(crate) fn local_script_source(&self) -> &Option<String> {
3659 &self.local_script_source
3660 }
3661
3662 pub(crate) fn set_navigation_start(&self) {
3663 self.navigation_start.set(CrossProcessInstant::now());
3664 }
3665
3666 pub(crate) fn navigation_start(&self) -> CrossProcessInstant {
3667 self.navigation_start.get()
3668 }
3669
3670 pub(crate) fn set_last_activation_timestamp(&self, time: UserActivationTimestamp) {
3671 self.last_activation_timestamp.set(time);
3672 }
3673
3674 pub(crate) fn send_to_embedder(&self, msg: EmbedderMsg) {
3675 self.as_global_scope()
3676 .script_to_embedder_chan()
3677 .send(msg)
3678 .unwrap();
3679 }
3680
3681 pub(crate) fn send_to_constellation(&self, msg: ScriptToConstellationMessage) {
3682 self.as_global_scope()
3683 .script_to_constellation_chan()
3684 .send(msg)
3685 .unwrap();
3686 }
3687
3688 #[cfg(feature = "webxr")]
3689 pub(crate) fn in_immersive_xr_session(&self) -> bool {
3690 self.navigator
3691 .get()
3692 .as_ref()
3693 .and_then(|nav| nav.xr())
3694 .is_some_and(|xr| xr.pending_or_active_session())
3695 }
3696
3697 #[cfg(all(feature = "webgl", not(feature = "webxr")))]
3698 pub(crate) fn in_immersive_xr_session(&self) -> bool {
3699 false
3700 }
3701
3702 fn handle_new_or_removed_web_fonts_post_reflow(
3704 &self,
3705 cx: &mut JSContext,
3706 changed_web_fonts: WebFontSetDifference,
3707 ) {
3708 if changed_web_fonts.is_empty() {
3709 return;
3710 }
3711
3712 let document = self.Document();
3713 let fonts = document.Fonts(cx);
3714 if !changed_web_fonts.removed_font_faces.is_empty() {
3715 fonts.notify_font_face_rules_removed(&changed_web_fonts.removed_font_faces);
3716 }
3717
3718 if !changed_web_fonts.removed_font_faces.is_empty() ||
3719 changed_web_fonts.cascade_index_of_any_rule_changed
3720 {
3721 document.dirty_all_nodes(cx.no_gc());
3724 }
3725
3726 if !changed_web_fonts.added_font_faces.is_empty() {
3727 fonts.switch_to_loading(cx);
3728
3729 for new_web_font in changed_web_fonts.added_font_faces {
3730 if let Some(font_face) = FontFace::new_for_web_font(cx, self.upcast(), new_web_font)
3731 {
3732 fonts.add(cx, font_face);
3733 }
3734 }
3735 }
3736 }
3737
3738 #[expect(unsafe_code)]
3740 fn process_lcp_candidate_post_reflow(&self, candidate: LCPCandidate, document: &Document) {
3741 let element = candidate.node.and_then(|node| {
3742 let node_address = UntrustedNodeAddress(node.id() as *const c_void);
3743 let node = unsafe { from_untrusted_node_address(node_address) };
3744 DomRoot::downcast::<Element>(node)
3745 });
3746 document.store_lcp_candidate(candidate, element.as_deref());
3747 }
3748
3749 #[expect(unsafe_code)]
3750 fn handle_pending_images_post_reflow(
3751 &self,
3752 cx: &mut JSContext,
3753 pending_images: Vec<PendingImage>,
3754 pending_rasterization_images: Vec<PendingRasterizationImage>,
3755 pending_svg_element_for_serialization: Vec<UntrustedNodeAddress>,
3756 ) {
3757 let pipeline_id = self.pipeline_id();
3758 let image_cache = self.image_cache();
3759 for image in pending_images {
3760 let id = image.id;
3761 let node = unsafe { from_untrusted_node_address(image.node) };
3762
3763 if let PendingImageState::Unrequested(ref url) = image.state {
3764 fetch_image_for_layout(
3765 url.clone(),
3766 &node,
3767 id,
3768 image.is_internal_request,
3769 image_cache.clone(),
3770 );
3771 }
3772
3773 let mut images = self.pending_layout_images.borrow_mut();
3774 if !images.contains_key(&id) {
3775 let trusted_node = Trusted::new(&*node);
3776 let sender = self.register_image_cache_listener(id, move |response, cx| {
3777 trusted_node
3778 .root()
3779 .owner_window()
3780 .pending_layout_image_notification(cx.no_gc(), response);
3781 });
3782
3783 image_cache.add_listener(ImageLoadListener::new(sender, pipeline_id, id));
3784 }
3785
3786 let nodes = images.entry(id).or_default();
3787 if !nodes.iter().any(|n| *n.node == *node) {
3788 nodes.push(PendingLayoutImageAncillaryData {
3789 node: Dom::from_ref(&*node),
3790 destination: image.destination,
3791 });
3792 }
3793 }
3794
3795 for image in pending_rasterization_images {
3796 let node = unsafe { from_untrusted_node_address(image.node) };
3797
3798 let mut images = self.pending_images_for_rasterization.borrow_mut();
3799 if !images.contains_key(&(image.id, image.size)) {
3800 let image_cache_sender = self.image_cache_sender.clone();
3801 image_cache.add_rasterization_complete_listener(
3802 pipeline_id,
3803 image.id,
3804 image.size,
3805 Box::new(move |response| {
3806 let _ = image_cache_sender.send(response);
3807 }),
3808 );
3809 }
3810
3811 let nodes = images.entry((image.id, image.size)).or_default();
3812 if !nodes.iter().any(|n| **n == *node) {
3813 nodes.push(Dom::from_ref(&*node));
3814 }
3815 }
3816
3817 for node in pending_svg_element_for_serialization.into_iter() {
3818 let node = unsafe { from_untrusted_node_address(node) };
3819 let svg = node.downcast::<SVGSVGElement>().unwrap();
3820 svg.serialize_and_cache_subtree(cx);
3821 node.dirty(cx.no_gc(), NodeDamage::Other);
3822 }
3823 }
3824
3825 pub(crate) fn has_sticky_activation(&self) -> bool {
3827 UserActivationTimestamp::TimeStamp(CrossProcessInstant::now()) >=
3829 self.last_activation_timestamp.get()
3830 }
3831
3832 pub(crate) fn has_transient_activation(&self) -> bool {
3834 let current_time = CrossProcessInstant::now();
3837 UserActivationTimestamp::TimeStamp(current_time) >= self.last_activation_timestamp.get() &&
3838 UserActivationTimestamp::TimeStamp(current_time) <
3839 self.last_activation_timestamp.get() +
3840 pref!(dom_transient_activation_duration_ms)
3841 }
3842
3843 pub(crate) fn consume_last_activation_timestamp(&self) {
3844 if self.last_activation_timestamp.get() != UserActivationTimestamp::PositiveInfinity {
3845 self.set_last_activation_timestamp(UserActivationTimestamp::NegativeInfinity);
3846 }
3847 }
3848
3849 pub(crate) fn consume_user_activation(&self) {
3851 if self.undiscarded_window_proxy().is_none() {
3854 return;
3855 }
3856
3857 let Some(top_level_document) = self.top_level_document_if_local() else {
3861 return;
3862 };
3863
3864 top_level_document
3872 .window()
3873 .consume_last_activation_timestamp();
3874 for document in SameOriginDescendantNavigablesIterator::new(&top_level_document) {
3875 document.window().consume_last_activation_timestamp();
3876 }
3877 }
3878
3879 #[allow(clippy::too_many_arguments)]
3880 pub(crate) fn new(
3881 cx: &mut JSContext,
3882 webview_id: WebViewId,
3883 runtime: Rc<Runtime>,
3884 script_chan: Sender<MainThreadScriptMsg>,
3885 layout: Box<dyn Layout>,
3886 image_cache_sender: Sender<ImageCacheResponseMessage>,
3887 resource_threads: ResourceThreads,
3888 storage_threads: StorageThreads,
3889 #[cfg(feature = "bluetooth")] bluetooth_thread: GenericSender<BluetoothRequest>,
3890 mem_profiler_chan: MemProfilerChan,
3891 time_profiler_chan: TimeProfilerChan,
3892 devtools_chan: Option<GenericCallback<ScriptToDevtoolsControlMsg>>,
3893 script_to_constellation_sender: ScriptToConstellationSender,
3894 embedder_chan: ScriptToEmbedderChan,
3895 control_chan: GenericSender<ScriptThreadMessage>,
3896 pipeline_id: PipelineId,
3897 parent_info: Option<PipelineId>,
3898 viewport_details: ViewportDetails,
3899 origin: MutableOrigin,
3900 creation_url: ServoUrl,
3901 top_level_creation_url: ServoUrl,
3902 navigation_start: CrossProcessInstant,
3903 #[cfg(feature = "webgl")] webgl_chan: Option<WebGLChan>,
3904 #[cfg(feature = "webxr")] webxr_registry: Option<webxr_api::Registry>,
3905 paint_api: CrossProcessPaintApi,
3906 unminify_js: bool,
3907 unminify_css: bool,
3908 local_script_source: Option<String>,
3909 user_scripts: Rc<Vec<UserScript>>,
3910 player_context: WindowGLContext,
3911 #[cfg(feature = "webgpu")] gpu_id_hub: Arc<IdentityHub>,
3912 inherited_secure_context: Option<bool>,
3913 embedder_theme: Theme,
3914 weak_script_thread: Weak<ScriptThread>,
3915 ) -> DomRoot<Self> {
3916 let error_reporter = CSSErrorReporter {
3917 pipelineid: pipeline_id,
3918 script_chan: control_chan,
3919 };
3920
3921 let win = Box::new(Self {
3922 webview_id,
3923 globalscope: GlobalScope::new_inherited(
3924 devtools_chan,
3925 mem_profiler_chan,
3926 time_profiler_chan,
3927 script_to_constellation_sender,
3928 embedder_chan,
3929 resource_threads,
3930 storage_threads,
3931 creation_url,
3932 Some(top_level_creation_url),
3933 #[cfg(feature = "webgpu")]
3934 gpu_id_hub,
3935 inherited_secure_context,
3936 unminify_js,
3937 ),
3938 caches: Default::default(),
3939 ongoing_navigation: Default::default(),
3940 script_chan,
3941 layout: RefCell::new(layout),
3942 image_cache_sender,
3943 navigator: Default::default(),
3944 #[cfg(feature = "webcrypto")]
3945 crypto: Default::default(),
3946 location: Default::default(),
3947 window_proxy: Default::default(),
3948 document: Default::default(),
3949 performance: Default::default(),
3950 navigation_start: Cell::new(navigation_start),
3951 screen: Default::default(),
3952 session_storage: Default::default(),
3953 local_storage: Default::default(),
3954 cookie_store: Default::default(),
3955 status: DomRefCell::new(DOMString::new()),
3956 parent_info,
3957 dom_static: GlobalStaticData::new(),
3958 js_runtime: DomRefCell::new(Some(runtime)),
3959 #[cfg(feature = "bluetooth")]
3960 bluetooth_thread,
3961 #[cfg(feature = "bluetooth")]
3962 bluetooth_extra_permission_data: BluetoothExtraPermissionData::new(),
3963 unhandled_resize_event: Default::default(),
3964 viewport_details_at_last_resize_steps: Cell::new(viewport_details),
3965 viewport_details: Cell::new(viewport_details),
3966 layout_blocker: Cell::new(LayoutBlocker::WaitingForParse),
3967 current_state: Cell::new(WindowState::Alive),
3968 devtools_marker_sender: Default::default(),
3969 devtools_markers: Default::default(),
3970 webdriver_load_status_sender: Default::default(),
3971 error_reporter,
3972 media_query_lists: DOMTracker::new(),
3973 #[cfg(feature = "bluetooth")]
3974 test_runner: Default::default(),
3975 #[cfg(feature = "webgl")]
3976 webgl_chan,
3977 #[cfg(feature = "webxr")]
3978 webxr_registry,
3979 pending_image_callbacks: Default::default(),
3980 pending_layout_images: Default::default(),
3981 pending_images_for_rasterization: Default::default(),
3982 unminified_css_dir: DomRefCell::new(if unminify_css {
3983 Some(unminified_path("unminified-css"))
3984 } else {
3985 None
3986 }),
3987 local_script_source,
3988 test_worklet: Default::default(),
3989 paint_worklet: Default::default(),
3990 exists_mut_observer: Cell::new(false),
3991 paint_api,
3992 user_scripts,
3993 player_context,
3994 throttled: Cell::new(false),
3995 layout_marker: DomRefCell::new(Rc::new(Cell::new(true))),
3996 current_event: DomRefCell::new(None),
3997 embedder_theme: Cell::new(embedder_theme),
3998 trusted_types: Default::default(),
3999 reporting_observer_list: Default::default(),
4000 report_list: Default::default(),
4001 endpoints_list: Default::default(),
4002 script_window_proxies: ScriptThread::window_proxies(),
4003 has_pending_screenshot_readiness_request: Default::default(),
4004 visual_viewport: Default::default(),
4005 weak_script_thread,
4006 has_changed_visual_viewport_dimension: Default::default(),
4007 pending_media_query_evaluation: Default::default(),
4008 last_activation_timestamp: Cell::new(UserActivationTimestamp::PositiveInfinity),
4009 devtools_wants_updates: Default::default(),
4010 has_dispatched_scroll_event: Cell::new(false),
4011 has_dispatched_input_event: Cell::new(false),
4012 });
4013
4014 WindowBinding::Wrap::<crate::DomTypeHolder>(cx, &origin, win)
4015 }
4016
4017 pub(crate) fn task_manager(&self) -> Rc<TaskManager> {
4018 self.Document().task_manager()
4019 }
4020
4021 pub(crate) fn pipeline_id(&self) -> PipelineId {
4022 self.Document().pipeline_id()
4023 }
4024
4025 pub(crate) fn live_devtools_updates(&self) -> bool {
4026 self.devtools_wants_updates.get()
4027 }
4028
4029 pub(crate) fn set_devtools_wants_updates(&self, value: bool) {
4030 self.devtools_wants_updates.set(value);
4031 }
4032
4033 pub(crate) fn cache_layout_value<T>(&self, value: T) -> LayoutValue<T>
4035 where
4036 T: Copy + MallocSizeOf,
4037 {
4038 LayoutValue::new(self.layout_marker.borrow().clone(), value)
4039 }
4040
4041 pub(crate) fn set_up_a_window_environment_settings_object(
4050 &self,
4051 layout: Box<dyn Layout>,
4052 creation_url: ServoUrl,
4053 top_level_creation_url: ServoUrl,
4054 navigation_start: CrossProcessInstant,
4055 viewport_details: ViewportDetails,
4056 ) {
4057 *self.layout.borrow_mut() = layout;
4058 self.set_viewport_details(viewport_details);
4059 self.navigation_start.set(navigation_start);
4060
4061 let global = self.upcast::<GlobalScope>();
4064 global.set_creation_url(creation_url);
4065 global.set_top_level_creation_url(top_level_creation_url);
4066
4067 self.Document().detach_window();
4068 }
4069}
4070
4071#[derive(MallocSizeOf)]
4076pub(crate) struct LayoutValue<T: MallocSizeOf> {
4077 #[conditional_malloc_size_of]
4078 is_valid: Rc<Cell<bool>>,
4079 value: T,
4080}
4081
4082#[expect(unsafe_code)]
4083unsafe impl<T: JSTraceable + MallocSizeOf> JSTraceable for LayoutValue<T> {
4084 unsafe fn trace(&self, trc: *mut js::jsapi::JSTracer) {
4085 unsafe { self.value.trace(trc) };
4086 }
4087}
4088
4089impl<T: Copy + MallocSizeOf> LayoutValue<T> {
4090 fn new(marker: Rc<Cell<bool>>, value: T) -> Self {
4091 LayoutValue {
4092 is_valid: marker,
4093 value,
4094 }
4095 }
4096
4097 pub(crate) fn get(&self) -> Result<T, ()> {
4099 if self.is_valid.get() {
4100 return Ok(self.value);
4101 }
4102 Err(())
4103 }
4104}
4105
4106impl Window {
4107 pub(crate) fn post_message(
4109 &self,
4110 target_origin: Option<ImmutableOrigin>,
4111 source_origin: ImmutableOrigin,
4112 source: &WindowProxy,
4113 data: StructuredSerializedData,
4114 ) {
4115 let this = Trusted::new(self);
4116 let source = Trusted::new(source);
4117 let task = task!(post_serialised_message: move |cx| {
4118 let this = this.root();
4119 let source = source.root();
4120 let document = this.Document();
4121
4122 if let Some(ref target_origin) = target_origin
4124 && !target_origin.same_origin(&*document.origin()) {
4125 return;
4126 }
4127
4128 let obj = this.reflector().get_jsobject();
4130 let mut realm = AutoRealm::new(cx, NonNull::new(obj.get()).unwrap());
4131 let cx = &mut *realm;
4132 rooted!(&in(cx) let mut message_clone = UndefinedValue());
4133 if let Ok(ports) = structuredclone::read(cx, this.upcast(), data, message_clone.handle_mut()) {
4134 MessageEvent::dispatch_jsval(
4136 cx,
4137 this.upcast(),
4138 this.upcast(),
4139 message_clone.handle(),
4140 Some(source_origin.ascii_serialization().as_ref()),
4141 Some(&*source),
4142 ports,
4143 );
4144 } else {
4145 MessageEvent::dispatch_error(
4147 cx,
4148 this.upcast(),
4149 this.upcast(),
4150 );
4151 }
4152 });
4153 self.as_global_scope()
4155 .task_manager()
4156 .dom_manipulation_task_source()
4157 .queue(task);
4158 }
4159}
4160
4161#[derive(Clone, MallocSizeOf)]
4162pub(crate) struct CSSErrorReporter {
4163 pub(crate) pipelineid: PipelineId,
4164 pub(crate) script_chan: GenericSender<ScriptThreadMessage>,
4165}
4166unsafe_no_jsmanaged_fields!(CSSErrorReporter);
4167
4168impl ParseErrorReporter for CSSErrorReporter {
4169 fn report_error(
4170 &self,
4171 url: &UrlExtraData,
4172 location: SourceLocation,
4173 error: ContextualParseError,
4174 ) {
4175 if log_enabled!(log::Level::Info) {
4176 info!(
4177 "Url:\t{}\n{}:{} {}",
4178 url.0.as_str(),
4179 location.line,
4180 location.column,
4181 error
4182 )
4183 }
4184
4185 let _ = self.script_chan.send(ScriptThreadMessage::ReportCSSError(
4187 self.pipelineid,
4188 url.0.to_string(),
4189 location.line,
4190 location.column,
4191 error.to_string(),
4192 ));
4193 }
4194}
4195
4196fn is_named_element_with_name_attribute(elem: &Element) -> bool {
4197 let type_ = match elem.upcast::<Node>().type_id() {
4198 NodeTypeId::Element(ElementTypeId::HTMLElement(type_)) => type_,
4199 _ => return false,
4200 };
4201 matches!(
4202 type_,
4203 HTMLElementTypeId::HTMLEmbedElement |
4204 HTMLElementTypeId::HTMLFormElement |
4205 HTMLElementTypeId::HTMLImageElement |
4206 HTMLElementTypeId::HTMLObjectElement
4207 )
4208}
4209
4210fn is_named_element_with_id_attribute(elem: &Element) -> bool {
4211 elem.is_html_element() || elem.is_svg_element()
4212}
4213
4214#[expect(unsafe_code)]
4215#[unsafe(no_mangle)]
4216unsafe extern "C" fn dump_js_stack(cx: *mut RawJSContext) {
4218 unsafe {
4219 DumpJSStack(cx, true, false, false);
4220 }
4221}
4222
4223impl WindowHelpers for Window {
4224 fn create_named_properties_object(
4225 cx: &mut JSContext,
4226 proto: HandleObject,
4227 object: MutableHandleObject,
4228 ) {
4229 Self::create_named_properties_object(cx, proto, object)
4230 }
4231}
4232
4233impl HasOrigin for Window {
4234 fn origin(&self) -> MutableOrigin {
4235 Window::origin(self)
4236 }
4237}