1use std::cell::{Cell, RefCell};
21use std::collections::HashSet;
22use std::default::Default;
23use std::option::Option;
24use std::rc::{Rc, Weak};
25use std::result::Result;
26use std::sync::Arc;
27use std::sync::atomic::{AtomicBool, Ordering};
28use std::thread::{self, JoinHandle};
29use std::time::{Duration, Instant, SystemTime};
30
31use background_hang_monitor_api::{
32 BackgroundHangMonitor, BackgroundHangMonitorExitSignal, BackgroundHangMonitorRegister,
33 HangAnnotation, MonitoredComponentId, MonitoredComponentType,
34};
35use chrono::{DateTime, Local};
36use crossbeam_channel::unbounded;
37use data_url::mime::Mime;
38use devtools_traits::{
39 CSSError, DevtoolScriptControlMsg, DevtoolsPageInfo, NavigationState,
40 ScriptToDevtoolsControlMsg, WorkerId,
41};
42use embedder_traits::user_contents::{UserContentManagerId, UserContents, UserScript};
43use embedder_traits::{
44 EmbedderControlId, EmbedderControlResponse, EmbedderMsg, FocusSequenceNumber,
45 InputEventOutcome, JavaScriptEvaluationError, JavaScriptEvaluationId, MediaSessionActionType,
46 Theme, ViewportDetails, WebDriverScriptCommand,
47};
48use encoding_rs::Encoding;
49use fonts::{FontContext, SystemFontServiceProxy};
50use headers::{HeaderMapExt, LastModified, ReferrerPolicy as ReferrerPolicyHeader};
51use http::header::REFRESH;
52use hyper_serde::Serde;
53use ipc_channel::router::ROUTER;
54use js::glue::GetWindowProxyClass;
55use js::jsapi::{GCReason, JS_GC, JSContext as UnsafeJSContext};
56use js::jsval::UndefinedValue;
57use js::rust::ParentRuntime;
58use js::rust::wrappers2::{JS_AddInterruptCallback, SetWindowProxyClass};
59use layout_api::{LayoutConfig, LayoutFactory, RestyleReason, ScriptThreadFactory};
60use media::WindowGLContext;
61use metrics::MAX_TASK_NS;
62use net_traits::image_cache::{ImageCache, ImageCacheFactory, ImageCacheResponseMessage};
63use net_traits::request::{Referrer, RequestId};
64use net_traits::response::ResponseInit;
65use net_traits::{
66 FetchMetadata, FetchResponseMsg, Metadata, NetworkError, ResourceFetchTiming, ResourceThreads,
67 ResourceTimingType,
68};
69use paint_api::{CrossProcessPaintApi, PinchZoomInfos, PipelineExitSource};
70use percent_encoding::percent_decode;
71use profile_traits::mem::{ProcessReports, ReportsChan, perform_memory_report};
72use profile_traits::time::ProfilerCategory;
73use profile_traits::time_profile;
74use rustc_hash::{FxHashMap, FxHashSet};
75use script_bindings::script_runtime::{JSContext, temp_cx};
76use script_traits::{
77 ConstellationInputEvent, DiscardBrowsingContext, DocumentActivity, InitialScriptState,
78 NewPipelineInfo, Painter, ProgressiveWebMetricType, ScriptThreadMessage,
79 UpdatePipelineIdReason,
80};
81use servo_arc::Arc as ServoArc;
82use servo_base::cross_process_instant::CrossProcessInstant;
83use servo_base::generic_channel::GenericSender;
84use servo_base::id::{
85 BrowsingContextId, HistoryStateId, PipelineId, PipelineNamespace, ScriptEventLoopId,
86 TEST_WEBVIEW_ID, WebViewId,
87};
88use servo_base::{Epoch, generic_channel};
89use servo_canvas_traits::webgl::WebGLPipeline;
90use servo_config::{opts, pref, prefs};
91use servo_constellation_traits::{
92 LoadData, LoadOrigin, NavigationHistoryBehavior, RemoteFocusOperation,
93 ScreenshotReadinessResponse, ScriptToConstellationChan, ScriptToConstellationMessage,
94 ScrollStateUpdate, StructuredSerializedData, TargetSnapshotParams, TraversalDirection,
95 WindowSizeType,
96};
97use servo_url::{ImmutableOrigin, MutableOrigin, OriginSnapshot, ServoUrl};
98use storage_traits::StorageThreads;
99use storage_traits::webstorage_thread::WebStorageType;
100use style::context::QuirksMode;
101use style::error_reporting::RustLogReporter;
102use style::global_style_data::GLOBAL_STYLE_DATA;
103use style::media_queries::MediaList;
104use style::stylesheets::{AllowImportRules, DocumentStyleSheet, Origin, Stylesheet};
105use style::thread_state::{self, ThreadState};
106use stylo_atoms::Atom;
107use timers::{TimerEventRequest, TimerId, TimerScheduler};
108use url::Position;
109#[cfg(feature = "webgpu")]
110use webgpu_traits::{WebGPUDevice, WebGPUMsg};
111
112use crate::devtools::DevtoolsState;
113use crate::document_collection::DocumentCollection;
114use crate::document_loader::DocumentLoader;
115use crate::dom::bindings::cell::DomRefCell;
116use crate::dom::bindings::codegen::Bindings::DocumentBinding::{
117 DocumentMethods, DocumentReadyState,
118};
119use crate::dom::bindings::codegen::Bindings::NavigatorBinding::NavigatorMethods;
120use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
121use crate::dom::bindings::conversions::{
122 ConversionResult, SafeFromJSValConvertible, StringificationBehavior,
123};
124use crate::dom::bindings::inheritance::Castable;
125use crate::dom::bindings::reflector::DomGlobal;
126use crate::dom::bindings::root::{Dom, DomRoot};
127use crate::dom::bindings::str::DOMString;
128use crate::dom::csp::{CspReporting, GlobalCspReporting, Violation};
129use crate::dom::customelementregistry::{
130 CallbackReaction, CustomElementDefinition, CustomElementReactionStack,
131};
132use crate::dom::document::focus::FocusableArea;
133use crate::dom::document::{
134 Document, DocumentSource, HasBrowsingContext, IsHTMLDocument, RenderingUpdateReason,
135};
136use crate::dom::element::Element;
137use crate::dom::globalscope::GlobalScope;
138use crate::dom::html::htmliframeelement::{HTMLIFrameElement, IframeContext, ProcessingMode};
139use crate::dom::node::{Node, NodeTraits};
140use crate::dom::servoparser::{ParserContext, ServoParser};
141use crate::dom::types::DebuggerGlobalScope;
142#[cfg(feature = "webgpu")]
143use crate::dom::webgpu::identityhub::IdentityHub;
144use crate::dom::window::Window;
145use crate::dom::windowproxy::{CreatorBrowsingContextInfo, WindowProxy};
146use crate::dom::worklet::WorkletThreadPool;
147use crate::dom::workletglobalscope::WorkletGlobalScopeInit;
148use crate::fetch::FetchCanceller;
149use crate::messaging::{
150 CommonScriptMsg, MainThreadScriptMsg, MixedMessage, ScriptEventLoopSender,
151 ScriptThreadReceivers, ScriptThreadSenders,
152};
153use crate::microtask::{Microtask, MicrotaskQueue};
154use crate::mime::{APPLICATION, CHARSET, MimeExt, TEXT, XML};
155use crate::navigation::{InProgressLoad, NavigationListener};
156use crate::network_listener::{FetchResponseListener, submit_timing};
157use crate::realms::{enter_auto_realm, enter_realm};
158use crate::script_mutation_observers::ScriptMutationObservers;
159use crate::script_runtime::{
160 CanGc, IntroductionType, JSContextHelper, Runtime, ScriptThreadEventCategory,
161 ThreadSafeJSContext,
162};
163use crate::script_window_proxies::ScriptWindowProxies;
164use crate::task_queue::TaskQueue;
165use crate::webdriver_handlers::jsval_to_webdriver;
166use crate::{devtools, webdriver_handlers};
167
168thread_local!(static SCRIPT_THREAD_ROOT: Cell<Option<*const ScriptThread>> = const { Cell::new(None) });
169
170fn with_optional_script_thread<R>(f: impl FnOnce(Option<&ScriptThread>) -> R) -> R {
171 SCRIPT_THREAD_ROOT.with(|root| {
172 f(root
173 .get()
174 .and_then(|script_thread| unsafe { script_thread.as_ref() }))
175 })
176}
177
178pub(crate) fn with_script_thread<R: Default>(f: impl FnOnce(&ScriptThread) -> R) -> R {
179 with_optional_script_thread(|script_thread| script_thread.map(f).unwrap_or_default())
180}
181
182pub(crate) struct IncompleteParserContexts(RefCell<Vec<(PipelineId, ParserContext)>>);
188
189unsafe_no_jsmanaged_fields!(TaskQueue<MainThreadScriptMsg>);
190
191type NodeIdSet = HashSet<String>;
192
193#[derive(Default)]
195pub(crate) struct ScriptUserInteractingGuard {
196 was_interacting: bool,
197 user_interaction_cell: Rc<Cell<bool>>,
198}
199
200impl ScriptUserInteractingGuard {
201 fn new(user_interaction_cell: Rc<Cell<bool>>) -> Self {
202 let was_interacting = user_interaction_cell.get();
203 user_interaction_cell.set(true);
204 Self {
205 was_interacting,
206 user_interaction_cell,
207 }
208 }
209}
210
211impl Drop for ScriptUserInteractingGuard {
212 fn drop(&mut self) {
213 self.user_interaction_cell.set(self.was_interacting)
214 }
215}
216
217struct ScriptThreadUserContents {
220 user_scripts: Rc<Vec<UserScript>>,
221 user_stylesheets: Rc<Vec<DocumentStyleSheet>>,
222}
223
224impl From<UserContents> for ScriptThreadUserContents {
225 fn from(user_contents: UserContents) -> Self {
226 let shared_lock = &GLOBAL_STYLE_DATA.shared_lock;
227 let user_stylesheets = user_contents
228 .stylesheets
229 .iter()
230 .map(|user_stylesheet| {
231 DocumentStyleSheet(ServoArc::new(Stylesheet::from_str(
232 user_stylesheet.source(),
233 user_stylesheet.url().into(),
234 Origin::User,
235 ServoArc::new(shared_lock.wrap(MediaList::empty())),
236 shared_lock.clone(),
237 None,
238 Some(&RustLogReporter),
239 QuirksMode::NoQuirks,
240 AllowImportRules::Yes,
241 )))
242 })
243 .collect();
244 Self {
245 user_scripts: Rc::new(user_contents.scripts),
246 user_stylesheets: Rc::new(user_stylesheets),
247 }
248 }
249}
250
251#[derive(JSTraceable)]
252#[cfg_attr(crown, expect(crown::unrooted_must_root))]
254pub struct ScriptThread {
255 #[no_trace]
258 this: Weak<ScriptThread>,
259
260 last_render_opportunity_time: Cell<Option<Instant>>,
262
263 documents: DomRefCell<DocumentCollection>,
265 window_proxies: Rc<ScriptWindowProxies>,
267 incomplete_loads: DomRefCell<Vec<InProgressLoad>>,
269 incomplete_parser_contexts: IncompleteParserContexts,
271 #[no_trace]
274 image_cache_factory: Arc<dyn ImageCacheFactory>,
275
276 receivers: ScriptThreadReceivers,
279
280 senders: ScriptThreadSenders,
283
284 #[no_trace]
287 resource_threads: ResourceThreads,
288
289 #[no_trace]
290 storage_threads: StorageThreads,
291
292 task_queue: TaskQueue<MainThreadScriptMsg>,
294
295 #[no_trace]
297 background_hang_monitor: Box<dyn BackgroundHangMonitor>,
298 closing: Arc<AtomicBool>,
300
301 #[no_trace]
304 timer_scheduler: RefCell<TimerScheduler>,
305
306 #[no_trace]
308 system_font_service: Arc<SystemFontServiceProxy>,
309
310 js_runtime: Rc<Runtime>,
312
313 #[no_trace]
315 closed_pipelines: DomRefCell<FxHashSet<PipelineId>>,
316
317 microtask_queue: Rc<MicrotaskQueue>,
319
320 mutation_observers: Rc<ScriptMutationObservers>,
321
322 #[no_trace]
324 webgl_chan: Option<WebGLPipeline>,
325
326 #[no_trace]
328 #[cfg(feature = "webxr")]
329 webxr_registry: Option<webxr_api::Registry>,
330
331 worklet_thread_pool: DomRefCell<Option<Rc<WorkletThreadPool>>>,
333
334 docs_with_no_blocking_loads: DomRefCell<FxHashSet<Dom<Document>>>,
337
338 custom_element_reaction_stack: Rc<CustomElementReactionStack>,
340
341 #[no_trace]
343 paint_api: CrossProcessPaintApi,
344
345 profile_script_events: bool,
347
348 unminify_js: bool,
350
351 local_script_source: Option<String>,
353
354 unminify_css: bool,
356
357 #[no_trace]
361 user_contents_for_manager_id:
362 RefCell<FxHashMap<UserContentManagerId, ScriptThreadUserContents>>,
363
364 #[no_trace]
366 player_context: WindowGLContext,
367
368 #[no_trace]
370 pipeline_to_node_ids: DomRefCell<FxHashMap<PipelineId, NodeIdSet>>,
371
372 is_user_interacting: Rc<Cell<bool>>,
374
375 #[no_trace]
377 #[cfg(feature = "webgpu")]
378 gpu_id_hub: Arc<IdentityHub>,
379
380 #[no_trace]
382 layout_factory: Arc<dyn LayoutFactory>,
383
384 #[no_trace]
388 scheduled_update_the_rendering: RefCell<Option<TimerId>>,
389
390 needs_rendering_update: Arc<AtomicBool>,
397
398 debugger_global: Dom<DebuggerGlobalScope>,
399
400 debugger_paused: Cell<bool>,
401
402 #[no_trace]
404 privileged_urls: Vec<ServoUrl>,
405
406 devtools_state: DevtoolsState,
407}
408
409struct BHMExitSignal {
410 closing: Arc<AtomicBool>,
411 js_context: ThreadSafeJSContext,
412}
413
414impl BackgroundHangMonitorExitSignal for BHMExitSignal {
415 fn signal_to_exit(&self) {
416 self.closing.store(true, Ordering::SeqCst);
417 self.js_context.request_interrupt_callback();
418 }
419}
420
421#[expect(unsafe_code)]
422unsafe extern "C" fn interrupt_callback(_cx: *mut UnsafeJSContext) -> bool {
423 let res = ScriptThread::can_continue_running();
424 if !res {
425 ScriptThread::prepare_for_shutdown();
426 }
427 res
428}
429
430struct ScriptMemoryFailsafe<'a> {
435 owner: Option<&'a ScriptThread>,
436}
437
438impl<'a> ScriptMemoryFailsafe<'a> {
439 fn neuter(&mut self) {
440 self.owner = None;
441 }
442
443 fn new(owner: &'a ScriptThread) -> ScriptMemoryFailsafe<'a> {
444 ScriptMemoryFailsafe { owner: Some(owner) }
445 }
446}
447
448impl Drop for ScriptMemoryFailsafe<'_> {
449 fn drop(&mut self) {
450 if let Some(owner) = self.owner {
451 for (_, document) in owner.documents.borrow().iter() {
452 document.window().clear_js_runtime_for_script_deallocation();
453 }
454 }
455 }
456}
457
458impl ScriptThreadFactory for ScriptThread {
459 fn create(
460 state: InitialScriptState,
461 layout_factory: Arc<dyn LayoutFactory>,
462 image_cache_factory: Arc<dyn ImageCacheFactory>,
463 background_hang_monitor_register: Box<dyn BackgroundHangMonitorRegister>,
464 ) -> JoinHandle<()> {
465 PipelineNamespace::set_installer_sender(state.namespace_request_sender.clone());
468
469 let script_thread_id = state.id;
470 thread::Builder::new()
471 .name(format!("Script#{script_thread_id}"))
472 .stack_size(8 * 1024 * 1024) .spawn(move || {
474 profile_traits::debug_event!(
475 "ScriptThread::spawned",
476 script_thread_id = script_thread_id.to_string()
477 );
478 thread_state::initialize(ThreadState::SCRIPT);
479 PipelineNamespace::install(state.pipeline_namespace_id);
480 ScriptEventLoopId::install(state.id);
481 let memory_profiler_sender = state.memory_profiler_sender.clone();
482 let reporter_name = format!("script-reporter-{script_thread_id:?}");
483 let (script_thread, mut cx) = ScriptThread::new(
484 state,
485 layout_factory,
486 image_cache_factory,
487 background_hang_monitor_register,
488 );
489 SCRIPT_THREAD_ROOT.with(|root| {
490 root.set(Some(Rc::as_ptr(&script_thread)));
491 });
492 let mut failsafe = ScriptMemoryFailsafe::new(&script_thread);
493
494 memory_profiler_sender.run_with_memory_reporting(
495 || script_thread.start(&mut cx),
496 reporter_name,
497 ScriptEventLoopSender::MainThread(script_thread.senders.self_sender.clone()),
498 CommonScriptMsg::CollectReports,
499 );
500
501 failsafe.neuter();
503 })
504 .expect("Thread spawning failed")
505 }
506}
507
508impl ScriptThread {
509 pub(crate) fn runtime_handle() -> ParentRuntime {
510 with_optional_script_thread(|script_thread| {
511 script_thread.unwrap().js_runtime.prepare_for_new_child()
512 })
513 }
514
515 pub(crate) fn can_continue_running() -> bool {
516 with_script_thread(|script_thread| script_thread.can_continue_running_inner())
517 }
518
519 pub(crate) fn prepare_for_shutdown() {
520 with_script_thread(|script_thread| {
521 script_thread.prepare_for_shutdown_inner();
522 })
523 }
524
525 pub(crate) fn mutation_observers() -> Rc<ScriptMutationObservers> {
526 with_script_thread(|script_thread| script_thread.mutation_observers.clone())
527 }
528
529 pub(crate) fn microtask_queue() -> Rc<MicrotaskQueue> {
530 with_script_thread(|script_thread| script_thread.microtask_queue.clone())
531 }
532
533 pub(crate) fn mark_document_with_no_blocked_loads(doc: &Document) {
534 with_script_thread(|script_thread| {
535 script_thread
536 .docs_with_no_blocking_loads
537 .borrow_mut()
538 .insert(Dom::from_ref(doc));
539 })
540 }
541
542 pub(crate) fn page_headers_available(
543 webview_id: WebViewId,
544 pipeline_id: PipelineId,
545 metadata: Option<&Metadata>,
546 origin: MutableOrigin,
547 cx: &mut js::context::JSContext,
548 ) -> Option<DomRoot<ServoParser>> {
549 with_script_thread(|script_thread| {
550 script_thread.handle_page_headers_available(
551 webview_id,
552 pipeline_id,
553 metadata,
554 origin,
555 cx,
556 )
557 })
558 }
559
560 pub(crate) fn process_event(msg: CommonScriptMsg, cx: &mut js::context::JSContext) -> bool {
564 with_script_thread(|script_thread| {
565 if !script_thread.can_continue_running_inner() {
566 return false;
567 }
568 script_thread.handle_msg_from_script(MainThreadScriptMsg::Common(msg), cx);
569 true
570 })
571 }
572
573 pub(crate) fn schedule_timer(&self, request: TimerEventRequest) -> TimerId {
575 self.timer_scheduler.borrow_mut().schedule_timer(request)
576 }
577
578 pub(crate) fn cancel_timer(&self, timer_id: TimerId) {
581 self.timer_scheduler.borrow_mut().cancel_timer(timer_id)
582 }
583
584 pub(crate) fn await_stable_state(task: Microtask) {
586 with_script_thread(|script_thread| {
587 script_thread
588 .microtask_queue
589 .enqueue(task, script_thread.get_cx());
590 });
591 }
592
593 fn check_load_origin(source: &LoadOrigin, target: &OriginSnapshot) -> bool {
598 match (source, target.immutable()) {
599 (LoadOrigin::Constellation, _) | (LoadOrigin::WebDriver, _) => {
600 true
602 },
603 (_, ImmutableOrigin::Opaque(_)) => {
604 true
608 },
609 (LoadOrigin::Script(source_origin), _) => source_origin.same_origin_domain(target),
610 }
611 }
612
613 pub(crate) fn set_needs_rendering_update(&self) {
617 self.needs_rendering_update.store(true, Ordering::Relaxed);
618 }
619
620 pub(crate) fn can_navigate_to_javascript_url(
622 cx: &mut js::context::JSContext,
623 initiator_global: &GlobalScope,
624 target_global: &GlobalScope,
625 load_data: &mut LoadData,
626 container: Option<&Element>,
627 ) -> bool {
628 if !Self::check_load_origin(&load_data.load_origin, &target_global.origin().snapshot()) {
632 return false;
633 }
634
635 if initiator_global
638 .get_csp_list()
639 .should_navigation_request_be_blocked(cx, initiator_global, load_data, container)
640 {
641 return false;
642 }
643
644 true
645 }
646
647 pub(crate) fn navigate_to_javascript_url(
650 cx: &mut js::context::JSContext,
651 initiator_global: &GlobalScope,
652 target_global: &GlobalScope,
653 load_data: &mut LoadData,
654 container: Option<&Element>,
655 initial_insertion: Option<bool>,
656 ) -> bool {
657 if !Self::can_navigate_to_javascript_url(
659 cx,
660 initiator_global,
661 target_global,
662 load_data,
663 container,
664 ) {
665 return false;
666 }
667
668 let Some(body) = Self::eval_js_url(cx, target_global, &load_data.url) else {
671 let window_proxy = target_global.as_window().window_proxy();
673 if let Some(frame_element) = window_proxy
674 .frame_element()
675 .and_then(Castable::downcast::<HTMLIFrameElement>)
676 {
677 if initial_insertion == Some(true) && frame_element.is_initial_blank_document() {
679 frame_element.run_iframe_load_event_steps(cx);
680 }
681 }
682 return false;
684 };
685
686 load_data.js_eval_result = Some(body);
692 load_data.url = target_global.get_url();
693 load_data
694 .headers
695 .typed_insert(headers::ContentType::from(mime::TEXT_HTML_UTF_8));
696 true
697 }
698
699 pub(crate) fn get_top_level_for_browsing_context(
700 sender_webview_id: WebViewId,
701 sender_pipeline_id: PipelineId,
702 browsing_context_id: BrowsingContextId,
703 ) -> Option<WebViewId> {
704 with_script_thread(|script_thread| {
705 script_thread.ask_constellation_for_top_level_info(
706 sender_webview_id,
707 sender_pipeline_id,
708 browsing_context_id,
709 )
710 })
711 }
712
713 pub(crate) fn find_document(id: PipelineId) -> Option<DomRoot<Document>> {
714 with_script_thread(|script_thread| script_thread.documents.borrow().find_document(id))
715 }
716
717 #[must_use]
721 pub(crate) fn user_interacting_guard() -> ScriptUserInteractingGuard {
722 with_script_thread(|script_thread| {
723 ScriptUserInteractingGuard::new(script_thread.is_user_interacting.clone())
724 })
725 }
726
727 pub(crate) fn is_user_interacting() -> bool {
728 with_script_thread(|script_thread| script_thread.is_user_interacting.get())
729 }
730
731 pub(crate) fn get_fully_active_document_ids(&self) -> FxHashSet<PipelineId> {
732 self.documents
733 .borrow()
734 .iter()
735 .filter_map(|(id, document)| {
736 if document.is_fully_active() {
737 Some(id)
738 } else {
739 None
740 }
741 })
742 .fold(FxHashSet::default(), |mut set, id| {
743 let _ = set.insert(id);
744 set
745 })
746 }
747
748 pub(crate) fn window_proxies() -> Rc<ScriptWindowProxies> {
749 with_script_thread(|script_thread| script_thread.window_proxies.clone())
750 }
751
752 pub(crate) fn find_window_proxy_by_name(name: &DOMString) -> Option<DomRoot<WindowProxy>> {
753 with_script_thread(|script_thread| {
754 script_thread.window_proxies.find_window_proxy_by_name(name)
755 })
756 }
757
758 pub(crate) fn worklet_thread_pool(image_cache: Arc<dyn ImageCache>) -> Rc<WorkletThreadPool> {
760 with_optional_script_thread(|script_thread| {
761 let script_thread = script_thread.unwrap();
762 script_thread
763 .worklet_thread_pool
764 .borrow_mut()
765 .get_or_insert_with(|| {
766 let init = WorkletGlobalScopeInit {
767 to_script_thread_sender: script_thread.senders.self_sender.clone(),
768 resource_threads: script_thread.resource_threads.clone(),
769 storage_threads: script_thread.storage_threads.clone(),
770 mem_profiler_chan: script_thread.senders.memory_profiler_sender.clone(),
771 time_profiler_chan: script_thread.senders.time_profiler_sender.clone(),
772 devtools_chan: script_thread.senders.devtools_server_sender.clone(),
773 to_constellation_sender: script_thread
774 .senders
775 .pipeline_to_constellation_sender
776 .clone(),
777 to_embedder_sender: script_thread
778 .senders
779 .pipeline_to_embedder_sender
780 .clone(),
781 image_cache,
782 #[cfg(feature = "webgpu")]
783 gpu_id_hub: script_thread.gpu_id_hub.clone(),
784 };
785 Rc::new(WorkletThreadPool::spawn(init))
786 })
787 .clone()
788 })
789 }
790
791 fn handle_register_paint_worklet(
792 &self,
793 pipeline_id: PipelineId,
794 name: Atom,
795 properties: Vec<Atom>,
796 painter: Box<dyn Painter>,
797 ) {
798 let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
799 warn!("Paint worklet registered after pipeline {pipeline_id} closed.");
800 return;
801 };
802
803 window
804 .layout_mut()
805 .register_paint_worklet_modules(name, properties, painter);
806 }
807
808 pub(crate) fn custom_element_reaction_stack() -> Rc<CustomElementReactionStack> {
809 with_optional_script_thread(|script_thread| {
810 script_thread
811 .as_ref()
812 .unwrap()
813 .custom_element_reaction_stack
814 .clone()
815 })
816 }
817
818 pub(crate) fn enqueue_callback_reaction(
819 element: &Element,
820 reaction: CallbackReaction,
821 definition: Option<Rc<CustomElementDefinition>>,
822 ) {
823 with_script_thread(|script_thread| {
824 script_thread
825 .custom_element_reaction_stack
826 .enqueue_callback_reaction(element, reaction, definition);
827 })
828 }
829
830 pub(crate) fn enqueue_upgrade_reaction(
831 element: &Element,
832 definition: Rc<CustomElementDefinition>,
833 ) {
834 with_script_thread(|script_thread| {
835 script_thread
836 .custom_element_reaction_stack
837 .enqueue_upgrade_reaction(element, definition);
838 })
839 }
840
841 pub(crate) fn invoke_backup_element_queue(cx: &mut js::context::JSContext) {
842 with_script_thread(|script_thread| {
843 script_thread
844 .custom_element_reaction_stack
845 .invoke_backup_element_queue(cx);
846 })
847 }
848
849 pub(crate) fn save_node_id(pipeline: PipelineId, node_id: String) {
850 with_script_thread(|script_thread| {
851 script_thread
852 .pipeline_to_node_ids
853 .borrow_mut()
854 .entry(pipeline)
855 .or_default()
856 .insert(node_id);
857 })
858 }
859
860 pub(crate) fn has_node_id(pipeline: PipelineId, node_id: &str) -> bool {
861 with_script_thread(|script_thread| {
862 script_thread
863 .pipeline_to_node_ids
864 .borrow()
865 .get(&pipeline)
866 .is_some_and(|node_ids| node_ids.contains(node_id))
867 })
868 }
869
870 #[servo_tracing::instrument(name = "ScripThread::new", level = "debug", skip_all)]
872 pub(crate) fn new(
873 state: InitialScriptState,
874 layout_factory: Arc<dyn LayoutFactory>,
875 image_cache_factory: Arc<dyn ImageCacheFactory>,
876 background_hang_monitor_register: Box<dyn BackgroundHangMonitorRegister>,
877 ) -> (Rc<ScriptThread>, js::context::JSContext) {
878 let (self_sender, self_receiver) = unbounded();
879 let mut runtime =
880 Runtime::new(Some(ScriptEventLoopSender::MainThread(self_sender.clone())));
881
882 let mut cx = unsafe { runtime.cx() };
885
886 unsafe {
887 SetWindowProxyClass(&cx, GetWindowProxyClass());
888 JS_AddInterruptCallback(&cx, Some(interrupt_callback));
889 }
890
891 let constellation_receiver = state
892 .constellation_to_script_receiver
893 .route_preserving_errors();
894
895 let devtools_server_sender = state.devtools_server_sender;
897 let (ipc_devtools_sender, ipc_devtools_receiver) = generic_channel::channel().unwrap();
898 let devtools_server_receiver = ipc_devtools_receiver.route_preserving_errors();
899
900 let task_queue = TaskQueue::new(self_receiver, self_sender.clone());
901
902 let closing = Arc::new(AtomicBool::new(false));
903 let background_hang_monitor_exit_signal = BHMExitSignal {
904 closing: closing.clone(),
905 js_context: runtime.thread_safe_js_context(),
906 };
907
908 let background_hang_monitor = background_hang_monitor_register.register_component(
909 MonitoredComponentId(state.id, MonitoredComponentType::Script),
912 Duration::from_millis(1000),
913 Duration::from_millis(5000),
914 Box::new(background_hang_monitor_exit_signal),
915 );
916
917 let (image_cache_sender, image_cache_receiver) = unbounded();
918
919 let receivers = ScriptThreadReceivers {
920 constellation_receiver,
921 image_cache_receiver,
922 devtools_server_receiver,
923 #[cfg(feature = "webgpu")]
925 webgpu_receiver: RefCell::new(crossbeam_channel::never()),
926 };
927
928 let opts = opts::get();
929 let senders = ScriptThreadSenders {
930 self_sender,
931 #[cfg(feature = "bluetooth")]
932 bluetooth_sender: state.bluetooth_sender,
933 constellation_sender: state.constellation_to_script_sender,
934 pipeline_to_constellation_sender: state.script_to_constellation_sender,
935 pipeline_to_embedder_sender: state.script_to_embedder_sender.clone(),
936 image_cache_sender,
937 time_profiler_sender: state.time_profiler_sender,
938 memory_profiler_sender: state.memory_profiler_sender,
939 devtools_server_sender,
940 devtools_client_to_script_thread_sender: ipc_devtools_sender,
941 };
942
943 let microtask_queue = runtime.microtask_queue.clone();
944 #[cfg(feature = "webgpu")]
945 let gpu_id_hub = Arc::new(IdentityHub::default());
946
947 let debugger_pipeline_id = PipelineId::new();
948 let script_to_constellation_chan = ScriptToConstellationChan {
949 sender: senders.pipeline_to_constellation_sender.clone(),
950 webview_id: TEST_WEBVIEW_ID,
954 pipeline_id: debugger_pipeline_id,
955 };
956 let debugger_global = DebuggerGlobalScope::new(
957 PipelineId::new(),
958 senders.devtools_server_sender.clone(),
959 senders.devtools_client_to_script_thread_sender.clone(),
960 senders.memory_profiler_sender.clone(),
961 senders.time_profiler_sender.clone(),
962 script_to_constellation_chan,
963 senders.pipeline_to_embedder_sender.clone(),
964 state.resource_threads.clone(),
965 state.storage_threads.clone(),
966 #[cfg(feature = "webgpu")]
967 gpu_id_hub.clone(),
968 &mut cx,
969 );
970
971 debugger_global.execute(&mut cx);
972
973 let user_contents_for_manager_id =
974 FxHashMap::from_iter(state.user_contents_for_manager_id.into_iter().map(
975 |(user_content_manager_id, user_contents)| {
976 (user_content_manager_id, user_contents.into())
977 },
978 ));
979
980 (
981 Rc::new_cyclic(|weak_script_thread| {
982 runtime.set_script_thread(weak_script_thread.clone());
983 Self {
984 documents: DomRefCell::new(DocumentCollection::default()),
985 last_render_opportunity_time: Default::default(),
986 window_proxies: Default::default(),
987 incomplete_loads: DomRefCell::new(vec![]),
988 incomplete_parser_contexts: IncompleteParserContexts(RefCell::new(vec![])),
989 senders,
990 receivers,
991 image_cache_factory,
992 resource_threads: state.resource_threads,
993 storage_threads: state.storage_threads,
994 task_queue,
995 background_hang_monitor,
996 closing,
997 timer_scheduler: Default::default(),
998 microtask_queue,
999 js_runtime: Rc::new(runtime),
1000 closed_pipelines: DomRefCell::new(FxHashSet::default()),
1001 mutation_observers: Default::default(),
1002 system_font_service: Arc::new(state.system_font_service.to_proxy()),
1003 webgl_chan: state.webgl_chan,
1004 #[cfg(feature = "webxr")]
1005 webxr_registry: state.webxr_registry,
1006 worklet_thread_pool: Default::default(),
1007 docs_with_no_blocking_loads: Default::default(),
1008 custom_element_reaction_stack: Rc::new(CustomElementReactionStack::new()),
1009 paint_api: state.cross_process_paint_api,
1010 profile_script_events: opts.debug.profile_script_events,
1011 unminify_js: opts.unminify_js,
1012 local_script_source: opts.local_script_source.clone(),
1013 unminify_css: opts.unminify_css,
1014 user_contents_for_manager_id: RefCell::new(user_contents_for_manager_id),
1015 player_context: state.player_context,
1016 pipeline_to_node_ids: Default::default(),
1017 is_user_interacting: Rc::new(Cell::new(false)),
1018 #[cfg(feature = "webgpu")]
1019 gpu_id_hub,
1020 layout_factory,
1021 scheduled_update_the_rendering: Default::default(),
1022 needs_rendering_update: Arc::new(AtomicBool::new(false)),
1023 debugger_global: debugger_global.as_traced(),
1024 debugger_paused: Cell::new(false),
1025 privileged_urls: state.privileged_urls,
1026 this: weak_script_thread.clone(),
1027 devtools_state: Default::default(),
1028 }
1029 }),
1030 cx,
1031 )
1032 }
1033
1034 #[expect(unsafe_code)]
1035 pub(crate) fn get_cx(&self) -> JSContext {
1036 unsafe { JSContext::from_ptr(js::rust::Runtime::get().unwrap().as_ptr()) }
1037 }
1038
1039 fn can_continue_running_inner(&self) -> bool {
1041 if self.closing.load(Ordering::SeqCst) {
1042 return false;
1043 }
1044 true
1045 }
1046
1047 fn prepare_for_shutdown_inner(&self) {
1049 let docs = self.documents.borrow();
1050 for (_, document) in docs.iter() {
1051 document
1052 .owner_global()
1053 .task_manager()
1054 .cancel_all_tasks_and_ignore_future_tasks();
1055 }
1056 }
1057
1058 pub(crate) fn start(&self, cx: &mut js::context::JSContext) {
1061 debug!("Starting script thread.");
1062 while self.handle_msgs(cx) {
1063 debug!("Running script thread.");
1065 }
1066 debug!("Stopped script thread.");
1067 }
1068
1069 fn process_pending_input_events(
1071 &self,
1072 cx: &mut js::context::JSContext,
1073 pipeline_id: PipelineId,
1074 ) {
1075 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
1076 warn!("Processing pending input events for closed pipeline {pipeline_id}.");
1077 return;
1078 };
1079 if document.window().Closed() {
1081 warn!("Input event sent to a pipeline with a closed window {pipeline_id}.");
1082 return;
1083 }
1084 if !document.event_handler().has_pending_input_events() {
1085 return;
1086 }
1087
1088 let _guard = ScriptUserInteractingGuard::new(self.is_user_interacting.clone());
1089 document.event_handler().handle_pending_input_events(cx);
1090 }
1091
1092 fn cancel_scheduled_update_the_rendering(&self) {
1093 if let Some(timer_id) = self.scheduled_update_the_rendering.borrow_mut().take() {
1094 self.timer_scheduler.borrow_mut().cancel_timer(timer_id);
1095 }
1096 }
1097
1098 fn schedule_update_the_rendering_timer_if_necessary(&self, delay: Duration) {
1099 if self.scheduled_update_the_rendering.borrow().is_some() {
1100 return;
1101 }
1102
1103 debug!("Scheduling ScriptThread animation frame.");
1104 let trigger_script_thread_animation = self.needs_rendering_update.clone();
1105 let timer_id = self.schedule_timer(TimerEventRequest {
1106 callback: Box::new(move || {
1107 trigger_script_thread_animation.store(true, Ordering::Relaxed);
1108 }),
1109 duration: delay,
1110 });
1111
1112 *self.scheduled_update_the_rendering.borrow_mut() = Some(timer_id);
1113 }
1114
1115 pub(crate) fn update_the_rendering(&self, cx: &mut js::context::JSContext) -> bool {
1122 self.last_render_opportunity_time.set(Some(Instant::now()));
1123 self.cancel_scheduled_update_the_rendering();
1124 self.needs_rendering_update.store(false, Ordering::Relaxed);
1125
1126 if !self.can_continue_running_inner() {
1127 return false;
1128 }
1129
1130 let documents_in_order = self.documents.borrow().documents_in_order();
1149
1150 let mut painters_generating_frames = FxHashSet::default();
1155 for pipeline_id in documents_in_order.iter() {
1156 let document = self
1157 .documents
1158 .borrow()
1159 .find_document(*pipeline_id)
1160 .expect("Got pipeline for Document not managed by this ScriptThread.");
1161
1162 if !document.is_fully_active() {
1163 continue;
1164 }
1165
1166 if document.waiting_on_canvas_image_updates() {
1167 continue;
1168 }
1169
1170 if
1173 document.is_render_blocked()
1175 {
1186 continue;
1187 }
1188
1189 document.clear_rendering_update_reasons();
1192
1193 self.process_pending_input_events(cx, *pipeline_id);
1200
1201 let resized = document.window().run_the_resize_steps(cx);
1203
1204 document.run_the_scroll_steps(cx);
1206
1207 if resized {
1209 document
1211 .window()
1212 .evaluate_media_queries_and_report_changes(cx);
1213
1214 document.react_to_environment_changes()
1217 }
1218
1219 let mut realm = enter_auto_realm(cx, &*document);
1220 let cx = &mut realm.current_realm();
1221
1222 document.update_animations_and_send_events(cx);
1226
1227 document.run_the_animation_frame_callbacks(cx);
1237
1238 let mut depth = Default::default();
1240 while document.gather_active_resize_observations_at_depth(&depth) {
1241 depth = document.broadcast_active_resize_observations(cx);
1243 }
1244
1245 if document.has_skipped_resize_observations() {
1246 document.deliver_resize_loop_error_notification(CanGc::from_cx(cx));
1247 document.add_rendering_update_reason(
1250 RenderingUpdateReason::ResizeObserverStartedObservingTarget,
1251 );
1252 }
1253
1254 document.focus_handler().perform_focus_fixup_rule(cx);
1259
1260 document
1268 .update_intersection_observer_steps(CrossProcessInstant::now(), CanGc::from_cx(cx));
1269
1270 if document.update_the_rendering().0.needs_frame() {
1275 painters_generating_frames.insert(document.webview_id().into());
1276 }
1277
1278 }
1281
1282 let should_generate_frame = !painters_generating_frames.is_empty();
1283 if should_generate_frame {
1284 self.paint_api
1285 .generate_frame(painters_generating_frames.into_iter().collect());
1286 }
1287
1288 self.perform_a_microtask_checkpoint(cx);
1291 should_generate_frame
1292 }
1293
1294 fn maybe_schedule_rendering_opportunity_after_ipc_message(
1301 &self,
1302 built_any_display_lists: bool,
1303 ) {
1304 let needs_rendering_update = self
1305 .documents
1306 .borrow()
1307 .iter()
1308 .any(|(_, document)| document.needs_rendering_update());
1309 let running_animations = self.documents.borrow().iter().any(|(_, document)| {
1310 document.is_fully_active() &&
1311 !document.window().throttled() &&
1312 (document.animations().running_animation_count() != 0 ||
1313 document.has_active_request_animation_frame_callbacks())
1314 });
1315
1316 if !needs_rendering_update && !running_animations {
1320 return;
1321 }
1322
1323 if running_animations && built_any_display_lists {
1327 return;
1328 }
1329
1330 let animation_delay = if running_animations && !needs_rendering_update {
1338 Duration::from_millis(30)
1342 } else {
1343 Duration::from_millis(20)
1346 };
1347
1348 let time_since_last_rendering_opportunity = self
1349 .last_render_opportunity_time
1350 .get()
1351 .map(|last_render_opportunity_time| Instant::now() - last_render_opportunity_time)
1352 .unwrap_or(Duration::MAX)
1353 .min(animation_delay);
1354 self.schedule_update_the_rendering_timer_if_necessary(
1355 animation_delay - time_since_last_rendering_opportunity,
1356 );
1357 }
1358
1359 fn maybe_fulfill_font_ready_promises(&self, cx: &mut js::context::JSContext) {
1362 let mut sent_message = false;
1363 for (_, document) in self.documents.borrow().iter() {
1364 sent_message =
1365 document.maybe_fulfill_font_ready_promise(CanGc::from_cx(cx)) || sent_message;
1366 }
1367
1368 if sent_message {
1369 self.perform_a_microtask_checkpoint(cx);
1370 }
1371 }
1372
1373 fn maybe_resolve_pending_screenshot_readiness_requests(&self, can_gc: CanGc) {
1377 for (_, document) in self.documents.borrow().iter() {
1378 document
1379 .window()
1380 .maybe_resolve_pending_screenshot_readiness_requests(can_gc);
1381 }
1382 }
1383
1384 fn handle_msgs(&self, cx: &mut js::context::JSContext) -> bool {
1386 let mut sequential = vec![];
1388
1389 self.background_hang_monitor.notify_wait();
1391
1392 debug!("Waiting for event.");
1394 let fully_active = self.get_fully_active_document_ids();
1395 let mut event = self.receivers.recv(
1396 &self.task_queue,
1397 &self.timer_scheduler.borrow(),
1398 &fully_active,
1399 );
1400
1401 loop {
1402 debug!("Handling event: {event:?}");
1403
1404 self.timer_scheduler
1406 .borrow_mut()
1407 .dispatch_completed_timers();
1408
1409 match event {
1411 MixedMessage::FromConstellation(ScriptThreadMessage::SpawnPipeline(
1415 new_pipeline_info,
1416 )) => {
1417 self.spawn_pipeline(new_pipeline_info);
1418 },
1419 MixedMessage::FromScript(MainThreadScriptMsg::Inactive) => {
1420 },
1423 MixedMessage::FromConstellation(ScriptThreadMessage::ExitFullScreen(id)) => self
1424 .profile_event(ScriptThreadEventCategory::ExitFullscreen, Some(id), || {
1425 self.handle_exit_fullscreen(id, cx);
1426 }),
1427 _ => {
1428 sequential.push(event);
1429 },
1430 }
1431
1432 match self.receivers.try_recv(&self.task_queue, &fully_active) {
1436 Some(new_event) => event = new_event,
1437 None => break,
1438 }
1439 }
1440
1441 debug!("Processing events.");
1443 for msg in sequential {
1444 debug!("Processing event {:?}.", msg);
1445 let category = self.categorize_msg(&msg);
1446 let pipeline_id = msg.pipeline_id();
1447 let _realm = pipeline_id.and_then(|id| {
1448 let global = self.documents.borrow().find_global(id);
1449 global.map(|global| enter_realm(&*global))
1450 });
1451
1452 if self.closing.load(Ordering::SeqCst) {
1453 match msg {
1455 MixedMessage::FromConstellation(ScriptThreadMessage::ExitScriptThread) => {
1456 self.handle_exit_script_thread_msg(cx);
1457 return false;
1458 },
1459 MixedMessage::FromConstellation(ScriptThreadMessage::ExitPipeline(
1460 webview_id,
1461 pipeline_id,
1462 discard_browsing_context,
1463 )) => {
1464 self.handle_exit_pipeline_msg(
1465 webview_id,
1466 pipeline_id,
1467 discard_browsing_context,
1468 cx,
1469 );
1470 },
1471 _ => {},
1472 }
1473 continue;
1474 }
1475
1476 let exiting = self.profile_event(category, pipeline_id, || {
1477 match msg {
1478 MixedMessage::FromConstellation(ScriptThreadMessage::ExitScriptThread) => {
1479 self.handle_exit_script_thread_msg(cx);
1480 return true;
1481 },
1482 MixedMessage::FromConstellation(inner_msg) => {
1483 self.handle_msg_from_constellation(inner_msg, cx)
1484 },
1485 MixedMessage::FromScript(inner_msg) => {
1486 self.handle_msg_from_script(inner_msg, cx)
1487 },
1488 MixedMessage::FromDevtools(inner_msg) => {
1489 self.handle_msg_from_devtools(inner_msg, cx)
1490 },
1491 MixedMessage::FromImageCache(inner_msg) => {
1492 self.handle_msg_from_image_cache(inner_msg, cx)
1493 },
1494 #[cfg(feature = "webgpu")]
1495 MixedMessage::FromWebGPUServer(inner_msg) => {
1496 self.handle_msg_from_webgpu_server(inner_msg, cx)
1497 },
1498 MixedMessage::TimerFired => {},
1499 }
1500
1501 false
1502 });
1503
1504 if exiting {
1506 return false;
1507 }
1508
1509 self.perform_a_microtask_checkpoint(cx);
1512 }
1513
1514 for (_, doc) in self.documents.borrow().iter() {
1515 let window = doc.window();
1516 window
1517 .upcast::<GlobalScope>()
1518 .perform_a_dom_garbage_collection_checkpoint();
1519 }
1520
1521 {
1522 let mut docs = self.docs_with_no_blocking_loads.borrow_mut();
1524 for document in docs.iter() {
1525 let _realm = enter_auto_realm(cx, &**document);
1526 document.maybe_queue_document_completion();
1527 }
1528 docs.clear();
1529 }
1530
1531 let built_any_display_lists =
1532 self.needs_rendering_update.load(Ordering::Relaxed) && self.update_the_rendering(cx);
1533
1534 self.maybe_fulfill_font_ready_promises(cx);
1535 self.maybe_resolve_pending_screenshot_readiness_requests(CanGc::from_cx(cx));
1536
1537 self.maybe_schedule_rendering_opportunity_after_ipc_message(built_any_display_lists);
1539
1540 true
1541 }
1542
1543 fn categorize_msg(&self, msg: &MixedMessage) -> ScriptThreadEventCategory {
1544 match *msg {
1545 MixedMessage::FromConstellation(ref inner_msg) => match *inner_msg {
1546 ScriptThreadMessage::SendInputEvent(..) => ScriptThreadEventCategory::InputEvent,
1547 _ => ScriptThreadEventCategory::ConstellationMsg,
1548 },
1549 MixedMessage::FromDevtools(_) => ScriptThreadEventCategory::DevtoolsMsg,
1550 MixedMessage::FromImageCache(_) => ScriptThreadEventCategory::ImageCacheMsg,
1551 MixedMessage::FromScript(ref inner_msg) => match *inner_msg {
1552 MainThreadScriptMsg::Common(CommonScriptMsg::Task(category, ..)) => category,
1553 MainThreadScriptMsg::RegisterPaintWorklet { .. } => {
1554 ScriptThreadEventCategory::WorkletEvent
1555 },
1556 _ => ScriptThreadEventCategory::ScriptEvent,
1557 },
1558 #[cfg(feature = "webgpu")]
1559 MixedMessage::FromWebGPUServer(_) => ScriptThreadEventCategory::WebGPUMsg,
1560 MixedMessage::TimerFired => ScriptThreadEventCategory::TimerEvent,
1561 }
1562 }
1563
1564 fn profile_event<F, R>(
1565 &self,
1566 category: ScriptThreadEventCategory,
1567 pipeline_id: Option<PipelineId>,
1568 f: F,
1569 ) -> R
1570 where
1571 F: FnOnce() -> R,
1572 {
1573 self.background_hang_monitor
1574 .notify_activity(HangAnnotation::Script(category.into()));
1575 let start = Instant::now();
1576 let value = if self.profile_script_events {
1577 let profiler_chan = self.senders.time_profiler_sender.clone();
1578 match category {
1579 ScriptThreadEventCategory::SpawnPipeline => {
1580 time_profile!(
1581 ProfilerCategory::ScriptSpawnPipeline,
1582 None,
1583 profiler_chan,
1584 f
1585 )
1586 },
1587 ScriptThreadEventCategory::ConstellationMsg => time_profile!(
1588 ProfilerCategory::ScriptConstellationMsg,
1589 None,
1590 profiler_chan,
1591 f
1592 ),
1593 ScriptThreadEventCategory::DatabaseAccessEvent => time_profile!(
1594 ProfilerCategory::ScriptDatabaseAccessEvent,
1595 None,
1596 profiler_chan,
1597 f
1598 ),
1599 ScriptThreadEventCategory::DevtoolsMsg => {
1600 time_profile!(ProfilerCategory::ScriptDevtoolsMsg, None, profiler_chan, f)
1601 },
1602 ScriptThreadEventCategory::DocumentEvent => time_profile!(
1603 ProfilerCategory::ScriptDocumentEvent,
1604 None,
1605 profiler_chan,
1606 f
1607 ),
1608 ScriptThreadEventCategory::InputEvent => {
1609 time_profile!(ProfilerCategory::ScriptInputEvent, None, profiler_chan, f)
1610 },
1611 ScriptThreadEventCategory::FileRead => {
1612 time_profile!(ProfilerCategory::ScriptFileRead, None, profiler_chan, f)
1613 },
1614 ScriptThreadEventCategory::FontLoading => {
1615 time_profile!(ProfilerCategory::ScriptFontLoading, None, profiler_chan, f)
1616 },
1617 ScriptThreadEventCategory::FormPlannedNavigation => time_profile!(
1618 ProfilerCategory::ScriptPlannedNavigation,
1619 None,
1620 profiler_chan,
1621 f
1622 ),
1623 ScriptThreadEventCategory::GeolocationEvent => {
1624 time_profile!(
1625 ProfilerCategory::ScriptGeolocationEvent,
1626 None,
1627 profiler_chan,
1628 f
1629 )
1630 },
1631 ScriptThreadEventCategory::NavigationAndTraversalEvent => {
1632 time_profile!(
1633 ProfilerCategory::ScriptNavigationAndTraversalEvent,
1634 None,
1635 profiler_chan,
1636 f
1637 )
1638 },
1639 ScriptThreadEventCategory::ImageCacheMsg => time_profile!(
1640 ProfilerCategory::ScriptImageCacheMsg,
1641 None,
1642 profiler_chan,
1643 f
1644 ),
1645 ScriptThreadEventCategory::NetworkEvent => {
1646 time_profile!(ProfilerCategory::ScriptNetworkEvent, None, profiler_chan, f)
1647 },
1648 ScriptThreadEventCategory::PortMessage => {
1649 time_profile!(ProfilerCategory::ScriptPortMessage, None, profiler_chan, f)
1650 },
1651 ScriptThreadEventCategory::Resize => {
1652 time_profile!(ProfilerCategory::ScriptResize, None, profiler_chan, f)
1653 },
1654 ScriptThreadEventCategory::ScriptEvent => {
1655 time_profile!(ProfilerCategory::ScriptEvent, None, profiler_chan, f)
1656 },
1657 ScriptThreadEventCategory::SetScrollState => time_profile!(
1658 ProfilerCategory::ScriptSetScrollState,
1659 None,
1660 profiler_chan,
1661 f
1662 ),
1663 ScriptThreadEventCategory::UpdateReplacedElement => time_profile!(
1664 ProfilerCategory::ScriptUpdateReplacedElement,
1665 None,
1666 profiler_chan,
1667 f
1668 ),
1669 ScriptThreadEventCategory::StylesheetLoad => time_profile!(
1670 ProfilerCategory::ScriptStylesheetLoad,
1671 None,
1672 profiler_chan,
1673 f
1674 ),
1675 ScriptThreadEventCategory::SetViewport => {
1676 time_profile!(ProfilerCategory::ScriptSetViewport, None, profiler_chan, f)
1677 },
1678 ScriptThreadEventCategory::TimerEvent => {
1679 time_profile!(ProfilerCategory::ScriptTimerEvent, None, profiler_chan, f)
1680 },
1681 ScriptThreadEventCategory::WebSocketEvent => time_profile!(
1682 ProfilerCategory::ScriptWebSocketEvent,
1683 None,
1684 profiler_chan,
1685 f
1686 ),
1687 ScriptThreadEventCategory::WorkerEvent => {
1688 time_profile!(ProfilerCategory::ScriptWorkerEvent, None, profiler_chan, f)
1689 },
1690 ScriptThreadEventCategory::WorkletEvent => {
1691 time_profile!(ProfilerCategory::ScriptWorkletEvent, None, profiler_chan, f)
1692 },
1693 ScriptThreadEventCategory::ServiceWorkerEvent => time_profile!(
1694 ProfilerCategory::ScriptServiceWorkerEvent,
1695 None,
1696 profiler_chan,
1697 f
1698 ),
1699 ScriptThreadEventCategory::EnterFullscreen => time_profile!(
1700 ProfilerCategory::ScriptEnterFullscreen,
1701 None,
1702 profiler_chan,
1703 f
1704 ),
1705 ScriptThreadEventCategory::ExitFullscreen => time_profile!(
1706 ProfilerCategory::ScriptExitFullscreen,
1707 None,
1708 profiler_chan,
1709 f
1710 ),
1711 ScriptThreadEventCategory::PerformanceTimelineTask => time_profile!(
1712 ProfilerCategory::ScriptPerformanceEvent,
1713 None,
1714 profiler_chan,
1715 f
1716 ),
1717 ScriptThreadEventCategory::Rendering => {
1718 time_profile!(ProfilerCategory::ScriptRendering, None, profiler_chan, f)
1719 },
1720 #[cfg(feature = "webgpu")]
1721 ScriptThreadEventCategory::WebGPUMsg => {
1722 time_profile!(ProfilerCategory::ScriptWebGPUMsg, None, profiler_chan, f)
1723 },
1724 }
1725 } else {
1726 f()
1727 };
1728 let task_duration = start.elapsed();
1729 for (doc_id, doc) in self.documents.borrow().iter() {
1730 if let Some(pipeline_id) = pipeline_id {
1731 if pipeline_id == doc_id && task_duration.as_nanos() > MAX_TASK_NS {
1732 if opts::get().debug.progressive_web_metrics {
1733 println!(
1734 "Task took longer than max allowed ({category:?}) {:?}",
1735 task_duration.as_nanos()
1736 );
1737 }
1738 doc.start_tti();
1739 }
1740 }
1741 doc.record_tti_if_necessary();
1742 }
1743 value
1744 }
1745
1746 fn handle_msg_from_constellation(
1747 &self,
1748 msg: ScriptThreadMessage,
1749 cx: &mut js::context::JSContext,
1750 ) {
1751 match msg {
1752 ScriptThreadMessage::StopDelayingLoadEventsMode(pipeline_id) => {
1753 self.handle_stop_delaying_load_events_mode(pipeline_id)
1754 },
1755 ScriptThreadMessage::NavigateIframe(
1756 parent_pipeline_id,
1757 browsing_context_id,
1758 load_data,
1759 history_handling,
1760 target_snapshot_params,
1761 ) => self.handle_navigate_iframe(
1762 parent_pipeline_id,
1763 browsing_context_id,
1764 load_data,
1765 history_handling,
1766 target_snapshot_params,
1767 cx,
1768 ),
1769 ScriptThreadMessage::UnloadDocument(pipeline_id) => {
1770 self.handle_unload_document(cx, pipeline_id)
1771 },
1772 ScriptThreadMessage::ResizeInactive(id, new_size) => {
1773 self.handle_resize_inactive_msg(id, new_size)
1774 },
1775 ScriptThreadMessage::ThemeChange(_, theme) => {
1776 self.handle_theme_change_msg(theme);
1777 },
1778 ScriptThreadMessage::GetDocumentOrigin(pipeline_id, result_sender) => {
1779 self.handle_get_document_origin(pipeline_id, result_sender);
1780 },
1781 ScriptThreadMessage::GetTitle(pipeline_id) => self.handle_get_title_msg(pipeline_id),
1782 ScriptThreadMessage::SetDocumentActivity(pipeline_id, activity) => {
1783 self.handle_set_document_activity_msg(cx, pipeline_id, activity)
1784 },
1785 ScriptThreadMessage::SetThrottled(webview_id, pipeline_id, throttled) => {
1786 self.handle_set_throttled_msg(webview_id, pipeline_id, throttled)
1787 },
1788 ScriptThreadMessage::SetThrottledInContainingIframe(
1789 _,
1790 parent_pipeline_id,
1791 browsing_context_id,
1792 throttled,
1793 ) => self.handle_set_throttled_in_containing_iframe_msg(
1794 parent_pipeline_id,
1795 browsing_context_id,
1796 throttled,
1797 ),
1798 ScriptThreadMessage::PostMessage {
1799 target: target_pipeline_id,
1800 source_webview,
1801 source_with_ancestry,
1802 target_origin: origin,
1803 source_origin,
1804 data,
1805 } => self.handle_post_message_msg(
1806 cx,
1807 target_pipeline_id,
1808 source_webview,
1809 source_with_ancestry,
1810 origin,
1811 source_origin,
1812 *data,
1813 ),
1814 ScriptThreadMessage::UpdatePipelineId(
1815 parent_pipeline_id,
1816 browsing_context_id,
1817 webview_id,
1818 new_pipeline_id,
1819 reason,
1820 ) => self.handle_update_pipeline_id(
1821 parent_pipeline_id,
1822 browsing_context_id,
1823 webview_id,
1824 new_pipeline_id,
1825 reason,
1826 cx,
1827 ),
1828 ScriptThreadMessage::UpdateHistoryState(pipeline_id, history_state_id, url) => {
1829 self.handle_update_history_state_msg(cx, pipeline_id, history_state_id, url)
1830 },
1831 ScriptThreadMessage::RemoveHistoryStates(pipeline_id, history_states) => {
1832 self.handle_remove_history_states(pipeline_id, history_states)
1833 },
1834 ScriptThreadMessage::FocusDocumentAsPartOfFocusingSteps(
1835 pipeline_id,
1836 sequence,
1837 iframe_browsing_context_id,
1838 ) => self.handle_focus_document_as_part_of_focusing_steps(
1839 cx,
1840 pipeline_id,
1841 sequence,
1842 iframe_browsing_context_id,
1843 ),
1844 ScriptThreadMessage::UnfocusDocumentAsPartOfFocusingSteps(pipeline_id, sequence) => {
1845 self.handle_unfocus_document_as_part_of_focusing_steps(cx, pipeline_id, sequence);
1846 },
1847 ScriptThreadMessage::FocusDocument(pipeline_id, remote_focus_operation) => {
1848 self.handle_focus_document(cx, pipeline_id, remote_focus_operation);
1849 },
1850 ScriptThreadMessage::WebDriverScriptCommand(pipeline_id, msg) => {
1851 self.handle_webdriver_msg(pipeline_id, msg, cx)
1852 },
1853 ScriptThreadMessage::WebFontLoaded(pipeline_id) => {
1854 self.handle_web_font_loaded(pipeline_id)
1855 },
1856 ScriptThreadMessage::DispatchIFrameLoadEvent {
1857 target: browsing_context_id,
1858 parent: parent_id,
1859 child: child_id,
1860 } => self.handle_iframe_load_event(parent_id, browsing_context_id, child_id, cx),
1861 ScriptThreadMessage::DispatchStorageEvent(
1862 pipeline_id,
1863 storage,
1864 url,
1865 key,
1866 old_value,
1867 new_value,
1868 ) => {
1869 self.handle_storage_event(pipeline_id, storage, url, key, old_value, new_value, cx)
1870 },
1871 ScriptThreadMessage::ReportCSSError(pipeline_id, filename, line, column, msg) => {
1872 self.handle_css_error_reporting(pipeline_id, filename, line, column, msg)
1873 },
1874 ScriptThreadMessage::Reload(pipeline_id) => self.handle_reload(pipeline_id, cx),
1875 ScriptThreadMessage::Resize(id, size, size_type) => {
1876 self.handle_resize_message(id, size, size_type);
1877 },
1878 ScriptThreadMessage::ExitPipeline(
1879 webview_id,
1880 pipeline_id,
1881 discard_browsing_context,
1882 ) => {
1883 self.handle_exit_pipeline_msg(webview_id, pipeline_id, discard_browsing_context, cx)
1884 },
1885 ScriptThreadMessage::PaintMetric(
1886 pipeline_id,
1887 metric_type,
1888 metric_value,
1889 first_reflow,
1890 ) => self.handle_paint_metric(
1891 pipeline_id,
1892 metric_type,
1893 metric_value,
1894 first_reflow,
1895 CanGc::from_cx(cx),
1896 ),
1897 ScriptThreadMessage::MediaSessionAction(pipeline_id, action) => {
1898 self.handle_media_session_action(cx, pipeline_id, action)
1899 },
1900 ScriptThreadMessage::SendInputEvent(webview_id, id, event) => {
1901 self.handle_input_event(webview_id, id, event)
1902 },
1903 #[cfg(feature = "webgpu")]
1904 ScriptThreadMessage::SetWebGPUPort(port) => {
1905 *self.receivers.webgpu_receiver.borrow_mut() = port.route_preserving_errors();
1906 },
1907 ScriptThreadMessage::TickAllAnimations(_webviews) => {
1908 self.set_needs_rendering_update();
1909 },
1910 ScriptThreadMessage::NoLongerWaitingOnAsychronousImageUpdates(pipeline_id) => {
1911 if let Some(document) = self.documents.borrow().find_document(pipeline_id) {
1912 document.handle_no_longer_waiting_on_asynchronous_image_updates();
1913 }
1914 },
1915 msg @ ScriptThreadMessage::SpawnPipeline(..) |
1916 msg @ ScriptThreadMessage::ExitFullScreen(..) |
1917 msg @ ScriptThreadMessage::ExitScriptThread => {
1918 panic!("should have handled {:?} already", msg)
1919 },
1920 ScriptThreadMessage::SetScrollStates(pipeline_id, scroll_states) => {
1921 self.handle_set_scroll_states(pipeline_id, scroll_states)
1922 },
1923 ScriptThreadMessage::EvaluateJavaScript(
1924 webview_id,
1925 pipeline_id,
1926 evaluation_id,
1927 script,
1928 ) => {
1929 self.handle_evaluate_javascript(webview_id, pipeline_id, evaluation_id, script, cx);
1930 },
1931 ScriptThreadMessage::SendImageKeysBatch(pipeline_id, image_keys) => {
1932 if let Some(window) = self.documents.borrow().find_window(pipeline_id) {
1933 window
1934 .image_cache()
1935 .fill_key_cache_with_batch_of_keys(image_keys);
1936 } else {
1937 warn!(
1938 "Could not find window corresponding to an image cache to send image keys to pipeline {:?}",
1939 pipeline_id
1940 );
1941 }
1942 },
1943 ScriptThreadMessage::RefreshCursor(pipeline_id) => {
1944 self.handle_refresh_cursor(pipeline_id);
1945 },
1946 ScriptThreadMessage::PreferencesUpdated(updates) => {
1947 let mut current_preferences = prefs::get().clone();
1948 for (name, value) in updates {
1949 current_preferences.set_value(&name, value);
1950 }
1951 prefs::set(current_preferences);
1952 },
1953 ScriptThreadMessage::ForwardKeyboardScroll(pipeline_id, scroll) => {
1954 if let Some(document) = self.documents.borrow().find_document(pipeline_id) {
1955 document.event_handler().do_keyboard_scroll(scroll);
1956 }
1957 },
1958 ScriptThreadMessage::RequestScreenshotReadiness(webview_id, pipeline_id) => {
1959 self.handle_request_screenshot_readiness(
1960 webview_id,
1961 pipeline_id,
1962 CanGc::from_cx(cx),
1963 );
1964 },
1965 ScriptThreadMessage::EmbedderControlResponse(id, response) => {
1966 self.handle_embedder_control_response(id, response, cx);
1967 },
1968 ScriptThreadMessage::SetUserContents(user_content_manager_id, user_contents) => {
1969 self.user_contents_for_manager_id
1970 .borrow_mut()
1971 .insert(user_content_manager_id, user_contents.into());
1972 },
1973 ScriptThreadMessage::DestroyUserContentManager(user_content_manager_id) => {
1974 self.user_contents_for_manager_id
1975 .borrow_mut()
1976 .remove(&user_content_manager_id);
1977 },
1978 ScriptThreadMessage::UpdatePinchZoomInfos(id, pinch_zoom_infos) => {
1979 self.handle_update_pinch_zoom_infos(id, pinch_zoom_infos, CanGc::from_cx(cx));
1980 },
1981 ScriptThreadMessage::SetAccessibilityActive(pipeline_id, active, epoch) => {
1982 self.set_accessibility_active(pipeline_id, active, epoch);
1983 },
1984 ScriptThreadMessage::TriggerGarbageCollection => unsafe {
1985 JS_GC(*GlobalScope::get_cx(), GCReason::API);
1986 },
1987 }
1988 }
1989
1990 fn handle_set_scroll_states(&self, pipeline_id: PipelineId, scroll_states: ScrollStateUpdate) {
1991 let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
1992 warn!("Received scroll states for closed pipeline {pipeline_id}");
1993 return;
1994 };
1995
1996 self.profile_event(
1997 ScriptThreadEventCategory::SetScrollState,
1998 Some(pipeline_id),
1999 || {
2000 window
2001 .layout_mut()
2002 .set_scroll_offsets_from_renderer(&scroll_states.offsets);
2003 },
2004 );
2005
2006 window
2007 .Document()
2008 .event_handler()
2009 .handle_embedder_scroll_event(scroll_states.scrolled_node);
2010 }
2011
2012 #[cfg(feature = "webgpu")]
2013 fn handle_msg_from_webgpu_server(&self, msg: WebGPUMsg, cx: &mut js::context::JSContext) {
2014 match msg {
2015 WebGPUMsg::FreeAdapter(id) => self.gpu_id_hub.free_adapter_id(id),
2016 WebGPUMsg::FreeDevice {
2017 device_id,
2018 pipeline_id,
2019 } => {
2020 self.gpu_id_hub.free_device_id(device_id);
2021 if let Some(global) = self.documents.borrow().find_global(pipeline_id) {
2022 global.remove_gpu_device(WebGPUDevice(device_id));
2023 } },
2025 WebGPUMsg::FreeBuffer(id) => self.gpu_id_hub.free_buffer_id(id),
2026 WebGPUMsg::FreePipelineLayout(id) => self.gpu_id_hub.free_pipeline_layout_id(id),
2027 WebGPUMsg::FreeComputePipeline(id) => self.gpu_id_hub.free_compute_pipeline_id(id),
2028 WebGPUMsg::FreeBindGroup(id) => self.gpu_id_hub.free_bind_group_id(id),
2029 WebGPUMsg::FreeBindGroupLayout(id) => self.gpu_id_hub.free_bind_group_layout_id(id),
2030 WebGPUMsg::FreeCommandBuffer(id) => self
2031 .gpu_id_hub
2032 .free_command_buffer_id(id.into_command_encoder_id()),
2033 WebGPUMsg::FreeSampler(id) => self.gpu_id_hub.free_sampler_id(id),
2034 WebGPUMsg::FreeShaderModule(id) => self.gpu_id_hub.free_shader_module_id(id),
2035 WebGPUMsg::FreeRenderBundle(id) => self.gpu_id_hub.free_render_bundle_id(id),
2036 WebGPUMsg::FreeRenderPipeline(id) => self.gpu_id_hub.free_render_pipeline_id(id),
2037 WebGPUMsg::FreeTexture(id) => self.gpu_id_hub.free_texture_id(id),
2038 WebGPUMsg::FreeTextureView(id) => self.gpu_id_hub.free_texture_view_id(id),
2039 WebGPUMsg::FreeComputePass(id) => self.gpu_id_hub.free_compute_pass_id(id),
2040 WebGPUMsg::FreeRenderPass(id) => self.gpu_id_hub.free_render_pass_id(id),
2041 WebGPUMsg::Exit => {
2042 *self.receivers.webgpu_receiver.borrow_mut() = crossbeam_channel::never()
2043 },
2044 WebGPUMsg::DeviceLost {
2045 pipeline_id,
2046 device,
2047 reason,
2048 msg,
2049 } => {
2050 let global = self.documents.borrow().find_global(pipeline_id).unwrap();
2051 global.gpu_device_lost(device, reason, msg);
2052 },
2053 WebGPUMsg::UncapturedError {
2054 device,
2055 pipeline_id,
2056 error,
2057 } => {
2058 let global = self.documents.borrow().find_global(pipeline_id).unwrap();
2059 let _ac = enter_auto_realm(cx, &*global);
2060 global.handle_uncaptured_gpu_error(device, error);
2061 },
2062 _ => {},
2063 }
2064 }
2065
2066 fn handle_msg_from_script(&self, msg: MainThreadScriptMsg, cx: &mut js::context::JSContext) {
2067 match msg {
2068 MainThreadScriptMsg::Common(CommonScriptMsg::Task(_, task, pipeline_id, _)) => {
2069 let _realm = pipeline_id.and_then(|id| {
2070 let global = self.documents.borrow().find_global(id);
2071 global.map(|global| enter_realm(&*global))
2072 });
2073 task.run_box(cx)
2074 },
2075 MainThreadScriptMsg::Common(CommonScriptMsg::CollectReports(chan)) => {
2076 self.collect_reports(chan)
2077 },
2078 MainThreadScriptMsg::Common(CommonScriptMsg::ReportCspViolations(
2079 pipeline_id,
2080 violations,
2081 )) => {
2082 if let Some(global) = self.documents.borrow().find_global(pipeline_id) {
2083 global.report_csp_violations(violations, None, None);
2084 }
2085 },
2086 MainThreadScriptMsg::NavigationResponse {
2087 pipeline_id,
2088 message,
2089 } => {
2090 self.handle_navigation_response(cx, pipeline_id, *message);
2091 },
2092 MainThreadScriptMsg::WorkletLoaded(pipeline_id) => {
2093 self.handle_worklet_loaded(pipeline_id)
2094 },
2095 MainThreadScriptMsg::RegisterPaintWorklet {
2096 pipeline_id,
2097 name,
2098 properties,
2099 painter,
2100 } => self.handle_register_paint_worklet(pipeline_id, name, properties, painter),
2101 MainThreadScriptMsg::Inactive => {},
2102 MainThreadScriptMsg::WakeUp => {},
2103 MainThreadScriptMsg::ForwardEmbedderControlResponseFromFileManager(
2104 control_id,
2105 response,
2106 ) => {
2107 self.handle_embedder_control_response(control_id, response, cx);
2108 },
2109 }
2110 }
2111
2112 fn handle_msg_from_devtools(
2113 &self,
2114 msg: DevtoolScriptControlMsg,
2115 cx: &mut js::context::JSContext,
2116 ) {
2117 let documents = self.documents.borrow();
2118 match msg {
2119 DevtoolScriptControlMsg::GetEventListenerInfo(id, node, reply) => {
2120 devtools::handle_get_event_listener_info(&self.devtools_state, id, &node, reply)
2121 },
2122 DevtoolScriptControlMsg::GetRootNode(id, reply) => {
2123 devtools::handle_get_root_node(cx, &self.devtools_state, &documents, id, reply)
2124 },
2125 DevtoolScriptControlMsg::GetDocumentElement(id, reply) => {
2126 devtools::handle_get_document_element(
2127 cx,
2128 &self.devtools_state,
2129 &documents,
2130 id,
2131 reply,
2132 )
2133 },
2134 DevtoolScriptControlMsg::GetStyleSheets(id, reply) => {
2135 devtools::handle_get_stylesheets(&documents, id, reply);
2136 },
2137 DevtoolScriptControlMsg::GetStyleSheetText(id, index, reply) => {
2138 devtools::handle_get_stylesheet_text(cx, &documents, id, index, reply);
2139 },
2140 DevtoolScriptControlMsg::GetChildren(id, node_id, reply) => {
2141 devtools::handle_get_children(cx, &self.devtools_state, id, &node_id, reply)
2142 },
2143 DevtoolScriptControlMsg::GetAttributeStyle(id, node_id, reply) => {
2144 devtools::handle_get_attribute_style(cx, &self.devtools_state, id, &node_id, reply)
2145 },
2146 DevtoolScriptControlMsg::GetStylesheetStyle(id, node_id, matched_rule, reply) => {
2147 devtools::handle_get_stylesheet_style(
2148 cx,
2149 &self.devtools_state,
2150 &documents,
2151 id,
2152 &node_id,
2153 matched_rule,
2154 reply,
2155 )
2156 },
2157 DevtoolScriptControlMsg::GetSelectors(id, node_id, reply) => {
2158 devtools::handle_get_selectors(
2159 cx,
2160 &self.devtools_state,
2161 &documents,
2162 id,
2163 &node_id,
2164 reply,
2165 )
2166 },
2167 DevtoolScriptControlMsg::GetComputedStyle(id, node_id, reply) => {
2168 devtools::handle_get_computed_style(&self.devtools_state, id, &node_id, reply)
2169 },
2170 DevtoolScriptControlMsg::GetLayout(id, node_id, reply) => {
2171 devtools::handle_get_layout(cx, &self.devtools_state, id, &node_id, reply)
2172 },
2173 DevtoolScriptControlMsg::GetXPath(id, node_id, reply) => {
2174 devtools::handle_get_xpath(&self.devtools_state, id, &node_id, reply)
2175 },
2176 DevtoolScriptControlMsg::ModifyAttribute(id, node_id, modifications) => {
2177 devtools::handle_modify_attribute(
2178 cx,
2179 &self.devtools_state,
2180 &documents,
2181 id,
2182 &node_id,
2183 modifications,
2184 )
2185 },
2186 DevtoolScriptControlMsg::ModifyRule(id, node_id, modifications) => {
2187 devtools::handle_modify_rule(
2188 cx,
2189 &self.devtools_state,
2190 &documents,
2191 id,
2192 &node_id,
2193 modifications,
2194 )
2195 },
2196 DevtoolScriptControlMsg::WantsLiveNotifications(id, to_send) => {
2197 match documents.find_window(id) {
2198 Some(window) => {
2199 window.set_devtools_wants_updates(to_send);
2200 },
2201 None => warn!("Message sent to closed pipeline {}.", id),
2202 }
2203 },
2204 DevtoolScriptControlMsg::SetTimelineMarkers(id, marker_types, reply) => {
2205 devtools::handle_set_timeline_markers(&documents, id, marker_types, reply)
2206 },
2207 DevtoolScriptControlMsg::DropTimelineMarkers(id, marker_types) => {
2208 devtools::handle_drop_timeline_markers(&documents, id, marker_types)
2209 },
2210 DevtoolScriptControlMsg::RequestAnimationFrame(id, name) => {
2211 devtools::handle_request_animation_frame(&documents, id, name)
2212 },
2213 DevtoolScriptControlMsg::NavigateTo(pipeline_id, url) => {
2214 self.handle_navigate_to(pipeline_id, url)
2215 },
2216 DevtoolScriptControlMsg::GoBack(pipeline_id) => {
2217 self.handle_traverse_history(pipeline_id, TraversalDirection::Back(1))
2218 },
2219 DevtoolScriptControlMsg::GoForward(pipeline_id) => {
2220 self.handle_traverse_history(pipeline_id, TraversalDirection::Forward(1))
2221 },
2222 DevtoolScriptControlMsg::Reload(id) => self.handle_reload(id, cx),
2223 DevtoolScriptControlMsg::GetCssDatabase(reply) => {
2224 devtools::handle_get_css_database(reply)
2225 },
2226 DevtoolScriptControlMsg::SimulateColorScheme(id, theme) => {
2227 match documents.find_window(id) {
2228 Some(window) => {
2229 window.set_theme(theme);
2230 },
2231 None => warn!("Message sent to closed pipeline {}.", id),
2232 }
2233 },
2234 DevtoolScriptControlMsg::HighlightDomNode(id, node_id) => {
2235 devtools::handle_highlight_dom_node(
2236 &self.devtools_state,
2237 &documents,
2238 id,
2239 node_id.as_deref(),
2240 )
2241 },
2242 DevtoolScriptControlMsg::Eval(code, id, frame_actor_id, reply) => {
2243 self.debugger_global
2244 .fire_eval(cx, code.into(), id, None, frame_actor_id, reply);
2245 },
2246 DevtoolScriptControlMsg::GetPossibleBreakpoints(spidermonkey_id, result_sender) => {
2247 self.debugger_global.fire_get_possible_breakpoints(
2248 cx,
2249 spidermonkey_id,
2250 result_sender,
2251 );
2252 },
2253 DevtoolScriptControlMsg::SetBreakpoint(spidermonkey_id, script_id, offset) => {
2254 self.debugger_global
2255 .fire_set_breakpoint(cx, spidermonkey_id, script_id, offset);
2256 },
2257 DevtoolScriptControlMsg::ClearBreakpoint(spidermonkey_id, script_id, offset) => {
2258 self.debugger_global
2259 .fire_clear_breakpoint(cx, spidermonkey_id, script_id, offset);
2260 },
2261 DevtoolScriptControlMsg::Interrupt => {
2262 self.debugger_global.fire_interrupt(CanGc::from_cx(cx));
2263 },
2264 DevtoolScriptControlMsg::ListFrames(pipeline_id, start, count, result_sender) => {
2265 self.debugger_global.fire_list_frames(
2266 pipeline_id,
2267 start,
2268 count,
2269 result_sender,
2270 CanGc::from_cx(cx),
2271 );
2272 },
2273 DevtoolScriptControlMsg::GetEnvironment(frame_actor_id, result_sender) => {
2274 self.debugger_global
2275 .fire_get_environment(cx, frame_actor_id, result_sender);
2276 },
2277 DevtoolScriptControlMsg::Resume(resume_limit_type, frame_actor_id) => {
2278 self.debugger_global
2279 .fire_resume(cx, resume_limit_type, frame_actor_id);
2280 self.debugger_paused.set(false);
2281 },
2282 }
2283 }
2284
2285 pub(crate) fn enter_debugger_pause_loop(&self) {
2288 self.debugger_paused.set(true);
2289
2290 #[allow(unsafe_code)]
2291 let mut cx = unsafe { js::context::JSContext::from_ptr(js::rust::Runtime::get().unwrap()) };
2292
2293 while self.debugger_paused.get() {
2294 match self.receivers.devtools_server_receiver.recv() {
2295 Ok(Ok(msg)) => self.handle_msg_from_devtools(msg, &mut cx),
2296 _ => {
2297 self.debugger_paused.set(false);
2298 break;
2299 },
2300 }
2301 }
2302 }
2303
2304 fn handle_msg_from_image_cache(
2305 &self,
2306 response: ImageCacheResponseMessage,
2307 cx: &mut js::context::JSContext,
2308 ) {
2309 match response {
2310 ImageCacheResponseMessage::NotifyPendingImageLoadStatus(pending_image_response) => {
2311 let window = self
2312 .documents
2313 .borrow()
2314 .find_window(pending_image_response.pipeline_id);
2315 if let Some(ref window) = window {
2316 window.pending_image_notification(pending_image_response, cx);
2317 }
2318 },
2319 ImageCacheResponseMessage::VectorImageRasterizationComplete(response) => {
2320 let window = self.documents.borrow().find_window(response.pipeline_id);
2321 if let Some(ref window) = window {
2322 window.handle_image_rasterization_complete_notification(response);
2323 }
2324 },
2325 };
2326 }
2327
2328 fn handle_webdriver_msg(
2329 &self,
2330 pipeline_id: PipelineId,
2331 msg: WebDriverScriptCommand,
2332 cx: &mut js::context::JSContext,
2333 ) {
2334 let documents = self.documents.borrow();
2335 match msg {
2336 WebDriverScriptCommand::AddCookie(params, reply) => {
2337 webdriver_handlers::handle_add_cookie(&documents, pipeline_id, params, reply)
2338 },
2339 WebDriverScriptCommand::DeleteCookies(reply) => {
2340 webdriver_handlers::handle_delete_cookies(&documents, pipeline_id, reply)
2341 },
2342 WebDriverScriptCommand::DeleteCookie(name, reply) => {
2343 webdriver_handlers::handle_delete_cookie(&documents, pipeline_id, name, reply)
2344 },
2345 WebDriverScriptCommand::ElementClear(element_id, reply) => {
2346 webdriver_handlers::handle_element_clear(
2347 cx,
2348 &documents,
2349 pipeline_id,
2350 element_id,
2351 reply,
2352 )
2353 },
2354 WebDriverScriptCommand::FindElementsCSSSelector(selector, reply) => {
2355 webdriver_handlers::handle_find_elements_css_selector(
2356 &documents,
2357 pipeline_id,
2358 selector,
2359 reply,
2360 )
2361 },
2362 WebDriverScriptCommand::FindElementsLinkText(selector, partial, reply) => {
2363 webdriver_handlers::handle_find_elements_link_text(
2364 &documents,
2365 pipeline_id,
2366 selector,
2367 partial,
2368 reply,
2369 )
2370 },
2371 WebDriverScriptCommand::FindElementsTagName(selector, reply) => {
2372 webdriver_handlers::handle_find_elements_tag_name(
2373 cx,
2374 &documents,
2375 pipeline_id,
2376 selector,
2377 reply,
2378 )
2379 },
2380 WebDriverScriptCommand::FindElementsXpathSelector(selector, reply) => {
2381 webdriver_handlers::handle_find_elements_xpath_selector(
2382 cx,
2383 &documents,
2384 pipeline_id,
2385 selector,
2386 reply,
2387 )
2388 },
2389 WebDriverScriptCommand::FindElementElementsCSSSelector(selector, element_id, reply) => {
2390 webdriver_handlers::handle_find_element_elements_css_selector(
2391 &documents,
2392 pipeline_id,
2393 element_id,
2394 selector,
2395 reply,
2396 )
2397 },
2398 WebDriverScriptCommand::FindElementElementsLinkText(
2399 selector,
2400 element_id,
2401 partial,
2402 reply,
2403 ) => webdriver_handlers::handle_find_element_elements_link_text(
2404 &documents,
2405 pipeline_id,
2406 element_id,
2407 selector,
2408 partial,
2409 reply,
2410 ),
2411 WebDriverScriptCommand::FindElementElementsTagName(selector, element_id, reply) => {
2412 webdriver_handlers::handle_find_element_elements_tag_name(
2413 cx,
2414 &documents,
2415 pipeline_id,
2416 element_id,
2417 selector,
2418 reply,
2419 )
2420 },
2421 WebDriverScriptCommand::FindElementElementsXPathSelector(
2422 selector,
2423 element_id,
2424 reply,
2425 ) => webdriver_handlers::handle_find_element_elements_xpath_selector(
2426 cx,
2427 &documents,
2428 pipeline_id,
2429 element_id,
2430 selector,
2431 reply,
2432 ),
2433 WebDriverScriptCommand::FindShadowElementsCSSSelector(
2434 selector,
2435 shadow_root_id,
2436 reply,
2437 ) => webdriver_handlers::handle_find_shadow_elements_css_selector(
2438 &documents,
2439 pipeline_id,
2440 shadow_root_id,
2441 selector,
2442 reply,
2443 ),
2444 WebDriverScriptCommand::FindShadowElementsLinkText(
2445 selector,
2446 shadow_root_id,
2447 partial,
2448 reply,
2449 ) => webdriver_handlers::handle_find_shadow_elements_link_text(
2450 &documents,
2451 pipeline_id,
2452 shadow_root_id,
2453 selector,
2454 partial,
2455 reply,
2456 ),
2457 WebDriverScriptCommand::FindShadowElementsTagName(selector, shadow_root_id, reply) => {
2458 webdriver_handlers::handle_find_shadow_elements_tag_name(
2459 &documents,
2460 pipeline_id,
2461 shadow_root_id,
2462 selector,
2463 reply,
2464 )
2465 },
2466 WebDriverScriptCommand::FindShadowElementsXPathSelector(
2467 selector,
2468 shadow_root_id,
2469 reply,
2470 ) => webdriver_handlers::handle_find_shadow_elements_xpath_selector(
2471 cx,
2472 &documents,
2473 pipeline_id,
2474 shadow_root_id,
2475 selector,
2476 reply,
2477 ),
2478 WebDriverScriptCommand::GetElementShadowRoot(element_id, reply) => {
2479 webdriver_handlers::handle_get_element_shadow_root(
2480 &documents,
2481 pipeline_id,
2482 element_id,
2483 reply,
2484 )
2485 },
2486 WebDriverScriptCommand::ElementClick(element_id, reply) => {
2487 webdriver_handlers::handle_element_click(
2488 cx,
2489 &documents,
2490 pipeline_id,
2491 element_id,
2492 reply,
2493 )
2494 },
2495 WebDriverScriptCommand::GetKnownElement(element_id, reply) => {
2496 webdriver_handlers::handle_get_known_element(
2497 &documents,
2498 pipeline_id,
2499 element_id,
2500 reply,
2501 )
2502 },
2503 WebDriverScriptCommand::GetKnownWindow(webview_id, reply) => {
2504 webdriver_handlers::handle_get_known_window(
2505 &documents,
2506 pipeline_id,
2507 webview_id,
2508 reply,
2509 )
2510 },
2511 WebDriverScriptCommand::GetKnownShadowRoot(element_id, reply) => {
2512 webdriver_handlers::handle_get_known_shadow_root(
2513 &documents,
2514 pipeline_id,
2515 element_id,
2516 reply,
2517 )
2518 },
2519 WebDriverScriptCommand::GetActiveElement(reply) => {
2520 webdriver_handlers::handle_get_active_element(&documents, pipeline_id, reply)
2521 },
2522 WebDriverScriptCommand::GetComputedRole(node_id, reply) => {
2523 webdriver_handlers::handle_get_computed_role(
2524 &documents,
2525 pipeline_id,
2526 node_id,
2527 reply,
2528 )
2529 },
2530 WebDriverScriptCommand::GetPageSource(reply) => {
2531 webdriver_handlers::handle_get_page_source(cx, &documents, pipeline_id, reply)
2532 },
2533 WebDriverScriptCommand::GetCookies(reply) => {
2534 webdriver_handlers::handle_get_cookies(&documents, pipeline_id, reply)
2535 },
2536 WebDriverScriptCommand::GetCookie(name, reply) => {
2537 webdriver_handlers::handle_get_cookie(&documents, pipeline_id, name, reply)
2538 },
2539 WebDriverScriptCommand::GetElementTagName(node_id, reply) => {
2540 webdriver_handlers::handle_get_name(&documents, pipeline_id, node_id, reply)
2541 },
2542 WebDriverScriptCommand::GetElementAttribute(node_id, name, reply) => {
2543 webdriver_handlers::handle_get_attribute(
2544 &documents,
2545 pipeline_id,
2546 node_id,
2547 name,
2548 reply,
2549 )
2550 },
2551 WebDriverScriptCommand::GetElementProperty(node_id, name, reply) => {
2552 webdriver_handlers::handle_get_property(
2553 &documents,
2554 pipeline_id,
2555 node_id,
2556 name,
2557 reply,
2558 cx,
2559 )
2560 },
2561 WebDriverScriptCommand::GetElementCSS(node_id, name, reply) => {
2562 webdriver_handlers::handle_get_css(&documents, pipeline_id, node_id, name, reply)
2563 },
2564 WebDriverScriptCommand::GetElementRect(node_id, reply) => {
2565 webdriver_handlers::handle_get_rect(cx, &documents, pipeline_id, node_id, reply)
2566 },
2567 WebDriverScriptCommand::ScrollAndGetBoundingClientRect(node_id, reply) => {
2568 webdriver_handlers::handle_scroll_and_get_bounding_client_rect(
2569 cx,
2570 &documents,
2571 pipeline_id,
2572 node_id,
2573 reply,
2574 )
2575 },
2576 WebDriverScriptCommand::GetElementText(node_id, reply) => {
2577 webdriver_handlers::handle_get_text(&documents, pipeline_id, node_id, reply)
2578 },
2579 WebDriverScriptCommand::GetElementInViewCenterPoint(node_id, reply) => {
2580 webdriver_handlers::handle_get_element_in_view_center_point(
2581 cx,
2582 &documents,
2583 pipeline_id,
2584 node_id,
2585 reply,
2586 )
2587 },
2588 WebDriverScriptCommand::GetParentFrameId(reply) => {
2589 webdriver_handlers::handle_get_parent_frame_id(&documents, pipeline_id, reply)
2590 },
2591 WebDriverScriptCommand::GetBrowsingContextId(webdriver_frame_id, reply) => {
2592 webdriver_handlers::handle_get_browsing_context_id(
2593 &documents,
2594 pipeline_id,
2595 webdriver_frame_id,
2596 reply,
2597 )
2598 },
2599 WebDriverScriptCommand::GetUrl(reply) => {
2600 webdriver_handlers::handle_get_url(&documents, pipeline_id, reply)
2601 },
2602 WebDriverScriptCommand::IsEnabled(element_id, reply) => {
2603 webdriver_handlers::handle_is_enabled(&documents, pipeline_id, element_id, reply)
2604 },
2605 WebDriverScriptCommand::IsSelected(element_id, reply) => {
2606 webdriver_handlers::handle_is_selected(&documents, pipeline_id, element_id, reply)
2607 },
2608 WebDriverScriptCommand::GetTitle(reply) => {
2609 webdriver_handlers::handle_get_title(&documents, pipeline_id, reply)
2610 },
2611 WebDriverScriptCommand::WillSendKeys(
2612 element_id,
2613 text,
2614 strict_file_interactability,
2615 reply,
2616 ) => webdriver_handlers::handle_will_send_keys(
2617 cx,
2618 &documents,
2619 pipeline_id,
2620 element_id,
2621 text,
2622 strict_file_interactability,
2623 reply,
2624 ),
2625 WebDriverScriptCommand::AddLoadStatusSender(_, response_sender) => {
2626 webdriver_handlers::handle_add_load_status_sender(
2627 &documents,
2628 pipeline_id,
2629 response_sender,
2630 )
2631 },
2632 WebDriverScriptCommand::RemoveLoadStatusSender(_) => {
2633 webdriver_handlers::handle_remove_load_status_sender(&documents, pipeline_id)
2634 },
2635 WebDriverScriptCommand::ExecuteScriptWithCallback(script, reply) => {
2642 let window = documents.find_window(pipeline_id);
2643 drop(documents);
2644 webdriver_handlers::handle_execute_async_script(window, script, reply, cx);
2645 },
2646 WebDriverScriptCommand::SetProtocolHandlerAutomationMode(mode) => {
2647 webdriver_handlers::set_protocol_handler_automation_mode(
2648 &documents,
2649 pipeline_id,
2650 mode,
2651 )
2652 },
2653 }
2654 }
2655
2656 pub(crate) fn handle_resize_message(
2659 &self,
2660 id: PipelineId,
2661 viewport_details: ViewportDetails,
2662 size_type: WindowSizeType,
2663 ) {
2664 self.profile_event(ScriptThreadEventCategory::Resize, Some(id), || {
2665 let window = self.documents.borrow().find_window(id);
2666 if let Some(ref window) = window {
2667 window.add_resize_event(viewport_details, size_type);
2668 return;
2669 }
2670 let mut loads = self.incomplete_loads.borrow_mut();
2671 if let Some(ref mut load) = loads.iter_mut().find(|load| load.pipeline_id == id) {
2672 load.viewport_details = viewport_details;
2673 }
2674 })
2675 }
2676
2677 fn handle_theme_change_msg(&self, theme: Theme) {
2679 for (_, document) in self.documents.borrow().iter() {
2680 document.window().set_theme(theme);
2681 }
2682 let mut loads = self.incomplete_loads.borrow_mut();
2683 for load in loads.iter_mut() {
2684 load.theme = theme;
2685 }
2686 }
2687
2688 fn handle_get_document_origin(
2689 &self,
2690 id: PipelineId,
2691 result_sender: GenericSender<Option<String>>,
2692 ) {
2693 let _ = result_sender.send(
2694 self.documents
2695 .borrow()
2696 .find_document(id)
2697 .map(|document| document.origin().immutable().ascii_serialization()),
2698 );
2699 }
2700
2701 fn handle_exit_fullscreen(&self, id: PipelineId, cx: &mut js::context::JSContext) {
2703 let document = self.documents.borrow().find_document(id);
2704 if let Some(document) = document {
2705 let mut realm = enter_auto_realm(cx, &*document);
2706 document.exit_fullscreen(CanGc::from_cx(&mut realm));
2707 }
2708 }
2709
2710 #[expect(unsafe_code)]
2711 pub(crate) fn spawn_pipeline(&self, new_pipeline_info: NewPipelineInfo) {
2712 let mut cx = unsafe { temp_cx() };
2713 let cx = &mut cx;
2714 self.profile_event(
2715 ScriptThreadEventCategory::SpawnPipeline,
2716 Some(new_pipeline_info.new_pipeline_id),
2717 || {
2718 self.devtools_state
2719 .notify_pipeline_created(new_pipeline_info.new_pipeline_id);
2720
2721 self.pre_page_load(cx, InProgressLoad::new(new_pipeline_info));
2723 },
2724 );
2725 }
2726
2727 fn collect_reports(&self, reports_chan: ReportsChan) {
2728 let documents = self.documents.borrow();
2729 let urls = itertools::join(documents.iter().map(|(_, d)| d.url().to_string()), ", ");
2730
2731 let mut reports = vec![];
2732 perform_memory_report(|ops| {
2733 for (_, document) in documents.iter() {
2734 document
2735 .window()
2736 .layout()
2737 .collect_reports(&mut reports, ops);
2738 }
2739
2740 let prefix = format!("url({urls})");
2741 reports.extend(self.get_cx().get_reports(prefix, ops));
2742 });
2743
2744 reports_chan.send(ProcessReports::new(reports));
2745 }
2746
2747 fn handle_set_throttled_in_containing_iframe_msg(
2749 &self,
2750 parent_pipeline_id: PipelineId,
2751 browsing_context_id: BrowsingContextId,
2752 throttled: bool,
2753 ) {
2754 let iframe = self
2755 .documents
2756 .borrow()
2757 .find_iframe(parent_pipeline_id, browsing_context_id);
2758 if let Some(iframe) = iframe {
2759 iframe.set_throttled(throttled);
2760 }
2761 }
2762
2763 fn handle_set_throttled_msg(
2764 &self,
2765 webview_id: WebViewId,
2766 pipeline_id: PipelineId,
2767 throttled: bool,
2768 ) {
2769 self.senders
2772 .pipeline_to_constellation_sender
2773 .send((
2774 webview_id,
2775 pipeline_id,
2776 ScriptToConstellationMessage::SetThrottledComplete(throttled),
2777 ))
2778 .unwrap();
2779
2780 let window = self.documents.borrow().find_window(pipeline_id);
2781 match window {
2782 Some(window) => {
2783 window.set_throttled(throttled);
2784 return;
2785 },
2786 None => {
2787 let mut loads = self.incomplete_loads.borrow_mut();
2788 if let Some(ref mut load) = loads
2789 .iter_mut()
2790 .find(|load| load.pipeline_id == pipeline_id)
2791 {
2792 load.throttled = throttled;
2793 return;
2794 }
2795 },
2796 }
2797
2798 warn!("SetThrottled sent to nonexistent pipeline");
2799 }
2800
2801 fn handle_set_document_activity_msg(
2803 &self,
2804 cx: &mut js::context::JSContext,
2805 id: PipelineId,
2806 activity: DocumentActivity,
2807 ) {
2808 debug!(
2809 "Setting activity of {} to be {:?} in {:?}.",
2810 id,
2811 activity,
2812 thread::current().name()
2813 );
2814 let document = self.documents.borrow().find_document(id);
2815 if let Some(document) = document {
2816 document.set_activity(cx, activity);
2817 return;
2818 }
2819 let mut loads = self.incomplete_loads.borrow_mut();
2820 if let Some(ref mut load) = loads.iter_mut().find(|load| load.pipeline_id == id) {
2821 load.activity = activity;
2822 return;
2823 }
2824 warn!("change of activity sent to nonexistent pipeline");
2825 }
2826
2827 fn handle_focus_document_as_part_of_focusing_steps(
2828 &self,
2829 cx: &mut js::context::JSContext,
2830 pipeline_id: PipelineId,
2831 sequence: FocusSequenceNumber,
2832 browsing_context_id: Option<BrowsingContextId>,
2833 ) {
2834 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
2835 warn!("Unknown {pipeline_id:?} for FocusDocumentAsPartOfFocusingSteps message.");
2836 return;
2837 };
2838
2839 let focus_handler = document.focus_handler();
2840 if focus_handler.focus_sequence() > sequence {
2841 debug!(
2842 "Disregarding the FocusDocumentAsPartOfFocusingSteps message because \
2843 the contained sequence number is too old ({sequence:?} < {:?})",
2844 focus_handler.focus_sequence()
2845 );
2846 return;
2847 }
2848
2849 let iframe_element = browsing_context_id.and_then(|browsing_context_id| {
2852 document
2853 .iframes()
2854 .get(browsing_context_id)
2855 .map(|iframe| iframe.element.as_rooted())
2856 });
2857 let focusable_area = iframe_element
2858 .map(|iframe_element| {
2859 let kind = iframe_element.upcast::<Element>().focusable_area_kind();
2860 FocusableArea::IFrameViewport {
2861 iframe_element,
2862 kind,
2863 }
2864 })
2865 .unwrap_or(FocusableArea::Viewport);
2866
2867 focus_handler.focus_update_steps(
2868 cx,
2869 focusable_area.focus_chain(),
2870 focus_handler.current_focus_chain(),
2871 &focusable_area,
2872 );
2873 }
2874
2875 fn handle_focus_document(
2876 &self,
2877 cx: &mut js::context::JSContext,
2878 pipeline_id: PipelineId,
2879 remote_focus_operation: RemoteFocusOperation,
2880 ) {
2881 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
2882 warn!("Unknown {pipeline_id:?} for FocusDocument message.");
2883 return;
2884 };
2885 match remote_focus_operation {
2886 RemoteFocusOperation::Viewport => document.window().Focus(cx),
2887 RemoteFocusOperation::Sequential(direction, iframe_browsing_context_id) => document
2888 .focus_handler()
2889 .sequential_focus_from_another_document(cx, iframe_browsing_context_id, direction),
2890 }
2891 }
2892
2893 fn handle_unfocus_document_as_part_of_focusing_steps(
2894 &self,
2895 cx: &mut js::context::JSContext,
2896 pipeline_id: PipelineId,
2897 sequence: FocusSequenceNumber,
2898 ) {
2899 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
2900 warn!("Unknown {pipeline_id:?} for UnfocusDocumentAsPartOfFocusingSteps");
2901 return;
2902 };
2903
2904 let window = document.window();
2907 if window.is_top_level() {
2908 return;
2909 }
2910
2911 let focus_handler = document.focus_handler();
2912 if focus_handler.focus_sequence() > sequence {
2913 debug!(
2914 "Disregarding the Unfocus message because the contained sequence number is \
2915 too old ({:?} < {:?})",
2916 sequence,
2917 focus_handler.focus_sequence()
2918 );
2919 return;
2920 }
2921
2922 focus_handler.focus_update_steps(
2923 cx,
2924 vec![],
2925 focus_handler.current_focus_chain(),
2926 &FocusableArea::Viewport,
2927 );
2928 }
2929
2930 #[expect(clippy::too_many_arguments)]
2931 fn handle_post_message_msg(
2933 &self,
2934 cx: &mut js::context::JSContext,
2935 pipeline_id: PipelineId,
2936 source_webview: WebViewId,
2937 source_with_ancestry: Vec<BrowsingContextId>,
2938 origin: Option<ImmutableOrigin>,
2939 source_origin: ImmutableOrigin,
2940 data: StructuredSerializedData,
2941 ) {
2942 let window = self.documents.borrow().find_window(pipeline_id);
2943 match window {
2944 None => warn!("postMessage after target pipeline {} closed.", pipeline_id),
2945 Some(window) => {
2946 let mut last = None;
2947 for browsing_context_id in source_with_ancestry.into_iter().rev() {
2948 if let Some(window_proxy) =
2949 self.window_proxies.find_window_proxy(browsing_context_id)
2950 {
2951 last = Some(window_proxy);
2952 continue;
2953 }
2954 let window_proxy = WindowProxy::new_dissimilar_origin(
2955 cx,
2956 window.upcast::<GlobalScope>(),
2957 browsing_context_id,
2958 source_webview,
2959 last.as_deref(),
2960 None,
2961 CreatorBrowsingContextInfo::from(last.as_deref(), None),
2962 );
2963 self.window_proxies
2964 .insert(browsing_context_id, window_proxy.clone());
2965 last = Some(window_proxy);
2966 }
2967
2968 let source = last.expect("Source with ancestry should contain at least one bc.");
2971
2972 window.post_message(origin, source_origin, &source, data)
2974 },
2975 }
2976 }
2977
2978 fn handle_stop_delaying_load_events_mode(&self, pipeline_id: PipelineId) {
2979 let window = self.documents.borrow().find_window(pipeline_id);
2980 if let Some(window) = window {
2981 match window.undiscarded_window_proxy() {
2982 Some(window_proxy) => window_proxy.stop_delaying_load_events_mode(),
2983 None => warn!(
2984 "Attempted to take {} of 'delaying-load-events-mode' after having been discarded.",
2985 pipeline_id
2986 ),
2987 };
2988 }
2989 }
2990
2991 fn handle_unload_document(&self, cx: &mut js::context::JSContext, pipeline_id: PipelineId) {
2992 let document = self.documents.borrow().find_document(pipeline_id);
2993 if let Some(document) = document {
2994 document.unload(cx, false);
2995 }
2996 }
2997
2998 fn handle_update_pipeline_id(
2999 &self,
3000 parent_pipeline_id: PipelineId,
3001 browsing_context_id: BrowsingContextId,
3002 webview_id: WebViewId,
3003 new_pipeline_id: PipelineId,
3004 reason: UpdatePipelineIdReason,
3005 cx: &mut js::context::JSContext,
3006 ) {
3007 let frame_element = self
3008 .documents
3009 .borrow()
3010 .find_iframe(parent_pipeline_id, browsing_context_id);
3011 let Some(frame_element) = frame_element else {
3012 return;
3013 };
3014 if !frame_element.update_pipeline_id(new_pipeline_id, reason, cx) {
3015 return;
3016 };
3017
3018 let Some(window) = self.documents.borrow().find_window(new_pipeline_id) else {
3019 return;
3020 };
3021 let _ = self.window_proxies.local_window_proxy(
3024 cx,
3025 &self.senders,
3026 &self.documents,
3027 &window,
3028 browsing_context_id,
3029 webview_id,
3030 Some(parent_pipeline_id),
3031 None,
3035 );
3036 }
3037
3038 fn handle_update_history_state_msg(
3039 &self,
3040 cx: &mut js::context::JSContext,
3041 pipeline_id: PipelineId,
3042 history_state_id: Option<HistoryStateId>,
3043 url: ServoUrl,
3044 ) {
3045 let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
3046 return warn!("update history state after pipeline {pipeline_id} closed.",);
3047 };
3048 window.History().activate_state(cx, history_state_id, url);
3049 }
3050
3051 fn handle_remove_history_states(
3052 &self,
3053 pipeline_id: PipelineId,
3054 history_states: Vec<HistoryStateId>,
3055 ) {
3056 let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
3057 return warn!("update history state after pipeline {pipeline_id} closed.",);
3058 };
3059 window.History().remove_states(history_states);
3060 }
3061
3062 fn handle_resize_inactive_msg(&self, id: PipelineId, new_viewport_details: ViewportDetails) {
3064 let window = self.documents.borrow().find_window(id)
3065 .expect("ScriptThread: received a resize msg for a pipeline not in this script thread. This is a bug.");
3066 window.set_viewport_details(new_viewport_details);
3067 }
3068
3069 fn handle_page_headers_available(
3072 &self,
3073 webview_id: WebViewId,
3074 pipeline_id: PipelineId,
3075 metadata: Option<&Metadata>,
3076 origin: MutableOrigin,
3077 cx: &mut js::context::JSContext,
3078 ) -> Option<DomRoot<ServoParser>> {
3079 if self.closed_pipelines.borrow().contains(&pipeline_id) {
3080 return None;
3082 }
3083
3084 let Some(idx) = self
3085 .incomplete_loads
3086 .borrow()
3087 .iter()
3088 .position(|load| load.pipeline_id == pipeline_id)
3089 else {
3090 unreachable!("Pipeline shouldn't have finished loading.");
3091 };
3092
3093 let is_204_205 = match metadata {
3098 Some(metadata) => metadata.status.in_range(204..=205),
3099 _ => false,
3100 };
3101
3102 if is_204_205 {
3103 if let Some(window) = self.documents.borrow().find_window(pipeline_id) {
3105 let window_proxy = window.window_proxy();
3106 if window_proxy.parent().is_some() {
3109 window_proxy.stop_delaying_load_events_mode();
3115 }
3116 }
3117 self.senders
3118 .pipeline_to_constellation_sender
3119 .send((
3120 webview_id,
3121 pipeline_id,
3122 ScriptToConstellationMessage::AbortLoadUrl,
3123 ))
3124 .unwrap();
3125 return None;
3126 };
3127
3128 let load = self.incomplete_loads.borrow_mut().remove(idx);
3129 metadata.map(|meta| self.load(meta, load, origin, cx))
3130 }
3131
3132 fn handle_get_title_msg(&self, pipeline_id: PipelineId) {
3134 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
3135 return warn!("Message sent to closed pipeline {pipeline_id}.");
3136 };
3137 document.send_title_to_embedder();
3138 }
3139
3140 fn handle_exit_pipeline_msg(
3142 &self,
3143 webview_id: WebViewId,
3144 pipeline_id: PipelineId,
3145 discard_bc: DiscardBrowsingContext,
3146 cx: &mut js::context::JSContext,
3147 ) {
3148 debug!("{pipeline_id}: Starting pipeline exit.");
3149
3150 let document = self.documents.borrow_mut().remove(pipeline_id);
3153 if let Some(document) = document {
3154 debug_assert!(
3156 !self
3157 .incomplete_loads
3158 .borrow()
3159 .iter()
3160 .any(|load| load.pipeline_id == pipeline_id)
3161 );
3162
3163 if let Some(parser) = document.get_current_parser() {
3164 parser.abort(cx);
3165 }
3166
3167 debug!("{pipeline_id}: Shutting down layout");
3168 document.window().layout_mut().exit_now();
3169
3170 debug!("{pipeline_id}: Clearing animations");
3172 document.animations().clear();
3173
3174 let window = document.window();
3177 if discard_bc == DiscardBrowsingContext::Yes {
3178 window.discard_browsing_context();
3179 }
3180
3181 debug!("{pipeline_id}: Clearing JavaScript runtime");
3182 window.clear_js_runtime();
3183 }
3184
3185 self.closed_pipelines.borrow_mut().insert(pipeline_id);
3187
3188 debug!("{pipeline_id}: Sending PipelineExited message to constellation");
3189 self.senders
3190 .pipeline_to_constellation_sender
3191 .send((
3192 webview_id,
3193 pipeline_id,
3194 ScriptToConstellationMessage::PipelineExited,
3195 ))
3196 .ok();
3197
3198 self.paint_api
3199 .pipeline_exited(webview_id, pipeline_id, PipelineExitSource::Script);
3200
3201 self.devtools_state.notify_pipeline_exited(pipeline_id);
3202
3203 debug!("{pipeline_id}: Finished pipeline exit");
3204 }
3205
3206 fn handle_exit_script_thread_msg(&self, cx: &mut js::context::JSContext) {
3208 debug!("Exiting script thread.");
3209
3210 let mut webview_and_pipeline_ids = Vec::new();
3211 webview_and_pipeline_ids.extend(
3212 self.incomplete_loads
3213 .borrow()
3214 .iter()
3215 .next()
3216 .map(|load| (load.webview_id, load.pipeline_id)),
3217 );
3218 webview_and_pipeline_ids.extend(
3219 self.documents
3220 .borrow()
3221 .iter()
3222 .next()
3223 .map(|(pipeline_id, document)| (document.webview_id(), pipeline_id)),
3224 );
3225
3226 for (webview_id, pipeline_id) in webview_and_pipeline_ids {
3227 self.handle_exit_pipeline_msg(webview_id, pipeline_id, DiscardBrowsingContext::Yes, cx);
3228 }
3229
3230 self.background_hang_monitor.unregister();
3231
3232 if opts::get().multiprocess {
3234 debug!("Exiting IPC router thread in script thread.");
3235 ROUTER.shutdown();
3236 }
3237
3238 debug!("Exited script thread.");
3239 }
3240
3241 pub(crate) fn handle_tick_all_animations_for_testing(id: PipelineId) {
3243 with_script_thread(|script_thread| {
3244 let Some(document) = script_thread.documents.borrow().find_document(id) else {
3245 warn!("Animation tick for tests for closed pipeline {id}.");
3246 return;
3247 };
3248 document.maybe_mark_animating_nodes_as_dirty();
3249 });
3250 }
3251
3252 fn handle_web_font_loaded(&self, pipeline_id: PipelineId) {
3254 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
3255 warn!("Web font loaded in closed pipeline {}.", pipeline_id);
3256 return;
3257 };
3258
3259 document.dirty_all_nodes();
3261 }
3262
3263 fn handle_worklet_loaded(&self, pipeline_id: PipelineId) {
3266 if let Some(document) = self.documents.borrow().find_document(pipeline_id) {
3267 document.add_restyle_reason(RestyleReason::PaintWorkletLoaded);
3268 }
3269 }
3270
3271 #[allow(clippy::too_many_arguments)]
3273 fn handle_storage_event(
3274 &self,
3275 pipeline_id: PipelineId,
3276 storage_type: WebStorageType,
3277 url: ServoUrl,
3278 key: Option<String>,
3279 old_value: Option<String>,
3280 new_value: Option<String>,
3281 cx: &mut js::context::JSContext,
3282 ) {
3283 let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
3284 return warn!("Storage event sent to closed pipeline {pipeline_id}.");
3285 };
3286
3287 let storage = match storage_type {
3288 WebStorageType::Local => window.GetLocalStorage(cx),
3289 WebStorageType::Session => window.GetSessionStorage(cx),
3290 };
3291 let Ok(storage) = storage else {
3292 return;
3293 };
3294
3295 storage.queue_storage_event(url, key, old_value, new_value);
3296 }
3297
3298 fn handle_iframe_load_event(
3300 &self,
3301 parent_id: PipelineId,
3302 browsing_context_id: BrowsingContextId,
3303 child_id: PipelineId,
3304 cx: &mut js::context::JSContext,
3305 ) {
3306 let iframe = self
3307 .documents
3308 .borrow()
3309 .find_iframe(parent_id, browsing_context_id);
3310 match iframe {
3311 Some(iframe) => iframe.iframe_load_event_steps(child_id, cx),
3312 None => warn!("Message sent to closed pipeline {}.", parent_id),
3313 }
3314 }
3315
3316 fn ask_constellation_for_top_level_info(
3317 &self,
3318 sender_webview_id: WebViewId,
3319 sender_pipeline_id: PipelineId,
3320 browsing_context_id: BrowsingContextId,
3321 ) -> Option<WebViewId> {
3322 let (result_sender, result_receiver) = generic_channel::channel().unwrap();
3323 let msg = ScriptToConstellationMessage::GetTopForBrowsingContext(
3324 browsing_context_id,
3325 result_sender,
3326 );
3327 self.senders
3328 .pipeline_to_constellation_sender
3329 .send((sender_webview_id, sender_pipeline_id, msg))
3330 .expect("Failed to send to constellation.");
3331 result_receiver
3332 .recv()
3333 .expect("Failed to get top-level id from constellation.")
3334 }
3335
3336 fn load(
3339 &self,
3340 metadata: &Metadata,
3341 incomplete: InProgressLoad,
3342 origin: MutableOrigin,
3343 cx: &mut js::context::JSContext,
3344 ) -> DomRoot<ServoParser> {
3345 let script_to_constellation_chan = ScriptToConstellationChan {
3346 sender: self.senders.pipeline_to_constellation_sender.clone(),
3347 webview_id: incomplete.webview_id,
3348 pipeline_id: incomplete.pipeline_id,
3349 };
3350
3351 let final_url = metadata.final_url.clone();
3352 let _ = script_to_constellation_chan
3353 .send(ScriptToConstellationMessage::SetFinalUrl(final_url.clone()));
3354
3355 debug!(
3356 "ScriptThread: loading {} on pipeline {:?}",
3357 incomplete.load_data.url, incomplete.pipeline_id
3358 );
3359
3360 let font_context = Arc::new(FontContext::new(
3361 self.system_font_service.clone(),
3362 self.paint_api.clone(),
3363 self.resource_threads.clone(),
3364 ));
3365
3366 let image_cache = self.image_cache_factory.create(
3367 incomplete.webview_id,
3368 incomplete.pipeline_id,
3369 &self.paint_api,
3370 );
3371
3372 let (user_contents, user_stylesheets) = incomplete
3373 .user_content_manager_id
3374 .and_then(|user_content_manager_id| {
3375 self.user_contents_for_manager_id
3376 .borrow()
3377 .get(&user_content_manager_id)
3378 .map(|script_thread_user_contents| {
3379 (
3380 script_thread_user_contents.user_scripts.clone(),
3381 script_thread_user_contents.user_stylesheets.clone(),
3382 )
3383 })
3384 })
3385 .unwrap_or_default();
3386
3387 let layout_config = LayoutConfig {
3388 id: incomplete.pipeline_id,
3389 webview_id: incomplete.webview_id,
3390 url: final_url.clone(),
3391 is_iframe: incomplete.parent_info.is_some(),
3392 script_chan: self.senders.constellation_sender.clone(),
3393 image_cache: image_cache.clone(),
3394 font_context: font_context.clone(),
3395 time_profiler_chan: self.senders.time_profiler_sender.clone(),
3396 paint_api: self.paint_api.clone(),
3397 viewport_details: incomplete.viewport_details,
3398 user_stylesheets,
3399 theme: incomplete.theme,
3400 embedder_chan: self.senders.pipeline_to_embedder_sender.clone(),
3401 };
3402
3403 let window = Window::new(
3405 cx,
3406 incomplete.webview_id,
3407 self.js_runtime.clone(),
3408 self.senders.self_sender.clone(),
3409 self.layout_factory.create(layout_config),
3410 font_context,
3411 self.senders.image_cache_sender.clone(),
3412 image_cache.clone(),
3413 self.resource_threads.clone(),
3414 self.storage_threads.clone(),
3415 #[cfg(feature = "bluetooth")]
3416 self.senders.bluetooth_sender.clone(),
3417 self.senders.memory_profiler_sender.clone(),
3418 self.senders.time_profiler_sender.clone(),
3419 self.senders.devtools_server_sender.clone(),
3420 script_to_constellation_chan,
3421 self.senders.pipeline_to_embedder_sender.clone(),
3422 self.senders.constellation_sender.clone(),
3423 incomplete.pipeline_id,
3424 incomplete.parent_info,
3425 incomplete.viewport_details,
3426 origin.clone(),
3427 final_url.clone(),
3428 final_url.clone(),
3433 incomplete.navigation_start,
3434 self.webgl_chan.as_ref().map(|chan| chan.channel()),
3435 #[cfg(feature = "webxr")]
3436 self.webxr_registry.clone(),
3437 self.paint_api.clone(),
3438 self.unminify_js,
3439 self.unminify_css,
3440 self.local_script_source.clone(),
3441 user_contents,
3442 self.player_context.clone(),
3443 #[cfg(feature = "webgpu")]
3444 self.gpu_id_hub.clone(),
3445 incomplete.load_data.inherited_secure_context,
3446 incomplete.theme,
3447 self.this.clone(),
3448 metadata.https_state,
3449 );
3450 self.debugger_global
3451 .fire_add_debuggee(cx, window.upcast(), incomplete.pipeline_id, None);
3452
3453 let mut realm = enter_auto_realm(cx, &*window);
3454 let cx = &mut realm;
3455
3456 let window_proxy = self.window_proxies.local_window_proxy(
3458 cx,
3459 &self.senders,
3460 &self.documents,
3461 &window,
3462 incomplete.browsing_context_id,
3463 incomplete.webview_id,
3464 incomplete.parent_info,
3465 incomplete.opener,
3466 );
3467 if window_proxy.parent().is_some() {
3468 window_proxy.stop_delaying_load_events_mode();
3473 }
3474 window.init_window_proxy(&window_proxy);
3475
3476 let last_modified = metadata.headers.as_ref().and_then(|headers| {
3484 headers.typed_get::<LastModified>().map(|tm| {
3485 let tm: SystemTime = tm.into();
3486 let local_time: DateTime<Local> = tm.into();
3487 local_time.format("%m/%d/%Y %H:%M:%S").to_string()
3488 })
3489 });
3490
3491 let loader = DocumentLoader::new_with_threads(
3492 self.resource_threads.clone(),
3493 Some(final_url.clone()),
3494 );
3495
3496 let content_type: Option<Mime> = metadata
3497 .content_type
3498 .clone()
3499 .map(Serde::into_inner)
3500 .map(Mime::from_ct);
3501 let encoding_hint_from_content_type = content_type
3502 .as_ref()
3503 .and_then(|mime| mime.get_parameter(CHARSET))
3504 .and_then(|charset| Encoding::for_label(charset.as_bytes()));
3505
3506 let is_html_document = match content_type {
3507 Some(ref mime) if mime.type_ == APPLICATION && mime.has_suffix("xml") => {
3508 IsHTMLDocument::NonHTMLDocument
3509 },
3510
3511 Some(ref mime) if mime.matches(TEXT, XML) || mime.matches(APPLICATION, XML) => {
3512 IsHTMLDocument::NonHTMLDocument
3513 },
3514 _ => IsHTMLDocument::HTMLDocument,
3515 };
3516
3517 let referrer = metadata
3518 .referrer
3519 .as_ref()
3520 .map(|referrer| referrer.clone().into_string());
3521
3522 let is_initial_about_blank = final_url.as_str() == "about:blank";
3523
3524 let document = Document::new(
3525 &window,
3526 HasBrowsingContext::Yes,
3527 Some(final_url.clone()),
3528 incomplete.load_data.about_base_url,
3529 origin,
3530 is_html_document,
3531 content_type,
3532 last_modified,
3533 incomplete.activity,
3534 DocumentSource::FromParser,
3535 loader,
3536 referrer,
3537 Some(metadata.status.raw_code()),
3538 incomplete.canceller,
3539 is_initial_about_blank,
3540 true,
3541 incomplete.load_data.inherited_insecure_requests_policy,
3542 incomplete.load_data.has_trustworthy_ancestor_origin,
3543 self.custom_element_reaction_stack.clone(),
3544 incomplete.load_data.creation_sandboxing_flag_set,
3545 CanGc::from_cx(cx),
3546 );
3547
3548 let referrer_policy = metadata
3549 .headers
3550 .as_deref()
3551 .and_then(|h| h.typed_get::<ReferrerPolicyHeader>())
3552 .into();
3553 document.set_referrer_policy(referrer_policy);
3554
3555 let refresh_header = metadata.headers.as_deref().and_then(|h| h.get(REFRESH));
3556 if let Some(refresh_val) = refresh_header {
3557 document.shared_declarative_refresh_steps(refresh_val.as_bytes());
3559 }
3560
3561 document.set_ready_state(cx, DocumentReadyState::Loading);
3562
3563 self.documents
3564 .borrow_mut()
3565 .insert(incomplete.pipeline_id, &document);
3566
3567 window.init_document(&document);
3568
3569 if let Some(frame) = window_proxy
3572 .frame_element()
3573 .and_then(|e| e.downcast::<HTMLIFrameElement>())
3574 {
3575 let parent_pipeline = frame.global().pipeline_id();
3576 self.handle_update_pipeline_id(
3577 parent_pipeline,
3578 window_proxy.browsing_context_id(),
3579 window_proxy.webview_id(),
3580 incomplete.pipeline_id,
3581 UpdatePipelineIdReason::Navigation,
3582 cx,
3583 );
3584 }
3585
3586 self.senders
3587 .pipeline_to_constellation_sender
3588 .send((
3589 incomplete.webview_id,
3590 incomplete.pipeline_id,
3591 ScriptToConstellationMessage::ActivateDocument,
3592 ))
3593 .unwrap();
3594
3595 let incomplete_browsing_context_id: BrowsingContextId = incomplete.webview_id.into();
3597 let is_top_level_global = incomplete_browsing_context_id == incomplete.browsing_context_id;
3598 self.notify_devtools(
3599 document.Title(),
3600 final_url.clone(),
3601 is_top_level_global,
3602 (
3603 incomplete.browsing_context_id,
3604 incomplete.pipeline_id,
3605 None,
3606 incomplete.webview_id,
3607 ),
3608 );
3609
3610 document.set_navigation_start(incomplete.navigation_start);
3611
3612 if is_html_document == IsHTMLDocument::NonHTMLDocument {
3613 ServoParser::parse_xml_document(
3614 &document,
3615 None,
3616 final_url,
3617 encoding_hint_from_content_type,
3618 cx,
3619 );
3620 } else {
3621 ServoParser::parse_html_document(
3622 &document,
3623 None,
3624 final_url,
3625 encoding_hint_from_content_type,
3626 incomplete.load_data.container_document_encoding,
3627 cx,
3628 );
3629 }
3630
3631 if incomplete.activity == DocumentActivity::FullyActive {
3632 window.resume(CanGc::from_cx(cx));
3633 } else {
3634 window.suspend(cx);
3635 }
3636
3637 if incomplete.throttled {
3638 window.set_throttled(true);
3639 }
3640
3641 document.get_current_parser().unwrap()
3642 }
3643
3644 fn notify_devtools(
3645 &self,
3646 title: DOMString,
3647 url: ServoUrl,
3648 is_top_level_global: bool,
3649 (browsing_context_id, pipeline_id, worker_id, webview_id): (
3650 BrowsingContextId,
3651 PipelineId,
3652 Option<WorkerId>,
3653 WebViewId,
3654 ),
3655 ) {
3656 if let Some(ref chan) = self.senders.devtools_server_sender {
3657 let page_info = DevtoolsPageInfo {
3658 title: String::from(title),
3659 url,
3660 is_top_level_global,
3661 is_service_worker: false,
3662 };
3663 chan.send(ScriptToDevtoolsControlMsg::NewGlobal(
3664 (browsing_context_id, pipeline_id, worker_id, webview_id),
3665 self.senders.devtools_client_to_script_thread_sender.clone(),
3666 page_info.clone(),
3667 ))
3668 .unwrap();
3669
3670 let state = NavigationState::Stop(pipeline_id, page_info);
3671 let _ = chan.send(ScriptToDevtoolsControlMsg::Navigate(
3672 browsing_context_id,
3673 state,
3674 ));
3675 }
3676 }
3677
3678 fn handle_input_event(
3680 &self,
3681 webview_id: WebViewId,
3682 pipeline_id: PipelineId,
3683 event: ConstellationInputEvent,
3684 ) {
3685 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
3686 warn!("Input event sent to closed pipeline {pipeline_id}.");
3687 let _ = self
3688 .senders
3689 .pipeline_to_embedder_sender
3690 .send(EmbedderMsg::InputEventsHandled(
3691 webview_id,
3692 vec![InputEventOutcome {
3693 id: event.event.id,
3694 result: Default::default(),
3695 }],
3696 ));
3697 return;
3698 };
3699 document.event_handler().note_pending_input_event(event);
3700 }
3701
3702 fn set_accessibility_active(&self, pipeline_id: PipelineId, active: bool, epoch: Epoch) {
3704 if !(pref!(accessibility_enabled)) {
3705 return;
3706 }
3707
3708 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
3709 if active {
3710 error!("Trying to set accessibility active on stale document: {pipeline_id}");
3711 }
3712 return;
3713 };
3714
3715 document
3716 .window()
3717 .layout()
3718 .set_accessibility_active(active, epoch);
3719 }
3720
3721 fn handle_navigate_iframe(
3723 &self,
3724 parent_pipeline_id: PipelineId,
3725 browsing_context_id: BrowsingContextId,
3726 load_data: LoadData,
3727 history_handling: NavigationHistoryBehavior,
3728 target_snapshot_params: TargetSnapshotParams,
3729 cx: &mut js::context::JSContext,
3730 ) {
3731 let iframe = self
3732 .documents
3733 .borrow()
3734 .find_iframe(parent_pipeline_id, browsing_context_id);
3735 if let Some(iframe) = iframe {
3736 iframe.navigate_or_reload_child_browsing_context(
3737 load_data,
3738 history_handling,
3739 ProcessingMode::NotFirstTime,
3740 target_snapshot_params,
3741 cx,
3742 );
3743 }
3744 }
3745
3746 fn eval_js_url(
3750 cx: &mut js::context::JSContext,
3751 global_scope: &GlobalScope,
3752 url: &ServoUrl,
3753 ) -> Option<String> {
3754 let encoded = &url[Position::AfterScheme..][1..];
3757
3758 let script_source = percent_decode(encoded.as_bytes()).decode_utf8_lossy();
3760
3761 let mut realm = enter_auto_realm(cx, global_scope);
3766 let cx = &mut realm.current_realm();
3767
3768 rooted!(&in(cx) let mut jsval = UndefinedValue());
3769 let evaluation_status = global_scope.evaluate_js_on_global(
3771 cx,
3772 script_source,
3773 "",
3774 Some(IntroductionType::JAVASCRIPT_URL),
3775 Some(jsval.handle_mut()),
3776 );
3777
3778 if evaluation_status.is_err() || !jsval.get().is_string() {
3782 return None;
3783 }
3784
3785 let strval = DOMString::safe_from_jsval(
3786 cx.into(),
3787 jsval.handle(),
3788 StringificationBehavior::Empty,
3789 CanGc::from_cx(cx),
3790 );
3791 match strval {
3792 Ok(ConversionResult::Success(s)) => {
3793 Some(String::from(s))
3796 },
3797 _ => unreachable!("Couldn't get a string from a JS string??"),
3798 }
3799 }
3800
3801 #[servo_tracing::instrument(skip_all)]
3804 fn pre_page_load(&self, cx: &mut js::context::JSContext, mut incomplete: InProgressLoad) {
3805 let url_str = incomplete.load_data.url.as_str();
3806 if url_str == "about:blank" || incomplete.load_data.js_eval_result.is_some() {
3807 self.start_synchronous_page_load(cx, incomplete);
3808 return;
3809 }
3810 if url_str == "about:srcdoc" {
3811 self.page_load_about_srcdoc(cx, incomplete);
3812 return;
3813 }
3814
3815 let context = ParserContext::new(
3816 incomplete.webview_id,
3817 incomplete.pipeline_id,
3818 incomplete.load_data.url.clone(),
3819 incomplete.load_data.creation_sandboxing_flag_set,
3820 incomplete.parent_info,
3821 incomplete.target_snapshot_params,
3822 incomplete.load_data.load_origin.clone(),
3823 );
3824 self.incomplete_parser_contexts
3825 .0
3826 .borrow_mut()
3827 .push((incomplete.pipeline_id, context));
3828
3829 let request_builder = incomplete.request_builder();
3830 incomplete.canceller = FetchCanceller::new(
3831 request_builder.id,
3832 false,
3833 self.resource_threads.core_thread.clone(),
3834 );
3835 NavigationListener::new(request_builder, self.senders.self_sender.clone())
3836 .initiate_fetch(&self.resource_threads.core_thread, None);
3837 self.incomplete_loads.borrow_mut().push(incomplete);
3838 }
3839
3840 fn handle_navigation_response(
3841 &self,
3842 cx: &mut js::context::JSContext,
3843 pipeline_id: PipelineId,
3844 message: FetchResponseMsg,
3845 ) {
3846 if let Some(metadata) = NavigationListener::http_redirect_metadata(&message) {
3847 self.handle_navigation_redirect(pipeline_id, metadata);
3848 return;
3849 };
3850
3851 match message {
3852 FetchResponseMsg::ProcessResponse(request_id, metadata) => {
3853 self.handle_fetch_metadata(cx, pipeline_id, request_id, metadata)
3854 },
3855 FetchResponseMsg::ProcessResponseChunk(request_id, chunk) => {
3856 self.handle_fetch_chunk(cx, pipeline_id, request_id, chunk.0)
3857 },
3858 FetchResponseMsg::ProcessResponseEOF(request_id, eof, timing) => {
3859 self.handle_fetch_eof(cx, pipeline_id, request_id, eof, timing)
3860 },
3861 FetchResponseMsg::ProcessCspViolations(request_id, violations) => {
3862 self.handle_csp_violations(pipeline_id, request_id, violations)
3863 },
3864 FetchResponseMsg::ProcessRequestBody(..) => {},
3865 }
3866 }
3867
3868 fn handle_fetch_metadata(
3869 &self,
3870 cx: &mut js::context::JSContext,
3871 id: PipelineId,
3872 request_id: RequestId,
3873 fetch_metadata: Result<FetchMetadata, NetworkError>,
3874 ) {
3875 match fetch_metadata {
3876 Ok(_) => (),
3877 Err(NetworkError::Crash(..)) => (),
3878 Err(ref e) => {
3879 warn!("Network error: {:?}", e);
3880 },
3881 };
3882
3883 let mut incomplete_parser_contexts = self.incomplete_parser_contexts.0.borrow_mut();
3884 let parser = incomplete_parser_contexts
3885 .iter_mut()
3886 .find(|&&mut (pipeline_id, _)| pipeline_id == id);
3887 if let Some(&mut (_, ref mut ctxt)) = parser {
3888 ctxt.process_response(cx, request_id, fetch_metadata);
3889 }
3890 }
3891
3892 fn handle_fetch_chunk(
3893 &self,
3894 cx: &mut js::context::JSContext,
3895 pipeline_id: PipelineId,
3896 request_id: RequestId,
3897 chunk: Vec<u8>,
3898 ) {
3899 let mut incomplete_parser_contexts = self.incomplete_parser_contexts.0.borrow_mut();
3900 let parser = incomplete_parser_contexts
3901 .iter_mut()
3902 .find(|&&mut (parser_pipeline_id, _)| parser_pipeline_id == pipeline_id);
3903 if let Some(&mut (_, ref mut ctxt)) = parser {
3904 ctxt.process_response_chunk(cx, request_id, chunk);
3905 }
3906 }
3907
3908 #[expect(clippy::redundant_clone, reason = "False positive")]
3909 fn handle_fetch_eof(
3910 &self,
3911 cx: &mut js::context::JSContext,
3912 id: PipelineId,
3913 request_id: RequestId,
3914 eof: Result<(), NetworkError>,
3915 timing: ResourceFetchTiming,
3916 ) {
3917 let idx = self
3918 .incomplete_parser_contexts
3919 .0
3920 .borrow()
3921 .iter()
3922 .position(|&(pipeline_id, _)| pipeline_id == id);
3923
3924 if let Some(idx) = idx {
3925 let (_, context) = self.incomplete_parser_contexts.0.borrow_mut().remove(idx);
3926
3927 if let Some(window_proxy) = context
3929 .get_document()
3930 .and_then(|document| document.browsing_context())
3931 {
3932 if let Some(frame_element) = window_proxy.frame_element() {
3933 let iframe_ctx = IframeContext::new(
3934 frame_element
3935 .downcast::<HTMLIFrameElement>()
3936 .expect("WindowProxy::frame_element should be an HTMLIFrameElement"),
3937 );
3938
3939 let mut resource_timing = timing.clone();
3941 resource_timing.timing_type = ResourceTimingType::Resource;
3942 submit_timing(cx, &iframe_ctx, &eof, &resource_timing);
3943 }
3944 }
3945
3946 context.process_response_eof(cx, request_id, eof, timing);
3947 }
3948 }
3949
3950 fn handle_csp_violations(
3951 &self,
3952 pipeline_id: PipelineId,
3953 _request_id: RequestId,
3954 violations: Vec<Violation>,
3955 ) {
3956 let mut incomplete_parser_contexts = self.incomplete_parser_contexts.0.borrow_mut();
3957 let parser = incomplete_parser_contexts
3958 .iter_mut()
3959 .find(|&&mut (parser_pipeline_id, _)| parser_pipeline_id == pipeline_id);
3960 let Some(&mut (_, ref mut ctxt)) = parser else {
3961 return;
3962 };
3963 let pipeline_id = ctxt.parent_info().unwrap_or(pipeline_id);
3965 if let Some(global) = self.documents.borrow().find_global(pipeline_id) {
3966 global.report_csp_violations(violations, None, None);
3967 }
3968 }
3969
3970 fn handle_navigation_redirect(&self, id: PipelineId, metadata: &Metadata) {
3971 assert!(metadata.location_url.is_some());
3975
3976 let mut incomplete_loads = self.incomplete_loads.borrow_mut();
3977 let Some(incomplete_load) = incomplete_loads
3978 .iter_mut()
3979 .find(|incomplete_load| incomplete_load.pipeline_id == id)
3980 else {
3981 return;
3982 };
3983
3984 incomplete_load.url_list.push(metadata.final_url.clone());
3987
3988 let mut request_builder = incomplete_load.request_builder();
3989 request_builder.referrer = metadata
3990 .referrer
3991 .clone()
3992 .map(Referrer::ReferrerUrl)
3993 .unwrap_or(Referrer::NoReferrer);
3994 request_builder.referrer_policy = metadata.referrer_policy;
3995 request_builder.origin = request_builder
3996 .client
3997 .as_ref()
3998 .expect("Must have a client during redirect")
3999 .origin
4000 .clone();
4001
4002 let headers = metadata
4003 .headers
4004 .as_ref()
4005 .map(|headers| headers.clone().into_inner())
4006 .unwrap_or_default();
4007
4008 let response_init = Some(ResponseInit {
4009 url: metadata.final_url.clone(),
4010 location_url: metadata.location_url.clone(),
4011 headers,
4012 referrer: metadata.referrer.clone(),
4013 status_code: metadata
4014 .status
4015 .try_code()
4016 .map(|code| code.as_u16())
4017 .unwrap_or(200),
4018 });
4019
4020 incomplete_load.canceller = FetchCanceller::new(
4021 request_builder.id,
4022 false,
4023 self.resource_threads.core_thread.clone(),
4024 );
4025 NavigationListener::new(request_builder, self.senders.self_sender.clone())
4026 .initiate_fetch(&self.resource_threads.core_thread, response_init);
4027 }
4028
4029 fn start_synchronous_page_load(
4032 &self,
4033 cx: &mut js::context::JSContext,
4034 mut incomplete: InProgressLoad,
4035 ) {
4036 let mut context = ParserContext::new(
4037 incomplete.webview_id,
4038 incomplete.pipeline_id,
4039 incomplete.load_data.url.clone(),
4040 incomplete.load_data.creation_sandboxing_flag_set,
4041 incomplete.parent_info,
4042 incomplete.target_snapshot_params,
4043 incomplete.load_data.load_origin.clone(),
4044 );
4045
4046 let mut meta = Metadata::default(incomplete.load_data.url.clone());
4047 meta.set_content_type(Some(&mime::TEXT_HTML));
4048 meta.set_referrer_policy(incomplete.load_data.referrer_policy);
4049
4050 let chunk = match incomplete.load_data.js_eval_result {
4053 Some(ref mut content) => std::mem::take(content),
4054 None => String::new(),
4055 };
4056
4057 let policy_container = incomplete.load_data.policy_container.clone();
4058 let about_base_url = incomplete.load_data.about_base_url.clone();
4059 self.incomplete_loads.borrow_mut().push(incomplete);
4060
4061 let dummy_request_id = RequestId::default();
4062 context.process_response(cx, dummy_request_id, Ok(FetchMetadata::Unfiltered(meta)));
4063 context.set_policy_container(policy_container.as_ref());
4064 context.set_about_base_url(about_base_url);
4065 context.process_response_chunk(cx, dummy_request_id, chunk.into());
4066 context.process_response_eof(
4067 cx,
4068 dummy_request_id,
4069 Ok(()),
4070 ResourceFetchTiming::new(ResourceTimingType::None),
4071 );
4072 }
4073
4074 fn page_load_about_srcdoc(
4076 &self,
4077 cx: &mut js::context::JSContext,
4078 mut incomplete: InProgressLoad,
4079 ) {
4080 let url = ServoUrl::parse("about:srcdoc").unwrap();
4081 let mut meta = Metadata::default(url.clone());
4082 meta.set_content_type(Some(&mime::TEXT_HTML));
4083 meta.set_referrer_policy(incomplete.load_data.referrer_policy);
4084
4085 let srcdoc = std::mem::take(&mut incomplete.load_data.srcdoc);
4086 let chunk = srcdoc.into_bytes();
4087
4088 let policy_container = incomplete.load_data.policy_container.clone();
4089 let creation_sandboxing_flag_set = incomplete.load_data.creation_sandboxing_flag_set;
4090
4091 let webview_id = incomplete.webview_id;
4092 let pipeline_id = incomplete.pipeline_id;
4093 let parent_info = incomplete.parent_info;
4094 let about_base_url = incomplete.load_data.about_base_url.clone();
4095 let target_snapshot_params = incomplete.target_snapshot_params;
4096 let load_origin = incomplete.load_data.load_origin.clone();
4097 self.incomplete_loads.borrow_mut().push(incomplete);
4098
4099 let mut context = ParserContext::new(
4100 webview_id,
4101 pipeline_id,
4102 url,
4103 creation_sandboxing_flag_set,
4104 parent_info,
4105 target_snapshot_params,
4106 load_origin,
4107 );
4108 let dummy_request_id = RequestId::default();
4109
4110 context.process_response(cx, dummy_request_id, Ok(FetchMetadata::Unfiltered(meta)));
4111 context.set_policy_container(policy_container.as_ref());
4112 context.set_about_base_url(about_base_url);
4113 context.process_response_chunk(cx, dummy_request_id, chunk);
4114 context.process_response_eof(
4115 cx,
4116 dummy_request_id,
4117 Ok(()),
4118 ResourceFetchTiming::new(ResourceTimingType::None),
4119 );
4120 }
4121
4122 fn handle_css_error_reporting(
4123 &self,
4124 pipeline_id: PipelineId,
4125 filename: String,
4126 line: u32,
4127 column: u32,
4128 msg: String,
4129 ) {
4130 let Some(ref sender) = self.senders.devtools_server_sender else {
4131 return;
4132 };
4133
4134 if let Some(window) = self.documents.borrow().find_window(pipeline_id) {
4135 if window.live_devtools_updates() {
4136 let css_error = CSSError {
4137 filename,
4138 line,
4139 column,
4140 msg,
4141 };
4142 let message = ScriptToDevtoolsControlMsg::ReportCSSError(pipeline_id, css_error);
4143 sender.send(message).unwrap();
4144 }
4145 }
4146 }
4147
4148 fn handle_navigate_to(&self, pipeline_id: PipelineId, url: ServoUrl) {
4149 if let Some(document) = self.documents.borrow().find_document(pipeline_id) {
4152 self.senders
4153 .pipeline_to_constellation_sender
4154 .send((
4155 document.webview_id(),
4156 pipeline_id,
4157 ScriptToConstellationMessage::LoadUrl(
4158 LoadData::new_for_new_unrelated_webview(url),
4159 NavigationHistoryBehavior::Push,
4160 TargetSnapshotParams::default(),
4161 ),
4162 ))
4163 .unwrap();
4164 }
4165 }
4166
4167 fn handle_traverse_history(&self, pipeline_id: PipelineId, direction: TraversalDirection) {
4168 if let Some(document) = self.documents.borrow().find_document(pipeline_id) {
4171 self.senders
4172 .pipeline_to_constellation_sender
4173 .send((
4174 document.webview_id(),
4175 pipeline_id,
4176 ScriptToConstellationMessage::TraverseHistory(direction),
4177 ))
4178 .unwrap();
4179 }
4180 }
4181
4182 fn handle_reload(&self, pipeline_id: PipelineId, cx: &mut js::context::JSContext) {
4183 let window = self.documents.borrow().find_window(pipeline_id);
4184 if let Some(window) = window {
4185 window.Location(cx).reload_without_origin_check(cx);
4186 }
4187 }
4188
4189 fn handle_paint_metric(
4190 &self,
4191 pipeline_id: PipelineId,
4192 metric_type: ProgressiveWebMetricType,
4193 metric_value: CrossProcessInstant,
4194 first_reflow: bool,
4195 can_gc: CanGc,
4196 ) {
4197 match self.documents.borrow().find_document(pipeline_id) {
4198 Some(document) => {
4199 document.handle_paint_metric(metric_type, metric_value, first_reflow, can_gc)
4200 },
4201 None => warn!(
4202 "Received paint metric ({metric_type:?}) for unknown document: {pipeline_id:?}"
4203 ),
4204 }
4205 }
4206
4207 fn handle_media_session_action(
4208 &self,
4209 cx: &mut js::context::JSContext,
4210 pipeline_id: PipelineId,
4211 action: MediaSessionActionType,
4212 ) {
4213 if let Some(window) = self.documents.borrow().find_window(pipeline_id) {
4214 let media_session = window.Navigator().MediaSession();
4215 media_session.handle_action(cx, action);
4216 } else {
4217 warn!("No MediaSession for this pipeline ID");
4218 };
4219 }
4220
4221 pub(crate) fn enqueue_microtask(job: Microtask) {
4222 with_script_thread(|script_thread| {
4223 script_thread
4224 .microtask_queue
4225 .enqueue(job, script_thread.get_cx());
4226 });
4227 }
4228
4229 pub(crate) fn perform_a_microtask_checkpoint(&self, cx: &mut js::context::JSContext) {
4230 if self.can_continue_running_inner() {
4232 let globals = self
4233 .documents
4234 .borrow()
4235 .iter()
4236 .map(|(_id, document)| DomRoot::from_ref(document.window().upcast()))
4237 .collect();
4238
4239 self.microtask_queue.checkpoint(
4240 cx,
4241 |id| self.documents.borrow().find_global(id),
4242 globals,
4243 )
4244 }
4245 }
4246
4247 fn handle_evaluate_javascript(
4248 &self,
4249 webview_id: WebViewId,
4250 pipeline_id: PipelineId,
4251 evaluation_id: JavaScriptEvaluationId,
4252 script: String,
4253 cx: &mut js::context::JSContext,
4254 ) {
4255 let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
4256 let _ = self.senders.pipeline_to_constellation_sender.send((
4257 webview_id,
4258 pipeline_id,
4259 ScriptToConstellationMessage::FinishJavaScriptEvaluation(
4260 evaluation_id,
4261 Err(JavaScriptEvaluationError::WebViewNotReady),
4262 ),
4263 ));
4264 return;
4265 };
4266
4267 let global_scope = window.as_global_scope();
4268 let mut realm = enter_auto_realm(cx, global_scope);
4269 let cx = &mut realm.current_realm();
4270
4271 rooted!(&in(cx) let mut return_value = UndefinedValue());
4272 if let Err(err) = global_scope.evaluate_js_on_global(
4273 cx,
4274 script.into(),
4275 "",
4276 None, Some(return_value.handle_mut()),
4278 ) {
4279 _ = self.senders.pipeline_to_constellation_sender.send((
4280 webview_id,
4281 pipeline_id,
4282 ScriptToConstellationMessage::FinishJavaScriptEvaluation(evaluation_id, Err(err)),
4283 ));
4284 return;
4285 };
4286
4287 let result = jsval_to_webdriver(cx, global_scope, return_value.handle());
4288 let _ = self.senders.pipeline_to_constellation_sender.send((
4289 webview_id,
4290 pipeline_id,
4291 ScriptToConstellationMessage::FinishJavaScriptEvaluation(evaluation_id, result),
4292 ));
4293 }
4294
4295 fn handle_refresh_cursor(&self, pipeline_id: PipelineId) {
4296 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
4297 return;
4298 };
4299 document.event_handler().handle_refresh_cursor();
4300 }
4301
4302 pub(crate) fn is_servo_privileged(url: ServoUrl) -> bool {
4303 with_script_thread(|script_thread| script_thread.privileged_urls.contains(&url))
4304 }
4305
4306 fn handle_request_screenshot_readiness(
4307 &self,
4308 webview_id: WebViewId,
4309 pipeline_id: PipelineId,
4310 can_gc: CanGc,
4311 ) {
4312 let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
4313 let _ = self.senders.pipeline_to_constellation_sender.send((
4314 webview_id,
4315 pipeline_id,
4316 ScriptToConstellationMessage::RespondToScreenshotReadinessRequest(
4317 ScreenshotReadinessResponse::NoLongerActive,
4318 ),
4319 ));
4320 return;
4321 };
4322 window.request_screenshot_readiness(can_gc);
4323 }
4324
4325 fn handle_embedder_control_response(
4326 &self,
4327 id: EmbedderControlId,
4328 response: EmbedderControlResponse,
4329 cx: &mut js::context::JSContext,
4330 ) {
4331 let Some(document) = self.documents.borrow().find_document(id.pipeline_id) else {
4332 return;
4333 };
4334 document
4335 .embedder_controls()
4336 .handle_embedder_control_response(cx, id, response);
4337 }
4338
4339 pub(crate) fn handle_update_pinch_zoom_infos(
4340 &self,
4341 pipeline_id: PipelineId,
4342 pinch_zoom_infos: PinchZoomInfos,
4343 can_gc: CanGc,
4344 ) {
4345 let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
4346 warn!("Visual viewport update for closed pipeline {pipeline_id}.");
4347 return;
4348 };
4349
4350 window.maybe_update_visual_viewport(pinch_zoom_infos, can_gc);
4351 }
4352
4353 pub(crate) fn devtools_want_updates_for_node(pipeline: PipelineId, node: &Node) -> bool {
4354 with_script_thread(|script_thread| {
4355 script_thread
4356 .devtools_state
4357 .wants_updates_for_node(pipeline, node)
4358 })
4359 }
4360}
4361
4362impl Drop for ScriptThread {
4363 fn drop(&mut self) {
4364 SCRIPT_THREAD_ROOT.with(|root| {
4365 root.set(None);
4366 });
4367 }
4368}