1use std::borrow::ToOwned;
6use std::cell::{Cell, RefCell, RefMut};
7use std::collections::HashSet;
8use std::collections::hash_map::Entry;
9use std::default::Default;
10use std::ffi::c_void;
11use std::io::{Write, stderr, stdout};
12use std::ptr::NonNull;
13use std::rc::{Rc, Weak};
14use std::sync::Arc;
15use std::time::{Duration, Instant};
16
17use app_units::Au;
18use base64::Engine;
19use content_security_policy::Violation;
20use content_security_policy::sandboxing_directive::SandboxingFlagSet;
21use crossbeam_channel::{Sender, unbounded};
22use cssparser::SourceLocation;
23use devtools_traits::{ScriptToDevtoolsControlMsg, TimelineMarker, TimelineMarkerType};
24use dom_struct::dom_struct;
25use embedder_traits::user_contents::UserScript;
26use embedder_traits::{
27 AlertResponse, ConfirmResponse, EmbedderMsg, JavaScriptEvaluationError, PromptResponse,
28 ScriptToEmbedderChan, SimpleDialogRequest, Theme, UntrustedNodeAddress, ViewportDetails,
29 WebDriverJSResult, WebDriverLoadStatus,
30};
31use euclid::{Point2D, Rect, Scale, Size2D, Vector2D};
32use fonts::{
33 CspViolationHandler, FontContext, NetworkTimingHandler, WebFontDocumentContext,
34 WebFontSetDifference,
35};
36use js::context::{JSContext, NoGC};
37use js::glue::DumpJSStack;
38use js::jsapi::{GCReason, Heap, JSContext as RawJSContext, JSObject, JSPROP_ENUMERATE};
39use js::jsval::{NullValue, UndefinedValue};
40use js::realm::{AutoRealm, CurrentRealm};
41use js::rust::wrappers2::{JS_DefineProperty, JS_GC};
42use js::rust::{
43 CustomAutoRooter, CustomAutoRooterGuard, HandleObject, HandleValue, MutableHandleObject,
44 MutableHandleValue,
45};
46use layout_api::{
47 AccessibilityDamage, AxesOverflow, BoxAreaType, CSSPixelRectVec, ElementsFromPointResult,
48 FragmentType, Layout, LayoutImageDestination, PendingImage, PendingImageState,
49 PendingRasterizationImage, PhysicalSides, QueryMsg, ReflowGoal, ReflowPhasesRun, ReflowRequest,
50 ReflowRequestRestyle, ReflowStatistics, RestyleReason, ScrollContainerQueryFlags,
51 ScrollContainerResponse, TrustedNodeAddress, combine_id_with_fragment_type,
52};
53use malloc_size_of::MallocSizeOf;
54use media::WindowGLContext;
55use net_traits::image_cache::{
56 ImageCache, ImageCacheResponseCallback, ImageCacheResponseMessage, ImageLoadListener,
57 ImageResponse, PendingImageId, PendingImageResponse, RasterizationCompleteResponse,
58};
59use net_traits::request::{Origin, Referrer, RequestClient};
60use net_traits::{ResourceFetchTiming, ResourceThreads};
61use num_traits::ToPrimitive;
62use paint_api::{CrossProcessPaintApi, PinchZoomInfos};
63use profile_traits::generic_channel as ProfiledGenericChannel;
64use profile_traits::mem::ProfilerChan as MemProfilerChan;
65use profile_traits::time::ProfilerChan as TimeProfilerChan;
66use rustc_hash::{FxBuildHasher, FxHashMap};
67use script_bindings::cell::{DomRefCell, Ref};
68use script_bindings::codegen::GenericBindings::WindowBinding::ScrollToOptions;
69use script_bindings::conversions::SafeToJSValConvertible;
70use script_bindings::dom::UnrootedDom;
71use script_bindings::interfaces::{HasOrigin, WindowHelpers};
72use script_bindings::like::Setlike;
73use script_bindings::reflector::DomObject;
74use script_bindings::root::Root;
75use script_traits::{ConstellationInputEvent, ScriptThreadMessage};
76use selectors::attr::CaseSensitivity;
77use servo_arc::Arc as ServoArc;
78use servo_base::cross_process_instant::CrossProcessInstant;
79use servo_base::generic_channel::{self, GenericCallback, GenericSender};
80use servo_base::id::{BrowsingContextId, PipelineId, WebViewId};
81#[cfg(feature = "bluetooth")]
82use servo_bluetooth_traits::BluetoothRequest;
83use servo_canvas_traits::webgl::WebGLChan;
84use servo_config::pref;
85use servo_constellation_traits::{
86 LoadData, LoadOrigin, ScreenshotReadinessResponse, ScriptToConstellationMessage,
87 ScriptToConstellationSender, StructuredSerializedData, WindowSizeType,
88};
89use servo_geometry::DeviceIndependentIntRect;
90use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
91use storage_traits::StorageThreads;
92use storage_traits::webstorage_thread::WebStorageType;
93use style::error_reporting::{ContextualParseError, ParseErrorReporter};
94use style::properties::PropertyId;
95use style::properties::style_structs::Font;
96use style::selector_parser::PseudoElement;
97use style::shared_lock::StylesheetGuards;
98use style::str::HTML_SPACE_CHARACTERS;
99use style::stylesheets::UrlExtraData;
100use style_traits::CSSPixel;
101use stylo_atoms::Atom;
102use time::Duration as TimeDuration;
103use webrender_api::ExternalScrollId;
104use webrender_api::units::{DeviceIntSize, DevicePixel, LayoutPixel, LayoutPoint};
105
106use crate::dom::bindings::codegen::Bindings::DocumentBinding::{
107 DocumentMethods, DocumentReadyState, NamedPropertyValue,
108};
109use crate::dom::bindings::codegen::Bindings::HTMLIFrameElementBinding::HTMLIFrameElementMethods;
110use crate::dom::bindings::codegen::Bindings::HistoryBinding::History_Binding::HistoryMethods;
111use crate::dom::bindings::codegen::Bindings::ImageBitmapBinding::{
112 ImageBitmapOptions, ImageBitmapSource,
113};
114use crate::dom::bindings::codegen::Bindings::MediaQueryListBinding::MediaQueryList_Binding::MediaQueryListMethods;
115use crate::dom::bindings::codegen::Bindings::MessagePortBinding::StructuredSerializeOptions;
116use crate::dom::bindings::codegen::Bindings::ReportingObserverBinding::Report;
117use crate::dom::bindings::codegen::Bindings::RequestBinding::{RequestInfo, RequestInit};
118use crate::dom::bindings::codegen::Bindings::VoidFunctionBinding::VoidFunction;
119use crate::dom::bindings::codegen::Bindings::WindowBinding::{
120 self, DeferredRequestInit, FrameRequestCallback, ScrollBehavior, WindowMethods,
121 WindowPostMessageOptions,
122};
123use crate::dom::bindings::codegen::UnionTypes::{
124 RequestOrUSVString, TrustedScriptOrString, TrustedScriptOrStringOrFunction,
125};
126use crate::dom::bindings::error::{
127 Error, ErrorInfo, ErrorResult, Fallible, javascript_error_info_from_error_info,
128};
129use crate::dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
130use crate::dom::bindings::num::Finite;
131use crate::dom::bindings::refcounted::Trusted;
132use crate::dom::bindings::reflector::DomGlobal;
133use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
134use crate::dom::bindings::str::{DOMString, USVString};
135use crate::dom::bindings::structuredclone;
136use crate::dom::bindings::trace::{
137 CustomTraceable, HashMapTracedValues, JSTraceable, RootedTraceableBox,
138};
139use crate::dom::bindings::utils::GlobalStaticData;
140use crate::dom::bindings::weakref::DOMTracker;
141#[cfg(feature = "bluetooth")]
142use crate::dom::bluetooth::BluetoothExtraPermissionData;
143use crate::dom::cookiestore::CookieStore;
144use crate::dom::crypto::Crypto;
145use crate::dom::csp::GlobalCspReporting;
146use crate::dom::css::cssstyledeclaration::{
147 CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner,
148};
149use crate::dom::customelementregistry::CustomElementRegistry;
150use crate::dom::document::focus::FocusableArea;
151use crate::dom::document::{
152 AnimationFrameCallback, Document, SameOriginDescendantNavigablesIterator,
153};
154use crate::dom::element::Element;
155use crate::dom::event::{Event, EventBubbles, EventCancelable};
156use crate::dom::eventtarget::EventTarget;
157use crate::dom::fetchlaterresult::FetchLaterResult;
158use crate::dom::globalscope::GlobalScope;
159use crate::dom::history::History;
160use crate::dom::html::htmlcollection::{CollectionFilter, HTMLCollection};
161use crate::dom::html::htmliframeelement::HTMLIFrameElement;
162use crate::dom::idbfactory::IDBFactory;
163use crate::dom::inputevent::HitTestResult;
164use crate::dom::location::Location;
165use crate::dom::medialist::MediaList;
166use crate::dom::mediaquerylist::{MediaQueryList, MediaQueryListMatchState};
167use crate::dom::mediaquerylistevent::MediaQueryListEvent;
168use crate::dom::messageevent::MessageEvent;
169use crate::dom::navigator::Navigator;
170use crate::dom::node::{Node, NodeDamage, NodeTraits, from_untrusted_node_address};
171use crate::dom::performance::performance::Performance;
172use crate::dom::performanceresourcetiming::InitiatorType;
173use crate::dom::promise::Promise;
174use crate::dom::reporting::reportingendpoint::{ReportingEndpoint, SendReportsToEndpoints};
175use crate::dom::reporting::reportingobserver::ReportingObserver;
176use crate::dom::screen::Screen;
177use crate::dom::scrolling_box::{ScrollingBox, ScrollingBoxSource};
178use crate::dom::selection::Selection;
179use crate::dom::shadowroot::ShadowRoot;
180use crate::dom::storage::Storage;
181#[cfg(feature = "bluetooth")]
182use crate::dom::testrunner::TestRunner;
183use crate::dom::trustedtypes::trustedtypepolicyfactory::TrustedTypePolicyFactory;
184use crate::dom::types::{FontFace, ImageBitmap, MouseEvent, SVGSVGElement, UIEvent};
185use crate::dom::useractivation::UserActivationTimestamp;
186use crate::dom::visualviewport::{VisualViewport, VisualViewportChanges};
187#[cfg(feature = "webgpu")]
188use crate::dom::webgpu::identityhub::IdentityHub;
189use crate::dom::windowproxy::{WindowProxy, WindowProxyHandler};
190use crate::dom::worklet::Worklet;
191use crate::dom::workletglobalscope::WorkletGlobalScopeType;
192use crate::layout_image::fetch_image_for_layout;
193use crate::messaging::{MainThreadScriptMsg, ScriptEventLoopReceiver, ScriptEventLoopSender};
194use crate::microtask::UserMicrotask;
195use crate::network_listener::{ResourceTimingListener, submit_timing};
196use crate::realms::enter_auto_realm;
197use crate::script_runtime::Runtime;
198use crate::script_thread::ScriptThread;
199use crate::script_window_proxies::ScriptWindowProxies;
200use crate::task_manager::TaskManager;
201use crate::task_source::SendableTaskSource;
202use crate::timers::{IsInterval, OneshotTimers, TimerCallback};
203use crate::unminify::unminified_path;
204use crate::webdriver_handlers::{find_node_by_unique_id_in_document, jsval_to_webdriver};
205use crate::{fetch, window_named_properties};
206
207#[derive(MallocSizeOf)]
212pub struct PendingImageCallback(
213 #[ignore_malloc_size_of = "dyn Fn is currently impossible to measure"]
214 #[expect(clippy::type_complexity)]
215 Box<dyn Fn(PendingImageResponse, &mut JSContext) + 'static>,
216);
217
218#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
220enum WindowState {
221 Alive,
222 Zombie, }
224
225const INITIAL_REFLOW_DELAY: Duration = Duration::from_millis(200);
228
229#[derive(Clone, Copy, MallocSizeOf)]
240enum LayoutBlocker {
241 WaitingForParse,
243 Parsing(Instant),
245 FiredLoadEventOrParsingTimerExpired,
249}
250
251impl LayoutBlocker {
252 fn layout_blocked(&self) -> bool {
253 !matches!(self, Self::FiredLoadEventOrParsingTimerExpired)
254 }
255}
256
257#[derive(Clone, Copy, Debug, Default, JSTraceable, MallocSizeOf, PartialEq)]
260pub(crate) struct OngoingNavigation(u32);
261
262type PendingImageRasterizationKey = (PendingImageId, DeviceIntSize);
263
264#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
268#[derive(JSTraceable, MallocSizeOf)]
269struct PendingLayoutImageAncillaryData {
270 node: Dom<Node>,
271 #[no_trace]
272 destination: LayoutImageDestination,
273}
274
275#[dom_struct]
276pub(crate) struct Window {
277 globalscope: GlobalScope,
278
279 #[ignore_malloc_size_of = "Weak does not need to be accounted"]
283 #[no_trace]
284 weak_script_thread: Weak<ScriptThread>,
285
286 #[no_trace]
290 webview_id: WebViewId,
291 script_chan: Sender<MainThreadScriptMsg>,
292 #[no_trace]
293 #[ignore_malloc_size_of = "TODO: Add MallocSizeOf support to layout"]
294 layout: RefCell<Box<dyn Layout>>,
295 navigator: MutNullableDom<Navigator>,
296 crypto: MutNullableDom<Crypto>,
297 #[no_trace]
298 image_cache_sender: Sender<ImageCacheResponseMessage>,
299 window_proxy: MutNullableDom<WindowProxy>,
300 document: MutNullableDom<Document>,
301 location: MutNullableDom<Location>,
302 performance: MutNullableDom<Performance>,
303 #[no_trace]
304 navigation_start: Cell<CrossProcessInstant>,
305 screen: MutNullableDom<Screen>,
306 session_storage: MutNullableDom<Storage>,
307 local_storage: MutNullableDom<Storage>,
308 cookie_store: MutNullableDom<CookieStore>,
310 status: DomRefCell<DOMString>,
311 trusted_types: MutNullableDom<TrustedTypePolicyFactory>,
312
313 ongoing_navigation: Cell<OngoingNavigation>,
316
317 #[no_trace]
320 devtools_markers: DomRefCell<HashSet<TimelineMarkerType>>,
321 #[no_trace]
322 devtools_marker_sender: DomRefCell<Option<GenericSender<Option<TimelineMarker>>>>,
323
324 #[no_trace]
326 unhandled_resize_event: DomRefCell<Option<(ViewportDetails, WindowSizeType)>>,
327
328 #[no_trace]
332 viewport_details_at_last_resize_steps: Cell<ViewportDetails>,
333
334 #[no_trace]
336 theme: Cell<Theme>,
337
338 #[no_trace]
340 parent_info: Option<PipelineId>,
341
342 dom_static: GlobalStaticData,
344
345 #[conditional_malloc_size_of]
347 js_runtime: DomRefCell<Option<Rc<Runtime>>>,
348
349 #[no_trace]
351 viewport_details: Cell<ViewportDetails>,
352
353 #[no_trace]
355 #[cfg(feature = "bluetooth")]
356 bluetooth_thread: GenericSender<BluetoothRequest>,
357
358 #[cfg(feature = "bluetooth")]
359 bluetooth_extra_permission_data: BluetoothExtraPermissionData,
360
361 #[no_trace]
365 layout_blocker: Cell<LayoutBlocker>,
366
367 #[no_trace]
369 webdriver_script_chan: DomRefCell<Option<GenericSender<WebDriverJSResult>>>,
370
371 #[no_trace]
373 webdriver_load_status_sender: RefCell<Option<GenericSender<WebDriverLoadStatus>>>,
374
375 current_state: Cell<WindowState>,
377
378 error_reporter: CSSErrorReporter,
379
380 media_query_lists: DOMTracker<MediaQueryList>,
382
383 #[cfg(feature = "bluetooth")]
384 test_runner: MutNullableDom<TestRunner>,
385
386 #[no_trace]
388 webgl_chan: Option<WebGLChan>,
389
390 #[ignore_malloc_size_of = "defined in webxr"]
391 #[no_trace]
392 #[cfg(feature = "webxr")]
393 webxr_registry: Option<webxr_api::Registry>,
394
395 #[no_trace]
399 pending_image_callbacks: DomRefCell<FxHashMap<PendingImageId, Vec<PendingImageCallback>>>,
400
401 pending_layout_images: DomRefCell<
406 HashMapTracedValues<PendingImageId, Vec<PendingLayoutImageAncillaryData>, FxBuildHasher>,
407 >,
408
409 pending_images_for_rasterization: DomRefCell<
413 HashMapTracedValues<PendingImageRasterizationKey, Vec<Dom<Node>>, FxBuildHasher>,
414 >,
415
416 unminified_css_dir: DomRefCell<Option<String>>,
419
420 local_script_source: Option<String>,
422
423 test_worklet: MutNullableDom<Worklet>,
425 paint_worklet: MutNullableDom<Worklet>,
427
428 exists_mut_observer: Cell<bool>,
430
431 #[no_trace]
433 paint_api: CrossProcessPaintApi,
434
435 #[no_trace]
438 #[conditional_malloc_size_of]
439 user_scripts: Rc<Vec<UserScript>>,
440
441 #[ignore_malloc_size_of = "defined in script_thread"]
443 #[no_trace]
444 player_context: WindowGLContext,
445
446 throttled: Cell<bool>,
447
448 #[conditional_malloc_size_of]
452 layout_marker: DomRefCell<Rc<Cell<bool>>>,
453
454 current_event: DomRefCell<Option<Dom<Event>>>,
456
457 reporting_observer_list: DomRefCell<Vec<Dom<ReportingObserver>>>,
459
460 report_list: DomRefCell<Vec<Report>>,
462
463 #[no_trace]
465 endpoints_list: DomRefCell<Vec<ReportingEndpoint>>,
466
467 #[conditional_malloc_size_of]
469 script_window_proxies: Rc<ScriptWindowProxies>,
470
471 has_pending_screenshot_readiness_request: Cell<bool>,
473
474 visual_viewport: MutNullableDom<VisualViewport>,
477
478 has_changed_visual_viewport_dimension: Cell<bool>,
480
481 pending_media_query_evaluation: Cell<bool>,
486
487 #[no_trace]
489 last_activation_timestamp: Cell<UserActivationTimestamp>,
490
491 devtools_wants_updates: Cell<bool>,
494}
495
496impl Window {
497 pub(crate) fn script_thread(&self) -> Rc<ScriptThread> {
498 Weak::upgrade(&self.weak_script_thread)
499 .expect("Weak reference should always be upgradable when a ScriptThread is running")
500 }
501
502 pub(crate) fn webview_id(&self) -> WebViewId {
503 self.webview_id
504 }
505
506 pub(crate) fn as_global_scope(&self) -> &GlobalScope {
507 self.upcast::<GlobalScope>()
508 }
509
510 pub(crate) fn layout(&self) -> Ref<'_, Box<dyn Layout>> {
511 self.layout.borrow()
512 }
513
514 pub(crate) fn layout_mut(&self) -> RefMut<'_, Box<dyn Layout>> {
515 self.layout.borrow_mut()
516 }
517
518 pub(crate) fn get_exists_mut_observer(&self) -> bool {
519 self.exists_mut_observer.get()
520 }
521
522 pub(crate) fn set_exists_mut_observer(&self) {
523 self.exists_mut_observer.set(true);
524 }
525
526 #[expect(unsafe_code)]
527 pub(crate) fn clear_js_runtime_for_script_deallocation(&self) {
528 self.as_global_scope()
529 .remove_web_messaging_and_dedicated_workers_infra();
530 unsafe {
531 *self.js_runtime.borrow_for_script_deallocation() = None;
532 self.window_proxy.set(None);
533 self.current_state.set(WindowState::Zombie);
534 self.as_global_scope()
535 .task_manager()
536 .cancel_all_tasks_and_ignore_future_tasks();
537 }
538 }
539
540 pub(crate) fn discard_browsing_context(&self) {
543 let proxy = match self.window_proxy.get() {
544 Some(proxy) => proxy,
545 None => panic!("Discarding a BC from a window that has none"),
546 };
547 proxy.discard_browsing_context();
548 self.as_global_scope()
552 .task_manager()
553 .cancel_all_tasks_and_ignore_future_tasks();
554 }
555
556 pub(crate) fn time_profiler_chan(&self) -> &TimeProfilerChan {
558 self.globalscope.time_profiler_chan()
559 }
560
561 pub(crate) fn origin(&self) -> MutableOrigin {
563 self.Document().origin().clone()
565 }
566
567 pub(crate) fn main_thread_script_chan(&self) -> &Sender<MainThreadScriptMsg> {
568 &self.script_chan
569 }
570
571 pub(crate) fn parent_info(&self) -> Option<PipelineId> {
572 self.parent_info
573 }
574
575 pub(crate) fn new_script_pair(&self) -> (ScriptEventLoopSender, ScriptEventLoopReceiver) {
576 let (sender, receiver) = unbounded();
577 (
578 ScriptEventLoopSender::MainThread(sender),
579 ScriptEventLoopReceiver::MainThread(receiver),
580 )
581 }
582
583 pub(crate) fn event_loop_sender(&self) -> ScriptEventLoopSender {
584 ScriptEventLoopSender::MainThread(self.script_chan.clone())
585 }
586
587 pub(crate) fn image_cache(&self) -> Arc<dyn ImageCache> {
588 self.Document().image_cache()
589 }
590
591 pub(crate) fn window_proxy(&self) -> DomRoot<WindowProxy> {
593 self.window_proxy.get().unwrap()
594 }
595
596 pub(crate) fn append_reporting_observer(&self, reporting_observer: &ReportingObserver) {
597 self.reporting_observer_list
598 .borrow_mut()
599 .push(Dom::from_ref(reporting_observer));
600 }
601
602 pub(crate) fn remove_reporting_observer(&self, reporting_observer: &ReportingObserver) {
603 let index = {
604 let list = self.reporting_observer_list.borrow();
605 list.iter()
606 .position(|observer| &**observer == reporting_observer)
607 };
608
609 if let Some(index) = index {
610 self.reporting_observer_list.borrow_mut().remove(index);
611 }
612 }
613
614 pub(crate) fn registered_reporting_observers(&self) -> Vec<DomRoot<ReportingObserver>> {
615 self.reporting_observer_list
616 .borrow()
617 .iter()
618 .map(|observer| DomRoot::from_ref(&**observer))
619 .collect()
620 }
621
622 pub(crate) fn append_report(&self, report: Report) {
623 self.report_list.borrow_mut().push(report);
624 let trusted_window = Trusted::new(self);
625 self.upcast::<GlobalScope>()
626 .task_manager()
627 .dom_manipulation_task_source()
628 .queue(task!(send_to_reporting_endpoints: move || {
629 let window = trusted_window.root();
630 let reports = std::mem::take(&mut *window.report_list.borrow_mut());
631 window.upcast::<GlobalScope>().send_reports_to_endpoints(
632 reports,
633 window.endpoints_list.borrow().clone(),
634 );
635 }));
636 }
637
638 pub(crate) fn buffered_reports(&self) -> Vec<Report> {
639 self.report_list.borrow().clone()
640 }
641
642 pub(crate) fn set_endpoints_list(&self, endpoints: Vec<ReportingEndpoint>) {
643 *self.endpoints_list.borrow_mut() = endpoints;
644 }
645
646 pub(crate) fn undiscarded_window_proxy(&self) -> Option<DomRoot<WindowProxy>> {
649 self.window_proxy.get().and_then(|window_proxy| {
650 if window_proxy.is_browsing_context_discarded() {
651 None
652 } else {
653 Some(window_proxy)
654 }
655 })
656 }
657
658 pub(crate) fn top_level_document_if_local(&self) -> Option<DomRoot<Document>> {
663 if self.is_top_level() {
664 return Some(self.Document());
665 }
666
667 let window_proxy = self.undiscarded_window_proxy()?;
668 self.script_window_proxies
669 .find_window_proxy(window_proxy.webview_id().into())?
670 .document()
671 }
672
673 #[cfg(feature = "bluetooth")]
674 pub(crate) fn bluetooth_thread(&self) -> GenericSender<BluetoothRequest> {
675 self.bluetooth_thread.clone()
676 }
677
678 #[cfg(feature = "bluetooth")]
679 pub(crate) fn bluetooth_extra_permission_data(&self) -> &BluetoothExtraPermissionData {
680 &self.bluetooth_extra_permission_data
681 }
682
683 pub(crate) fn css_error_reporter(&self) -> &CSSErrorReporter {
684 &self.error_reporter
685 }
686
687 pub(crate) fn webgl_chan(&self) -> Option<WebGLChan> {
688 self.webgl_chan.clone()
689 }
690
691 pub(crate) fn webgl_chan_value(&self) -> Option<WebGLChan> {
693 self.webgl_chan.clone()
694 }
695
696 #[cfg(feature = "webxr")]
697 pub(crate) fn webxr_registry(&self) -> Option<webxr_api::Registry> {
698 self.webxr_registry.clone()
699 }
700
701 fn new_paint_worklet(&self, cx: &mut JSContext) -> DomRoot<Worklet> {
702 debug!("Creating new paint worklet.");
703 Worklet::new(cx, self, WorkletGlobalScopeType::Paint)
704 }
705
706 pub(crate) fn register_image_cache_listener(
707 &self,
708 id: PendingImageId,
709 callback: impl Fn(PendingImageResponse, &mut JSContext) + 'static,
710 ) -> ImageCacheResponseCallback {
711 self.pending_image_callbacks
712 .borrow_mut()
713 .entry(id)
714 .or_default()
715 .push(PendingImageCallback(Box::new(callback)));
716
717 let image_cache_sender = self.image_cache_sender.clone();
718 Box::new(move |message| {
719 let _ = image_cache_sender.send(message);
720 })
721 }
722
723 fn pending_layout_image_notification(&self, response: PendingImageResponse) {
724 let mut images = self.pending_layout_images.borrow_mut();
725 let nodes = images.entry(response.id);
726 let nodes = match nodes {
727 Entry::Occupied(nodes) => nodes,
728 Entry::Vacant(_) => return,
729 };
730 if matches!(
731 response.response,
732 ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode
733 ) {
734 for ancillary_data in nodes.get() {
735 match ancillary_data.destination {
736 LayoutImageDestination::BoxTreeConstruction => {
737 ancillary_data.node.dirty(NodeDamage::Other);
738 },
739 LayoutImageDestination::DisplayListBuilding => {
740 self.layout().set_needs_new_display_list();
741 },
742 }
743 }
744 }
745
746 match response.response {
747 ImageResponse::MetadataLoaded(_) => {},
748 ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode => {
749 nodes.remove();
750 },
751 }
752 }
753
754 pub(crate) fn handle_image_rasterization_complete_notification(
755 &self,
756 response: RasterizationCompleteResponse,
757 ) {
758 let mut images = self.pending_images_for_rasterization.borrow_mut();
759 let nodes = images.entry((response.image_id, response.requested_size));
760 let nodes = match nodes {
761 Entry::Occupied(nodes) => nodes,
762 Entry::Vacant(_) => return,
763 };
764 for node in nodes.get() {
765 node.dirty(NodeDamage::Other);
766 }
767 nodes.remove();
768 }
769
770 pub(crate) fn pending_image_notification(
771 &self,
772 response: PendingImageResponse,
773 cx: &mut JSContext,
774 ) {
775 let mut images = std::mem::take(&mut *self.pending_image_callbacks.borrow_mut());
780 let Entry::Occupied(callbacks) = images.entry(response.id) else {
781 let _ = std::mem::replace(&mut *self.pending_image_callbacks.borrow_mut(), images);
782 return;
783 };
784
785 for callback in callbacks.get() {
786 callback.0(response.clone(), cx);
787 }
788
789 match response.response {
790 ImageResponse::MetadataLoaded(_) => {},
791 ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode => {
792 callbacks.remove();
793 },
794 }
795
796 let _ = std::mem::replace(&mut *self.pending_image_callbacks.borrow_mut(), images);
797 }
798
799 pub(crate) fn paint_api(&self) -> &CrossProcessPaintApi {
800 &self.paint_api
801 }
802
803 pub(crate) fn userscripts(&self) -> &[UserScript] {
804 &self.user_scripts
805 }
806
807 pub(crate) fn get_player_context(&self) -> WindowGLContext {
808 self.player_context.clone()
809 }
810
811 pub(crate) fn dispatch_event_with_target_override(&self, cx: &mut JSContext, event: &Event) {
813 event.dispatch(cx, self.upcast(), true);
814 }
815
816 pub(crate) fn font_context(&self) -> &Arc<FontContext> {
817 self.as_global_scope()
818 .font_context()
819 .expect("A `Window` should always have a `FontContext`")
820 }
821
822 pub(crate) fn ongoing_navigation(&self) -> OngoingNavigation {
823 self.ongoing_navigation.get()
824 }
825
826 pub(crate) fn set_ongoing_navigation(&self) -> OngoingNavigation {
828 let new_value = self.ongoing_navigation.get().0.wrapping_add(1);
832
833 self.ongoing_navigation.set(OngoingNavigation(new_value));
840
841 OngoingNavigation(new_value)
843 }
844
845 fn stop_loading(&self, cx: &mut JSContext) {
847 let doc = self.Document();
849
850 self.set_ongoing_navigation();
860
861 doc.abort_a_document_and_its_descendants(cx);
863 }
864
865 fn destroy_top_level_traversable(&self, cx: &mut JSContext) {
867 let document = self.Document();
873 document.destroy_document_and_its_descendants(cx);
875 self.send_to_constellation(ScriptToConstellationMessage::DiscardTopLevelBrowsingContext);
877 }
878
879 fn definitely_close(&self, cx: &mut JSContext) {
881 let document = self.Document();
882 if !document.check_if_unloading_is_cancelled(cx, false) {
887 return;
888 }
889 document.unload(cx, false);
893 self.destroy_top_level_traversable(cx);
895 }
896
897 fn cannot_show_simple_dialogs(&self) -> bool {
899 if self
902 .Document()
903 .has_active_sandboxing_flag(SandboxingFlagSet::SANDBOXED_MODALS_FLAG)
904 {
905 return true;
906 }
907
908 false
927 }
928
929 pub(crate) fn perform_a_microtask_checkpoint(&self, cx: &mut JSContext) {
930 self.script_thread().perform_a_microtask_checkpoint(cx);
931 }
932
933 pub(crate) fn web_font_context(&self, no_gc: &NoGC) -> WebFontDocumentContext {
934 let global = self.as_global_scope();
935 let task_source = global
936 .task_manager()
937 .dom_manipulation_task_source()
938 .to_sendable();
939 let target_global = Trusted::new(global);
940 let document = self.document_unrooted(no_gc);
941 WebFontDocumentContext {
942 policy_container: document.policy_container().clone(),
943 request_client: self.request_client(Some(no_gc)),
944 document_url: document.base_url(),
945 csp_handler: Box::new(FontCspHandler {
946 global: target_global.clone(),
947 task_source: task_source.clone(),
948 }),
949 network_timing_handler: Box::new(FontNetworkTimingHandler {
950 global: target_global,
951 task_source,
952 }),
953 }
954 }
955
956 pub(crate) fn request_client(&self, no_gc: Option<&NoGC>) -> RequestClient {
958 let (
961 preloaded_resources,
962 insecure_requests_policy,
963 has_trustworthy_ancestor_origin,
964 policy_container,
965 origin,
966 ) = if let Some(no_gc) = no_gc {
967 let document = self.document_unrooted(no_gc);
968 (
969 document.preloaded_resources().clone(),
970 document.insecure_requests_policy(),
971 document.has_trustworthy_ancestor_or_current_origin(),
972 document.policy_container().clone(),
973 document.origin().clone(),
974 )
975 } else {
976 let document = self.Document();
977 (
978 document.preloaded_resources().clone(),
979 document.insecure_requests_policy(),
980 document.has_trustworthy_ancestor_or_current_origin(),
981 document.policy_container().clone(),
982 document.origin().clone(),
983 )
984 };
985 RequestClient {
986 preloaded_resources,
987 policy_container,
988 origin: Origin::Origin(origin.immutable().clone()),
989 is_nested_browsing_context: !self.is_top_level(),
990 insecure_requests_policy,
991 has_trustworthy_ancestor_origin,
992 }
993 }
994
995 #[expect(unsafe_code)]
996 pub(crate) fn gc(&self, cx: &mut JSContext) {
997 unsafe { JS_GC(cx, GCReason::API) };
998 }
999
1000 pub(crate) fn with_timers<T>(&self, f: impl FnOnce(&OneshotTimers) -> T) -> T {
1001 let document = self.Document();
1002 f(document.timers())
1003 }
1004}
1005
1006#[derive(Debug, MallocSizeOf)]
1007struct FontCspHandler {
1008 global: Trusted<GlobalScope>,
1009 task_source: SendableTaskSource,
1010}
1011
1012impl CspViolationHandler for FontCspHandler {
1013 fn process_violations(&self, violations: Vec<Violation>) {
1014 let global = self.global.clone();
1015 self.task_source.queue(task!(csp_violation: move |cx| {
1016 global.root().report_csp_violations(cx, violations, None, None);
1017 }));
1018 }
1019
1020 fn clone(&self) -> Box<dyn CspViolationHandler> {
1021 Box::new(Self {
1022 global: self.global.clone(),
1023 task_source: self.task_source.clone(),
1024 })
1025 }
1026}
1027
1028#[derive(Debug, MallocSizeOf)]
1029struct FontNetworkTimingHandler {
1030 global: Trusted<GlobalScope>,
1031 task_source: SendableTaskSource,
1032}
1033
1034impl NetworkTimingHandler for FontNetworkTimingHandler {
1035 fn submit_timing(&self, url: ServoUrl, response: ResourceFetchTiming) {
1036 let global = self.global.clone();
1037 self.task_source.queue(task!(network_timing: move |cx| {
1038 submit_timing(
1039 cx,
1040 &FontFetchListener {
1041 url,
1042 global
1043 },
1044 &Ok(()),
1045 &response,
1046 );
1047 }));
1048 }
1049
1050 fn clone(&self) -> Box<dyn NetworkTimingHandler> {
1051 Box::new(Self {
1052 global: self.global.clone(),
1053 task_source: self.task_source.clone(),
1054 })
1055 }
1056}
1057
1058#[derive(Debug)]
1059struct FontFetchListener {
1060 global: Trusted<GlobalScope>,
1061 url: ServoUrl,
1062}
1063
1064impl ResourceTimingListener for FontFetchListener {
1065 fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
1066 (InitiatorType::Css, self.url.clone())
1067 }
1068
1069 fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
1070 self.global.root()
1071 }
1072}
1073
1074pub(crate) fn base64_btoa(input: DOMString) -> Fallible<DOMString> {
1076 if input.str().chars().any(|c: char| c > '\u{FF}') {
1080 Err(Error::InvalidCharacter(None))
1081 } else {
1082 let octets = input
1087 .str()
1088 .chars()
1089 .map(|c: char| c as u8)
1090 .collect::<Vec<u8>>();
1091
1092 let config =
1095 base64::engine::general_purpose::GeneralPurposeConfig::new().with_encode_padding(true);
1096 let engine = base64::engine::GeneralPurpose::new(&base64::alphabet::STANDARD, config);
1097 Ok(DOMString::from(engine.encode(octets)))
1098 }
1099}
1100
1101pub(crate) fn base64_atob(input: DOMString) -> Fallible<DOMString> {
1103 fn is_html_space(c: char) -> bool {
1105 HTML_SPACE_CHARACTERS.contains(&c)
1106 }
1107 let without_spaces = input
1108 .str()
1109 .chars()
1110 .filter(|&c| !is_html_space(c))
1111 .collect::<String>();
1112 let mut input = &*without_spaces;
1113
1114 if input.len() % 4 == 0 {
1118 if input.ends_with("==") {
1119 input = &input[..input.len() - 2]
1120 } else if input.ends_with('=') {
1121 input = &input[..input.len() - 1]
1122 }
1123 }
1124
1125 if input.len() % 4 == 1 {
1128 return Err(Error::InvalidCharacter(None));
1129 }
1130
1131 if input
1139 .chars()
1140 .any(|c| c != '+' && c != '/' && !c.is_alphanumeric())
1141 {
1142 return Err(Error::InvalidCharacter(None));
1143 }
1144
1145 let config = base64::engine::general_purpose::GeneralPurposeConfig::new()
1146 .with_decode_padding_mode(base64::engine::DecodePaddingMode::RequireNone)
1147 .with_decode_allow_trailing_bits(true);
1148 let engine = base64::engine::GeneralPurpose::new(&base64::alphabet::STANDARD, config);
1149
1150 let data = engine
1151 .decode(input)
1152 .map_err(|_| Error::InvalidCharacter(None))?;
1153 Ok(data.iter().map(|&b| b as char).collect::<String>().into())
1154}
1155
1156impl WindowMethods<crate::DomTypeHolder> for Window {
1157 fn Alert_(&self) {
1159 self.Alert(DOMString::new());
1162 }
1163
1164 fn Alert(&self, mut message: DOMString) {
1166 if self.cannot_show_simple_dialogs() {
1168 return;
1169 }
1170
1171 message.normalize_newlines();
1175
1176 {
1187 let stderr = stderr();
1191 let mut stderr = stderr.lock();
1192 let stdout = stdout();
1193 let mut stdout = stdout.lock();
1194 writeln!(&mut stdout, "\nALERT: {message}").unwrap();
1195 stdout.flush().unwrap();
1196 stderr.flush().unwrap();
1197 }
1198
1199 let (sender, receiver) =
1200 ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1201 let dialog = SimpleDialogRequest::Alert {
1202 id: self.Document().embedder_controls().next_control_id(),
1203 message: String::from(message),
1204 response_sender: sender,
1205 };
1206 self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1207 receiver.recv().unwrap_or_else(|_| {
1208 debug!("Alert dialog was cancelled or failed to show.");
1210 AlertResponse::Ok
1211 });
1212
1213 }
1216
1217 fn Confirm(&self, mut message: DOMString) -> bool {
1219 if self.cannot_show_simple_dialogs() {
1221 return false;
1222 }
1223
1224 message.normalize_newlines();
1226
1227 let (sender, receiver) =
1233 ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1234 let dialog = SimpleDialogRequest::Confirm {
1235 id: self.Document().embedder_controls().next_control_id(),
1236 message: String::from(message),
1237 response_sender: sender,
1238 };
1239 self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1240
1241 match receiver.recv() {
1257 Ok(ConfirmResponse::Ok) => true,
1258 Ok(ConfirmResponse::Cancel) => false,
1259 Err(_) => {
1260 warn!("Confirm dialog was cancelled or failed to show.");
1261 false
1262 },
1263 }
1264 }
1265
1266 fn Prompt(&self, mut message: DOMString, default: DOMString) -> Option<DOMString> {
1268 if self.cannot_show_simple_dialogs() {
1270 return None;
1271 }
1272
1273 message.normalize_newlines();
1275
1276 let (sender, receiver) =
1284 ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1285 let dialog = SimpleDialogRequest::Prompt {
1286 id: self.Document().embedder_controls().next_control_id(),
1287 message: String::from(message),
1288 default: String::from(default),
1289 response_sender: sender,
1290 };
1291 self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1292
1293 match receiver.recv() {
1312 Ok(PromptResponse::Ok(input)) => Some(input.into()),
1313 Ok(PromptResponse::Cancel) => None,
1314 Err(_) => {
1315 warn!("Prompt dialog was cancelled or failed to show.");
1316 None
1317 },
1318 }
1319 }
1320
1321 fn Stop(&self, cx: &mut JSContext) {
1323 self.stop_loading(cx);
1328 }
1329
1330 fn Focus(&self, cx: &mut JSContext) {
1332 let document = self.Document();
1341 if !document.is_active() || self.undiscarded_window_proxy().is_none() {
1342 return;
1343 }
1344
1345 document.focus_handler().focus(cx, FocusableArea::Viewport);
1350
1351 }
1356
1357 fn Blur(&self) {
1359 }
1362
1363 fn Open(
1365 &self,
1366 cx: &mut JSContext,
1367 url: USVString,
1368 target: DOMString,
1369 features: DOMString,
1370 ) -> Fallible<Option<DomRoot<WindowProxy>>> {
1371 self.window_proxy().open(cx, url, target, features)
1372 }
1373
1374 fn GetOpener(&self, cx: &mut CurrentRealm, mut retval: MutableHandleValue) -> Fallible<()> {
1376 let current = match self.window_proxy.get() {
1378 Some(proxy) => proxy,
1379 None => {
1381 retval.set(NullValue());
1382 return Ok(());
1383 },
1384 };
1385 if current.is_browsing_context_discarded() {
1390 retval.set(NullValue());
1391 return Ok(());
1392 }
1393 current.opener(cx, retval);
1395 Ok(())
1396 }
1397
1398 #[expect(unsafe_code)]
1399 fn SetOpener(&self, cx: &mut JSContext, value: HandleValue) -> ErrorResult {
1401 if value.is_null() {
1403 if let Some(proxy) = self.window_proxy.get() {
1404 proxy.disown();
1405 }
1406 return Ok(());
1407 }
1408
1409 let obj = self.reflector().get_jsobject();
1411 let result = unsafe {
1412 JS_DefineProperty(cx, obj, c"opener".as_ptr(), value, JSPROP_ENUMERATE as u32)
1413 };
1414
1415 if result { Ok(()) } else { Err(Error::JSFailed) }
1416 }
1417
1418 fn Closed(&self) -> bool {
1420 self.window_proxy
1421 .get()
1422 .map(|ref proxy| proxy.is_browsing_context_discarded() || proxy.is_closing())
1423 .unwrap_or(true)
1424 }
1425
1426 fn Close(&self, cx: &mut JSContext) {
1428 let window_proxy = match self.window_proxy.get() {
1430 Some(proxy) => proxy,
1431 None => return,
1433 };
1434 if window_proxy.is_closing() {
1436 return;
1437 }
1438 if let Ok(history_length) = self.History(cx).GetLength() {
1441 let is_auxiliary = window_proxy.is_auxiliary();
1442
1443 let is_script_closable = (self.is_top_level() && history_length == 1) ||
1445 is_auxiliary ||
1446 pref!(dom_allow_scripts_to_close_windows);
1447
1448 if is_script_closable {
1452 window_proxy.close();
1454
1455 let this = Trusted::new(self);
1457 let task = task!(window_close_browsing_context: move |cx| {
1458 let window = this.root();
1459 window.definitely_close(cx);
1460 });
1461 self.as_global_scope()
1462 .task_manager()
1463 .dom_manipulation_task_source()
1464 .queue(task);
1465 }
1466 }
1467 }
1468
1469 fn Document(&self) -> DomRoot<Document> {
1471 self.document
1472 .get()
1473 .expect("Document accessed before initialization.")
1474 }
1475
1476 fn History(&self, cx: &mut JSContext) -> DomRoot<History> {
1478 self.Document().history(cx)
1479 }
1480
1481 fn IndexedDB(&self, cx: &mut JSContext) -> DomRoot<IDBFactory> {
1483 self.upcast::<GlobalScope>().ensure_indexeddb_factory(cx)
1484 }
1485
1486 fn CustomElements(&self, cx: &mut JSContext) -> DomRoot<CustomElementRegistry> {
1488 let document = self.Document();
1491 if let Some(registry) = document.custom_element_registry() {
1492 return registry;
1493 }
1494 let registry = CustomElementRegistry::new(cx, self);
1497 document.set_custom_element_registry(®istry);
1498 registry
1500 }
1501
1502 fn Location(&self, cx: &mut JSContext) -> DomRoot<Location> {
1504 self.location.or_init(|| Location::new(cx, self))
1505 }
1506
1507 fn GetSessionStorage(&self, cx: &mut JSContext) -> Fallible<DomRoot<Storage>> {
1509 if let Some(storage) = self.session_storage.get() {
1512 return Ok(storage);
1513 }
1514
1515 if !self.origin().is_tuple() {
1519 return Err(Error::Security(Some(
1520 "Cannot access sessionStorage from opaque origin.".to_string(),
1521 )));
1522 }
1523
1524 let storage = Storage::new(cx, self, WebStorageType::Session);
1526
1527 self.session_storage.set(Some(&storage));
1529
1530 Ok(storage)
1532 }
1533
1534 fn GetLocalStorage(&self, cx: &mut JSContext) -> Fallible<DomRoot<Storage>> {
1536 if let Some(storage) = self.local_storage.get() {
1539 return Ok(storage);
1540 }
1541
1542 if !self.origin().is_tuple() {
1546 return Err(Error::Security(Some(
1547 "Cannot access localStorage from opaque origin.".to_string(),
1548 )));
1549 }
1550
1551 let storage = Storage::new(cx, self, WebStorageType::Local);
1553
1554 self.local_storage.set(Some(&storage));
1556
1557 Ok(storage)
1559 }
1560
1561 fn CookieStore(&self, cx: &mut JSContext) -> DomRoot<CookieStore> {
1563 self.cookie_store
1564 .or_init(|| CookieStore::new(cx, self.upcast::<GlobalScope>()))
1565 }
1566
1567 fn Crypto(&self, cx: &mut JSContext) -> DomRoot<Crypto> {
1569 self.crypto
1570 .or_init(|| Crypto::new(cx, self.as_global_scope()))
1571 }
1572
1573 fn GetFrameElement(&self) -> Option<DomRoot<Element>> {
1575 let window_proxy = self.window_proxy.get()?;
1577
1578 let container = window_proxy.frame_element()?;
1580
1581 let container_doc = container.owner_document();
1583 let current_doc = GlobalScope::current()
1584 .expect("No current global object")
1585 .as_window()
1586 .Document();
1587 if !current_doc
1588 .origin()
1589 .same_origin_domain(&container_doc.origin())
1590 {
1591 return None;
1592 }
1593 Some(DomRoot::from_ref(container))
1595 }
1596
1597 fn ReportError(&self, cx: &mut JSContext, error: HandleValue) {
1599 self.as_global_scope().report_an_exception(cx, error);
1600 }
1601
1602 fn Navigator(&self, cx: &mut JSContext) -> DomRoot<Navigator> {
1604 self.navigator.or_init(|| Navigator::new(cx, self))
1605 }
1606
1607 fn ClientInformation(&self, cx: &mut JSContext) -> DomRoot<Navigator> {
1609 self.Navigator(cx)
1610 }
1611
1612 fn SetTimeout(
1614 &self,
1615 cx: &mut JSContext,
1616 callback: TrustedScriptOrStringOrFunction,
1617 timeout: i32,
1618 args: Vec<HandleValue>,
1619 ) -> Fallible<i32> {
1620 let callback = match callback {
1621 TrustedScriptOrStringOrFunction::String(i) => {
1622 TimerCallback::StringTimerCallback(TrustedScriptOrString::String(i))
1623 },
1624 TrustedScriptOrStringOrFunction::TrustedScript(i) => {
1625 TimerCallback::StringTimerCallback(TrustedScriptOrString::TrustedScript(i))
1626 },
1627 TrustedScriptOrStringOrFunction::Function(i) => TimerCallback::FunctionTimerCallback(i),
1628 };
1629 self.as_global_scope().set_timeout_or_interval(
1630 cx,
1631 callback,
1632 args,
1633 Duration::from_millis(timeout.max(0) as u64),
1634 IsInterval::NonInterval,
1635 )
1636 }
1637
1638 fn ClearTimeout(&self, handle: i32) {
1640 self.as_global_scope().clear_timeout_or_interval(handle);
1641 }
1642
1643 fn SetInterval(
1645 &self,
1646 cx: &mut JSContext,
1647 callback: TrustedScriptOrStringOrFunction,
1648 timeout: i32,
1649 args: Vec<HandleValue>,
1650 ) -> Fallible<i32> {
1651 let callback = match callback {
1652 TrustedScriptOrStringOrFunction::String(i) => {
1653 TimerCallback::StringTimerCallback(TrustedScriptOrString::String(i))
1654 },
1655 TrustedScriptOrStringOrFunction::TrustedScript(i) => {
1656 TimerCallback::StringTimerCallback(TrustedScriptOrString::TrustedScript(i))
1657 },
1658 TrustedScriptOrStringOrFunction::Function(i) => TimerCallback::FunctionTimerCallback(i),
1659 };
1660 self.as_global_scope().set_timeout_or_interval(
1661 cx,
1662 callback,
1663 args,
1664 Duration::from_millis(timeout.max(0) as u64),
1665 IsInterval::Interval,
1666 )
1667 }
1668
1669 fn ClearInterval(&self, handle: i32) {
1671 self.ClearTimeout(handle);
1672 }
1673
1674 fn QueueMicrotask(&self, cx: &JSContext, callback: Rc<VoidFunction>) {
1676 ScriptThread::enqueue_microtask(
1677 cx,
1678 Box::new(UserMicrotask {
1679 callback,
1680 global: Dom::from_ref(&self.globalscope),
1681 }),
1682 );
1683 }
1684
1685 fn CreateImageBitmap(
1687 &self,
1688 realm: &mut CurrentRealm,
1689 image: ImageBitmapSource,
1690 options: &ImageBitmapOptions,
1691 ) -> Rc<Promise> {
1692 ImageBitmap::create_image_bitmap(
1693 self.as_global_scope(),
1694 image,
1695 0,
1696 0,
1697 None,
1698 None,
1699 options,
1700 realm,
1701 )
1702 }
1703
1704 fn CreateImageBitmap_(
1706 &self,
1707 realm: &mut CurrentRealm,
1708 image: ImageBitmapSource,
1709 sx: i32,
1710 sy: i32,
1711 sw: i32,
1712 sh: i32,
1713 options: &ImageBitmapOptions,
1714 ) -> Rc<Promise> {
1715 ImageBitmap::create_image_bitmap(
1716 self.as_global_scope(),
1717 image,
1718 sx,
1719 sy,
1720 Some(sw),
1721 Some(sh),
1722 options,
1723 realm,
1724 )
1725 }
1726
1727 fn Window(&self) -> DomRoot<WindowProxy> {
1729 self.window_proxy()
1730 }
1731
1732 fn Self_(&self) -> DomRoot<WindowProxy> {
1734 self.window_proxy()
1735 }
1736
1737 fn Frames(&self) -> DomRoot<WindowProxy> {
1739 self.window_proxy()
1740 }
1741
1742 fn Length(&self) -> u32 {
1744 self.Document().iframes().iter().count() as u32
1745 }
1746
1747 fn GetParent(&self) -> Option<DomRoot<WindowProxy>> {
1749 let window_proxy = self.undiscarded_window_proxy()?;
1751
1752 if let Some(parent) = window_proxy.parent() {
1754 return Some(DomRoot::from_ref(parent));
1755 }
1756 Some(window_proxy)
1758 }
1759
1760 fn GetTop(&self) -> Option<DomRoot<WindowProxy>> {
1762 let window_proxy = self.undiscarded_window_proxy()?;
1764
1765 Some(DomRoot::from_ref(window_proxy.top()))
1767 }
1768
1769 fn Performance(&self, cx: &mut JSContext) -> DomRoot<Performance> {
1772 self.performance
1773 .or_init(|| Performance::new(cx, self.as_global_scope(), self.navigation_start.get()))
1774 }
1775
1776 global_event_handlers!();
1778
1779 window_event_handlers!();
1781
1782 fn Screen(&self, cx: &mut JSContext) -> DomRoot<Screen> {
1784 self.screen.or_init(|| Screen::new(cx, self))
1785 }
1786
1787 fn GetVisualViewport(&self, cx: &mut JSContext) -> Option<DomRoot<VisualViewport>> {
1789 if !self.Document().is_fully_active() {
1793 return None;
1794 }
1795
1796 Some(self.get_or_init_visual_viewport(cx))
1797 }
1798
1799 fn Btoa(&self, btoa: DOMString) -> Fallible<DOMString> {
1801 base64_btoa(btoa)
1802 }
1803
1804 fn Atob(&self, atob: DOMString) -> Fallible<DOMString> {
1806 base64_atob(atob)
1807 }
1808
1809 fn RequestAnimationFrame(&self, callback: Rc<FrameRequestCallback>) -> u32 {
1811 self.Document()
1812 .request_animation_frame(AnimationFrameCallback::FrameRequestCallback { callback })
1813 }
1814
1815 fn CancelAnimationFrame(&self, ident: u32) {
1817 let doc = self.Document();
1818 doc.cancel_animation_frame(ident);
1819 }
1820
1821 fn PostMessage(
1823 &self,
1824 cx: &mut JSContext,
1825 message: HandleValue,
1826 target_origin: USVString,
1827 transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
1828 ) -> ErrorResult {
1829 let incumbent = GlobalScope::incumbent().expect("no incumbent global?");
1830 let source = incumbent.as_window();
1831 let source_origin = source.Document().origin().immutable().clone();
1832
1833 self.post_message_impl(&target_origin, source_origin, source, cx, message, transfer)
1834 }
1835
1836 fn PostMessage_(
1838 &self,
1839 cx: &mut JSContext,
1840 message: HandleValue,
1841 options: RootedTraceableBox<WindowPostMessageOptions>,
1842 ) -> ErrorResult {
1843 let mut rooted = CustomAutoRooter::new(
1844 options
1845 .parent
1846 .transfer
1847 .iter()
1848 .map(|js: &RootedTraceableBox<Heap<*mut JSObject>>| js.get())
1849 .collect(),
1850 );
1851 #[expect(unsafe_code)]
1852 let transfer = unsafe { CustomAutoRooterGuard::new(cx.raw_cx(), &mut rooted) };
1853
1854 let incumbent = GlobalScope::incumbent().expect("no incumbent global?");
1855 let source = incumbent.as_window();
1856
1857 let source_origin = source.Document().origin().immutable().clone();
1858
1859 self.post_message_impl(
1860 &options.targetOrigin,
1861 source_origin,
1862 source,
1863 cx,
1864 message,
1865 transfer,
1866 )
1867 }
1868
1869 fn CaptureEvents(&self) {
1871 }
1873
1874 fn ReleaseEvents(&self) {
1876 }
1878
1879 fn WebdriverCallback(&self, realm: &mut CurrentRealm, value: HandleValue) {
1881 let webdriver_script_sender = self.webdriver_script_chan.borrow_mut().take();
1882 if let Some(webdriver_script_sender) = webdriver_script_sender {
1883 let result = jsval_to_webdriver(realm, &self.globalscope, value);
1884 let _ = webdriver_script_sender.send(result);
1885 }
1886 }
1887
1888 fn WebdriverException(&self, cx: &mut JSContext, value: HandleValue) {
1889 let webdriver_script_sender = self.webdriver_script_chan.borrow_mut().take();
1890 if let Some(webdriver_script_sender) = webdriver_script_sender {
1891 let error_info = ErrorInfo::from_value(cx, value);
1892 let _ = webdriver_script_sender.send(Err(
1893 JavaScriptEvaluationError::EvaluationFailure(Some(
1894 javascript_error_info_from_error_info(cx, &error_info, value),
1895 )),
1896 ));
1897 }
1898 }
1899
1900 fn WebdriverElement(&self, id: DOMString) -> Option<DomRoot<Element>> {
1901 find_node_by_unique_id_in_document(&self.Document(), id.into()).and_then(Root::downcast)
1902 }
1903
1904 fn WebdriverFrame(&self, browsing_context_id: DOMString) -> Option<DomRoot<WindowProxy>> {
1905 self.Document()
1906 .iframes()
1907 .iter()
1908 .find(|iframe| {
1909 iframe
1910 .browsing_context_id()
1911 .as_ref()
1912 .map(BrowsingContextId::to_string) ==
1913 Some(browsing_context_id.to_string())
1914 })
1915 .and_then(|iframe| iframe.GetContentWindow())
1916 }
1917
1918 fn WebdriverWindow(&self, webview_id: DOMString) -> DomRoot<WindowProxy> {
1919 let window_proxy = &self
1920 .window_proxy
1921 .get()
1922 .expect("Should always have a WindowProxy when calling WebdriverWindow");
1923 assert!(
1924 self.is_top_level(),
1925 "Window must be top level browsing context."
1926 );
1927 assert!(self.webview_id().to_string() == webview_id);
1928 DomRoot::from_ref(window_proxy)
1929 }
1930
1931 fn WebdriverShadowRoot(&self, id: DOMString) -> Option<DomRoot<ShadowRoot>> {
1932 find_node_by_unique_id_in_document(&self.Document(), id.into()).and_then(Root::downcast)
1933 }
1934
1935 fn GetComputedStyle(
1937 &self,
1938 cx: &mut JSContext,
1939 element: &Element,
1940 pseudo: Option<DOMString>,
1941 ) -> DomRoot<CSSStyleDeclaration> {
1942 let mut is_null = false;
1946
1947 let pseudo = pseudo.map(|mut s| {
1953 s.make_ascii_lowercase();
1954 s
1955 });
1956 let pseudo = match pseudo {
1957 Some(ref pseudo) if pseudo == ":before" || pseudo == "::before" => {
1958 Some(PseudoElement::Before)
1959 },
1960 Some(ref pseudo) if pseudo == ":after" || pseudo == "::after" => {
1961 Some(PseudoElement::After)
1962 },
1963 Some(ref pseudo) if pseudo == "::selection" => Some(PseudoElement::Selection),
1964 Some(ref pseudo) if pseudo == "::marker" => Some(PseudoElement::Marker),
1965 Some(ref pseudo) if pseudo == "::placeholder" => Some(PseudoElement::Placeholder),
1966 Some(ref pseudo) if pseudo.starts_with(':') => {
1967 is_null = true;
1970 None
1971 },
1972 _ => None,
1973 };
1974
1975 CSSStyleDeclaration::new(
1991 cx,
1992 self,
1993 if is_null {
1994 CSSStyleOwner::Null
1995 } else {
1996 CSSStyleOwner::Element(Dom::from_ref(element))
1997 },
1998 pseudo,
1999 CSSModificationAccess::Readonly,
2000 )
2001 }
2002
2003 fn InnerHeight(&self) -> i32 {
2006 self.viewport_details
2007 .get()
2008 .size
2009 .height
2010 .to_i32()
2011 .unwrap_or(0)
2012 }
2013
2014 fn InnerWidth(&self) -> i32 {
2017 self.viewport_details.get().size.width.to_i32().unwrap_or(0)
2018 }
2019
2020 fn ScrollX(&self) -> i32 {
2022 self.scroll_offset().x as i32
2023 }
2024
2025 fn PageXOffset(&self) -> i32 {
2027 self.ScrollX()
2028 }
2029
2030 fn ScrollY(&self) -> i32 {
2032 self.scroll_offset().y as i32
2033 }
2034
2035 fn PageYOffset(&self) -> i32 {
2037 self.ScrollY()
2038 }
2039
2040 fn Scroll(&self, cx: &mut JSContext, options: &ScrollToOptions) {
2042 let x = options.left.unwrap_or(0.0) as f32;
2047
2048 let y = options.top.unwrap_or(0.0) as f32;
2051
2052 self.scroll(cx, x, y, options.parent.behavior);
2054 }
2055
2056 fn Scroll_(&self, cx: &mut JSContext, x: f64, y: f64) {
2058 self.scroll(cx, x as f32, y as f32, ScrollBehavior::Auto);
2062 }
2063
2064 fn ScrollTo(&self, cx: &mut JSContext, options: &ScrollToOptions) {
2069 self.Scroll(cx, options);
2070 }
2071
2072 fn ScrollTo_(&self, cx: &mut JSContext, x: f64, y: f64) {
2077 self.Scroll_(cx, x, y)
2078 }
2079
2080 fn ScrollBy(&self, cx: &mut JSContext, options: &ScrollToOptions) {
2082 let mut options = options.clone();
2088 let x = options.left.unwrap_or(0.0);
2089 let x = if x.is_finite() { x } else { 0.0 };
2090 let y = options.top.unwrap_or(0.0);
2091 let y = if y.is_finite() { y } else { 0.0 };
2092
2093 options.left.replace(x + self.ScrollX() as f64);
2095
2096 options.top.replace(y + self.ScrollY() as f64);
2098
2099 self.Scroll(cx, &options)
2101 }
2102
2103 fn ScrollBy_(&self, cx: &mut JSContext, x: f64, y: f64) {
2105 let mut options = ScrollToOptions::empty();
2109
2110 options.left.replace(x);
2113
2114 options.top.replace(y);
2116
2117 self.ScrollBy(cx, &options);
2119 }
2120
2121 fn ResizeTo(&self, width: i32, height: i32) {
2123 let window_proxy = match self.window_proxy.get() {
2125 Some(proxy) => proxy,
2126 None => return,
2127 };
2128
2129 if !window_proxy.is_auxiliary() {
2132 return;
2133 }
2134
2135 let dpr = self.device_pixel_ratio();
2136 let size = Size2D::new(width, height).to_f32() * dpr;
2137 self.send_to_embedder(EmbedderMsg::ResizeTo(self.webview_id(), size.to_i32()));
2138 }
2139
2140 fn ResizeBy(&self, x: i32, y: i32) {
2142 let size = self.client_window().size();
2143 self.ResizeTo(x + size.width, y + size.height)
2145 }
2146
2147 fn MoveTo(&self, x: i32, y: i32) {
2149 let dpr = self.device_pixel_ratio();
2152 let point = Point2D::new(x, y).to_f32() * dpr;
2153 let msg = EmbedderMsg::MoveTo(self.webview_id(), point.to_i32());
2154 self.send_to_embedder(msg);
2155 }
2156
2157 fn MoveBy(&self, x: i32, y: i32) {
2159 let origin = self.client_window().min;
2160 self.MoveTo(x + origin.x, y + origin.y)
2162 }
2163
2164 fn ScreenX(&self) -> i32 {
2166 self.client_window().min.x
2167 }
2168
2169 fn ScreenLeft(&self) -> i32 {
2171 self.client_window().min.x
2172 }
2173
2174 fn ScreenY(&self) -> i32 {
2176 self.client_window().min.y
2177 }
2178
2179 fn ScreenTop(&self) -> i32 {
2181 self.client_window().min.y
2182 }
2183
2184 fn OuterHeight(&self) -> i32 {
2186 self.client_window().height()
2187 }
2188
2189 fn OuterWidth(&self) -> i32 {
2191 self.client_window().width()
2192 }
2193
2194 fn DevicePixelRatio(&self) -> Finite<f64> {
2196 Finite::wrap(self.device_pixel_ratio().get() as f64)
2197 }
2198
2199 fn Status(&self) -> DOMString {
2201 self.status.borrow().clone()
2202 }
2203
2204 fn SetStatus(&self, status: DOMString) {
2206 *self.status.borrow_mut() = status
2207 }
2208
2209 fn MatchMedia(&self, cx: &mut JSContext, query: DOMString) -> DomRoot<MediaQueryList> {
2211 let media_query_list = MediaList::parse_media_list(&query.str(), self);
2212 let document = self.Document();
2213 let mql = MediaQueryList::new(cx, &document, media_query_list);
2214 self.media_query_lists.track(&*mql);
2215 mql
2216 }
2217
2218 fn Fetch(
2220 &self,
2221 realm: &mut CurrentRealm,
2222 input: RequestOrUSVString,
2223 init: RootedTraceableBox<RequestInit>,
2224 ) -> Rc<Promise> {
2225 fetch::Fetch(self.upcast(), input, init, realm)
2226 }
2227
2228 fn FetchLater(
2230 &self,
2231 cx: &mut JSContext,
2232 input: RequestInfo,
2233 init: RootedTraceableBox<DeferredRequestInit>,
2234 ) -> Fallible<DomRoot<FetchLaterResult>> {
2235 fetch::FetchLater(cx, self, input, init)
2236 }
2237
2238 #[cfg(feature = "bluetooth")]
2239 fn TestRunner(&self, cx: &mut JSContext) -> DomRoot<TestRunner> {
2240 self.test_runner
2241 .or_init(|| TestRunner::new(cx, self.upcast()))
2242 }
2243
2244 fn RunningAnimationCount(&self) -> u32 {
2245 self.document
2246 .get()
2247 .map_or(0, |d| d.animations().running_animation_count() as u32)
2248 }
2249
2250 fn SetName(&self, name: DOMString) {
2252 if let Some(proxy) = self.undiscarded_window_proxy() {
2253 proxy.set_name(name);
2254 }
2255 }
2256
2257 fn Name(&self) -> DOMString {
2259 match self.undiscarded_window_proxy() {
2260 Some(proxy) => proxy.get_name(),
2261 None => "".into(),
2262 }
2263 }
2264
2265 fn Origin(&self) -> USVString {
2267 USVString(self.origin().immutable().ascii_serialization())
2268 }
2269
2270 fn GetSelection(&self, cx: &mut JSContext) -> Option<DomRoot<Selection>> {
2272 self.document.get().and_then(|d| d.GetSelection(cx))
2273 }
2274
2275 fn Event(&self, cx: &mut JSContext, rval: MutableHandleValue) {
2277 if let Some(ref event) = *self.current_event.borrow() {
2278 event.reflector().get_jsobject().safe_to_jsval(cx, rval);
2279 }
2280 }
2281
2282 fn IsSecureContext(&self) -> bool {
2283 self.as_global_scope().is_secure_context()
2284 }
2285
2286 fn NamedGetter(&self, cx: &mut JSContext, name: DOMString) -> Option<NamedPropertyValue> {
2288 if name.is_empty() {
2289 return None;
2290 }
2291 let document = self.Document();
2292
2293 let iframes: Vec<_> = document
2295 .iframes()
2296 .iter()
2297 .filter(|iframe| {
2298 if let Some(window) = iframe.GetContentWindow() {
2299 return window.get_name() == name;
2300 }
2301 false
2302 })
2303 .collect();
2304
2305 let iframe_iter = iframes.iter().map(|iframe| iframe.upcast::<Element>());
2306
2307 let name = Atom::from(name);
2308
2309 let elements_with_name = document.get_elements_with_name(cx, &name);
2311 let name_iter = elements_with_name
2312 .iter()
2313 .map(|element| &**element)
2314 .filter(|elem| is_named_element_with_name_attribute(elem));
2315
2316 let elements_with_id = document.get_elements_with_id(cx, &name);
2317 let id_iter = elements_with_id
2318 .iter()
2319 .map(|element| &**element)
2320 .filter(|elem| is_named_element_with_id_attribute(elem));
2321
2322 for elem in iframe_iter.clone() {
2324 if let Some(nested_window_proxy) = elem
2325 .downcast::<HTMLIFrameElement>()
2326 .and_then(|iframe| iframe.GetContentWindow())
2327 {
2328 return Some(NamedPropertyValue::WindowProxy(nested_window_proxy));
2329 }
2330 }
2331
2332 let mut elements = iframe_iter.chain(name_iter).chain(id_iter);
2333
2334 let first = elements.next()?;
2335
2336 if elements.next().is_none() {
2337 return Some(NamedPropertyValue::Element(DomRoot::from_ref(first)));
2339 }
2340
2341 #[derive(JSTraceable, MallocSizeOf)]
2343 struct WindowNamedGetter {
2344 #[no_trace]
2345 name: Atom,
2346 }
2347 impl CollectionFilter for WindowNamedGetter {
2348 fn filter(&self, elem: &Element, _root: &Node) -> bool {
2349 let type_ = match elem.upcast::<Node>().type_id() {
2350 NodeTypeId::Element(ElementTypeId::HTMLElement(type_)) => type_,
2351 _ => return false,
2352 };
2353 if elem.get_id().as_ref() == Some(&self.name) {
2354 return true;
2355 }
2356 match type_ {
2357 HTMLElementTypeId::HTMLEmbedElement |
2358 HTMLElementTypeId::HTMLFormElement |
2359 HTMLElementTypeId::HTMLImageElement |
2360 HTMLElementTypeId::HTMLObjectElement => {
2361 elem.get_name().as_ref() == Some(&self.name)
2362 },
2363 _ => false,
2364 }
2365 }
2366 }
2367 let collection = HTMLCollection::create(
2368 cx,
2369 self,
2370 document.upcast(),
2371 Box::new(WindowNamedGetter { name }),
2372 );
2373 Some(NamedPropertyValue::HTMLCollection(collection))
2374 }
2375
2376 fn SupportedPropertyNames(&self, no_gc: &NoGC) -> Vec<DOMString> {
2378 self.Document().SupportedPropertyNames(no_gc)
2379 }
2380
2381 fn StructuredClone(
2383 &self,
2384 cx: &mut JSContext,
2385 value: HandleValue,
2386 options: RootedTraceableBox<StructuredSerializeOptions>,
2387 retval: MutableHandleValue,
2388 ) -> Fallible<()> {
2389 self.as_global_scope()
2390 .structured_clone(cx, value, options, retval)
2391 }
2392
2393 fn TrustedTypes(&self, cx: &mut JSContext) -> DomRoot<TrustedTypePolicyFactory> {
2394 self.trusted_types
2395 .or_init(|| TrustedTypePolicyFactory::new(cx, self.as_global_scope()))
2396 }
2397}
2398
2399impl Window {
2400 pub(crate) fn scroll_offset(&self) -> Vector2D<f32, LayoutPixel> {
2401 self.scroll_offset_query_with_external_scroll_id(self.pipeline_id().root_scroll_id())
2402 }
2403
2404 pub(crate) fn create_named_properties_object(
2407 cx: &mut JSContext,
2408 proto: HandleObject,
2409 object: MutableHandleObject,
2410 ) {
2411 window_named_properties::create(cx, proto, object)
2412 }
2413
2414 pub(crate) fn current_event(&self) -> Option<DomRoot<Event>> {
2415 self.current_event
2416 .borrow()
2417 .as_ref()
2418 .map(|e| DomRoot::from_ref(&**e))
2419 }
2420
2421 pub(crate) fn set_current_event(&self, event: Option<&Event>) -> Option<DomRoot<Event>> {
2422 let current = self.current_event();
2423 *self.current_event.borrow_mut() = event.map(Dom::from_ref);
2424 current
2425 }
2426
2427 fn post_message_impl(
2429 &self,
2430 target_origin: &USVString,
2431 source_origin: ImmutableOrigin,
2432 source: &Window,
2433 cx: &mut JSContext,
2434 message: HandleValue,
2435 transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
2436 ) -> ErrorResult {
2437 let data = structuredclone::write(cx, message, Some(transfer))?;
2439
2440 let target_origin = match target_origin.0[..].as_ref() {
2442 "*" => None,
2443 "/" => Some(source_origin.clone()),
2444 url => match ServoUrl::parse(url) {
2445 Ok(url) => Some(url.origin()),
2446 Err(_) => return Err(Error::Syntax(None)),
2447 },
2448 };
2449
2450 self.post_message(target_origin, source_origin, &source.window_proxy(), data);
2452 Ok(())
2453 }
2454
2455 pub(crate) fn paint_worklet(&self, cx: &mut JSContext) -> DomRoot<Worklet> {
2457 self.paint_worklet.or_init(|| self.new_paint_worklet(cx))
2458 }
2459
2460 pub(crate) fn clear_js_runtime(&self) {
2461 self.as_global_scope()
2462 .remove_web_messaging_and_dedicated_workers_infra();
2463
2464 self.Document().teardown_custom_element_registry();
2467
2468 self.current_state.set(WindowState::Zombie);
2469 *self.js_runtime.borrow_mut() = None;
2470
2471 if let Some(performance) = self.performance.get() {
2472 performance.clear_and_disable_performance_entry_buffer();
2473 }
2474
2475 self.as_global_scope()
2476 .task_manager()
2477 .cancel_all_tasks_and_ignore_future_tasks();
2478
2479 if let Some(factory) = self.upcast::<GlobalScope>().indexeddb_factory() {
2484 factory.abort_pending_upgrades_and_close_databases();
2485 }
2486
2487 self.pending_image_callbacks.borrow_mut().clear();
2490 }
2491
2492 pub(crate) fn scroll(&self, cx: &mut JSContext, x: f32, y: f32, behavior: ScrollBehavior) {
2494 let xfinite = if x.is_finite() { x } else { 0.0 };
2496 let yfinite = if y.is_finite() { y } else { 0.0 };
2497
2498 let viewport = self.viewport_details.get().size;
2508
2509 let scrolling_area = self.scrolling_area_query(None).to_f32();
2528 let x = xfinite.clamp(0.0, 0.0f32.max(scrolling_area.width() - viewport.width));
2529 let y = yfinite.clamp(0.0, 0.0f32.max(scrolling_area.height() - viewport.height));
2530
2531 let scroll_offset = self.scroll_offset();
2534 if x == scroll_offset.x && y == scroll_offset.y {
2535 return;
2536 }
2537
2538 self.perform_a_scroll(
2543 cx,
2544 x,
2545 y,
2546 self.pipeline_id().root_scroll_id(),
2547 behavior,
2548 None,
2549 );
2550 }
2551
2552 pub(crate) fn perform_a_scroll(
2554 &self,
2555 cx: &mut JSContext,
2556 x: f32,
2557 y: f32,
2558 scroll_id: ExternalScrollId,
2559 _behavior: ScrollBehavior,
2560 element: Option<&Element>,
2561 ) {
2562 let (reflow_phases_run, _) = self.reflow(
2566 cx,
2567 ReflowGoal::UpdateScrollNode(scroll_id, Vector2D::new(x, y)),
2568 );
2569 if reflow_phases_run.needs_frame() {
2570 self.paint_api()
2571 .generate_frame(vec![self.webview_id().into()]);
2572 }
2573
2574 if reflow_phases_run.contains(ReflowPhasesRun::UpdatedScrollNodeOffset) {
2579 match element {
2580 Some(element) if !scroll_id.is_root() => element.handle_scroll_event(),
2581 _ => self.Document().handle_viewport_scroll_event(),
2582 };
2583 }
2584 }
2585
2586 pub(crate) fn device_pixel_ratio(&self) -> Scale<f32, CSSPixel, DevicePixel> {
2587 self.viewport_details.get().hidpi_scale_factor
2588 }
2589
2590 fn client_window(&self) -> DeviceIndependentIntRect {
2591 let (sender, receiver) = generic_channel::channel().expect("Failed to create IPC channel!");
2592
2593 self.send_to_embedder(EmbedderMsg::GetWindowRect(self.webview_id(), sender));
2594
2595 receiver.recv().unwrap_or_default()
2596 }
2597
2598 pub(crate) fn advance_animation_clock(&self, delta: TimeDuration) {
2601 self.Document()
2602 .advance_animation_timeline_for_testing(delta);
2603 ScriptThread::handle_tick_all_animations_for_testing(self.pipeline_id());
2604 }
2605
2606 pub(crate) fn reflow(
2614 &self,
2615 cx: &mut JSContext,
2616 reflow_goal: ReflowGoal,
2617 ) -> (ReflowPhasesRun, ReflowStatistics) {
2618 let document = self.Document();
2619
2620 if !document.is_fully_active() {
2622 return Default::default();
2623 }
2624
2625 self.document_unrooted(cx.no_gc())
2626 .ensure_safe_to_run_script_or_layout();
2627
2628 match reflow_goal {
2632 ReflowGoal::LayoutQuery(_) | ReflowGoal::UpdateScrollNode(..) => {
2633 self.flush_ancestor_layouts_if_necessary(cx);
2634 },
2635 ReflowGoal::UpdateTheRendering => { },
2636 }
2637
2638 let pipeline_id = self.pipeline_id();
2642 if reflow_goal == ReflowGoal::UpdateTheRendering &&
2643 self.layout_blocker.get().layout_blocked()
2644 {
2645 debug!("Suppressing pre-load-event reflow pipeline {pipeline_id}");
2646 return Default::default();
2647 }
2648
2649 debug!("script: performing reflow for goal {reflow_goal:?}");
2650 let marker = if self.need_emit_timeline_marker(TimelineMarkerType::Reflow) {
2651 Some(TimelineMarker::start("Reflow".to_owned()))
2652 } else {
2653 None
2654 };
2655
2656 let restyle_reason = document.restyle_reason(cx.no_gc());
2657 document.clear_restyle_reasons();
2658 let restyle = if restyle_reason.needs_restyle() {
2659 debug!("Invalidating layout cache due to reflow condition {restyle_reason:?}",);
2660 self.layout_marker.borrow().set(false);
2662 *self.layout_marker.borrow_mut() = Rc::new(Cell::new(true));
2664
2665 if restyle_reason.contains(RestyleReason::ViewportChanged) &&
2669 self.layout().device().used_viewport_size()
2670 {
2671 document.dirty_all_nodes(cx.no_gc());
2672 }
2673
2674 let stylesheets_changed = document.flush_stylesheets_for_reflow();
2675 let pending_restyles = document.drain_pending_restyles(cx.no_gc());
2676 let dirty_root = document
2677 .take_dirty_root()
2678 .filter(|_| !stylesheets_changed)
2679 .or_else(|| document.GetDocumentElement())
2680 .map(|root| root.upcast::<Node>().to_trusted_node_address());
2681
2682 Some(ReflowRequestRestyle {
2683 reason: restyle_reason,
2684 dirty_root,
2685 stylesheets_changed,
2686 pending_restyles,
2687 })
2688 } else {
2689 None
2690 };
2691
2692 document.id_map().resolve_all(cx.no_gc(), document.upcast());
2695
2696 let document_context = self.web_font_context(cx.no_gc());
2697
2698 let rooted_nodes_for_accessibility_integrity_check =
2699 document.rooted_nodes_for_accessibility_integrity_check();
2700 let mut accessibility_damage: Option<Vec<(TrustedNodeAddress, AccessibilityDamage)>> = None;
2701 if self.layout().accessibility_active() {
2702 let mut accessibility_data = document.accessibility_data_mut();
2703 accessibility_damage = Some(accessibility_data.drain_pending_accessibility_damage());
2704 }
2705
2706 let reflow = ReflowRequest {
2708 document: document.upcast::<Node>().to_trusted_node_address(),
2709 epoch: document.current_rendering_epoch(),
2710 restyle,
2711 viewport_details: self.viewport_details.get(),
2712 origin: self.origin().immutable().clone(),
2713 reflow_goal,
2714 animation_timeline_value: document.current_animation_timeline_value(),
2715 animations: document.animations().sets.clone(),
2716 animating_images: document.image_animation_manager().animating_images(),
2717 highlighted_dom_node: document.highlighted_dom_node().map(|node| node.to_opaque()),
2718 document_context,
2719 accessibility_damage,
2720 rooted_nodes_for_accessibility_integrity_check,
2721 };
2722
2723 let Some(reflow_result) = self.layout.borrow_mut().reflow(reflow) else {
2724 return Default::default();
2725 };
2726
2727 debug!("script: layout complete");
2728 if let Some(marker) = marker {
2729 self.emit_timeline_marker(marker.end());
2730 }
2731
2732 self.handle_new_or_removed_web_fonts_post_reflow(cx, reflow_result.changed_web_fonts);
2733
2734 self.handle_pending_images_post_reflow(
2735 cx,
2736 reflow_result.pending_images,
2737 reflow_result.pending_rasterization_images,
2738 reflow_result.pending_svg_elements_for_serialization,
2739 );
2740
2741 if let Some(iframe_sizes) = reflow_result.iframe_sizes {
2742 document
2743 .iframes_mut()
2744 .handle_new_iframe_sizes_after_layout(cx, self, iframe_sizes);
2745 }
2746
2747 document.update_animations_post_reflow();
2748
2749 (
2750 reflow_result.reflow_phases_run,
2751 reflow_result.reflow_statistics,
2752 )
2753 }
2754
2755 pub(crate) fn request_screenshot_readiness(&self, cx: &mut JSContext) {
2756 self.has_pending_screenshot_readiness_request.set(true);
2757 self.maybe_resolve_pending_screenshot_readiness_requests(cx);
2758 }
2759
2760 pub(crate) fn maybe_resolve_pending_screenshot_readiness_requests(&self, cx: &mut JSContext) {
2761 let pending_request = self.has_pending_screenshot_readiness_request.get();
2762 if !pending_request {
2763 return;
2764 }
2765
2766 let document = self.Document();
2767 if document.ReadyState() != DocumentReadyState::Complete {
2768 return;
2769 }
2770
2771 if document.render_blocking_element_count() > 0 {
2772 return;
2773 }
2774
2775 if document.GetDocumentElement().is_some_and(|elem| {
2779 elem.has_class(&atom!("reftest-wait"), CaseSensitivity::CaseSensitive) ||
2780 elem.has_class(&Atom::from("test-wait"), CaseSensitivity::CaseSensitive)
2781 }) {
2782 return;
2783 }
2784
2785 if self.font_context().web_fonts_still_loading() != 0 {
2786 return;
2787 }
2788
2789 if self.Document().Fonts(cx).waiting_to_fullfill_promise() {
2790 return;
2791 }
2792
2793 if !self.pending_layout_images.borrow().is_empty() ||
2794 !self.pending_images_for_rasterization.borrow().is_empty()
2795 {
2796 return;
2797 }
2798
2799 let document = self.Document();
2800 if document.needs_rendering_update(cx.no_gc()) {
2801 return;
2802 }
2803
2804 let epoch = document.current_rendering_epoch();
2807 let pipeline_id = self.pipeline_id();
2808 debug!("Ready to take screenshot of {pipeline_id:?} at epoch={epoch:?}");
2809
2810 self.send_to_constellation(
2811 ScriptToConstellationMessage::RespondToScreenshotReadinessRequest(
2812 ScreenshotReadinessResponse::Ready(epoch),
2813 ),
2814 );
2815 self.has_pending_screenshot_readiness_request.set(false);
2816 }
2817
2818 pub(crate) fn reflow_if_reflow_timer_expired(&self, cx: &mut JSContext) {
2821 if !matches!(
2824 self.layout_blocker.get(),
2825 LayoutBlocker::Parsing(instant) if instant + INITIAL_REFLOW_DELAY < Instant::now()
2826 ) {
2827 return;
2828 }
2829 self.allow_layout_if_necessary(cx);
2830 }
2831
2832 pub(crate) fn prevent_layout_until_load_event(&self) {
2836 if !matches!(self.layout_blocker.get(), LayoutBlocker::WaitingForParse) {
2839 return;
2840 }
2841
2842 self.layout_blocker
2843 .set(LayoutBlocker::Parsing(Instant::now()));
2844 }
2845
2846 pub(crate) fn allow_layout_if_necessary(&self, cx: &mut JSContext) {
2849 if matches!(
2850 self.layout_blocker.get(),
2851 LayoutBlocker::FiredLoadEventOrParsingTimerExpired
2852 ) {
2853 return;
2854 }
2855
2856 self.layout_blocker
2857 .set(LayoutBlocker::FiredLoadEventOrParsingTimerExpired);
2858
2859 let document = self.Document();
2871 if !document.is_render_blocked() && document.update_the_rendering(cx).0.needs_frame() {
2872 self.paint_api()
2873 .generate_frame(vec![self.webview_id().into()]);
2874 }
2875 }
2876
2877 pub(crate) fn layout_blocked(&self) -> bool {
2878 self.layout_blocker.get().layout_blocked()
2879 }
2880
2881 fn flush_ancestor_layouts_if_necessary(&self, cx: &mut JSContext) {
2882 let Some(parent_pipeline_id) = self.parent_info else {
2883 return;
2884 };
2885 let Some(parent_window) = ScriptThread::find_window(parent_pipeline_id) else {
2886 return;
2887 };
2888 if !parent_window.Document().is_safe_to_run_script_or_layout() {
2891 return;
2892 }
2893 if parent_window.Document().is_render_blocked() {
2896 return;
2897 }
2898 parent_window.flush_ancestor_layouts_if_necessary(cx);
2899 if parent_window
2900 .document_unrooted(cx.no_gc())
2901 .restyle_reason(cx.no_gc())
2902 .needs_restyle()
2903 {
2904 parent_window.reflow(
2905 cx,
2906 ReflowGoal::LayoutQuery(QueryMsg::FlushForUpdateTheRenderingQuery),
2907 );
2908 }
2909 }
2910
2911 #[expect(unsafe_code)]
2913 pub(crate) fn layout_reflow(&self, query_msg: QueryMsg) {
2914 let mut cx = unsafe { script_bindings::script_runtime::temp_cx() };
2916
2917 self.reflow(&mut cx, ReflowGoal::LayoutQuery(query_msg));
2918 }
2919
2920 pub(crate) fn reflow_for_non_flushing_update_the_rendering_queries(&self, cx: &mut JSContext) {
2922 self.reflow(
2923 cx,
2924 ReflowGoal::LayoutQuery(QueryMsg::FlushForUpdateTheRenderingQuery),
2925 );
2926 }
2927
2928 pub(crate) fn resolved_font_style_query(
2929 &self,
2930 node: &Node,
2931 value: String,
2932 ) -> Option<ServoArc<Font>> {
2933 self.layout_reflow(QueryMsg::ResolvedFontStyleQuery);
2934
2935 let document = self.Document();
2936 let animations = document.animations().sets.clone();
2937 self.layout.borrow().query_resolved_font_style(
2938 node.to_trusted_node_address(),
2939 &value,
2940 animations,
2941 document.current_animation_timeline_value(),
2942 )
2943 }
2944
2945 #[expect(unsafe_code)]
2948 pub(crate) fn containing_block_node_query_without_reflow(
2949 &self,
2950 node: &Node,
2951 ) -> Option<DomRoot<Node>> {
2952 self.layout
2953 .borrow()
2954 .query_containing_block(node.to_trusted_node_address())
2955 .map(|address| unsafe { from_untrusted_node_address(address) })
2956 }
2957
2958 pub(crate) fn is_containing_block_descendant_query_without_reflow(
2961 &self,
2962 possible_ancestor: &Node,
2963 possible_descendant: &Node,
2964 ) -> bool {
2965 self.layout.borrow().query_containing_block_is_descendant(
2966 possible_ancestor.to_trusted_node_address(),
2967 possible_descendant.to_trusted_node_address(),
2968 )
2969 }
2970
2971 pub(crate) fn padding_query_without_reflow(&self, node: &Node) -> Option<PhysicalSides> {
2976 let layout = self.layout.borrow();
2977 layout.query_padding(node.to_trusted_node_address())
2978 }
2979
2980 pub(crate) fn box_area_query_without_reflow(
2985 &self,
2986 node: &Node,
2987 area: BoxAreaType,
2988 exclude_transform_and_inline: bool,
2989 ) -> Option<Rect<Au, CSSPixel>> {
2990 let layout = self.layout.borrow();
2991 layout.ensure_stacking_context_tree(self.viewport_details.get());
2992 layout.query_box_area(
2993 node.to_trusted_node_address(),
2994 area,
2995 exclude_transform_and_inline,
2996 )
2997 }
2998
2999 pub(crate) fn box_area_query(
3000 &self,
3001 node: &Node,
3002 area: BoxAreaType,
3003 exclude_transform_and_inline: bool,
3004 ) -> Option<Rect<Au, CSSPixel>> {
3005 self.layout_reflow(QueryMsg::BoxArea);
3006 self.box_area_query_without_reflow(node, area, exclude_transform_and_inline)
3007 }
3008
3009 pub(crate) fn box_areas_query(&self, node: &Node, area: BoxAreaType) -> CSSPixelRectVec {
3010 self.layout_reflow(QueryMsg::BoxAreas);
3011 self.layout
3012 .borrow()
3013 .query_box_areas(node.to_trusted_node_address(), area)
3014 }
3015
3016 pub(crate) fn client_rect_query(&self, node: &Node) -> Rect<i32, CSSPixel> {
3017 self.layout_reflow(QueryMsg::ClientRectQuery);
3018 self.layout
3019 .borrow()
3020 .query_client_rect(node.to_trusted_node_address())
3021 }
3022
3023 pub(crate) fn current_css_zoom_query(&self, node: &Node) -> f32 {
3024 self.layout_reflow(QueryMsg::CurrentCSSZoomQuery);
3025 self.layout
3026 .borrow()
3027 .query_current_css_zoom(node.to_trusted_node_address())
3028 }
3029
3030 pub(crate) fn document_unrooted<'a>(&self, no_gc: &'a NoGC) -> UnrootedDom<'a, Document> {
3032 self.document
3033 .get_unrooted(no_gc)
3034 .expect("Document accessed before initialization.")
3035 }
3036
3037 pub(crate) fn scrolling_area_query(&self, node: Option<&Node>) -> Rect<i32, CSSPixel> {
3040 self.layout_reflow(QueryMsg::ScrollingAreaOrOffsetQuery);
3041 self.layout
3042 .borrow()
3043 .query_scrolling_area(node.map(Node::to_trusted_node_address))
3044 }
3045
3046 pub(crate) fn scroll_offset_query(&self, node: &Node) -> Vector2D<f32, LayoutPixel> {
3047 let external_scroll_id = ExternalScrollId(
3048 combine_id_with_fragment_type(node.to_opaque().id(), FragmentType::FragmentBody),
3049 self.pipeline_id().into(),
3050 );
3051 self.scroll_offset_query_with_external_scroll_id(external_scroll_id)
3052 }
3053
3054 fn scroll_offset_query_with_external_scroll_id(
3055 &self,
3056 external_scroll_id: ExternalScrollId,
3057 ) -> Vector2D<f32, LayoutPixel> {
3058 self.layout_reflow(QueryMsg::ScrollingAreaOrOffsetQuery);
3059 self.scroll_offset_query_with_external_scroll_id_no_reflow(external_scroll_id)
3060 }
3061
3062 fn scroll_offset_query_with_external_scroll_id_no_reflow(
3063 &self,
3064 external_scroll_id: ExternalScrollId,
3065 ) -> Vector2D<f32, LayoutPixel> {
3066 self.layout
3067 .borrow()
3068 .scroll_offset(external_scroll_id)
3069 .unwrap_or_default()
3070 }
3071
3072 pub(crate) fn scroll_an_element(
3075 &self,
3076 cx: &mut JSContext,
3077 element: &Element,
3078 x: f32,
3079 y: f32,
3080 behavior: ScrollBehavior,
3081 ) {
3082 let scroll_id = ExternalScrollId(
3083 combine_id_with_fragment_type(
3084 element.upcast::<Node>().to_opaque().id(),
3085 FragmentType::FragmentBody,
3086 ),
3087 self.pipeline_id().into(),
3088 );
3089
3090 self.perform_a_scroll(cx, x, y, scroll_id, behavior, Some(element));
3094 }
3095
3096 pub(crate) fn resolved_style_query(
3097 &self,
3098 element: TrustedNodeAddress,
3099 pseudo: Option<PseudoElement>,
3100 property: PropertyId,
3101 ) -> DOMString {
3102 self.layout_reflow(QueryMsg::ResolvedStyleQuery(property.clone()));
3103
3104 let document = self.Document();
3105 let animations = document.animations().sets.clone();
3106 DOMString::from(self.layout.borrow().query_resolved_style(
3107 element,
3108 pseudo,
3109 property,
3110 animations,
3111 document.current_animation_timeline_value(),
3112 ))
3113 }
3114
3115 pub(crate) fn get_iframe_viewport_details_if_known(
3119 &self,
3120 browsing_context_id: BrowsingContextId,
3121 ) -> Option<ViewportDetails> {
3122 self.layout_reflow(QueryMsg::InnerWindowDimensionsQuery);
3124 self.Document()
3125 .iframes()
3126 .get(browsing_context_id)
3127 .and_then(|iframe| iframe.size)
3128 }
3129
3130 #[expect(unsafe_code)]
3131 pub(crate) fn offset_parent_query(
3132 &self,
3133 node: &Node,
3134 ) -> (Option<DomRoot<Element>>, Rect<Au, CSSPixel>) {
3135 self.layout_reflow(QueryMsg::OffsetParentQuery);
3136 let response = self
3137 .layout
3138 .borrow()
3139 .query_offset_parent(node.to_trusted_node_address());
3140 let element = response.node_address.and_then(|parent_node_address| {
3141 let node = unsafe { from_untrusted_node_address(parent_node_address) };
3142 DomRoot::downcast(node)
3143 });
3144 (element, response.rect)
3145 }
3146
3147 pub(crate) fn scroll_container_query(
3148 &self,
3149 node: Option<&Node>,
3150 flags: ScrollContainerQueryFlags,
3151 ) -> Option<ScrollContainerResponse> {
3152 self.layout_reflow(QueryMsg::ScrollParentQuery);
3153 self.layout
3154 .borrow()
3155 .query_scroll_container(node.map(Node::to_trusted_node_address), flags)
3156 }
3157
3158 #[expect(unsafe_code)]
3159 pub(crate) fn scrolling_box_query(
3160 &self,
3161 node: Option<&Node>,
3162 flags: ScrollContainerQueryFlags,
3163 ) -> Option<ScrollingBox> {
3164 self.scroll_container_query(node, flags)
3165 .and_then(|response| {
3166 Some(match response {
3167 ScrollContainerResponse::Viewport(overflow) => {
3168 (ScrollingBoxSource::Viewport(self.Document()), overflow)
3169 },
3170 ScrollContainerResponse::Element(parent_node_address, overflow) => {
3171 let node = unsafe { from_untrusted_node_address(parent_node_address) };
3172 (
3173 ScrollingBoxSource::Element(DomRoot::downcast(node)?),
3174 overflow,
3175 )
3176 },
3177 })
3178 })
3179 .map(|(source, overflow)| ScrollingBox::new(source, overflow))
3180 }
3181
3182 pub(crate) fn text_index_query_on_node_for_event(
3183 &self,
3184 node: &Node,
3185 mouse_event: &MouseEvent,
3186 ) -> Option<usize> {
3187 let point_in_viewport = mouse_event.point_in_viewport()?.map(Au::from_f32_px);
3191
3192 self.layout_reflow(QueryMsg::TextIndexQuery);
3193 self.layout
3194 .borrow()
3195 .query_text_index(node.to_trusted_node_address(), point_in_viewport)
3196 }
3197
3198 pub(crate) fn elements_from_point_query(
3199 &self,
3200 point: LayoutPoint,
3201 ) -> Vec<ElementsFromPointResult> {
3202 self.layout_reflow(QueryMsg::ElementsFromPoint);
3203 self.layout().query_elements_from_point(point)
3204 }
3205
3206 pub(crate) fn query_effective_overflow(&self, node: &Node) -> Option<AxesOverflow> {
3207 self.layout_reflow(QueryMsg::EffectiveOverflow);
3208 self.query_effective_overflow_without_reflow(node)
3209 }
3210
3211 pub(crate) fn query_effective_overflow_without_reflow(
3212 &self,
3213 node: &Node,
3214 ) -> Option<AxesOverflow> {
3215 self.layout
3216 .borrow()
3217 .query_effective_overflow(node.to_trusted_node_address())
3218 }
3219
3220 pub(crate) fn hit_test_from_input_event(
3221 &self,
3222 input_event: &ConstellationInputEvent,
3223 ) -> Option<HitTestResult> {
3224 self.hit_test_from_point_in_viewport(
3225 input_event.hit_test_result.as_ref()?.point_in_viewport,
3226 )
3227 }
3228
3229 #[expect(unsafe_code)]
3230 pub(crate) fn hit_test_from_point_in_viewport(
3231 &self,
3232 point_in_frame: Point2D<f32, CSSPixel>,
3233 ) -> Option<HitTestResult> {
3234 let result = self
3235 .elements_from_point_query(point_in_frame.cast_unit())
3236 .into_iter()
3237 .nth(0)?;
3238
3239 let point_relative_to_initial_containing_block =
3240 point_in_frame + self.scroll_offset().cast_unit();
3241
3242 let address = UntrustedNodeAddress(result.node.0 as *const c_void);
3245 Some(HitTestResult {
3246 node: unsafe { from_untrusted_node_address(address) },
3247 cursor: result.cursor,
3248 point_in_node: result.point_in_target,
3249 point_in_frame,
3250 point_relative_to_initial_containing_block,
3251 })
3252 }
3253
3254 pub(crate) fn init_window_proxy(&self, window_proxy: &WindowProxy) {
3255 assert!(self.window_proxy.get().is_none());
3256 self.window_proxy.set(Some(window_proxy));
3257 }
3258
3259 pub(crate) fn init_document(&self, document: &Document) {
3260 assert!(self.document.get().is_none());
3261 assert!(document.window() == self);
3262 self.document.set(Some(document));
3263 }
3264
3265 pub(crate) fn load_data_for_document(
3266 &self,
3267 url: ServoUrl,
3268 pipeline_id: PipelineId,
3269 ) -> LoadData {
3270 let source_document = self.Document();
3271 let secure_context = if self.is_top_level() {
3272 None
3273 } else {
3274 Some(self.IsSecureContext())
3275 };
3276 LoadData::new(
3277 LoadOrigin::Script(self.origin().snapshot()),
3278 url,
3279 source_document.about_base_url(),
3280 Some(pipeline_id),
3281 Referrer::ReferrerUrl(source_document.url()),
3282 source_document.get_referrer_policy(),
3283 secure_context,
3284 Some(source_document.insecure_requests_policy()),
3285 source_document.has_trustworthy_ancestor_origin(),
3286 source_document.creation_sandboxing_flag_set_considering_parent_iframe(),
3287 )
3288 }
3289
3290 pub(crate) fn set_viewport_details(&self, viewport_details: ViewportDetails) {
3293 self.viewport_details.set(viewport_details);
3294 if !self.layout_mut().set_viewport_details(viewport_details) {
3295 return;
3296 }
3297 self.Document()
3298 .add_restyle_reason(RestyleReason::ViewportChanged);
3299 }
3300
3301 pub(crate) fn viewport_details(&self) -> ViewportDetails {
3302 self.viewport_details.get()
3303 }
3304
3305 pub(crate) fn get_or_init_visual_viewport(
3306 &self,
3307 cx: &mut JSContext,
3308 ) -> DomRoot<VisualViewport> {
3309 self.visual_viewport.or_init(|| {
3310 VisualViewport::new_from_layout_viewport(cx, self, self.viewport_details().size)
3311 })
3312 }
3313
3314 pub(crate) fn maybe_update_visual_viewport(
3316 &self,
3317 cx: &mut JSContext,
3318 pinch_zoom_infos: PinchZoomInfos,
3319 ) {
3320 if pinch_zoom_infos.rect == Rect::from_size(self.viewport_details().size) &&
3323 self.visual_viewport.get().is_none()
3324 {
3325 return;
3326 }
3327
3328 let visual_viewport = self.get_or_init_visual_viewport(cx);
3329 let changes = visual_viewport.update_from_pinch_zoom_infos(pinch_zoom_infos);
3330
3331 if changes.intersects(VisualViewportChanges::DimensionChanged) {
3332 self.has_changed_visual_viewport_dimension.set(true);
3333 }
3334 if changes.intersects(VisualViewportChanges::OffsetChanged) {
3335 visual_viewport.handle_scroll_event();
3336 }
3337 }
3338
3339 pub(crate) fn theme(&self) -> Theme {
3341 self.theme.get()
3342 }
3343
3344 pub(crate) fn set_theme(&self, new_theme: Theme) {
3346 self.theme.set(new_theme);
3347 if !self.layout_mut().set_theme(new_theme) {
3348 return;
3349 }
3350 self.Document()
3351 .add_restyle_reason(RestyleReason::ThemeChanged);
3352 self.pending_media_query_evaluation.set(true);
3355 }
3356
3357 pub(crate) fn take_pending_media_query_evaluation(&self) -> bool {
3360 self.pending_media_query_evaluation.replace(false)
3361 }
3362
3363 pub(crate) fn has_pending_media_query_evaluation(&self) -> bool {
3364 self.pending_media_query_evaluation.get()
3365 }
3366
3367 pub(crate) fn get_url(&self) -> ServoUrl {
3368 self.Document().url()
3369 }
3370
3371 pub(crate) fn windowproxy_handler(&self) -> &'static WindowProxyHandler {
3372 self.dom_static.windowproxy_handler
3373 }
3374
3375 pub(crate) fn add_resize_event(&self, event: ViewportDetails, event_type: WindowSizeType) {
3376 if self.viewport_details() == event {
3377 return;
3378 }
3379
3380 self.set_viewport_details(event);
3382
3383 *self.unhandled_resize_event.borrow_mut() = Some((event, event_type))
3386 }
3387
3388 pub(crate) fn take_unhandled_resize_event(&self) -> Option<(ViewportDetails, WindowSizeType)> {
3389 self.unhandled_resize_event.borrow_mut().take()
3390 }
3391
3392 pub(crate) fn has_unhandled_resize_event(&self) -> bool {
3394 self.unhandled_resize_event.borrow().is_some()
3395 }
3396
3397 pub(crate) fn suspend(&self, cx: &mut JSContext) {
3398 self.as_global_scope().suspend();
3400
3401 if self.window_proxy().currently_active() == Some(self.global().pipeline_id()) {
3403 self.window_proxy().unset_currently_active(cx);
3404 }
3405
3406 self.gc(cx);
3411 }
3412
3413 pub(crate) fn resume(&self, cx: &mut JSContext) {
3414 self.as_global_scope().resume();
3416
3417 self.window_proxy().set_currently_active(cx, self);
3419
3420 self.Document().title_changed();
3423 }
3424
3425 pub(crate) fn need_emit_timeline_marker(&self, timeline_type: TimelineMarkerType) -> bool {
3426 let markers = self.devtools_markers.borrow();
3427 markers.contains(&timeline_type)
3428 }
3429
3430 pub(crate) fn emit_timeline_marker(&self, marker: TimelineMarker) {
3431 let sender = self.devtools_marker_sender.borrow();
3432 let sender = sender.as_ref().expect("There is no marker sender");
3433 sender.send(Some(marker)).unwrap();
3434 }
3435
3436 pub(crate) fn set_devtools_timeline_markers(
3437 &self,
3438 markers: Vec<TimelineMarkerType>,
3439 reply: GenericSender<Option<TimelineMarker>>,
3440 ) {
3441 *self.devtools_marker_sender.borrow_mut() = Some(reply);
3442 self.devtools_markers.borrow_mut().extend(markers);
3443 }
3444
3445 pub(crate) fn drop_devtools_timeline_markers(&self, markers: Vec<TimelineMarkerType>) {
3446 let mut devtools_markers = self.devtools_markers.borrow_mut();
3447 for marker in markers {
3448 devtools_markers.remove(&marker);
3449 }
3450 if devtools_markers.is_empty() {
3451 *self.devtools_marker_sender.borrow_mut() = None;
3452 }
3453 }
3454
3455 pub(crate) fn set_webdriver_script_chan(&self, chan: Option<GenericSender<WebDriverJSResult>>) {
3456 *self.webdriver_script_chan.borrow_mut() = chan;
3457 }
3458
3459 pub(crate) fn set_webdriver_load_status_sender(
3460 &self,
3461 sender: Option<GenericSender<WebDriverLoadStatus>>,
3462 ) {
3463 *self.webdriver_load_status_sender.borrow_mut() = sender;
3464 }
3465
3466 pub(crate) fn webdriver_load_status_sender(
3467 &self,
3468 ) -> Option<GenericSender<WebDriverLoadStatus>> {
3469 self.webdriver_load_status_sender.borrow().clone()
3470 }
3471
3472 pub(crate) fn is_alive(&self) -> bool {
3473 self.current_state.get() == WindowState::Alive
3474 }
3475
3476 pub(crate) fn is_top_level(&self) -> bool {
3478 self.parent_info.is_none()
3479 }
3480
3481 fn run_resize_steps_for_layout_viewport(&self, cx: &mut JSContext) -> bool {
3486 let Some((new_size, size_type)) = self.take_unhandled_resize_event() else {
3487 return false;
3488 };
3489
3490 let current_viewport = self.viewport_details();
3493 if current_viewport == self.viewport_details_at_last_resize_steps.get() {
3494 return false;
3495 }
3496 self.viewport_details_at_last_resize_steps
3497 .set(current_viewport);
3498
3499 debug!(
3500 "Running resize steps for pipeline {:?} with viewport {new_size:?}",
3501 self.pipeline_id(),
3502 );
3503
3504 if size_type == WindowSizeType::Resize {
3506 let mut realm = enter_auto_realm(cx, self);
3507 let cx = &mut realm.current_realm();
3508 let uievent = UIEvent::new(
3509 cx,
3510 self,
3511 atom!("resize"),
3512 EventBubbles::DoesNotBubble,
3513 EventCancelable::NotCancelable,
3514 Some(self),
3515 0i32,
3516 0u32,
3517 );
3518 uievent.upcast::<Event>().fire(cx, self.upcast());
3519 }
3520
3521 true
3522 }
3523
3524 pub(crate) fn run_the_resize_steps(&self, cx: &mut JSContext) -> bool {
3529 let layout_viewport_resized = self.run_resize_steps_for_layout_viewport(cx);
3530
3531 if self.has_changed_visual_viewport_dimension.get() {
3532 let visual_viewport = self.get_or_init_visual_viewport(cx);
3533
3534 let uievent = UIEvent::new(
3535 cx,
3536 self,
3537 atom!("resize"),
3538 EventBubbles::DoesNotBubble,
3539 EventCancelable::NotCancelable,
3540 Some(self),
3541 0i32,
3542 0u32,
3543 );
3544 uievent.upcast::<Event>().fire(cx, visual_viewport.upcast());
3545
3546 self.has_changed_visual_viewport_dimension.set(false);
3547 }
3548
3549 layout_viewport_resized
3550 }
3551
3552 pub(crate) fn evaluate_media_queries_and_report_changes(&self, cx: &mut JSContext) {
3555 let mut realm = enter_auto_realm(cx, self);
3556 let cx = &mut realm.current_realm();
3557 rooted_vec!(let mut mql_list);
3558
3559 self.media_query_lists.for_each(|mql| {
3560 if let MediaQueryListMatchState::Changed = mql.evaluate_changes() {
3561 mql_list.push(Dom::from_ref(&*mql));
3563 }
3564 });
3565 for mql in mql_list.iter() {
3567 let event = MediaQueryListEvent::new(
3568 cx,
3569 &mql.global(),
3570 atom!("change"),
3571 false,
3572 false,
3573 mql.Media(),
3574 mql.Matches(),
3575 );
3576 event
3577 .upcast::<Event>()
3578 .fire(cx, mql.upcast::<EventTarget>());
3579 }
3580 }
3581
3582 pub(crate) fn set_throttled(&self, throttled: bool) {
3584 self.throttled.set(throttled);
3585 if throttled {
3586 self.as_global_scope().slow_down_timers();
3587 } else {
3588 self.as_global_scope().speed_up_timers();
3589 }
3590 }
3591
3592 pub(crate) fn throttled(&self) -> bool {
3593 self.throttled.get()
3594 }
3595
3596 pub(crate) fn unminified_css_dir(&self) -> Option<String> {
3597 self.unminified_css_dir.borrow().clone()
3598 }
3599
3600 pub(crate) fn local_script_source(&self) -> &Option<String> {
3601 &self.local_script_source
3602 }
3603
3604 pub(crate) fn set_navigation_start(&self) {
3605 self.navigation_start.set(CrossProcessInstant::now());
3606 }
3607
3608 pub(crate) fn navigation_start(&self) -> CrossProcessInstant {
3609 self.navigation_start.get()
3610 }
3611
3612 pub(crate) fn set_last_activation_timestamp(&self, time: UserActivationTimestamp) {
3613 self.last_activation_timestamp.set(time);
3614 }
3615
3616 pub(crate) fn send_to_embedder(&self, msg: EmbedderMsg) {
3617 self.as_global_scope()
3618 .script_to_embedder_chan()
3619 .send(msg)
3620 .unwrap();
3621 }
3622
3623 pub(crate) fn send_to_constellation(&self, msg: ScriptToConstellationMessage) {
3624 self.as_global_scope()
3625 .script_to_constellation_chan()
3626 .send(msg)
3627 .unwrap();
3628 }
3629
3630 #[cfg(feature = "webxr")]
3631 pub(crate) fn in_immersive_xr_session(&self) -> bool {
3632 self.navigator
3633 .get()
3634 .as_ref()
3635 .and_then(|nav| nav.xr())
3636 .is_some_and(|xr| xr.pending_or_active_session())
3637 }
3638
3639 #[cfg(not(feature = "webxr"))]
3640 pub(crate) fn in_immersive_xr_session(&self) -> bool {
3641 false
3642 }
3643
3644 fn handle_new_or_removed_web_fonts_post_reflow(
3646 &self,
3647 cx: &mut JSContext,
3648 changed_web_fonts: WebFontSetDifference,
3649 ) {
3650 if changed_web_fonts.is_empty() {
3651 return;
3652 }
3653
3654 let document = self.Document();
3655 let fonts = document.Fonts(cx);
3656 if !changed_web_fonts.removed_font_faces.is_empty() {
3657 fonts.notify_font_face_rules_removed(&changed_web_fonts.removed_font_faces);
3658
3659 document.dirty_all_nodes(cx.no_gc());
3662 }
3663
3664 if !changed_web_fonts.added_font_faces.is_empty() {
3665 fonts.switch_to_loading(cx);
3666
3667 let shared_locks = document.shared_style_locks();
3668 let guards = StylesheetGuards {
3669 author: &shared_locks.author.read(),
3670 ua_or_user: &shared_locks.ua_or_user.read(),
3671 };
3672 for new_web_font in changed_web_fonts.added_font_faces {
3673 if let Some(font_face) =
3674 FontFace::new_for_web_font(cx, self.upcast(), new_web_font, &guards)
3675 {
3676 fonts.add(cx, font_face);
3677 }
3678 }
3679 }
3680 }
3681
3682 #[expect(unsafe_code)]
3683 fn handle_pending_images_post_reflow(
3684 &self,
3685 cx: &mut JSContext,
3686 pending_images: Vec<PendingImage>,
3687 pending_rasterization_images: Vec<PendingRasterizationImage>,
3688 pending_svg_element_for_serialization: Vec<UntrustedNodeAddress>,
3689 ) {
3690 let pipeline_id = self.pipeline_id();
3691 let image_cache = self.image_cache();
3692 for image in pending_images {
3693 let id = image.id;
3694 let node = unsafe { from_untrusted_node_address(image.node) };
3695
3696 if let PendingImageState::Unrequested(ref url) = image.state {
3697 fetch_image_for_layout(
3698 url.clone(),
3699 &node,
3700 id,
3701 image.is_internal_request,
3702 image_cache.clone(),
3703 );
3704 }
3705
3706 let mut images = self.pending_layout_images.borrow_mut();
3707 if !images.contains_key(&id) {
3708 let trusted_node = Trusted::new(&*node);
3709 let sender = self.register_image_cache_listener(id, move |response, _| {
3710 trusted_node
3711 .root()
3712 .owner_window()
3713 .pending_layout_image_notification(response);
3714 });
3715
3716 image_cache.add_listener(ImageLoadListener::new(sender, pipeline_id, id));
3717 }
3718
3719 let nodes = images.entry(id).or_default();
3720 if !nodes.iter().any(|n| std::ptr::eq(&*(n.node), &*node)) {
3721 nodes.push(PendingLayoutImageAncillaryData {
3722 node: Dom::from_ref(&*node),
3723 destination: image.destination,
3724 });
3725 }
3726 }
3727
3728 for image in pending_rasterization_images {
3729 let node = unsafe { from_untrusted_node_address(image.node) };
3730
3731 let mut images = self.pending_images_for_rasterization.borrow_mut();
3732 if !images.contains_key(&(image.id, image.size)) {
3733 let image_cache_sender = self.image_cache_sender.clone();
3734 image_cache.add_rasterization_complete_listener(
3735 pipeline_id,
3736 image.id,
3737 image.size,
3738 Box::new(move |response| {
3739 let _ = image_cache_sender.send(response);
3740 }),
3741 );
3742 }
3743
3744 let nodes = images.entry((image.id, image.size)).or_default();
3745 if !nodes.iter().any(|n| std::ptr::eq(&**n, &*node)) {
3746 nodes.push(Dom::from_ref(&*node));
3747 }
3748 }
3749
3750 for node in pending_svg_element_for_serialization.into_iter() {
3751 let node = unsafe { from_untrusted_node_address(node) };
3752 let svg = node.downcast::<SVGSVGElement>().unwrap();
3753 svg.serialize_and_cache_subtree(cx);
3754 node.dirty(NodeDamage::Other);
3755 }
3756 }
3757
3758 pub(crate) fn has_sticky_activation(&self) -> bool {
3760 UserActivationTimestamp::TimeStamp(CrossProcessInstant::now()) >=
3762 self.last_activation_timestamp.get()
3763 }
3764
3765 pub(crate) fn has_transient_activation(&self) -> bool {
3767 let current_time = CrossProcessInstant::now();
3770 UserActivationTimestamp::TimeStamp(current_time) >= self.last_activation_timestamp.get() &&
3771 UserActivationTimestamp::TimeStamp(current_time) <
3772 self.last_activation_timestamp.get() +
3773 pref!(dom_transient_activation_duration_ms)
3774 }
3775
3776 pub(crate) fn consume_last_activation_timestamp(&self) {
3777 if self.last_activation_timestamp.get() != UserActivationTimestamp::PositiveInfinity {
3778 self.set_last_activation_timestamp(UserActivationTimestamp::NegativeInfinity);
3779 }
3780 }
3781
3782 pub(crate) fn consume_user_activation(&self) {
3784 if self.undiscarded_window_proxy().is_none() {
3787 return;
3788 }
3789
3790 let Some(top_level_document) = self.top_level_document_if_local() else {
3794 return;
3795 };
3796
3797 top_level_document
3805 .window()
3806 .consume_last_activation_timestamp();
3807 for document in SameOriginDescendantNavigablesIterator::new(&top_level_document) {
3808 document.window().consume_last_activation_timestamp();
3809 }
3810 }
3811
3812 #[allow(clippy::too_many_arguments)]
3813 pub(crate) fn new(
3814 cx: &mut JSContext,
3815 webview_id: WebViewId,
3816 runtime: Rc<Runtime>,
3817 script_chan: Sender<MainThreadScriptMsg>,
3818 layout: Box<dyn Layout>,
3819 font_context: Arc<FontContext>,
3820 image_cache_sender: Sender<ImageCacheResponseMessage>,
3821 resource_threads: ResourceThreads,
3822 storage_threads: StorageThreads,
3823 #[cfg(feature = "bluetooth")] bluetooth_thread: GenericSender<BluetoothRequest>,
3824 mem_profiler_chan: MemProfilerChan,
3825 time_profiler_chan: TimeProfilerChan,
3826 devtools_chan: Option<GenericCallback<ScriptToDevtoolsControlMsg>>,
3827 script_to_constellation_sender: ScriptToConstellationSender,
3828 embedder_chan: ScriptToEmbedderChan,
3829 control_chan: GenericSender<ScriptThreadMessage>,
3830 pipeline_id: PipelineId,
3831 parent_info: Option<PipelineId>,
3832 viewport_details: ViewportDetails,
3833 origin: MutableOrigin,
3834 creation_url: ServoUrl,
3835 top_level_creation_url: ServoUrl,
3836 navigation_start: CrossProcessInstant,
3837 webgl_chan: Option<WebGLChan>,
3838 #[cfg(feature = "webxr")] webxr_registry: Option<webxr_api::Registry>,
3839 paint_api: CrossProcessPaintApi,
3840 unminify_js: bool,
3841 unminify_css: bool,
3842 local_script_source: Option<String>,
3843 user_scripts: Rc<Vec<UserScript>>,
3844 player_context: WindowGLContext,
3845 #[cfg(feature = "webgpu")] gpu_id_hub: Arc<IdentityHub>,
3846 inherited_secure_context: Option<bool>,
3847 theme: Theme,
3848 weak_script_thread: Weak<ScriptThread>,
3849 ) -> DomRoot<Self> {
3850 let error_reporter = CSSErrorReporter {
3851 pipelineid: pipeline_id,
3852 script_chan: control_chan,
3853 };
3854
3855 let win = Box::new(Self {
3856 webview_id,
3857 globalscope: GlobalScope::new_inherited(
3858 devtools_chan,
3859 mem_profiler_chan,
3860 time_profiler_chan,
3861 script_to_constellation_sender,
3862 embedder_chan,
3863 resource_threads,
3864 storage_threads,
3865 creation_url,
3866 Some(top_level_creation_url),
3867 #[cfg(feature = "webgpu")]
3868 gpu_id_hub,
3869 inherited_secure_context,
3870 unminify_js,
3871 Some(font_context),
3872 ),
3873 ongoing_navigation: Default::default(),
3874 script_chan,
3875 layout: RefCell::new(layout),
3876 image_cache_sender,
3877 navigator: Default::default(),
3878 crypto: Default::default(),
3879 location: Default::default(),
3880 window_proxy: Default::default(),
3881 document: Default::default(),
3882 performance: Default::default(),
3883 navigation_start: Cell::new(navigation_start),
3884 screen: Default::default(),
3885 session_storage: Default::default(),
3886 local_storage: Default::default(),
3887 cookie_store: Default::default(),
3888 status: DomRefCell::new(DOMString::new()),
3889 parent_info,
3890 dom_static: GlobalStaticData::new(),
3891 js_runtime: DomRefCell::new(Some(runtime)),
3892 #[cfg(feature = "bluetooth")]
3893 bluetooth_thread,
3894 #[cfg(feature = "bluetooth")]
3895 bluetooth_extra_permission_data: BluetoothExtraPermissionData::new(),
3896 unhandled_resize_event: Default::default(),
3897 viewport_details_at_last_resize_steps: Cell::new(viewport_details),
3898 viewport_details: Cell::new(viewport_details),
3899 layout_blocker: Cell::new(LayoutBlocker::WaitingForParse),
3900 current_state: Cell::new(WindowState::Alive),
3901 devtools_marker_sender: Default::default(),
3902 devtools_markers: Default::default(),
3903 webdriver_script_chan: Default::default(),
3904 webdriver_load_status_sender: Default::default(),
3905 error_reporter,
3906 media_query_lists: DOMTracker::new(),
3907 #[cfg(feature = "bluetooth")]
3908 test_runner: Default::default(),
3909 webgl_chan,
3910 #[cfg(feature = "webxr")]
3911 webxr_registry,
3912 pending_image_callbacks: Default::default(),
3913 pending_layout_images: Default::default(),
3914 pending_images_for_rasterization: Default::default(),
3915 unminified_css_dir: DomRefCell::new(if unminify_css {
3916 Some(unminified_path("unminified-css"))
3917 } else {
3918 None
3919 }),
3920 local_script_source,
3921 test_worklet: Default::default(),
3922 paint_worklet: Default::default(),
3923 exists_mut_observer: Cell::new(false),
3924 paint_api,
3925 user_scripts,
3926 player_context,
3927 throttled: Cell::new(false),
3928 layout_marker: DomRefCell::new(Rc::new(Cell::new(true))),
3929 current_event: DomRefCell::new(None),
3930 theme: Cell::new(theme),
3931 trusted_types: Default::default(),
3932 reporting_observer_list: Default::default(),
3933 report_list: Default::default(),
3934 endpoints_list: Default::default(),
3935 script_window_proxies: ScriptThread::window_proxies(),
3936 has_pending_screenshot_readiness_request: Default::default(),
3937 visual_viewport: Default::default(),
3938 weak_script_thread,
3939 has_changed_visual_viewport_dimension: Default::default(),
3940 pending_media_query_evaluation: Default::default(),
3941 last_activation_timestamp: Cell::new(UserActivationTimestamp::PositiveInfinity),
3942 devtools_wants_updates: Default::default(),
3943 });
3944
3945 WindowBinding::Wrap::<crate::DomTypeHolder>(cx, &origin, win)
3946 }
3947
3948 pub(crate) fn task_manager(&self) -> Rc<TaskManager> {
3949 self.Document().task_manager()
3950 }
3951
3952 pub(crate) fn pipeline_id(&self) -> PipelineId {
3953 self.Document().pipeline_id()
3954 }
3955
3956 pub(crate) fn live_devtools_updates(&self) -> bool {
3957 self.devtools_wants_updates.get()
3958 }
3959
3960 pub(crate) fn set_devtools_wants_updates(&self, value: bool) {
3961 self.devtools_wants_updates.set(value);
3962 }
3963
3964 pub(crate) fn cache_layout_value<T>(&self, value: T) -> LayoutValue<T>
3966 where
3967 T: Copy + MallocSizeOf,
3968 {
3969 LayoutValue::new(self.layout_marker.borrow().clone(), value)
3970 }
3971}
3972
3973#[derive(MallocSizeOf)]
3978pub(crate) struct LayoutValue<T: MallocSizeOf> {
3979 #[conditional_malloc_size_of]
3980 is_valid: Rc<Cell<bool>>,
3981 value: T,
3982}
3983
3984#[expect(unsafe_code)]
3985unsafe impl<T: JSTraceable + MallocSizeOf> JSTraceable for LayoutValue<T> {
3986 unsafe fn trace(&self, trc: *mut js::jsapi::JSTracer) {
3987 unsafe { self.value.trace(trc) };
3988 }
3989}
3990
3991impl<T: Copy + MallocSizeOf> LayoutValue<T> {
3992 fn new(marker: Rc<Cell<bool>>, value: T) -> Self {
3993 LayoutValue {
3994 is_valid: marker,
3995 value,
3996 }
3997 }
3998
3999 pub(crate) fn get(&self) -> Result<T, ()> {
4001 if self.is_valid.get() {
4002 return Ok(self.value);
4003 }
4004 Err(())
4005 }
4006}
4007
4008impl Window {
4009 pub(crate) fn post_message(
4011 &self,
4012 target_origin: Option<ImmutableOrigin>,
4013 source_origin: ImmutableOrigin,
4014 source: &WindowProxy,
4015 data: StructuredSerializedData,
4016 ) {
4017 let this = Trusted::new(self);
4018 let source = Trusted::new(source);
4019 let task = task!(post_serialised_message: move |cx| {
4020 let this = this.root();
4021 let source = source.root();
4022 let document = this.Document();
4023
4024 if let Some(ref target_origin) = target_origin
4026 && !target_origin.same_origin(&*document.origin()) {
4027 return;
4028 }
4029
4030 let obj = this.reflector().get_jsobject();
4032 let mut realm = AutoRealm::new(cx, NonNull::new(obj.get()).unwrap());
4033 let cx = &mut *realm;
4034 rooted!(&in(cx) let mut message_clone = UndefinedValue());
4035 if let Ok(ports) = structuredclone::read(cx, this.upcast(), data, message_clone.handle_mut()) {
4036 MessageEvent::dispatch_jsval(
4038 cx,
4039 this.upcast(),
4040 this.upcast(),
4041 message_clone.handle(),
4042 Some(&source_origin.ascii_serialization()),
4043 Some(&*source),
4044 ports,
4045 );
4046 } else {
4047 MessageEvent::dispatch_error(
4049 cx,
4050 this.upcast(),
4051 this.upcast(),
4052 );
4053 }
4054 });
4055 self.as_global_scope()
4057 .task_manager()
4058 .dom_manipulation_task_source()
4059 .queue(task);
4060 }
4061}
4062
4063#[derive(Clone, MallocSizeOf)]
4064pub(crate) struct CSSErrorReporter {
4065 pub(crate) pipelineid: PipelineId,
4066 pub(crate) script_chan: GenericSender<ScriptThreadMessage>,
4067}
4068unsafe_no_jsmanaged_fields!(CSSErrorReporter);
4069
4070impl ParseErrorReporter for CSSErrorReporter {
4071 fn report_error(
4072 &self,
4073 url: &UrlExtraData,
4074 location: SourceLocation,
4075 error: ContextualParseError,
4076 ) {
4077 if log_enabled!(log::Level::Info) {
4078 info!(
4079 "Url:\t{}\n{}:{} {}",
4080 url.0.as_str(),
4081 location.line,
4082 location.column,
4083 error
4084 )
4085 }
4086
4087 let _ = self.script_chan.send(ScriptThreadMessage::ReportCSSError(
4089 self.pipelineid,
4090 url.0.to_string(),
4091 location.line,
4092 location.column,
4093 error.to_string(),
4094 ));
4095 }
4096}
4097
4098fn is_named_element_with_name_attribute(elem: &Element) -> bool {
4099 let type_ = match elem.upcast::<Node>().type_id() {
4100 NodeTypeId::Element(ElementTypeId::HTMLElement(type_)) => type_,
4101 _ => return false,
4102 };
4103 matches!(
4104 type_,
4105 HTMLElementTypeId::HTMLEmbedElement |
4106 HTMLElementTypeId::HTMLFormElement |
4107 HTMLElementTypeId::HTMLImageElement |
4108 HTMLElementTypeId::HTMLObjectElement
4109 )
4110}
4111
4112fn is_named_element_with_id_attribute(elem: &Element) -> bool {
4113 elem.is_html_element() || elem.is_svg_element()
4114}
4115
4116#[expect(unsafe_code)]
4117#[unsafe(no_mangle)]
4118unsafe extern "C" fn dump_js_stack(cx: *mut RawJSContext) {
4120 unsafe {
4121 DumpJSStack(cx, true, false, false);
4122 }
4123}
4124
4125impl WindowHelpers for Window {
4126 fn create_named_properties_object(
4127 cx: &mut JSContext,
4128 proto: HandleObject,
4129 object: MutableHandleObject,
4130 ) {
4131 Self::create_named_properties_object(cx, proto, object)
4132 }
4133}
4134
4135impl HasOrigin for Window {
4136 fn origin(&self) -> MutableOrigin {
4137 Window::origin(self)
4138 }
4139}