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