1use std::cell::{Cell, RefCell};
21use std::collections::HashSet;
22use std::default::Default;
23use std::option::Option;
24use std::rc::Rc;
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, HangAnnotation, MonitoredComponentId,
33 MonitoredComponentType,
34};
35use base::cross_process_instant::CrossProcessInstant;
36use base::id::{BrowsingContextId, HistoryStateId, PipelineId, PipelineNamespace, WebViewId};
37use canvas_traits::webgl::WebGLPipeline;
38use chrono::{DateTime, Local};
39use compositing_traits::{CrossProcessCompositorApi, PipelineExitSource};
40use constellation_traits::{
41 JsEvalResult, LoadData, LoadOrigin, NavigationHistoryBehavior, ScreenshotReadinessResponse,
42 ScriptToConstellationChan, ScriptToConstellationMessage, StructuredSerializedData,
43 WindowSizeType,
44};
45use crossbeam_channel::unbounded;
46use data_url::mime::Mime;
47use devtools_traits::{
48 CSSError, DevtoolScriptControlMsg, DevtoolsPageInfo, NavigationState,
49 ScriptToDevtoolsControlMsg, WorkerId,
50};
51use embedder_traits::user_content_manager::UserContentManager;
52use embedder_traits::{
53 EmbedderControlId, EmbedderControlResponse, EmbedderMsg, FocusSequenceNumber,
54 JavaScriptEvaluationError, JavaScriptEvaluationId, MediaSessionActionType, Theme,
55 ViewportDetails, WebDriverScriptCommand,
56};
57use euclid::default::Rect;
58use fonts::{FontContext, SystemFontServiceProxy};
59use headers::{HeaderMapExt, LastModified, ReferrerPolicy as ReferrerPolicyHeader};
60use http::header::REFRESH;
61use hyper_serde::Serde;
62use ipc_channel::ipc;
63use ipc_channel::router::ROUTER;
64use js::glue::GetWindowProxyClass;
65use js::jsapi::{
66 JS_AddInterruptCallback, JSContext as UnsafeJSContext, JSTracer, SetWindowProxyClass,
67};
68use js::jsval::UndefinedValue;
69use js::rust::ParentRuntime;
70use layout_api::{LayoutConfig, LayoutFactory, RestyleReason, ScriptThreadFactory};
71use media::WindowGLContext;
72use metrics::MAX_TASK_NS;
73use net_traits::image_cache::{ImageCache, ImageCacheResponseMessage};
74use net_traits::request::{Referrer, RequestId};
75use net_traits::response::ResponseInit;
76use net_traits::{
77 FetchMetadata, FetchResponseListener, FetchResponseMsg, Metadata, NetworkError,
78 ResourceFetchTiming, ResourceThreads, ResourceTimingType,
79};
80use percent_encoding::percent_decode;
81use profile_traits::mem::{ProcessReports, ReportsChan, perform_memory_report};
82use profile_traits::time::ProfilerCategory;
83use profile_traits::time_profile;
84use rustc_hash::{FxHashMap, FxHashSet};
85use script_traits::{
86 ConstellationInputEvent, DiscardBrowsingContext, DocumentActivity, InitialScriptState,
87 NewLayoutInfo, Painter, ProgressiveWebMetricType, ScriptThreadMessage, UpdatePipelineIdReason,
88};
89use servo_config::{opts, prefs};
90use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
91use storage_traits::StorageThreads;
92use storage_traits::webstorage_thread::StorageType;
93use style::thread_state::{self, ThreadState};
94use stylo_atoms::Atom;
95use timers::{TimerEventRequest, TimerId, TimerScheduler};
96use url::Position;
97#[cfg(feature = "webgpu")]
98use webgpu_traits::{WebGPUDevice, WebGPUMsg};
99use webrender_api::ExternalScrollId;
100use webrender_api::units::LayoutVector2D;
101
102use crate::document_collection::DocumentCollection;
103use crate::document_loader::DocumentLoader;
104use crate::dom::bindings::cell::DomRefCell;
105use crate::dom::bindings::codegen::Bindings::DocumentBinding::{
106 DocumentMethods, DocumentReadyState,
107};
108use crate::dom::bindings::codegen::Bindings::NavigatorBinding::NavigatorMethods;
109use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
110use crate::dom::bindings::conversions::{
111 ConversionResult, SafeFromJSValConvertible, StringificationBehavior,
112};
113use crate::dom::bindings::inheritance::Castable;
114use crate::dom::bindings::refcounted::Trusted;
115use crate::dom::bindings::reflector::DomGlobal;
116use crate::dom::bindings::root::{Dom, DomRoot};
117use crate::dom::bindings::settings_stack::AutoEntryScript;
118use crate::dom::bindings::str::DOMString;
119use crate::dom::bindings::trace::JSTraceable;
120use crate::dom::csp::{CspReporting, GlobalCspReporting, Violation};
121use crate::dom::customelementregistry::{
122 CallbackReaction, CustomElementDefinition, CustomElementReactionStack,
123};
124use crate::dom::document::{
125 Document, DocumentSource, FocusInitiator, HasBrowsingContext, IsHTMLDocument,
126 RenderingUpdateReason,
127};
128use crate::dom::element::Element;
129use crate::dom::globalscope::GlobalScope;
130use crate::dom::html::htmliframeelement::HTMLIFrameElement;
131use crate::dom::node::NodeTraits;
132use crate::dom::servoparser::{ParserContext, ServoParser};
133use crate::dom::types::DebuggerGlobalScope;
134#[cfg(feature = "webgpu")]
135use crate::dom::webgpu::identityhub::IdentityHub;
136use crate::dom::window::Window;
137use crate::dom::windowproxy::{CreatorBrowsingContextInfo, WindowProxy};
138use crate::dom::worklet::WorkletThreadPool;
139use crate::dom::workletglobalscope::WorkletGlobalScopeInit;
140use crate::fetch::FetchCanceller;
141use crate::messaging::{
142 CommonScriptMsg, MainThreadScriptMsg, MixedMessage, ScriptEventLoopSender,
143 ScriptThreadReceivers, ScriptThreadSenders,
144};
145use crate::microtask::{Microtask, MicrotaskQueue};
146use crate::mime::{APPLICATION, MimeExt, TEXT, XML};
147use crate::navigation::{InProgressLoad, NavigationListener};
148use crate::realms::enter_realm;
149use crate::script_module::ScriptFetchOptions;
150use crate::script_mutation_observers::ScriptMutationObservers;
151use crate::script_runtime::{
152 CanGc, IntroductionType, JSContext, JSContextHelper, Runtime, ScriptThreadEventCategory,
153 ThreadSafeJSContext,
154};
155use crate::script_window_proxies::ScriptWindowProxies;
156use crate::task_queue::TaskQueue;
157use crate::task_source::{SendableTaskSource, TaskSourceName};
158use crate::webdriver_handlers::jsval_to_webdriver;
159use crate::{devtools, webdriver_handlers};
160
161thread_local!(static SCRIPT_THREAD_ROOT: Cell<Option<*const ScriptThread>> = const { Cell::new(None) });
162
163fn with_optional_script_thread<R>(f: impl FnOnce(Option<&ScriptThread>) -> R) -> R {
164 SCRIPT_THREAD_ROOT.with(|root| {
165 f(root
166 .get()
167 .and_then(|script_thread| unsafe { script_thread.as_ref() }))
168 })
169}
170
171pub(crate) fn with_script_thread<R: Default>(f: impl FnOnce(&ScriptThread) -> R) -> R {
172 with_optional_script_thread(|script_thread| script_thread.map(f).unwrap_or_default())
173}
174
175pub(crate) unsafe fn trace_thread(tr: *mut JSTracer) {
181 with_script_thread(|script_thread| {
182 trace!("tracing fields of ScriptThread");
183 unsafe { script_thread.trace(tr) };
184 })
185}
186
187pub(crate) struct IncompleteParserContexts(RefCell<Vec<(PipelineId, ParserContext)>>);
193
194unsafe_no_jsmanaged_fields!(TaskQueue<MainThreadScriptMsg>);
195
196type NodeIdSet = HashSet<String>;
197
198#[derive(Default)]
200pub(crate) struct ScriptUserInteractingGuard {
201 was_interacting: bool,
202 user_interaction_cell: Rc<Cell<bool>>,
203}
204
205impl ScriptUserInteractingGuard {
206 fn new(user_interaction_cell: Rc<Cell<bool>>) -> Self {
207 let was_interacting = user_interaction_cell.get();
208 user_interaction_cell.set(true);
209 Self {
210 was_interacting,
211 user_interaction_cell,
212 }
213 }
214}
215
216impl Drop for ScriptUserInteractingGuard {
217 fn drop(&mut self) {
218 self.user_interaction_cell.set(self.was_interacting)
219 }
220}
221
222#[derive(JSTraceable)]
223#[cfg_attr(crown, allow(crown::unrooted_must_root))]
225pub struct ScriptThread {
226 last_render_opportunity_time: Cell<Option<Instant>>,
228
229 documents: DomRefCell<DocumentCollection>,
231 window_proxies: Rc<ScriptWindowProxies>,
233 incomplete_loads: DomRefCell<Vec<InProgressLoad>>,
235 incomplete_parser_contexts: IncompleteParserContexts,
237 #[no_trace]
239 image_cache: Arc<dyn ImageCache>,
240
241 receivers: ScriptThreadReceivers,
244
245 senders: ScriptThreadSenders,
248
249 #[no_trace]
252 resource_threads: ResourceThreads,
253
254 #[no_trace]
255 storage_threads: StorageThreads,
256
257 task_queue: TaskQueue<MainThreadScriptMsg>,
259
260 #[no_trace]
262 background_hang_monitor: Box<dyn BackgroundHangMonitor>,
263 closing: Arc<AtomicBool>,
265
266 #[no_trace]
269 timer_scheduler: RefCell<TimerScheduler>,
270
271 #[no_trace]
273 system_font_service: Arc<SystemFontServiceProxy>,
274
275 js_runtime: Rc<Runtime>,
277
278 #[no_trace]
280 closed_pipelines: DomRefCell<FxHashSet<PipelineId>>,
281
282 microtask_queue: Rc<MicrotaskQueue>,
284
285 mutation_observers: Rc<ScriptMutationObservers>,
286
287 #[no_trace]
289 webgl_chan: Option<WebGLPipeline>,
290
291 #[no_trace]
293 #[cfg(feature = "webxr")]
294 webxr_registry: Option<webxr_api::Registry>,
295
296 worklet_thread_pool: DomRefCell<Option<Rc<WorkletThreadPool>>>,
298
299 docs_with_no_blocking_loads: DomRefCell<HashSet<Dom<Document>>>,
302
303 custom_element_reaction_stack: Rc<CustomElementReactionStack>,
305
306 #[no_trace]
308 compositor_api: CrossProcessCompositorApi,
309
310 profile_script_events: bool,
312
313 print_pwm: bool,
315
316 unminify_js: bool,
318
319 local_script_source: Option<String>,
321
322 unminify_css: bool,
324
325 #[no_trace]
327 user_content_manager: UserContentManager,
328
329 #[no_trace]
331 player_context: WindowGLContext,
332
333 #[no_trace]
335 pipeline_to_node_ids: DomRefCell<FxHashMap<PipelineId, NodeIdSet>>,
336
337 is_user_interacting: Rc<Cell<bool>>,
339
340 #[no_trace]
342 #[cfg(feature = "webgpu")]
343 gpu_id_hub: Arc<IdentityHub>,
344
345 inherited_secure_context: Option<bool>,
347
348 #[no_trace]
350 layout_factory: Arc<dyn LayoutFactory>,
351
352 #[no_trace]
356 scheduled_update_the_rendering: RefCell<Option<TimerId>>,
357
358 needs_rendering_update: Arc<AtomicBool>,
365
366 debugger_global: Dom<DebuggerGlobalScope>,
367
368 #[no_trace]
370 privileged_urls: Vec<ServoUrl>,
371}
372
373struct BHMExitSignal {
374 closing: Arc<AtomicBool>,
375 js_context: ThreadSafeJSContext,
376}
377
378impl BackgroundHangMonitorExitSignal for BHMExitSignal {
379 fn signal_to_exit(&self) {
380 self.closing.store(true, Ordering::SeqCst);
381 self.js_context.request_interrupt_callback();
382 }
383}
384
385#[allow(unsafe_code)]
386unsafe extern "C" fn interrupt_callback(_cx: *mut UnsafeJSContext) -> bool {
387 let res = ScriptThread::can_continue_running();
388 if !res {
389 ScriptThread::prepare_for_shutdown();
390 }
391 res
392}
393
394struct ScriptMemoryFailsafe<'a> {
399 owner: Option<&'a ScriptThread>,
400}
401
402impl<'a> ScriptMemoryFailsafe<'a> {
403 fn neuter(&mut self) {
404 self.owner = None;
405 }
406
407 fn new(owner: &'a ScriptThread) -> ScriptMemoryFailsafe<'a> {
408 ScriptMemoryFailsafe { owner: Some(owner) }
409 }
410}
411
412impl Drop for ScriptMemoryFailsafe<'_> {
413 #[cfg_attr(crown, allow(crown::unrooted_must_root))]
414 fn drop(&mut self) {
415 if let Some(owner) = self.owner {
416 for (_, document) in owner.documents.borrow().iter() {
417 document.window().clear_js_runtime_for_script_deallocation();
418 }
419 }
420 }
421}
422
423impl ScriptThreadFactory for ScriptThread {
424 fn create(
425 state: InitialScriptState,
426 layout_factory: Arc<dyn LayoutFactory>,
427 system_font_service: Arc<SystemFontServiceProxy>,
428 load_data: LoadData,
429 ) -> JoinHandle<()> {
430 thread::Builder::new()
431 .name(format!("Script{:?}", state.id))
432 .spawn(move || {
433 thread_state::initialize(ThreadState::SCRIPT | ThreadState::LAYOUT);
434 PipelineNamespace::install(state.pipeline_namespace_id);
435 WebViewId::install(state.webview_id);
436 let memory_profiler_sender = state.memory_profiler_sender.clone();
437
438 let in_progress_load = InProgressLoad::new(
439 state.id,
440 state.browsing_context_id,
441 state.webview_id,
442 state.parent_info,
443 state.opener,
444 state.viewport_details,
445 state.theme,
446 MutableOrigin::new(load_data.url.origin()),
447 load_data,
448 );
449 let reporter_name = format!("script-reporter-{:?}", state.id);
450 let script_thread = ScriptThread::new(state, layout_factory, system_font_service);
451
452 SCRIPT_THREAD_ROOT.with(|root| {
453 root.set(Some(&script_thread as *const _));
454 });
455
456 let mut failsafe = ScriptMemoryFailsafe::new(&script_thread);
457
458 script_thread.pre_page_load(in_progress_load);
459
460 memory_profiler_sender.run_with_memory_reporting(
461 || {
462 script_thread.start(CanGc::note());
463
464 let _ = script_thread
465 .senders
466 .content_process_shutdown_sender
467 .send(());
468 },
469 reporter_name,
470 ScriptEventLoopSender::MainThread(script_thread.senders.self_sender.clone()),
471 CommonScriptMsg::CollectReports,
472 );
473
474 failsafe.neuter();
476 })
477 .expect("Thread spawning failed")
478 }
479}
480
481impl ScriptThread {
482 pub(crate) fn runtime_handle() -> ParentRuntime {
483 with_optional_script_thread(|script_thread| {
484 script_thread.unwrap().js_runtime.prepare_for_new_child()
485 })
486 }
487
488 pub(crate) fn can_continue_running() -> bool {
489 with_script_thread(|script_thread| script_thread.can_continue_running_inner())
490 }
491
492 pub(crate) fn prepare_for_shutdown() {
493 with_script_thread(|script_thread| {
494 script_thread.prepare_for_shutdown_inner();
495 })
496 }
497
498 pub(crate) fn mutation_observers() -> Rc<ScriptMutationObservers> {
499 with_script_thread(|script_thread| script_thread.mutation_observers.clone())
500 }
501
502 pub(crate) fn microtask_queue() -> Rc<MicrotaskQueue> {
503 with_script_thread(|script_thread| script_thread.microtask_queue.clone())
504 }
505
506 pub(crate) fn mark_document_with_no_blocked_loads(doc: &Document) {
507 with_script_thread(|script_thread| {
508 script_thread
509 .docs_with_no_blocking_loads
510 .borrow_mut()
511 .insert(Dom::from_ref(doc));
512 })
513 }
514
515 pub(crate) fn page_headers_available(
516 webview_id: WebViewId,
517 pipeline_id: PipelineId,
518 metadata: Option<Metadata>,
519 can_gc: CanGc,
520 ) -> Option<DomRoot<ServoParser>> {
521 with_script_thread(|script_thread| {
522 script_thread.handle_page_headers_available(webview_id, pipeline_id, metadata, can_gc)
523 })
524 }
525
526 pub(crate) fn process_event(msg: CommonScriptMsg, can_gc: CanGc) -> bool {
530 with_script_thread(|script_thread| {
531 if !script_thread.can_continue_running_inner() {
532 return false;
533 }
534 script_thread.handle_msg_from_script(MainThreadScriptMsg::Common(msg), can_gc);
535 true
536 })
537 }
538
539 pub(crate) fn schedule_timer(&self, request: TimerEventRequest) -> TimerId {
541 self.timer_scheduler.borrow_mut().schedule_timer(request)
542 }
543
544 pub(crate) fn cancel_timer(&self, timer_id: TimerId) {
547 self.timer_scheduler.borrow_mut().cancel_timer(timer_id)
548 }
549
550 pub(crate) fn await_stable_state(task: Microtask) {
552 with_script_thread(|script_thread| {
553 script_thread
554 .microtask_queue
555 .enqueue(task, script_thread.get_cx());
556 });
557 }
558
559 pub(crate) fn check_load_origin(source: &LoadOrigin, target: &ImmutableOrigin) -> bool {
564 match (source, target) {
565 (LoadOrigin::Constellation, _) | (LoadOrigin::WebDriver, _) => {
566 true
568 },
569 (_, ImmutableOrigin::Opaque(_)) => {
570 true
574 },
575 (LoadOrigin::Script(source_origin), _) => source_origin == target,
576 }
577 }
578
579 pub(crate) fn set_needs_rendering_update(&self) {
583 self.needs_rendering_update.store(true, Ordering::Relaxed);
584 }
585
586 pub(crate) fn navigate(
588 webview_id: WebViewId,
589 pipeline_id: PipelineId,
590 mut load_data: LoadData,
591 history_handling: NavigationHistoryBehavior,
592 ) {
593 with_script_thread(|script_thread| {
594 let is_javascript = load_data.url.scheme() == "javascript";
595 if is_javascript {
598 let window = match script_thread.documents.borrow().find_window(pipeline_id) {
599 None => return,
600 Some(window) => window,
601 };
602 let global = window.as_global_scope();
603 let trusted_global = Trusted::new(global);
604 let sender = script_thread
605 .senders
606 .pipeline_to_constellation_sender
607 .clone();
608 let task = task!(navigate_javascript: move || {
609 if trusted_global.root().is::<Window>() {
611 let global = &trusted_global.root();
612 if Self::navigate_to_javascript_url(global, global, &mut load_data, None, CanGc::note()) {
613 sender
614 .send((webview_id, pipeline_id, ScriptToConstellationMessage::LoadUrl(load_data, history_handling)))
615 .unwrap();
616 }
617 }
618 });
619 global
621 .task_manager()
622 .dom_manipulation_task_source()
623 .queue(task);
624 } else {
625 script_thread
626 .senders
627 .pipeline_to_constellation_sender
628 .send((
629 webview_id,
630 pipeline_id,
631 ScriptToConstellationMessage::LoadUrl(load_data, history_handling),
632 ))
633 .expect("Sending a LoadUrl message to the constellation failed");
634 }
635 });
636 }
637
638 pub(crate) fn navigate_to_javascript_url(
640 global: &GlobalScope,
641 containing_global: &GlobalScope,
642 load_data: &mut LoadData,
643 container: Option<&Element>,
644 can_gc: CanGc,
645 ) -> bool {
646 if !Self::check_load_origin(&load_data.load_origin, &global.get_url().origin()) {
650 return false;
651 }
652
653 if global
656 .get_csp_list()
657 .should_navigation_request_be_blocked(global, load_data, container, can_gc)
658 {
659 return false;
660 }
661
662 Self::eval_js_url(containing_global, load_data, can_gc);
665 true
666 }
667
668 pub(crate) fn process_attach_layout(new_layout_info: NewLayoutInfo, origin: MutableOrigin) {
669 with_script_thread(|script_thread| {
670 let pipeline_id = Some(new_layout_info.new_pipeline_id);
671 script_thread.profile_event(
672 ScriptThreadEventCategory::AttachLayout,
673 pipeline_id,
674 || {
675 script_thread.handle_new_layout(new_layout_info, origin);
676 },
677 )
678 });
679 }
680
681 pub(crate) fn get_top_level_for_browsing_context(
682 sender_webview_id: WebViewId,
683 sender_pipeline_id: PipelineId,
684 browsing_context_id: BrowsingContextId,
685 ) -> Option<WebViewId> {
686 with_script_thread(|script_thread| {
687 script_thread.ask_constellation_for_top_level_info(
688 sender_webview_id,
689 sender_pipeline_id,
690 browsing_context_id,
691 )
692 })
693 }
694
695 pub(crate) fn find_document(id: PipelineId) -> Option<DomRoot<Document>> {
696 with_script_thread(|script_thread| script_thread.documents.borrow().find_document(id))
697 }
698
699 #[must_use]
703 pub(crate) fn user_interacting_guard() -> ScriptUserInteractingGuard {
704 with_script_thread(|script_thread| {
705 ScriptUserInteractingGuard::new(script_thread.is_user_interacting.clone())
706 })
707 }
708
709 pub(crate) fn is_user_interacting() -> bool {
710 with_script_thread(|script_thread| script_thread.is_user_interacting.get())
711 }
712
713 pub(crate) fn get_fully_active_document_ids(&self) -> FxHashSet<PipelineId> {
714 self.documents
715 .borrow()
716 .iter()
717 .filter_map(|(id, document)| {
718 if document.is_fully_active() {
719 Some(id)
720 } else {
721 None
722 }
723 })
724 .fold(FxHashSet::default(), |mut set, id| {
725 let _ = set.insert(id);
726 set
727 })
728 }
729
730 pub(crate) fn window_proxies() -> Rc<ScriptWindowProxies> {
731 with_script_thread(|script_thread| script_thread.window_proxies.clone())
732 }
733
734 pub(crate) fn find_window_proxy_by_name(name: &DOMString) -> Option<DomRoot<WindowProxy>> {
735 with_script_thread(|script_thread| {
736 script_thread.window_proxies.find_window_proxy_by_name(name)
737 })
738 }
739
740 pub(crate) fn worklet_thread_pool(image_cache: Arc<dyn ImageCache>) -> Rc<WorkletThreadPool> {
742 with_optional_script_thread(|script_thread| {
743 let script_thread = script_thread.unwrap();
744 script_thread
745 .worklet_thread_pool
746 .borrow_mut()
747 .get_or_insert_with(|| {
748 let init = WorkletGlobalScopeInit {
749 to_script_thread_sender: script_thread.senders.self_sender.clone(),
750 resource_threads: script_thread.resource_threads.clone(),
751 storage_threads: script_thread.storage_threads.clone(),
752 mem_profiler_chan: script_thread.senders.memory_profiler_sender.clone(),
753 time_profiler_chan: script_thread.senders.time_profiler_sender.clone(),
754 devtools_chan: script_thread.senders.devtools_server_sender.clone(),
755 to_constellation_sender: script_thread
756 .senders
757 .pipeline_to_constellation_sender
758 .clone(),
759 to_embedder_sender: script_thread
760 .senders
761 .pipeline_to_embedder_sender
762 .clone(),
763 image_cache,
764 #[cfg(feature = "webgpu")]
765 gpu_id_hub: script_thread.gpu_id_hub.clone(),
766 inherited_secure_context: script_thread.inherited_secure_context,
767 };
768 Rc::new(WorkletThreadPool::spawn(init))
769 })
770 .clone()
771 })
772 }
773
774 fn handle_register_paint_worklet(
775 &self,
776 pipeline_id: PipelineId,
777 name: Atom,
778 properties: Vec<Atom>,
779 painter: Box<dyn Painter>,
780 ) {
781 let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
782 warn!("Paint worklet registered after pipeline {pipeline_id} closed.");
783 return;
784 };
785
786 window
787 .layout_mut()
788 .register_paint_worklet_modules(name, properties, painter);
789 }
790
791 pub(crate) fn custom_element_reaction_stack() -> Rc<CustomElementReactionStack> {
792 with_optional_script_thread(|script_thread| {
793 script_thread
794 .as_ref()
795 .unwrap()
796 .custom_element_reaction_stack
797 .clone()
798 })
799 }
800
801 pub(crate) fn enqueue_callback_reaction(
802 element: &Element,
803 reaction: CallbackReaction,
804 definition: Option<Rc<CustomElementDefinition>>,
805 ) {
806 with_script_thread(|script_thread| {
807 script_thread
808 .custom_element_reaction_stack
809 .enqueue_callback_reaction(element, reaction, definition);
810 })
811 }
812
813 pub(crate) fn enqueue_upgrade_reaction(
814 element: &Element,
815 definition: Rc<CustomElementDefinition>,
816 ) {
817 with_script_thread(|script_thread| {
818 script_thread
819 .custom_element_reaction_stack
820 .enqueue_upgrade_reaction(element, definition);
821 })
822 }
823
824 pub(crate) fn invoke_backup_element_queue(can_gc: CanGc) {
825 with_script_thread(|script_thread| {
826 script_thread
827 .custom_element_reaction_stack
828 .invoke_backup_element_queue(can_gc);
829 })
830 }
831
832 pub(crate) fn save_node_id(pipeline: PipelineId, node_id: String) {
833 with_script_thread(|script_thread| {
834 script_thread
835 .pipeline_to_node_ids
836 .borrow_mut()
837 .entry(pipeline)
838 .or_default()
839 .insert(node_id);
840 })
841 }
842
843 pub(crate) fn has_node_id(pipeline: PipelineId, node_id: &str) -> bool {
844 with_script_thread(|script_thread| {
845 script_thread
846 .pipeline_to_node_ids
847 .borrow()
848 .get(&pipeline)
849 .is_some_and(|node_ids| node_ids.contains(node_id))
850 })
851 }
852
853 pub(crate) fn new(
855 state: InitialScriptState,
856 layout_factory: Arc<dyn LayoutFactory>,
857 system_font_service: Arc<SystemFontServiceProxy>,
858 ) -> ScriptThread {
859 let (self_sender, self_receiver) = unbounded();
860 let runtime = Runtime::new(Some(SendableTaskSource {
861 sender: ScriptEventLoopSender::MainThread(self_sender.clone()),
862 pipeline_id: state.id,
863 name: TaskSourceName::Networking,
864 canceller: Default::default(),
865 }));
866 let cx = runtime.cx();
867
868 unsafe {
869 SetWindowProxyClass(cx, GetWindowProxyClass());
870 JS_AddInterruptCallback(cx, Some(interrupt_callback));
871 }
872
873 let constellation_receiver = state.constellation_receiver.route_preserving_errors();
874
875 let devtools_server_sender = state.devtools_server_sender;
877 let (ipc_devtools_sender, ipc_devtools_receiver) = ipc::channel().unwrap();
878 let devtools_server_receiver = devtools_server_sender
879 .as_ref()
880 .map(|_| ROUTER.route_ipc_receiver_to_new_crossbeam_receiver(ipc_devtools_receiver))
881 .unwrap_or_else(crossbeam_channel::never);
882
883 let task_queue = TaskQueue::new(self_receiver, self_sender.clone());
884
885 let closing = Arc::new(AtomicBool::new(false));
886 let background_hang_monitor_exit_signal = BHMExitSignal {
887 closing: closing.clone(),
888 js_context: runtime.thread_safe_js_context(),
889 };
890
891 let background_hang_monitor = state.background_hang_monitor_register.register_component(
892 MonitoredComponentId(state.id, MonitoredComponentType::Script),
893 Duration::from_millis(1000),
894 Duration::from_millis(5000),
895 Box::new(background_hang_monitor_exit_signal),
896 );
897
898 let (image_cache_sender, image_cache_receiver) = unbounded();
899 let (ipc_image_cache_sender, ipc_image_cache_receiver) = ipc::channel().unwrap();
900 ROUTER.add_typed_route(
901 ipc_image_cache_receiver,
902 Box::new(move |message| {
903 let _ = image_cache_sender.send(message.unwrap());
904 }),
905 );
906
907 let receivers = ScriptThreadReceivers {
908 constellation_receiver,
909 image_cache_receiver,
910 devtools_server_receiver,
911 #[cfg(feature = "webgpu")]
913 webgpu_receiver: RefCell::new(crossbeam_channel::never()),
914 };
915
916 let opts = opts::get();
917 let senders = ScriptThreadSenders {
918 self_sender,
919 #[cfg(feature = "bluetooth")]
920 bluetooth_sender: state.bluetooth_sender,
921 constellation_sender: state.constellation_sender,
922 pipeline_to_constellation_sender: state.pipeline_to_constellation_sender.sender.clone(),
923 pipeline_to_embedder_sender: state.pipeline_to_embedder_sender.clone(),
924 image_cache_sender: ipc_image_cache_sender,
925 time_profiler_sender: state.time_profiler_sender,
926 memory_profiler_sender: state.memory_profiler_sender,
927 devtools_server_sender,
928 devtools_client_to_script_thread_sender: ipc_devtools_sender,
929 content_process_shutdown_sender: state.content_process_shutdown_sender,
930 };
931
932 let microtask_queue = runtime.microtask_queue.clone();
933 let js_runtime = Rc::new(runtime);
934 #[cfg(feature = "webgpu")]
935 let gpu_id_hub = Arc::new(IdentityHub::default());
936
937 let pipeline_id = PipelineId::new();
938 let script_to_constellation_chan = ScriptToConstellationChan {
939 sender: senders.pipeline_to_constellation_sender.clone(),
940 webview_id: state.webview_id,
941 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 CanGc::note(),
956 );
957 debugger_global.execute(CanGc::note());
958
959 ScriptThread {
960 documents: DomRefCell::new(DocumentCollection::default()),
961 last_render_opportunity_time: Default::default(),
962 window_proxies: Default::default(),
963 incomplete_loads: DomRefCell::new(vec![]),
964 incomplete_parser_contexts: IncompleteParserContexts(RefCell::new(vec![])),
965 senders,
966 receivers,
967 image_cache: state.image_cache.clone(),
968 resource_threads: state.resource_threads,
969 storage_threads: state.storage_threads,
970 task_queue,
971 background_hang_monitor,
972 closing,
973 timer_scheduler: Default::default(),
974 microtask_queue,
975 js_runtime,
976 closed_pipelines: DomRefCell::new(FxHashSet::default()),
977 mutation_observers: Default::default(),
978 system_font_service,
979 webgl_chan: state.webgl_chan,
980 #[cfg(feature = "webxr")]
981 webxr_registry: state.webxr_registry,
982 worklet_thread_pool: Default::default(),
983 docs_with_no_blocking_loads: Default::default(),
984 custom_element_reaction_stack: Rc::new(CustomElementReactionStack::new()),
985 compositor_api: state.compositor_api,
986 profile_script_events: opts.debug.profile_script_events,
987 print_pwm: opts.print_pwm,
988 unminify_js: opts.unminify_js,
989 local_script_source: opts.local_script_source.clone(),
990 unminify_css: opts.unminify_css,
991 user_content_manager: state.user_content_manager,
992 player_context: state.player_context,
993 pipeline_to_node_ids: Default::default(),
994 is_user_interacting: Rc::new(Cell::new(false)),
995 #[cfg(feature = "webgpu")]
996 gpu_id_hub,
997 inherited_secure_context: state.inherited_secure_context,
998 layout_factory,
999 scheduled_update_the_rendering: Default::default(),
1000 needs_rendering_update: Arc::new(AtomicBool::new(false)),
1001 debugger_global: debugger_global.as_traced(),
1002 privileged_urls: state.privileged_urls,
1003 }
1004 }
1005
1006 #[allow(unsafe_code)]
1007 pub(crate) fn get_cx(&self) -> JSContext {
1008 unsafe { JSContext::from_ptr(self.js_runtime.cx()) }
1009 }
1010
1011 fn can_continue_running_inner(&self) -> bool {
1013 if self.closing.load(Ordering::SeqCst) {
1014 return false;
1015 }
1016 true
1017 }
1018
1019 fn prepare_for_shutdown_inner(&self) {
1021 let docs = self.documents.borrow();
1022 for (_, document) in docs.iter() {
1023 document
1024 .owner_global()
1025 .task_manager()
1026 .cancel_all_tasks_and_ignore_future_tasks();
1027 }
1028 }
1029
1030 pub(crate) fn start(&self, can_gc: CanGc) {
1033 debug!("Starting script thread.");
1034 while self.handle_msgs(can_gc) {
1035 debug!("Running script thread.");
1037 }
1038 debug!("Stopped script thread.");
1039 }
1040
1041 fn process_pending_input_events(&self, pipeline_id: PipelineId, can_gc: CanGc) {
1043 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
1044 warn!("Processing pending compositor events for closed pipeline {pipeline_id}.");
1045 return;
1046 };
1047 if document.window().Closed() {
1049 warn!("Compositor event sent to a pipeline with a closed window {pipeline_id}.");
1050 return;
1051 }
1052
1053 let _guard = ScriptUserInteractingGuard::new(self.is_user_interacting.clone());
1054 document.event_handler().handle_pending_input_events(can_gc);
1055 }
1056
1057 fn cancel_scheduled_update_the_rendering(&self) {
1058 if let Some(timer_id) = self.scheduled_update_the_rendering.borrow_mut().take() {
1059 self.timer_scheduler.borrow_mut().cancel_timer(timer_id);
1060 }
1061 }
1062
1063 fn schedule_update_the_rendering_timer_if_necessary(&self, delay: Duration) {
1064 if self.scheduled_update_the_rendering.borrow().is_some() {
1065 return;
1066 }
1067
1068 debug!("Scheduling ScriptThread animation frame.");
1069 let trigger_script_thread_animation = self.needs_rendering_update.clone();
1070 let timer_id = self.schedule_timer(TimerEventRequest {
1071 callback: Box::new(move || {
1072 trigger_script_thread_animation.store(true, Ordering::Relaxed);
1073 }),
1074 duration: delay,
1075 });
1076
1077 *self.scheduled_update_the_rendering.borrow_mut() = Some(timer_id);
1078 }
1079
1080 pub(crate) fn update_the_rendering(&self, can_gc: CanGc) -> bool {
1087 self.last_render_opportunity_time.set(Some(Instant::now()));
1088 self.cancel_scheduled_update_the_rendering();
1089 self.needs_rendering_update.store(false, Ordering::Relaxed);
1090
1091 if !self.can_continue_running_inner() {
1092 return false;
1093 }
1094
1095 let documents_in_order = self.documents.borrow().documents_in_order();
1118
1119 let mut should_generate_frame = false;
1124 for pipeline_id in documents_in_order.iter() {
1125 let document = self
1126 .documents
1127 .borrow()
1128 .find_document(*pipeline_id)
1129 .expect("Got pipeline for Document not managed by this ScriptThread.");
1130
1131 if !document.is_fully_active() {
1132 continue;
1133 }
1134
1135 if document.waiting_on_canvas_image_updates() {
1136 continue;
1137 }
1138
1139 document.clear_rendering_update_reasons();
1142
1143 self.process_pending_input_events(*pipeline_id, can_gc);
1150
1151 let resized = document.window().run_the_resize_steps(can_gc);
1153
1154 document.run_the_scroll_steps(can_gc);
1156
1157 if resized {
1159 document
1161 .window()
1162 .evaluate_media_queries_and_report_changes(can_gc);
1163
1164 document.react_to_environment_changes()
1167 }
1168
1169 document.update_animations_and_send_events(can_gc);
1173
1174 document.run_the_animation_frame_callbacks(can_gc);
1184
1185 let _realm = enter_realm(&*document);
1187 let mut depth = Default::default();
1188 while document.gather_active_resize_observations_at_depth(&depth) {
1189 depth = document.broadcast_active_resize_observations(can_gc);
1191 }
1192
1193 if document.has_skipped_resize_observations() {
1194 document.deliver_resize_loop_error_notification(can_gc);
1195 document.add_rendering_update_reason(
1198 RenderingUpdateReason::ResizeObserverStartedObservingTarget,
1199 );
1200 }
1201
1202 document.update_intersection_observer_steps(CrossProcessInstant::now(), can_gc);
1213
1214 should_generate_frame =
1219 document.update_the_rendering().needs_frame() || should_generate_frame;
1220
1221 }
1224
1225 if should_generate_frame {
1226 self.compositor_api.generate_frame();
1227 }
1228
1229 self.perform_a_microtask_checkpoint(can_gc);
1232 should_generate_frame
1233 }
1234
1235 fn maybe_schedule_rendering_opportunity_after_ipc_message(
1242 &self,
1243 built_any_display_lists: bool,
1244 ) {
1245 let needs_rendering_update = self
1246 .documents
1247 .borrow()
1248 .iter()
1249 .any(|(_, document)| document.needs_rendering_update());
1250 let running_animations = self.documents.borrow().iter().any(|(_, document)| {
1251 document.is_fully_active() &&
1252 !document.window().throttled() &&
1253 (document.animations().running_animation_count() != 0 ||
1254 document.has_active_request_animation_frame_callbacks())
1255 });
1256
1257 if !needs_rendering_update && !running_animations {
1261 return;
1262 }
1263
1264 if running_animations && built_any_display_lists {
1268 return;
1269 }
1270
1271 let animation_delay = if running_animations && !needs_rendering_update {
1279 Duration::from_millis(30)
1283 } else {
1284 Duration::from_millis(20)
1287 };
1288
1289 let time_since_last_rendering_opportunity = self
1290 .last_render_opportunity_time
1291 .get()
1292 .map(|last_render_opportunity_time| Instant::now() - last_render_opportunity_time)
1293 .unwrap_or(Duration::MAX)
1294 .min(animation_delay);
1295 self.schedule_update_the_rendering_timer_if_necessary(
1296 animation_delay - time_since_last_rendering_opportunity,
1297 );
1298 }
1299
1300 fn maybe_fulfill_font_ready_promises(&self, can_gc: CanGc) {
1303 let mut sent_message = false;
1304 for (_, document) in self.documents.borrow().iter() {
1305 sent_message = document.maybe_fulfill_font_ready_promise(can_gc) || sent_message;
1306 }
1307
1308 if sent_message {
1309 self.perform_a_microtask_checkpoint(can_gc);
1310 }
1311 }
1312
1313 fn maybe_resolve_pending_screenshot_readiness_requests(&self, can_gc: CanGc) {
1317 for (_, document) in self.documents.borrow().iter() {
1318 document
1319 .window()
1320 .maybe_resolve_pending_screenshot_readiness_requests(can_gc);
1321 }
1322 }
1323
1324 fn handle_msgs(&self, can_gc: CanGc) -> bool {
1326 let mut sequential = vec![];
1328
1329 self.background_hang_monitor.notify_wait();
1331
1332 debug!("Waiting for event.");
1334 let fully_active = self.get_fully_active_document_ids();
1335 let mut event = self.receivers.recv(
1336 &self.task_queue,
1337 &self.timer_scheduler.borrow(),
1338 &fully_active,
1339 );
1340
1341 loop {
1342 debug!("Handling event: {event:?}");
1343
1344 self.timer_scheduler
1346 .borrow_mut()
1347 .dispatch_completed_timers();
1348
1349 let _realm = event.pipeline_id().map(|id| {
1350 let global = self.documents.borrow().find_global(id);
1351 global.map(|global| enter_realm(&*global))
1352 });
1353
1354 match event {
1356 MixedMessage::FromConstellation(ScriptThreadMessage::AttachLayout(
1360 new_layout_info,
1361 )) => {
1362 let pipeline_id = new_layout_info.new_pipeline_id;
1363 self.profile_event(
1364 ScriptThreadEventCategory::AttachLayout,
1365 Some(pipeline_id),
1366 || {
1367 let not_an_about_blank_and_about_srcdoc_load =
1371 new_layout_info.load_data.url.as_str() != "about:blank" &&
1372 new_layout_info.load_data.url.as_str() != "about:srcdoc";
1373 let origin = if not_an_about_blank_and_about_srcdoc_load {
1374 MutableOrigin::new(new_layout_info.load_data.url.origin())
1375 } else if let Some(parent) =
1376 new_layout_info.parent_info.and_then(|pipeline_id| {
1377 self.documents.borrow().find_document(pipeline_id)
1378 })
1379 {
1380 parent.origin().clone()
1381 } else if let Some(creator) = new_layout_info
1382 .load_data
1383 .creator_pipeline_id
1384 .and_then(|pipeline_id| {
1385 self.documents.borrow().find_document(pipeline_id)
1386 })
1387 {
1388 creator.origin().clone()
1389 } else {
1390 MutableOrigin::new(ImmutableOrigin::new_opaque())
1391 };
1392
1393 self.handle_new_layout(new_layout_info, origin);
1394 },
1395 )
1396 },
1397 MixedMessage::FromConstellation(ScriptThreadMessage::Resize(
1398 id,
1399 size,
1400 size_type,
1401 )) => {
1402 self.handle_resize_message(id, size, size_type);
1403 },
1404 MixedMessage::FromConstellation(ScriptThreadMessage::Viewport(id, rect)) => self
1405 .profile_event(ScriptThreadEventCategory::SetViewport, Some(id), || {
1406 self.handle_viewport(id, rect);
1407 }),
1408 MixedMessage::FromConstellation(ScriptThreadMessage::TickAllAnimations(
1409 _webviews,
1410 )) => {
1411 self.set_needs_rendering_update();
1412 },
1413 MixedMessage::FromConstellation(
1414 ScriptThreadMessage::NoLongerWaitingOnAsychronousImageUpdates(pipeline_id),
1415 ) => {
1416 if let Some(document) = self.documents.borrow().find_document(pipeline_id) {
1417 document.handle_no_longer_waiting_on_asynchronous_image_updates();
1418 }
1419 },
1420 MixedMessage::FromConstellation(ScriptThreadMessage::SendInputEvent(
1421 webview_id,
1422 id,
1423 event,
1424 )) => self.handle_input_event(webview_id, id, event),
1425 MixedMessage::FromScript(MainThreadScriptMsg::Common(CommonScriptMsg::Task(
1426 _,
1427 _,
1428 _,
1429 TaskSourceName::Rendering,
1430 ))) => {
1431 },
1435 MixedMessage::FromScript(MainThreadScriptMsg::Inactive) => {
1436 },
1439 MixedMessage::FromConstellation(ScriptThreadMessage::ExitFullScreen(id)) => self
1440 .profile_event(ScriptThreadEventCategory::ExitFullscreen, Some(id), || {
1441 self.handle_exit_fullscreen(id, can_gc);
1442 }),
1443 _ => {
1444 sequential.push(event);
1445 },
1446 }
1447
1448 match self.receivers.try_recv(&self.task_queue, &fully_active) {
1452 Some(new_event) => event = new_event,
1453 None => break,
1454 }
1455 }
1456
1457 debug!("Processing events.");
1459 for msg in sequential {
1460 debug!("Processing event {:?}.", msg);
1461 let category = self.categorize_msg(&msg);
1462 let pipeline_id = msg.pipeline_id();
1463 let _realm = pipeline_id.and_then(|id| {
1464 let global = self.documents.borrow().find_global(id);
1465 global.map(|global| enter_realm(&*global))
1466 });
1467
1468 if self.closing.load(Ordering::SeqCst) {
1469 match msg {
1471 MixedMessage::FromConstellation(ScriptThreadMessage::ExitScriptThread) => {
1472 self.handle_exit_script_thread_msg(can_gc);
1473 return false;
1474 },
1475 MixedMessage::FromConstellation(ScriptThreadMessage::ExitPipeline(
1476 webview_id,
1477 pipeline_id,
1478 discard_browsing_context,
1479 )) => {
1480 self.handle_exit_pipeline_msg(
1481 webview_id,
1482 pipeline_id,
1483 discard_browsing_context,
1484 can_gc,
1485 );
1486 },
1487 _ => {},
1488 }
1489 continue;
1490 }
1491
1492 let exiting = self.profile_event(category, pipeline_id, move || {
1493 match msg {
1494 MixedMessage::FromConstellation(ScriptThreadMessage::ExitScriptThread) => {
1495 self.handle_exit_script_thread_msg(can_gc);
1496 return true;
1497 },
1498 MixedMessage::FromConstellation(inner_msg) => {
1499 self.handle_msg_from_constellation(inner_msg, can_gc)
1500 },
1501 MixedMessage::FromScript(inner_msg) => {
1502 self.handle_msg_from_script(inner_msg, can_gc)
1503 },
1504 MixedMessage::FromDevtools(inner_msg) => {
1505 self.handle_msg_from_devtools(inner_msg, can_gc)
1506 },
1507 MixedMessage::FromImageCache(inner_msg) => {
1508 self.handle_msg_from_image_cache(inner_msg)
1509 },
1510 #[cfg(feature = "webgpu")]
1511 MixedMessage::FromWebGPUServer(inner_msg) => {
1512 self.handle_msg_from_webgpu_server(inner_msg)
1513 },
1514 MixedMessage::TimerFired => {},
1515 }
1516
1517 false
1518 });
1519
1520 if exiting {
1522 return false;
1523 }
1524
1525 self.perform_a_microtask_checkpoint(can_gc);
1528 }
1529
1530 for (_, doc) in self.documents.borrow().iter() {
1531 let window = doc.window();
1532 window
1533 .upcast::<GlobalScope>()
1534 .perform_a_dom_garbage_collection_checkpoint();
1535 }
1536
1537 {
1538 let mut docs = self.docs_with_no_blocking_loads.borrow_mut();
1540 for document in docs.iter() {
1541 let _realm = enter_realm(&**document);
1542 document.maybe_queue_document_completion();
1543 }
1544 docs.clear();
1545 }
1546
1547 let built_any_display_lists = self.needs_rendering_update.load(Ordering::Relaxed) &&
1548 self.update_the_rendering(can_gc);
1549
1550 self.maybe_fulfill_font_ready_promises(can_gc);
1551 self.maybe_resolve_pending_screenshot_readiness_requests(can_gc);
1552
1553 self.maybe_schedule_rendering_opportunity_after_ipc_message(built_any_display_lists);
1555
1556 true
1557 }
1558
1559 fn categorize_msg(&self, msg: &MixedMessage) -> ScriptThreadEventCategory {
1560 match *msg {
1561 MixedMessage::FromConstellation(ref inner_msg) => match *inner_msg {
1562 ScriptThreadMessage::SendInputEvent(..) => ScriptThreadEventCategory::InputEvent,
1563 _ => ScriptThreadEventCategory::ConstellationMsg,
1564 },
1565 MixedMessage::FromDevtools(_) => ScriptThreadEventCategory::DevtoolsMsg,
1567 MixedMessage::FromImageCache(_) => ScriptThreadEventCategory::ImageCacheMsg,
1568 MixedMessage::FromScript(ref inner_msg) => match *inner_msg {
1569 MainThreadScriptMsg::Common(CommonScriptMsg::Task(category, ..)) => category,
1570 MainThreadScriptMsg::RegisterPaintWorklet { .. } => {
1571 ScriptThreadEventCategory::WorkletEvent
1572 },
1573 _ => ScriptThreadEventCategory::ScriptEvent,
1574 },
1575 #[cfg(feature = "webgpu")]
1576 MixedMessage::FromWebGPUServer(_) => ScriptThreadEventCategory::WebGPUMsg,
1577 MixedMessage::TimerFired => ScriptThreadEventCategory::TimerEvent,
1578 }
1579 }
1580
1581 fn profile_event<F, R>(
1582 &self,
1583 category: ScriptThreadEventCategory,
1584 pipeline_id: Option<PipelineId>,
1585 f: F,
1586 ) -> R
1587 where
1588 F: FnOnce() -> R,
1589 {
1590 self.background_hang_monitor
1591 .notify_activity(HangAnnotation::Script(category.into()));
1592 let start = Instant::now();
1593 let value = if self.profile_script_events {
1594 let profiler_chan = self.senders.time_profiler_sender.clone();
1595 match category {
1596 ScriptThreadEventCategory::AttachLayout => {
1597 time_profile!(ProfilerCategory::ScriptAttachLayout, None, profiler_chan, f)
1598 },
1599 ScriptThreadEventCategory::ConstellationMsg => time_profile!(
1600 ProfilerCategory::ScriptConstellationMsg,
1601 None,
1602 profiler_chan,
1603 f
1604 ),
1605 ScriptThreadEventCategory::DatabaseAccessEvent => time_profile!(
1606 ProfilerCategory::ScriptDatabaseAccessEvent,
1607 None,
1608 profiler_chan,
1609 f
1610 ),
1611 ScriptThreadEventCategory::DevtoolsMsg => {
1612 time_profile!(ProfilerCategory::ScriptDevtoolsMsg, None, profiler_chan, f)
1613 },
1614 ScriptThreadEventCategory::DocumentEvent => time_profile!(
1615 ProfilerCategory::ScriptDocumentEvent,
1616 None,
1617 profiler_chan,
1618 f
1619 ),
1620 ScriptThreadEventCategory::InputEvent => {
1621 time_profile!(ProfilerCategory::ScriptInputEvent, None, profiler_chan, f)
1622 },
1623 ScriptThreadEventCategory::FileRead => {
1624 time_profile!(ProfilerCategory::ScriptFileRead, None, profiler_chan, f)
1625 },
1626 ScriptThreadEventCategory::FontLoading => {
1627 time_profile!(ProfilerCategory::ScriptFontLoading, None, profiler_chan, f)
1628 },
1629 ScriptThreadEventCategory::FormPlannedNavigation => time_profile!(
1630 ProfilerCategory::ScriptPlannedNavigation,
1631 None,
1632 profiler_chan,
1633 f
1634 ),
1635 ScriptThreadEventCategory::GeolocationEvent => {
1636 time_profile!(
1637 ProfilerCategory::ScriptGeolocationEvent,
1638 None,
1639 profiler_chan,
1640 f
1641 )
1642 },
1643 ScriptThreadEventCategory::HistoryEvent => {
1644 time_profile!(ProfilerCategory::ScriptHistoryEvent, None, profiler_chan, f)
1645 },
1646 ScriptThreadEventCategory::ImageCacheMsg => time_profile!(
1647 ProfilerCategory::ScriptImageCacheMsg,
1648 None,
1649 profiler_chan,
1650 f
1651 ),
1652 ScriptThreadEventCategory::NetworkEvent => {
1653 time_profile!(ProfilerCategory::ScriptNetworkEvent, None, profiler_chan, f)
1654 },
1655 ScriptThreadEventCategory::PortMessage => {
1656 time_profile!(ProfilerCategory::ScriptPortMessage, None, profiler_chan, f)
1657 },
1658 ScriptThreadEventCategory::Resize => {
1659 time_profile!(ProfilerCategory::ScriptResize, None, profiler_chan, f)
1660 },
1661 ScriptThreadEventCategory::ScriptEvent => {
1662 time_profile!(ProfilerCategory::ScriptEvent, None, profiler_chan, f)
1663 },
1664 ScriptThreadEventCategory::SetScrollState => time_profile!(
1665 ProfilerCategory::ScriptSetScrollState,
1666 None,
1667 profiler_chan,
1668 f
1669 ),
1670 ScriptThreadEventCategory::UpdateReplacedElement => time_profile!(
1671 ProfilerCategory::ScriptUpdateReplacedElement,
1672 None,
1673 profiler_chan,
1674 f
1675 ),
1676 ScriptThreadEventCategory::StylesheetLoad => time_profile!(
1677 ProfilerCategory::ScriptStylesheetLoad,
1678 None,
1679 profiler_chan,
1680 f
1681 ),
1682 ScriptThreadEventCategory::SetViewport => {
1683 time_profile!(ProfilerCategory::ScriptSetViewport, None, profiler_chan, f)
1684 },
1685 ScriptThreadEventCategory::TimerEvent => {
1686 time_profile!(ProfilerCategory::ScriptTimerEvent, None, profiler_chan, f)
1687 },
1688 ScriptThreadEventCategory::WebSocketEvent => time_profile!(
1689 ProfilerCategory::ScriptWebSocketEvent,
1690 None,
1691 profiler_chan,
1692 f
1693 ),
1694 ScriptThreadEventCategory::WorkerEvent => {
1695 time_profile!(ProfilerCategory::ScriptWorkerEvent, None, profiler_chan, f)
1696 },
1697 ScriptThreadEventCategory::WorkletEvent => {
1698 time_profile!(ProfilerCategory::ScriptWorkletEvent, None, profiler_chan, f)
1699 },
1700 ScriptThreadEventCategory::ServiceWorkerEvent => time_profile!(
1701 ProfilerCategory::ScriptServiceWorkerEvent,
1702 None,
1703 profiler_chan,
1704 f
1705 ),
1706 ScriptThreadEventCategory::EnterFullscreen => time_profile!(
1707 ProfilerCategory::ScriptEnterFullscreen,
1708 None,
1709 profiler_chan,
1710 f
1711 ),
1712 ScriptThreadEventCategory::ExitFullscreen => time_profile!(
1713 ProfilerCategory::ScriptExitFullscreen,
1714 None,
1715 profiler_chan,
1716 f
1717 ),
1718 ScriptThreadEventCategory::PerformanceTimelineTask => time_profile!(
1719 ProfilerCategory::ScriptPerformanceEvent,
1720 None,
1721 profiler_chan,
1722 f
1723 ),
1724 ScriptThreadEventCategory::Rendering => {
1725 time_profile!(ProfilerCategory::ScriptRendering, None, profiler_chan, f)
1726 },
1727 #[cfg(feature = "webgpu")]
1728 ScriptThreadEventCategory::WebGPUMsg => {
1729 time_profile!(ProfilerCategory::ScriptWebGPUMsg, None, profiler_chan, f)
1730 },
1731 }
1732 } else {
1733 f()
1734 };
1735 let task_duration = start.elapsed();
1736 for (doc_id, doc) in self.documents.borrow().iter() {
1737 if let Some(pipeline_id) = pipeline_id {
1738 if pipeline_id == doc_id && task_duration.as_nanos() > MAX_TASK_NS {
1739 if self.print_pwm {
1740 println!(
1741 "Task took longer than max allowed ({:?}) {:?}",
1742 category,
1743 task_duration.as_nanos()
1744 );
1745 }
1746 doc.start_tti();
1747 }
1748 }
1749 doc.record_tti_if_necessary();
1750 }
1751 value
1752 }
1753
1754 fn handle_msg_from_constellation(&self, msg: ScriptThreadMessage, can_gc: CanGc) {
1755 match msg {
1756 ScriptThreadMessage::StopDelayingLoadEventsMode(pipeline_id) => {
1757 self.handle_stop_delaying_load_events_mode(pipeline_id)
1758 },
1759 ScriptThreadMessage::NavigateIframe(
1760 parent_pipeline_id,
1761 browsing_context_id,
1762 load_data,
1763 history_handling,
1764 ) => self.handle_navigate_iframe(
1765 parent_pipeline_id,
1766 browsing_context_id,
1767 load_data,
1768 history_handling,
1769 can_gc,
1770 ),
1771 ScriptThreadMessage::UnloadDocument(pipeline_id) => {
1772 self.handle_unload_document(pipeline_id, can_gc)
1773 },
1774 ScriptThreadMessage::ResizeInactive(id, new_size) => {
1775 self.handle_resize_inactive_msg(id, new_size)
1776 },
1777 ScriptThreadMessage::ThemeChange(_, theme) => {
1778 self.handle_theme_change_msg(theme);
1779 },
1780 ScriptThreadMessage::GetTitle(pipeline_id) => self.handle_get_title_msg(pipeline_id),
1781 ScriptThreadMessage::SetDocumentActivity(pipeline_id, activity) => {
1782 self.handle_set_document_activity_msg(pipeline_id, activity, can_gc)
1783 },
1784 ScriptThreadMessage::SetThrottled(webview_id, pipeline_id, throttled) => {
1785 self.handle_set_throttled_msg(webview_id, pipeline_id, throttled)
1786 },
1787 ScriptThreadMessage::SetThrottledInContainingIframe(
1788 _,
1789 parent_pipeline_id,
1790 browsing_context_id,
1791 throttled,
1792 ) => self.handle_set_throttled_in_containing_iframe_msg(
1793 parent_pipeline_id,
1794 browsing_context_id,
1795 throttled,
1796 ),
1797 ScriptThreadMessage::PostMessage {
1798 target: target_pipeline_id,
1799 source_webview,
1800 source_with_ancestry,
1801 target_origin: origin,
1802 source_origin,
1803 data,
1804 } => self.handle_post_message_msg(
1805 target_pipeline_id,
1806 source_webview,
1807 source_with_ancestry,
1808 origin,
1809 source_origin,
1810 *data,
1811 ),
1812 ScriptThreadMessage::UpdatePipelineId(
1813 parent_pipeline_id,
1814 browsing_context_id,
1815 webview_id,
1816 new_pipeline_id,
1817 reason,
1818 ) => self.handle_update_pipeline_id(
1819 parent_pipeline_id,
1820 browsing_context_id,
1821 webview_id,
1822 new_pipeline_id,
1823 reason,
1824 can_gc,
1825 ),
1826 ScriptThreadMessage::UpdateHistoryState(pipeline_id, history_state_id, url) => {
1827 self.handle_update_history_state_msg(pipeline_id, history_state_id, url, can_gc)
1828 },
1829 ScriptThreadMessage::RemoveHistoryStates(pipeline_id, history_states) => {
1830 self.handle_remove_history_states(pipeline_id, history_states)
1831 },
1832 ScriptThreadMessage::FocusIFrame(parent_pipeline_id, frame_id, sequence) => {
1833 self.handle_focus_iframe_msg(parent_pipeline_id, frame_id, sequence, can_gc)
1834 },
1835 ScriptThreadMessage::FocusDocument(pipeline_id, sequence) => {
1836 self.handle_focus_document_msg(pipeline_id, sequence, can_gc)
1837 },
1838 ScriptThreadMessage::Unfocus(pipeline_id, sequence) => {
1839 self.handle_unfocus_msg(pipeline_id, sequence, can_gc)
1840 },
1841 ScriptThreadMessage::WebDriverScriptCommand(pipeline_id, msg) => {
1842 self.handle_webdriver_msg(pipeline_id, msg, can_gc)
1843 },
1844 ScriptThreadMessage::WebFontLoaded(pipeline_id, success) => {
1845 self.handle_web_font_loaded(pipeline_id, success)
1846 },
1847 ScriptThreadMessage::DispatchIFrameLoadEvent {
1848 target: browsing_context_id,
1849 parent: parent_id,
1850 child: child_id,
1851 } => self.handle_iframe_load_event(parent_id, browsing_context_id, child_id, can_gc),
1852 ScriptThreadMessage::DispatchStorageEvent(
1853 pipeline_id,
1854 storage,
1855 url,
1856 key,
1857 old_value,
1858 new_value,
1859 ) => self.handle_storage_event(pipeline_id, storage, url, key, old_value, new_value),
1860 ScriptThreadMessage::ReportCSSError(pipeline_id, filename, line, column, msg) => {
1861 self.handle_css_error_reporting(pipeline_id, filename, line, column, msg)
1862 },
1863 ScriptThreadMessage::Reload(pipeline_id) => self.handle_reload(pipeline_id, can_gc),
1864 ScriptThreadMessage::ExitPipeline(
1865 webview_id,
1866 pipeline_id,
1867 discard_browsing_context,
1868 ) => self.handle_exit_pipeline_msg(
1869 webview_id,
1870 pipeline_id,
1871 discard_browsing_context,
1872 can_gc,
1873 ),
1874 ScriptThreadMessage::PaintMetric(
1875 pipeline_id,
1876 metric_type,
1877 metric_value,
1878 first_reflow,
1879 ) => self.handle_paint_metric(
1880 pipeline_id,
1881 metric_type,
1882 metric_value,
1883 first_reflow,
1884 can_gc,
1885 ),
1886 ScriptThreadMessage::MediaSessionAction(pipeline_id, action) => {
1887 self.handle_media_session_action(pipeline_id, action, can_gc)
1888 },
1889 #[cfg(feature = "webgpu")]
1890 ScriptThreadMessage::SetWebGPUPort(port) => {
1891 *self.receivers.webgpu_receiver.borrow_mut() =
1892 ROUTER.route_ipc_receiver_to_new_crossbeam_receiver(port);
1893 },
1894 msg @ ScriptThreadMessage::AttachLayout(..) |
1895 msg @ ScriptThreadMessage::Viewport(..) |
1896 msg @ ScriptThreadMessage::Resize(..) |
1897 msg @ ScriptThreadMessage::ExitFullScreen(..) |
1898 msg @ ScriptThreadMessage::SendInputEvent(..) |
1899 msg @ ScriptThreadMessage::TickAllAnimations(..) |
1900 msg @ ScriptThreadMessage::NoLongerWaitingOnAsychronousImageUpdates(..) |
1901 msg @ ScriptThreadMessage::ExitScriptThread => {
1902 panic!("should have handled {:?} already", msg)
1903 },
1904 ScriptThreadMessage::SetScrollStates(pipeline_id, scroll_states) => {
1905 self.handle_set_scroll_states(pipeline_id, scroll_states)
1906 },
1907 ScriptThreadMessage::EvaluateJavaScript(
1908 webview_id,
1909 pipeline_id,
1910 evaluation_id,
1911 script,
1912 ) => {
1913 self.handle_evaluate_javascript(
1914 webview_id,
1915 pipeline_id,
1916 evaluation_id,
1917 script,
1918 can_gc,
1919 );
1920 },
1921 ScriptThreadMessage::SendImageKeysBatch(pipeline_id, image_keys) => {
1922 if let Some(window) = self.documents.borrow().find_window(pipeline_id) {
1923 window
1924 .image_cache()
1925 .fill_key_cache_with_batch_of_keys(image_keys);
1926 } else {
1927 warn!(
1928 "Could not find window corresponding to an image cache to send image keys to pipeline {:?}",
1929 pipeline_id
1930 );
1931 }
1932 },
1933 ScriptThreadMessage::RefreshCursor(pipeline_id) => {
1934 self.handle_refresh_cursor(pipeline_id);
1935 },
1936 ScriptThreadMessage::PreferencesUpdated(updates) => {
1937 let mut current_preferences = prefs::get().clone();
1938 for (name, value) in updates {
1939 current_preferences.set_value(&name, value);
1940 }
1941 prefs::set(current_preferences);
1942 },
1943 ScriptThreadMessage::ForwardKeyboardScroll(pipeline_id, scroll) => {
1944 if let Some(document) = self.documents.borrow().find_document(pipeline_id) {
1945 document.event_handler().do_keyboard_scroll(scroll);
1946 }
1947 },
1948 ScriptThreadMessage::RequestScreenshotReadiness(webview_id, pipeline_id) => {
1949 self.handle_request_screenshot_readiness(webview_id, pipeline_id, can_gc);
1950 },
1951 ScriptThreadMessage::EmbedderControlResponse(id, response) => {
1952 self.handle_embedder_control_response(id, response, can_gc);
1953 },
1954 }
1955 }
1956
1957 fn handle_set_scroll_states(
1958 &self,
1959 pipeline_id: PipelineId,
1960 scroll_states: FxHashMap<ExternalScrollId, LayoutVector2D>,
1961 ) {
1962 let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
1963 warn!("Received scroll states for closed pipeline {pipeline_id}");
1964 return;
1965 };
1966
1967 self.profile_event(
1968 ScriptThreadEventCategory::SetScrollState,
1969 Some(pipeline_id),
1970 || {
1971 window
1972 .layout_mut()
1973 .set_scroll_offsets_from_renderer(&scroll_states);
1974 },
1975 )
1976 }
1977
1978 #[cfg(feature = "webgpu")]
1979 fn handle_msg_from_webgpu_server(&self, msg: WebGPUMsg) {
1980 match msg {
1981 WebGPUMsg::FreeAdapter(id) => self.gpu_id_hub.free_adapter_id(id),
1982 WebGPUMsg::FreeDevice {
1983 device_id,
1984 pipeline_id,
1985 } => {
1986 self.gpu_id_hub.free_device_id(device_id);
1987 if let Some(global) = self.documents.borrow().find_global(pipeline_id) {
1988 global.remove_gpu_device(WebGPUDevice(device_id));
1989 } },
1991 WebGPUMsg::FreeBuffer(id) => self.gpu_id_hub.free_buffer_id(id),
1992 WebGPUMsg::FreePipelineLayout(id) => self.gpu_id_hub.free_pipeline_layout_id(id),
1993 WebGPUMsg::FreeComputePipeline(id) => self.gpu_id_hub.free_compute_pipeline_id(id),
1994 WebGPUMsg::FreeBindGroup(id) => self.gpu_id_hub.free_bind_group_id(id),
1995 WebGPUMsg::FreeBindGroupLayout(id) => self.gpu_id_hub.free_bind_group_layout_id(id),
1996 WebGPUMsg::FreeCommandBuffer(id) => self
1997 .gpu_id_hub
1998 .free_command_buffer_id(id.into_command_encoder_id()),
1999 WebGPUMsg::FreeSampler(id) => self.gpu_id_hub.free_sampler_id(id),
2000 WebGPUMsg::FreeShaderModule(id) => self.gpu_id_hub.free_shader_module_id(id),
2001 WebGPUMsg::FreeRenderBundle(id) => self.gpu_id_hub.free_render_bundle_id(id),
2002 WebGPUMsg::FreeRenderPipeline(id) => self.gpu_id_hub.free_render_pipeline_id(id),
2003 WebGPUMsg::FreeTexture(id) => self.gpu_id_hub.free_texture_id(id),
2004 WebGPUMsg::FreeTextureView(id) => self.gpu_id_hub.free_texture_view_id(id),
2005 WebGPUMsg::FreeComputePass(id) => self.gpu_id_hub.free_compute_pass_id(id),
2006 WebGPUMsg::FreeRenderPass(id) => self.gpu_id_hub.free_render_pass_id(id),
2007 WebGPUMsg::Exit => {
2008 *self.receivers.webgpu_receiver.borrow_mut() = crossbeam_channel::never()
2009 },
2010 WebGPUMsg::DeviceLost {
2011 pipeline_id,
2012 device,
2013 reason,
2014 msg,
2015 } => {
2016 let global = self.documents.borrow().find_global(pipeline_id).unwrap();
2017 global.gpu_device_lost(device, reason, msg);
2018 },
2019 WebGPUMsg::UncapturedError {
2020 device,
2021 pipeline_id,
2022 error,
2023 } => {
2024 let global = self.documents.borrow().find_global(pipeline_id).unwrap();
2025 let _ac = enter_realm(&*global);
2026 global.handle_uncaptured_gpu_error(device, error);
2027 },
2028 _ => {},
2029 }
2030 }
2031
2032 fn handle_msg_from_script(&self, msg: MainThreadScriptMsg, can_gc: CanGc) {
2033 match msg {
2034 MainThreadScriptMsg::Common(CommonScriptMsg::Task(_, task, pipeline_id, _)) => {
2035 let _realm = pipeline_id.and_then(|id| {
2036 let global = self.documents.borrow().find_global(id);
2037 global.map(|global| enter_realm(&*global))
2038 });
2039 task.run_box()
2040 },
2041 MainThreadScriptMsg::Common(CommonScriptMsg::CollectReports(chan)) => {
2042 self.collect_reports(chan)
2043 },
2044 MainThreadScriptMsg::Common(CommonScriptMsg::ReportCspViolations(
2045 pipeline_id,
2046 violations,
2047 )) => {
2048 if let Some(global) = self.documents.borrow().find_global(pipeline_id) {
2049 global.report_csp_violations(violations, None, None);
2050 }
2051 },
2052 MainThreadScriptMsg::NavigationResponse {
2053 pipeline_id,
2054 message,
2055 } => {
2056 self.handle_navigation_response(pipeline_id, *message);
2057 },
2058 MainThreadScriptMsg::WorkletLoaded(pipeline_id) => {
2059 self.handle_worklet_loaded(pipeline_id)
2060 },
2061 MainThreadScriptMsg::RegisterPaintWorklet {
2062 pipeline_id,
2063 name,
2064 properties,
2065 painter,
2066 } => self.handle_register_paint_worklet(pipeline_id, name, properties, painter),
2067 MainThreadScriptMsg::Inactive => {},
2068 MainThreadScriptMsg::WakeUp => {},
2069 MainThreadScriptMsg::ForwardEmbedderControlResponseFromFileManager(
2070 control_id,
2071 response,
2072 ) => {
2073 self.handle_embedder_control_response(control_id, response, can_gc);
2074 },
2075 }
2076 }
2077
2078 fn handle_msg_from_devtools(&self, msg: DevtoolScriptControlMsg, can_gc: CanGc) {
2079 let documents = self.documents.borrow();
2080 match msg {
2081 DevtoolScriptControlMsg::EvaluateJS(id, s, reply) => match documents.find_window(id) {
2082 Some(window) => {
2083 let global = window.as_global_scope();
2084 let _aes = AutoEntryScript::new(global);
2085 devtools::handle_evaluate_js(global, s, reply, can_gc)
2086 },
2087 None => warn!("Message sent to closed pipeline {}.", id),
2088 },
2089 DevtoolScriptControlMsg::GetRootNode(id, reply) => {
2090 devtools::handle_get_root_node(&documents, id, reply, can_gc)
2091 },
2092 DevtoolScriptControlMsg::GetDocumentElement(id, reply) => {
2093 devtools::handle_get_document_element(&documents, id, reply, can_gc)
2094 },
2095 DevtoolScriptControlMsg::GetChildren(id, node_id, reply) => {
2096 devtools::handle_get_children(&documents, id, node_id, reply, can_gc)
2097 },
2098 DevtoolScriptControlMsg::GetAttributeStyle(id, node_id, reply) => {
2099 devtools::handle_get_attribute_style(&documents, id, node_id, reply, can_gc)
2100 },
2101 DevtoolScriptControlMsg::GetStylesheetStyle(
2102 id,
2103 node_id,
2104 selector,
2105 stylesheet,
2106 reply,
2107 ) => devtools::handle_get_stylesheet_style(
2108 &documents, id, node_id, selector, stylesheet, reply, can_gc,
2109 ),
2110 DevtoolScriptControlMsg::GetSelectors(id, node_id, reply) => {
2111 devtools::handle_get_selectors(&documents, id, node_id, reply, can_gc)
2112 },
2113 DevtoolScriptControlMsg::GetComputedStyle(id, node_id, reply) => {
2114 devtools::handle_get_computed_style(&documents, id, node_id, reply)
2115 },
2116 DevtoolScriptControlMsg::GetLayout(id, node_id, reply) => {
2117 devtools::handle_get_layout(&documents, id, node_id, reply, can_gc)
2118 },
2119 DevtoolScriptControlMsg::GetXPath(id, node_id, reply) => {
2120 devtools::handle_get_xpath(&documents, id, node_id, reply)
2121 },
2122 DevtoolScriptControlMsg::ModifyAttribute(id, node_id, modifications) => {
2123 devtools::handle_modify_attribute(&documents, id, node_id, modifications, can_gc)
2124 },
2125 DevtoolScriptControlMsg::ModifyRule(id, node_id, modifications) => {
2126 devtools::handle_modify_rule(&documents, id, node_id, modifications, can_gc)
2127 },
2128 DevtoolScriptControlMsg::WantsLiveNotifications(id, to_send) => match documents
2129 .find_window(id)
2130 {
2131 Some(window) => devtools::handle_wants_live_notifications(window.upcast(), to_send),
2132 None => warn!("Message sent to closed pipeline {}.", id),
2133 },
2134 DevtoolScriptControlMsg::SetTimelineMarkers(id, marker_types, reply) => {
2135 devtools::handle_set_timeline_markers(&documents, id, marker_types, reply)
2136 },
2137 DevtoolScriptControlMsg::DropTimelineMarkers(id, marker_types) => {
2138 devtools::handle_drop_timeline_markers(&documents, id, marker_types)
2139 },
2140 DevtoolScriptControlMsg::RequestAnimationFrame(id, name) => {
2141 devtools::handle_request_animation_frame(&documents, id, name)
2142 },
2143 DevtoolScriptControlMsg::Reload(id) => devtools::handle_reload(&documents, id, can_gc),
2144 DevtoolScriptControlMsg::GetCssDatabase(reply) => {
2145 devtools::handle_get_css_database(reply)
2146 },
2147 DevtoolScriptControlMsg::SimulateColorScheme(id, theme) => {
2148 match documents.find_window(id) {
2149 Some(window) => {
2150 window.handle_theme_change(theme);
2151 },
2152 None => warn!("Message sent to closed pipeline {}.", id),
2153 }
2154 },
2155 DevtoolScriptControlMsg::HighlightDomNode(id, node_id) => {
2156 devtools::handle_highlight_dom_node(&documents, id, node_id)
2157 },
2158 DevtoolScriptControlMsg::GetPossibleBreakpoints(spidermonkey_id, result_sender) => {
2159 self.debugger_global.fire_get_possible_breakpoints(
2160 can_gc,
2161 spidermonkey_id,
2162 result_sender,
2163 );
2164 },
2165 }
2166 }
2167
2168 fn handle_msg_from_image_cache(&self, response: ImageCacheResponseMessage) {
2169 match response {
2170 ImageCacheResponseMessage::NotifyPendingImageLoadStatus(pending_image_response) => {
2171 let window = self
2172 .documents
2173 .borrow()
2174 .find_window(pending_image_response.pipeline_id);
2175 if let Some(ref window) = window {
2176 window.pending_image_notification(pending_image_response);
2177 }
2178 },
2179 ImageCacheResponseMessage::VectorImageRasterizationComplete(response) => {
2180 let window = self.documents.borrow().find_window(response.pipeline_id);
2181 if let Some(ref window) = window {
2182 window.handle_image_rasterization_complete_notification(response);
2183 }
2184 },
2185 };
2186 }
2187
2188 fn handle_webdriver_msg(
2189 &self,
2190 pipeline_id: PipelineId,
2191 msg: WebDriverScriptCommand,
2192 can_gc: CanGc,
2193 ) {
2194 let documents = self.documents.borrow();
2195 match msg {
2196 WebDriverScriptCommand::AddCookie(params, reply) => {
2197 webdriver_handlers::handle_add_cookie(&documents, pipeline_id, params, reply)
2198 },
2199 WebDriverScriptCommand::DeleteCookies(reply) => {
2200 webdriver_handlers::handle_delete_cookies(&documents, pipeline_id, reply)
2201 },
2202 WebDriverScriptCommand::DeleteCookie(name, reply) => {
2203 webdriver_handlers::handle_delete_cookie(&documents, pipeline_id, name, reply)
2204 },
2205 WebDriverScriptCommand::ElementClear(element_id, reply) => {
2206 webdriver_handlers::handle_element_clear(
2207 &documents,
2208 pipeline_id,
2209 element_id,
2210 reply,
2211 can_gc,
2212 )
2213 },
2214 WebDriverScriptCommand::FindElementsCSSSelector(selector, reply) => {
2215 webdriver_handlers::handle_find_elements_css_selector(
2216 &documents,
2217 pipeline_id,
2218 selector,
2219 reply,
2220 )
2221 },
2222 WebDriverScriptCommand::FindElementsLinkText(selector, partial, reply) => {
2223 webdriver_handlers::handle_find_elements_link_text(
2224 &documents,
2225 pipeline_id,
2226 selector,
2227 partial,
2228 reply,
2229 )
2230 },
2231 WebDriverScriptCommand::FindElementsTagName(selector, reply) => {
2232 webdriver_handlers::handle_find_elements_tag_name(
2233 &documents,
2234 pipeline_id,
2235 selector,
2236 reply,
2237 can_gc,
2238 )
2239 },
2240 WebDriverScriptCommand::FindElementsXpathSelector(selector, reply) => {
2241 webdriver_handlers::handle_find_elements_xpath_selector(
2242 &documents,
2243 pipeline_id,
2244 selector,
2245 reply,
2246 can_gc,
2247 )
2248 },
2249 WebDriverScriptCommand::FindElementElementsCSSSelector(selector, element_id, reply) => {
2250 webdriver_handlers::handle_find_element_elements_css_selector(
2251 &documents,
2252 pipeline_id,
2253 element_id,
2254 selector,
2255 reply,
2256 )
2257 },
2258 WebDriverScriptCommand::FindElementElementsLinkText(
2259 selector,
2260 element_id,
2261 partial,
2262 reply,
2263 ) => webdriver_handlers::handle_find_element_elements_link_text(
2264 &documents,
2265 pipeline_id,
2266 element_id,
2267 selector,
2268 partial,
2269 reply,
2270 ),
2271 WebDriverScriptCommand::FindElementElementsTagName(selector, element_id, reply) => {
2272 webdriver_handlers::handle_find_element_elements_tag_name(
2273 &documents,
2274 pipeline_id,
2275 element_id,
2276 selector,
2277 reply,
2278 can_gc,
2279 )
2280 },
2281 WebDriverScriptCommand::FindElementElementsXPathSelector(
2282 selector,
2283 element_id,
2284 reply,
2285 ) => webdriver_handlers::handle_find_element_elements_xpath_selector(
2286 &documents,
2287 pipeline_id,
2288 element_id,
2289 selector,
2290 reply,
2291 can_gc,
2292 ),
2293 WebDriverScriptCommand::FindShadowElementsCSSSelector(
2294 selector,
2295 shadow_root_id,
2296 reply,
2297 ) => webdriver_handlers::handle_find_shadow_elements_css_selector(
2298 &documents,
2299 pipeline_id,
2300 shadow_root_id,
2301 selector,
2302 reply,
2303 ),
2304 WebDriverScriptCommand::FindShadowElementsLinkText(
2305 selector,
2306 shadow_root_id,
2307 partial,
2308 reply,
2309 ) => webdriver_handlers::handle_find_shadow_elements_link_text(
2310 &documents,
2311 pipeline_id,
2312 shadow_root_id,
2313 selector,
2314 partial,
2315 reply,
2316 ),
2317 WebDriverScriptCommand::FindShadowElementsTagName(selector, shadow_root_id, reply) => {
2318 webdriver_handlers::handle_find_shadow_elements_tag_name(
2319 &documents,
2320 pipeline_id,
2321 shadow_root_id,
2322 selector,
2323 reply,
2324 )
2325 },
2326 WebDriverScriptCommand::FindShadowElementsXPathSelector(
2327 selector,
2328 shadow_root_id,
2329 reply,
2330 ) => webdriver_handlers::handle_find_shadow_elements_xpath_selector(
2331 &documents,
2332 pipeline_id,
2333 shadow_root_id,
2334 selector,
2335 reply,
2336 can_gc,
2337 ),
2338 WebDriverScriptCommand::GetElementShadowRoot(element_id, reply) => {
2339 webdriver_handlers::handle_get_element_shadow_root(
2340 &documents,
2341 pipeline_id,
2342 element_id,
2343 reply,
2344 )
2345 },
2346 WebDriverScriptCommand::ElementClick(element_id, reply) => {
2347 webdriver_handlers::handle_element_click(
2348 &documents,
2349 pipeline_id,
2350 element_id,
2351 reply,
2352 can_gc,
2353 )
2354 },
2355 WebDriverScriptCommand::GetKnownElement(element_id, reply) => {
2356 webdriver_handlers::handle_get_known_element(
2357 &documents,
2358 pipeline_id,
2359 element_id,
2360 reply,
2361 )
2362 },
2363 WebDriverScriptCommand::GetKnownWindow(webview_id, reply) => {
2364 webdriver_handlers::handle_get_known_window(
2365 &documents,
2366 pipeline_id,
2367 webview_id,
2368 reply,
2369 )
2370 },
2371 WebDriverScriptCommand::GetKnownShadowRoot(element_id, reply) => {
2372 webdriver_handlers::handle_get_known_shadow_root(
2373 &documents,
2374 pipeline_id,
2375 element_id,
2376 reply,
2377 )
2378 },
2379 WebDriverScriptCommand::GetActiveElement(reply) => {
2380 webdriver_handlers::handle_get_active_element(&documents, pipeline_id, reply)
2381 },
2382 WebDriverScriptCommand::GetComputedRole(node_id, reply) => {
2383 webdriver_handlers::handle_get_computed_role(
2384 &documents,
2385 pipeline_id,
2386 node_id,
2387 reply,
2388 )
2389 },
2390 WebDriverScriptCommand::GetPageSource(reply) => {
2391 webdriver_handlers::handle_get_page_source(&documents, pipeline_id, reply, can_gc)
2392 },
2393 WebDriverScriptCommand::GetCookies(reply) => {
2394 webdriver_handlers::handle_get_cookies(&documents, pipeline_id, reply)
2395 },
2396 WebDriverScriptCommand::GetCookie(name, reply) => {
2397 webdriver_handlers::handle_get_cookie(&documents, pipeline_id, name, reply)
2398 },
2399 WebDriverScriptCommand::GetElementTagName(node_id, reply) => {
2400 webdriver_handlers::handle_get_name(&documents, pipeline_id, node_id, reply)
2401 },
2402 WebDriverScriptCommand::GetElementAttribute(node_id, name, reply) => {
2403 webdriver_handlers::handle_get_attribute(
2404 &documents,
2405 pipeline_id,
2406 node_id,
2407 name,
2408 reply,
2409 )
2410 },
2411 WebDriverScriptCommand::GetElementProperty(node_id, name, reply) => {
2412 webdriver_handlers::handle_get_property(
2413 &documents,
2414 pipeline_id,
2415 node_id,
2416 name,
2417 reply,
2418 can_gc,
2419 )
2420 },
2421 WebDriverScriptCommand::GetElementCSS(node_id, name, reply) => {
2422 webdriver_handlers::handle_get_css(&documents, pipeline_id, node_id, name, reply)
2423 },
2424 WebDriverScriptCommand::GetElementRect(node_id, reply) => {
2425 webdriver_handlers::handle_get_rect(&documents, pipeline_id, node_id, reply, can_gc)
2426 },
2427 WebDriverScriptCommand::ScrollAndGetBoundingClientRect(node_id, reply) => {
2428 webdriver_handlers::handle_scroll_and_get_bounding_client_rect(
2429 &documents,
2430 pipeline_id,
2431 node_id,
2432 reply,
2433 can_gc,
2434 )
2435 },
2436 WebDriverScriptCommand::GetElementText(node_id, reply) => {
2437 webdriver_handlers::handle_get_text(&documents, pipeline_id, node_id, reply)
2438 },
2439 WebDriverScriptCommand::GetElementInViewCenterPoint(node_id, reply) => {
2440 webdriver_handlers::handle_get_element_in_view_center_point(
2441 &documents,
2442 pipeline_id,
2443 node_id,
2444 reply,
2445 can_gc,
2446 )
2447 },
2448 WebDriverScriptCommand::GetParentFrameId(reply) => {
2449 webdriver_handlers::handle_get_parent_frame_id(&documents, pipeline_id, reply)
2450 },
2451 WebDriverScriptCommand::GetBrowsingContextId(webdriver_frame_id, reply) => {
2452 webdriver_handlers::handle_get_browsing_context_id(
2453 &documents,
2454 pipeline_id,
2455 webdriver_frame_id,
2456 reply,
2457 )
2458 },
2459 WebDriverScriptCommand::GetUrl(reply) => {
2460 webdriver_handlers::handle_get_url(&documents, pipeline_id, reply, can_gc)
2461 },
2462 WebDriverScriptCommand::IsEnabled(element_id, reply) => {
2463 webdriver_handlers::handle_is_enabled(&documents, pipeline_id, element_id, reply)
2464 },
2465 WebDriverScriptCommand::IsSelected(element_id, reply) => {
2466 webdriver_handlers::handle_is_selected(&documents, pipeline_id, element_id, reply)
2467 },
2468 WebDriverScriptCommand::GetTitle(reply) => {
2469 webdriver_handlers::handle_get_title(&documents, pipeline_id, reply)
2470 },
2471 WebDriverScriptCommand::WillSendKeys(
2472 element_id,
2473 text,
2474 strict_file_interactability,
2475 reply,
2476 ) => webdriver_handlers::handle_will_send_keys(
2477 &documents,
2478 pipeline_id,
2479 element_id,
2480 text,
2481 strict_file_interactability,
2482 reply,
2483 can_gc,
2484 ),
2485 WebDriverScriptCommand::AddLoadStatusSender(_, response_sender) => {
2486 webdriver_handlers::handle_add_load_status_sender(
2487 &documents,
2488 pipeline_id,
2489 response_sender,
2490 )
2491 },
2492 WebDriverScriptCommand::RemoveLoadStatusSender(_) => {
2493 webdriver_handlers::handle_remove_load_status_sender(&documents, pipeline_id)
2494 },
2495 WebDriverScriptCommand::ExecuteScript(script, reply) => {
2502 let window = documents.find_window(pipeline_id);
2503 drop(documents);
2504 webdriver_handlers::handle_execute_script(window, script, reply, can_gc);
2505 },
2506 WebDriverScriptCommand::ExecuteAsyncScript(script, reply) => {
2507 let window = documents.find_window(pipeline_id);
2508 drop(documents);
2509 webdriver_handlers::handle_execute_async_script(window, script, reply, can_gc);
2510 },
2511 }
2512 }
2513
2514 pub(crate) fn handle_resize_message(
2517 &self,
2518 id: PipelineId,
2519 viewport_details: ViewportDetails,
2520 size_type: WindowSizeType,
2521 ) {
2522 self.profile_event(ScriptThreadEventCategory::Resize, Some(id), || {
2523 let window = self.documents.borrow().find_window(id);
2524 if let Some(ref window) = window {
2525 window.add_resize_event(viewport_details, size_type);
2526 return;
2527 }
2528 let mut loads = self.incomplete_loads.borrow_mut();
2529 if let Some(ref mut load) = loads.iter_mut().find(|load| load.pipeline_id == id) {
2530 load.viewport_details = viewport_details;
2531 }
2532 })
2533 }
2534
2535 fn handle_theme_change_msg(&self, theme: Theme) {
2537 for (_, document) in self.documents.borrow().iter() {
2538 document.window().handle_theme_change(theme);
2539 }
2540 }
2541
2542 fn handle_exit_fullscreen(&self, id: PipelineId, can_gc: CanGc) {
2544 let document = self.documents.borrow().find_document(id);
2545 if let Some(document) = document {
2546 let _ac = enter_realm(&*document);
2547 document.exit_fullscreen(can_gc);
2548 }
2549 }
2550
2551 fn handle_viewport(&self, id: PipelineId, rect: Rect<f32>) {
2552 let document = self.documents.borrow().find_document(id);
2553 if let Some(document) = document {
2554 document.window().set_viewport_size(rect.size);
2555 return;
2556 }
2557 let loads = self.incomplete_loads.borrow();
2558 if loads.iter().any(|load| load.pipeline_id == id) {
2559 return;
2560 }
2561 warn!("Page rect message sent to nonexistent pipeline");
2562 }
2563
2564 fn handle_new_layout(&self, new_layout_info: NewLayoutInfo, origin: MutableOrigin) {
2565 let NewLayoutInfo {
2566 parent_info,
2567 new_pipeline_id,
2568 browsing_context_id,
2569 webview_id,
2570 opener,
2571 load_data,
2572 viewport_details,
2573 theme,
2574 } = new_layout_info;
2575
2576 let new_load = InProgressLoad::new(
2578 new_pipeline_id,
2579 browsing_context_id,
2580 webview_id,
2581 parent_info,
2582 opener,
2583 viewport_details,
2584 theme,
2585 origin,
2586 load_data,
2587 );
2588 self.pre_page_load(new_load);
2589 }
2590
2591 fn collect_reports(&self, reports_chan: ReportsChan) {
2592 let documents = self.documents.borrow();
2593 let urls = itertools::join(documents.iter().map(|(_, d)| d.url().to_string()), ", ");
2594
2595 let mut reports = vec![];
2596 perform_memory_report(|ops| {
2597 for (_, document) in documents.iter() {
2598 document
2599 .window()
2600 .layout()
2601 .collect_reports(&mut reports, ops);
2602 }
2603
2604 let prefix = format!("url({urls})");
2605 reports.extend(self.get_cx().get_reports(prefix.clone(), ops));
2606 });
2607
2608 reports_chan.send(ProcessReports::new(reports));
2609 }
2610
2611 fn handle_set_throttled_in_containing_iframe_msg(
2613 &self,
2614 parent_pipeline_id: PipelineId,
2615 browsing_context_id: BrowsingContextId,
2616 throttled: bool,
2617 ) {
2618 let iframe = self
2619 .documents
2620 .borrow()
2621 .find_iframe(parent_pipeline_id, browsing_context_id);
2622 if let Some(iframe) = iframe {
2623 iframe.set_throttled(throttled);
2624 }
2625 }
2626
2627 fn handle_set_throttled_msg(
2628 &self,
2629 webview_id: WebViewId,
2630 pipeline_id: PipelineId,
2631 throttled: bool,
2632 ) {
2633 self.senders
2636 .pipeline_to_constellation_sender
2637 .send((
2638 webview_id,
2639 pipeline_id,
2640 ScriptToConstellationMessage::SetThrottledComplete(throttled),
2641 ))
2642 .unwrap();
2643
2644 let window = self.documents.borrow().find_window(pipeline_id);
2645 match window {
2646 Some(window) => {
2647 window.set_throttled(throttled);
2648 return;
2649 },
2650 None => {
2651 let mut loads = self.incomplete_loads.borrow_mut();
2652 if let Some(ref mut load) = loads
2653 .iter_mut()
2654 .find(|load| load.pipeline_id == pipeline_id)
2655 {
2656 load.throttled = throttled;
2657 return;
2658 }
2659 },
2660 }
2661
2662 warn!("SetThrottled sent to nonexistent pipeline");
2663 }
2664
2665 fn handle_set_document_activity_msg(
2667 &self,
2668 id: PipelineId,
2669 activity: DocumentActivity,
2670 can_gc: CanGc,
2671 ) {
2672 debug!(
2673 "Setting activity of {} to be {:?} in {:?}.",
2674 id,
2675 activity,
2676 thread::current().name()
2677 );
2678 let document = self.documents.borrow().find_document(id);
2679 if let Some(document) = document {
2680 document.set_activity(activity, can_gc);
2681 return;
2682 }
2683 let mut loads = self.incomplete_loads.borrow_mut();
2684 if let Some(ref mut load) = loads.iter_mut().find(|load| load.pipeline_id == id) {
2685 load.activity = activity;
2686 return;
2687 }
2688 warn!("change of activity sent to nonexistent pipeline");
2689 }
2690
2691 fn handle_focus_iframe_msg(
2692 &self,
2693 parent_pipeline_id: PipelineId,
2694 browsing_context_id: BrowsingContextId,
2695 sequence: FocusSequenceNumber,
2696 can_gc: CanGc,
2697 ) {
2698 let document = self
2699 .documents
2700 .borrow()
2701 .find_document(parent_pipeline_id)
2702 .unwrap();
2703
2704 let Some(iframe_element_root) = ({
2705 let iframes = document.iframes();
2708 iframes
2709 .get(browsing_context_id)
2710 .map(|iframe| DomRoot::from_ref(iframe.element.upcast()))
2711 }) else {
2712 return;
2713 };
2714
2715 if document.get_focus_sequence() > sequence {
2716 debug!(
2717 "Disregarding the FocusIFrame message because the contained sequence number is \
2718 too old ({:?} < {:?})",
2719 sequence,
2720 document.get_focus_sequence()
2721 );
2722 return;
2723 }
2724
2725 document.request_focus(Some(&iframe_element_root), FocusInitiator::Remote, can_gc);
2726 }
2727
2728 fn handle_focus_document_msg(
2729 &self,
2730 pipeline_id: PipelineId,
2731 sequence: FocusSequenceNumber,
2732 can_gc: CanGc,
2733 ) {
2734 if let Some(doc) = self.documents.borrow().find_document(pipeline_id) {
2735 if doc.get_focus_sequence() > sequence {
2736 debug!(
2737 "Disregarding the FocusDocument message because the contained sequence number is \
2738 too old ({:?} < {:?})",
2739 sequence,
2740 doc.get_focus_sequence()
2741 );
2742 return;
2743 }
2744 doc.request_focus(None, FocusInitiator::Remote, can_gc);
2745 } else {
2746 warn!(
2747 "Couldn't find document by pipleline_id:{pipeline_id:?} when handle_focus_document_msg."
2748 );
2749 }
2750 }
2751
2752 fn handle_unfocus_msg(
2753 &self,
2754 pipeline_id: PipelineId,
2755 sequence: FocusSequenceNumber,
2756 can_gc: CanGc,
2757 ) {
2758 if let Some(doc) = self.documents.borrow().find_document(pipeline_id) {
2759 if doc.get_focus_sequence() > sequence {
2760 debug!(
2761 "Disregarding the Unfocus message because the contained sequence number is \
2762 too old ({:?} < {:?})",
2763 sequence,
2764 doc.get_focus_sequence()
2765 );
2766 return;
2767 }
2768 doc.handle_container_unfocus(can_gc);
2769 } else {
2770 warn!(
2771 "Couldn't find document by pipleline_id:{pipeline_id:?} when handle_unfocus_msg."
2772 );
2773 }
2774 }
2775
2776 fn handle_post_message_msg(
2778 &self,
2779 pipeline_id: PipelineId,
2780 source_webview: WebViewId,
2781 source_with_ancestry: Vec<BrowsingContextId>,
2782 origin: Option<ImmutableOrigin>,
2783 source_origin: ImmutableOrigin,
2784 data: StructuredSerializedData,
2785 ) {
2786 let window = self.documents.borrow().find_window(pipeline_id);
2787 match window {
2788 None => warn!("postMessage after target pipeline {} closed.", pipeline_id),
2789 Some(window) => {
2790 let mut last = None;
2791 for browsing_context_id in source_with_ancestry.into_iter().rev() {
2792 if let Some(window_proxy) = self.window_proxies.get(browsing_context_id) {
2793 last = Some(window_proxy);
2794 continue;
2795 }
2796 let window_proxy = WindowProxy::new_dissimilar_origin(
2797 window.upcast::<GlobalScope>(),
2798 browsing_context_id,
2799 source_webview,
2800 last.as_deref(),
2801 None,
2802 CreatorBrowsingContextInfo::from(last.as_deref(), None),
2803 );
2804 self.window_proxies
2805 .insert(browsing_context_id, window_proxy.clone());
2806 last = Some(window_proxy);
2807 }
2808
2809 let source = last.expect("Source with ancestry should contain at least one bc.");
2812
2813 window.post_message(origin, source_origin, &source, data)
2815 },
2816 }
2817 }
2818
2819 fn handle_stop_delaying_load_events_mode(&self, pipeline_id: PipelineId) {
2820 let window = self.documents.borrow().find_window(pipeline_id);
2821 if let Some(window) = window {
2822 match window.undiscarded_window_proxy() {
2823 Some(window_proxy) => window_proxy.stop_delaying_load_events_mode(),
2824 None => warn!(
2825 "Attempted to take {} of 'delaying-load-events-mode' after having been discarded.",
2826 pipeline_id
2827 ),
2828 };
2829 }
2830 }
2831
2832 fn handle_unload_document(&self, pipeline_id: PipelineId, can_gc: CanGc) {
2833 let document = self.documents.borrow().find_document(pipeline_id);
2834 if let Some(document) = document {
2835 document.unload(false, can_gc);
2836 }
2837 }
2838
2839 fn handle_update_pipeline_id(
2840 &self,
2841 parent_pipeline_id: PipelineId,
2842 browsing_context_id: BrowsingContextId,
2843 webview_id: WebViewId,
2844 new_pipeline_id: PipelineId,
2845 reason: UpdatePipelineIdReason,
2846 can_gc: CanGc,
2847 ) {
2848 let frame_element = self
2849 .documents
2850 .borrow()
2851 .find_iframe(parent_pipeline_id, browsing_context_id);
2852 if let Some(frame_element) = frame_element {
2853 frame_element.update_pipeline_id(new_pipeline_id, reason, can_gc);
2854 }
2855
2856 if let Some(window) = self.documents.borrow().find_window(new_pipeline_id) {
2857 let _ = self.window_proxies.local_window_proxy(
2860 &self.senders,
2861 &self.documents,
2862 &window,
2863 browsing_context_id,
2864 webview_id,
2865 Some(parent_pipeline_id),
2866 None,
2870 );
2871 }
2872 }
2873
2874 fn handle_update_history_state_msg(
2875 &self,
2876 pipeline_id: PipelineId,
2877 history_state_id: Option<HistoryStateId>,
2878 url: ServoUrl,
2879 can_gc: CanGc,
2880 ) {
2881 let window = self.documents.borrow().find_window(pipeline_id);
2882 match window {
2883 None => {
2884 warn!(
2885 "update history state after pipeline {} closed.",
2886 pipeline_id
2887 );
2888 },
2889 Some(window) => window
2890 .History()
2891 .activate_state(history_state_id, url, can_gc),
2892 }
2893 }
2894
2895 fn handle_remove_history_states(
2896 &self,
2897 pipeline_id: PipelineId,
2898 history_states: Vec<HistoryStateId>,
2899 ) {
2900 let window = self.documents.borrow().find_window(pipeline_id);
2901 match window {
2902 None => {
2903 warn!(
2904 "update history state after pipeline {} closed.",
2905 pipeline_id
2906 );
2907 },
2908 Some(window) => window.History().remove_states(history_states),
2909 }
2910 }
2911
2912 fn handle_resize_inactive_msg(&self, id: PipelineId, new_viewport_details: ViewportDetails) {
2914 let window = self.documents.borrow().find_window(id)
2915 .expect("ScriptThread: received a resize msg for a pipeline not in this script thread. This is a bug.");
2916 window.set_viewport_details(new_viewport_details);
2917 }
2918
2919 fn handle_page_headers_available(
2922 &self,
2923 webview_id: WebViewId,
2924 pipeline_id: PipelineId,
2925 metadata: Option<Metadata>,
2926 can_gc: CanGc,
2927 ) -> Option<DomRoot<ServoParser>> {
2928 if self.closed_pipelines.borrow().contains(&pipeline_id) {
2929 return None;
2931 }
2932
2933 let Some(idx) = self
2934 .incomplete_loads
2935 .borrow()
2936 .iter()
2937 .position(|load| load.pipeline_id == pipeline_id)
2938 else {
2939 unreachable!("Pipeline shouldn't have finished loading.");
2940 };
2941
2942 let is_204_205 = match metadata {
2945 Some(ref metadata) => metadata.status.in_range(204..=205),
2946 _ => false,
2947 };
2948
2949 if is_204_205 {
2950 if let Some(window) = self.documents.borrow().find_window(pipeline_id) {
2952 let window_proxy = window.window_proxy();
2953 if window_proxy.parent().is_some() {
2956 window_proxy.stop_delaying_load_events_mode();
2962 }
2963 }
2964 self.senders
2965 .pipeline_to_constellation_sender
2966 .send((
2967 webview_id,
2968 pipeline_id,
2969 ScriptToConstellationMessage::AbortLoadUrl,
2970 ))
2971 .unwrap();
2972 return None;
2973 };
2974
2975 let load = self.incomplete_loads.borrow_mut().remove(idx);
2976 metadata.map(|meta| self.load(meta, load, can_gc))
2977 }
2978
2979 fn handle_get_title_msg(&self, pipeline_id: PipelineId) {
2981 let document = match self.documents.borrow().find_document(pipeline_id) {
2982 Some(document) => document,
2983 None => return warn!("Message sent to closed pipeline {}.", pipeline_id),
2984 };
2985 document.send_title_to_embedder();
2986 }
2987
2988 fn handle_exit_pipeline_msg(
2990 &self,
2991 webview_id: WebViewId,
2992 pipeline_id: PipelineId,
2993 discard_bc: DiscardBrowsingContext,
2994 can_gc: CanGc,
2995 ) {
2996 debug!("{pipeline_id}: Starting pipeline exit.");
2997
2998 let document = self.documents.borrow_mut().remove(pipeline_id);
3001 if let Some(document) = document {
3002 debug_assert!(
3004 !self
3005 .incomplete_loads
3006 .borrow()
3007 .iter()
3008 .any(|load| load.pipeline_id == pipeline_id)
3009 );
3010
3011 if let Some(parser) = document.get_current_parser() {
3012 parser.abort(can_gc);
3013 }
3014
3015 debug!("{pipeline_id}: Shutting down layout");
3016 document.window().layout_mut().exit_now();
3017
3018 debug!("{pipeline_id}: Clearing animations");
3020 document.animations().clear();
3021
3022 let window = document.window();
3025 if discard_bc == DiscardBrowsingContext::Yes {
3026 window.discard_browsing_context();
3027 }
3028
3029 debug!("{pipeline_id}: Clearing JavaScript runtime");
3030 window.clear_js_runtime();
3031 }
3032
3033 self.closed_pipelines.borrow_mut().insert(pipeline_id);
3035
3036 debug!("{pipeline_id}: Sending PipelineExited message to constellation");
3037 self.senders
3038 .pipeline_to_constellation_sender
3039 .send((
3040 webview_id,
3041 pipeline_id,
3042 ScriptToConstellationMessage::PipelineExited,
3043 ))
3044 .ok();
3045
3046 self.compositor_api
3047 .pipeline_exited(webview_id, pipeline_id, PipelineExitSource::Script);
3048
3049 debug!("{pipeline_id}: Finished pipeline exit");
3050 }
3051
3052 fn handle_exit_script_thread_msg(&self, can_gc: CanGc) {
3054 debug!("Exiting script thread.");
3055
3056 let mut webview_and_pipeline_ids = Vec::new();
3057 webview_and_pipeline_ids.extend(
3058 self.incomplete_loads
3059 .borrow()
3060 .iter()
3061 .next()
3062 .map(|load| (load.webview_id, load.pipeline_id)),
3063 );
3064 webview_and_pipeline_ids.extend(
3065 self.documents
3066 .borrow()
3067 .iter()
3068 .next()
3069 .map(|(pipeline_id, document)| (document.webview_id(), pipeline_id)),
3070 );
3071
3072 for (webview_id, pipeline_id) in webview_and_pipeline_ids {
3073 self.handle_exit_pipeline_msg(
3074 webview_id,
3075 pipeline_id,
3076 DiscardBrowsingContext::Yes,
3077 can_gc,
3078 );
3079 }
3080
3081 self.background_hang_monitor.unregister();
3082
3083 if opts::get().multiprocess {
3085 debug!("Exiting IPC router thread in script thread.");
3086 ROUTER.shutdown();
3087 }
3088
3089 debug!("Exited script thread.");
3090 }
3091
3092 pub(crate) fn handle_tick_all_animations_for_testing(id: PipelineId) {
3094 with_script_thread(|script_thread| {
3095 let Some(document) = script_thread.documents.borrow().find_document(id) else {
3096 warn!("Animation tick for tests for closed pipeline {id}.");
3097 return;
3098 };
3099 document.maybe_mark_animating_nodes_as_dirty();
3100 });
3101 }
3102
3103 fn handle_web_font_loaded(&self, pipeline_id: PipelineId, _success: bool) {
3105 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
3106 warn!("Web font loaded in closed pipeline {}.", pipeline_id);
3107 return;
3108 };
3109
3110 document.dirty_all_nodes();
3112 }
3113
3114 fn handle_worklet_loaded(&self, pipeline_id: PipelineId) {
3117 if let Some(document) = self.documents.borrow().find_document(pipeline_id) {
3118 document.add_restyle_reason(RestyleReason::PaintWorkletLoaded);
3119 }
3120 }
3121
3122 fn handle_storage_event(
3124 &self,
3125 pipeline_id: PipelineId,
3126 storage_type: StorageType,
3127 url: ServoUrl,
3128 key: Option<String>,
3129 old_value: Option<String>,
3130 new_value: Option<String>,
3131 ) {
3132 let window = match self.documents.borrow().find_window(pipeline_id) {
3133 None => return warn!("Storage event sent to closed pipeline {}.", pipeline_id),
3134 Some(window) => window,
3135 };
3136
3137 let storage = match storage_type {
3138 StorageType::Local => window.LocalStorage(),
3139 StorageType::Session => window.SessionStorage(),
3140 };
3141
3142 storage.queue_storage_event(url, key, old_value, new_value);
3143 }
3144
3145 fn handle_iframe_load_event(
3147 &self,
3148 parent_id: PipelineId,
3149 browsing_context_id: BrowsingContextId,
3150 child_id: PipelineId,
3151 can_gc: CanGc,
3152 ) {
3153 let iframe = self
3154 .documents
3155 .borrow()
3156 .find_iframe(parent_id, browsing_context_id);
3157 match iframe {
3158 Some(iframe) => iframe.iframe_load_event_steps(child_id, can_gc),
3159 None => warn!("Message sent to closed pipeline {}.", parent_id),
3160 }
3161 }
3162
3163 fn ask_constellation_for_top_level_info(
3164 &self,
3165 sender_webview_id: WebViewId,
3166 sender_pipeline_id: PipelineId,
3167 browsing_context_id: BrowsingContextId,
3168 ) -> Option<WebViewId> {
3169 let (result_sender, result_receiver) = ipc::channel().unwrap();
3170 let msg = ScriptToConstellationMessage::GetTopForBrowsingContext(
3171 browsing_context_id,
3172 result_sender,
3173 );
3174 self.senders
3175 .pipeline_to_constellation_sender
3176 .send((sender_webview_id, sender_pipeline_id, msg))
3177 .expect("Failed to send to constellation.");
3178 result_receiver
3179 .recv()
3180 .expect("Failed to get top-level id from constellation.")
3181 }
3182
3183 fn load(
3186 &self,
3187 metadata: Metadata,
3188 incomplete: InProgressLoad,
3189 can_gc: CanGc,
3190 ) -> DomRoot<ServoParser> {
3191 let script_to_constellation_chan = ScriptToConstellationChan {
3192 sender: self.senders.pipeline_to_constellation_sender.clone(),
3193 webview_id: incomplete.webview_id,
3194 pipeline_id: incomplete.pipeline_id,
3195 };
3196
3197 let final_url = metadata.final_url.clone();
3198 let _ = script_to_constellation_chan
3199 .send(ScriptToConstellationMessage::SetFinalUrl(final_url.clone()));
3200
3201 debug!(
3202 "ScriptThread: loading {} on pipeline {:?}",
3203 incomplete.load_data.url, incomplete.pipeline_id
3204 );
3205
3206 let origin = if final_url.as_str() == "about:blank" || final_url.as_str() == "about:srcdoc"
3207 {
3208 incomplete.origin.clone()
3209 } else {
3210 MutableOrigin::new(final_url.origin())
3211 };
3212
3213 let font_context = Arc::new(FontContext::new(
3214 self.system_font_service.clone(),
3215 self.compositor_api.clone(),
3216 self.resource_threads.clone(),
3217 ));
3218
3219 let image_cache = self
3220 .image_cache
3221 .create_new_image_cache(Some(incomplete.pipeline_id), self.compositor_api.clone());
3222
3223 let layout_config = LayoutConfig {
3224 id: incomplete.pipeline_id,
3225 webview_id: incomplete.webview_id,
3226 url: final_url.clone(),
3227 is_iframe: incomplete.parent_info.is_some(),
3228 script_chan: self.senders.constellation_sender.clone(),
3229 image_cache: image_cache.clone(),
3230 font_context: font_context.clone(),
3231 time_profiler_chan: self.senders.time_profiler_sender.clone(),
3232 compositor_api: self.compositor_api.clone(),
3233 viewport_details: incomplete.viewport_details,
3234 theme: incomplete.theme,
3235 };
3236
3237 let window = Window::new(
3239 incomplete.webview_id,
3240 self.js_runtime.clone(),
3241 self.senders.self_sender.clone(),
3242 self.layout_factory.create(layout_config),
3243 font_context,
3244 self.senders.image_cache_sender.clone(),
3245 image_cache.clone(),
3246 self.resource_threads.clone(),
3247 self.storage_threads.clone(),
3248 #[cfg(feature = "bluetooth")]
3249 self.senders.bluetooth_sender.clone(),
3250 self.senders.memory_profiler_sender.clone(),
3251 self.senders.time_profiler_sender.clone(),
3252 self.senders.devtools_server_sender.clone(),
3253 script_to_constellation_chan,
3254 self.senders.pipeline_to_embedder_sender.clone(),
3255 self.senders.constellation_sender.clone(),
3256 incomplete.pipeline_id,
3257 incomplete.parent_info,
3258 incomplete.viewport_details,
3259 origin.clone(),
3260 final_url.clone(),
3261 final_url.clone(),
3266 incomplete.navigation_start,
3267 self.webgl_chan.as_ref().map(|chan| chan.channel()),
3268 #[cfg(feature = "webxr")]
3269 self.webxr_registry.clone(),
3270 self.microtask_queue.clone(),
3271 self.compositor_api.clone(),
3272 self.unminify_js,
3273 self.unminify_css,
3274 self.local_script_source.clone(),
3275 self.user_content_manager.clone(),
3276 self.player_context.clone(),
3277 #[cfg(feature = "webgpu")]
3278 self.gpu_id_hub.clone(),
3279 incomplete.load_data.inherited_secure_context,
3280 incomplete.theme,
3281 );
3282 self.debugger_global.fire_add_debuggee(
3283 can_gc,
3284 window.upcast(),
3285 incomplete.pipeline_id,
3286 None,
3287 );
3288
3289 let _realm = enter_realm(&*window);
3290
3291 let window_proxy = self.window_proxies.local_window_proxy(
3293 &self.senders,
3294 &self.documents,
3295 &window,
3296 incomplete.browsing_context_id,
3297 incomplete.webview_id,
3298 incomplete.parent_info,
3299 incomplete.opener,
3300 );
3301 if window_proxy.parent().is_some() {
3302 window_proxy.stop_delaying_load_events_mode();
3307 }
3308 window.init_window_proxy(&window_proxy);
3309
3310 let last_modified = metadata.headers.as_ref().and_then(|headers| {
3311 headers.typed_get::<LastModified>().map(|tm| {
3312 let tm: SystemTime = tm.into();
3313 let local_time: DateTime<Local> = tm.into();
3314 local_time.format("%m/%d/%Y %H:%M:%S").to_string()
3315 })
3316 });
3317
3318 let loader = DocumentLoader::new_with_threads(
3319 self.resource_threads.clone(),
3320 Some(final_url.clone()),
3321 );
3322
3323 let content_type: Option<Mime> = metadata
3324 .content_type
3325 .map(Serde::into_inner)
3326 .map(Mime::from_ct);
3327
3328 let is_html_document = match content_type {
3329 Some(ref mime) if mime.type_ == APPLICATION && mime.has_suffix("xml") => {
3330 IsHTMLDocument::NonHTMLDocument
3331 },
3332
3333 Some(ref mime) if mime.matches(TEXT, XML) || mime.matches(APPLICATION, XML) => {
3334 IsHTMLDocument::NonHTMLDocument
3335 },
3336 _ => IsHTMLDocument::HTMLDocument,
3337 };
3338
3339 let referrer = metadata
3340 .referrer
3341 .as_ref()
3342 .map(|referrer| referrer.clone().into_string());
3343
3344 let is_initial_about_blank = final_url.as_str() == "about:blank";
3345
3346 let document = Document::new(
3347 &window,
3348 HasBrowsingContext::Yes,
3349 Some(final_url.clone()),
3350 origin,
3351 is_html_document,
3352 content_type,
3353 last_modified,
3354 incomplete.activity,
3355 DocumentSource::FromParser,
3356 loader,
3357 referrer,
3358 Some(metadata.status.raw_code()),
3359 incomplete.canceller,
3360 is_initial_about_blank,
3361 true,
3362 incomplete.load_data.inherited_insecure_requests_policy,
3363 incomplete.load_data.has_trustworthy_ancestor_origin,
3364 self.custom_element_reaction_stack.clone(),
3365 incomplete.load_data.creation_sandboxing_flag_set,
3366 can_gc,
3367 );
3368
3369 let referrer_policy = metadata
3370 .headers
3371 .as_deref()
3372 .and_then(|h| h.typed_get::<ReferrerPolicyHeader>())
3373 .into();
3374 document.set_referrer_policy(referrer_policy);
3375
3376 let refresh_header = metadata.headers.as_deref().and_then(|h| h.get(REFRESH));
3377 if let Some(refresh_val) = refresh_header {
3378 document.shared_declarative_refresh_steps(refresh_val.as_bytes());
3380 }
3381
3382 document.set_ready_state(DocumentReadyState::Loading, can_gc);
3383
3384 self.documents
3385 .borrow_mut()
3386 .insert(incomplete.pipeline_id, &document);
3387
3388 window.init_document(&document);
3389
3390 if let Some(frame) = window_proxy
3393 .frame_element()
3394 .and_then(|e| e.downcast::<HTMLIFrameElement>())
3395 {
3396 let parent_pipeline = frame.global().pipeline_id();
3397 self.handle_update_pipeline_id(
3398 parent_pipeline,
3399 window_proxy.browsing_context_id(),
3400 window_proxy.webview_id(),
3401 incomplete.pipeline_id,
3402 UpdatePipelineIdReason::Navigation,
3403 can_gc,
3404 );
3405 }
3406
3407 self.senders
3408 .pipeline_to_constellation_sender
3409 .send((
3410 incomplete.webview_id,
3411 incomplete.pipeline_id,
3412 ScriptToConstellationMessage::ActivateDocument,
3413 ))
3414 .unwrap();
3415
3416 let incomplete_browsing_context_id: BrowsingContextId = incomplete.webview_id.into();
3418 let is_top_level_global = incomplete_browsing_context_id == incomplete.browsing_context_id;
3419 self.notify_devtools(
3420 document.Title(),
3421 final_url.clone(),
3422 is_top_level_global,
3423 (
3424 incomplete.browsing_context_id,
3425 incomplete.pipeline_id,
3426 None,
3427 incomplete.webview_id,
3428 ),
3429 );
3430
3431 document.set_https_state(metadata.https_state);
3432 document.set_navigation_start(incomplete.navigation_start);
3433
3434 if is_html_document == IsHTMLDocument::NonHTMLDocument {
3435 ServoParser::parse_xml_document(&document, None, final_url, can_gc);
3436 } else {
3437 ServoParser::parse_html_document(&document, None, final_url, can_gc);
3438 }
3439
3440 if incomplete.activity == DocumentActivity::FullyActive {
3441 window.resume(can_gc);
3442 } else {
3443 window.suspend(can_gc);
3444 }
3445
3446 if incomplete.throttled {
3447 window.set_throttled(true);
3448 }
3449
3450 document.get_current_parser().unwrap()
3451 }
3452
3453 fn notify_devtools(
3454 &self,
3455 title: DOMString,
3456 url: ServoUrl,
3457 is_top_level_global: bool,
3458 (browsing_context_id, pipeline_id, worker_id, webview_id): (
3459 BrowsingContextId,
3460 PipelineId,
3461 Option<WorkerId>,
3462 WebViewId,
3463 ),
3464 ) {
3465 if let Some(ref chan) = self.senders.devtools_server_sender {
3466 let page_info = DevtoolsPageInfo {
3467 title: String::from(title),
3468 url,
3469 is_top_level_global,
3470 };
3471 chan.send(ScriptToDevtoolsControlMsg::NewGlobal(
3472 (browsing_context_id, pipeline_id, worker_id, webview_id),
3473 self.senders.devtools_client_to_script_thread_sender.clone(),
3474 page_info.clone(),
3475 ))
3476 .unwrap();
3477
3478 let state = NavigationState::Stop(pipeline_id, page_info);
3479 let _ = chan.send(ScriptToDevtoolsControlMsg::Navigate(
3480 browsing_context_id,
3481 state,
3482 ));
3483 }
3484 }
3485
3486 fn handle_input_event(
3489 &self,
3490 webview_id: WebViewId,
3491 pipeline_id: PipelineId,
3492 event: ConstellationInputEvent,
3493 ) {
3494 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
3495 warn!("Compositor event sent to closed pipeline {pipeline_id}.");
3496 let _ = self
3497 .senders
3498 .pipeline_to_embedder_sender
3499 .send(EmbedderMsg::InputEventHandled(
3500 webview_id,
3501 event.event.id,
3502 Default::default(),
3503 ));
3504 return;
3505 };
3506 document.event_handler().note_pending_input_event(event);
3507 }
3508
3509 fn handle_navigate_iframe(
3511 &self,
3512 parent_pipeline_id: PipelineId,
3513 browsing_context_id: BrowsingContextId,
3514 load_data: LoadData,
3515 history_handling: NavigationHistoryBehavior,
3516 can_gc: CanGc,
3517 ) {
3518 let iframe = self
3519 .documents
3520 .borrow()
3521 .find_iframe(parent_pipeline_id, browsing_context_id);
3522 if let Some(iframe) = iframe {
3523 iframe.navigate_or_reload_child_browsing_context(load_data, history_handling, can_gc);
3524 }
3525 }
3526
3527 pub(crate) fn eval_js_url(global_scope: &GlobalScope, load_data: &mut LoadData, can_gc: CanGc) {
3530 let encoded = &load_data.url[Position::AfterScheme..][1..];
3535
3536 let script_source = percent_decode(encoded.as_bytes()).decode_utf8_lossy();
3538
3539 let _ac = enter_realm(global_scope);
3541 rooted!(in(*GlobalScope::get_cx()) let mut jsval = UndefinedValue());
3542 _ = global_scope.evaluate_js_on_global_with_result(
3543 &script_source,
3544 jsval.handle_mut(),
3545 ScriptFetchOptions::default_classic_script(global_scope),
3546 global_scope.api_base_url(),
3547 can_gc,
3548 Some(IntroductionType::JAVASCRIPT_URL),
3549 );
3550
3551 load_data.js_eval_result = if jsval.get().is_string() {
3552 let strval = DOMString::safe_from_jsval(
3553 GlobalScope::get_cx(),
3554 jsval.handle(),
3555 StringificationBehavior::Empty,
3556 );
3557 match strval {
3558 Ok(ConversionResult::Success(s)) => {
3559 Some(JsEvalResult::Ok(String::from(s).as_bytes().to_vec()))
3560 },
3561 _ => None,
3562 }
3563 } else {
3564 Some(JsEvalResult::NoContent)
3565 };
3566
3567 load_data.url = ServoUrl::parse("about:blank").unwrap();
3568 }
3569
3570 fn pre_page_load(&self, mut incomplete: InProgressLoad) {
3573 let url_str = incomplete.load_data.url.as_str();
3574 if url_str == "about:blank" {
3575 self.start_page_load_about_blank(incomplete);
3576 return;
3577 }
3578 if url_str == "about:srcdoc" {
3579 self.page_load_about_srcdoc(incomplete);
3580 return;
3581 }
3582
3583 let context = ParserContext::new(
3584 incomplete.webview_id,
3585 incomplete.pipeline_id,
3586 incomplete.load_data.url.clone(),
3587 incomplete.load_data.creation_sandboxing_flag_set,
3588 );
3589 self.incomplete_parser_contexts
3590 .0
3591 .borrow_mut()
3592 .push((incomplete.pipeline_id, context));
3593
3594 let request_builder = incomplete.request_builder();
3595 incomplete.canceller = FetchCanceller::new(
3596 request_builder.id,
3597 self.resource_threads.core_thread.clone(),
3598 );
3599 NavigationListener::new(request_builder, self.senders.self_sender.clone())
3600 .initiate_fetch(&self.resource_threads.core_thread, None);
3601 self.incomplete_loads.borrow_mut().push(incomplete);
3602 }
3603
3604 fn handle_navigation_response(&self, pipeline_id: PipelineId, message: FetchResponseMsg) {
3605 if let Some(metadata) = NavigationListener::http_redirect_metadata(&message) {
3606 self.handle_navigation_redirect(pipeline_id, metadata);
3607 return;
3608 };
3609
3610 match message {
3611 FetchResponseMsg::ProcessResponse(request_id, metadata) => {
3612 self.handle_fetch_metadata(pipeline_id, request_id, metadata)
3613 },
3614 FetchResponseMsg::ProcessResponseChunk(request_id, chunk) => {
3615 self.handle_fetch_chunk(pipeline_id, request_id, chunk)
3616 },
3617 FetchResponseMsg::ProcessResponseEOF(request_id, eof) => {
3618 self.handle_fetch_eof(pipeline_id, request_id, eof)
3619 },
3620 FetchResponseMsg::ProcessCspViolations(request_id, violations) => {
3621 self.handle_csp_violations(pipeline_id, request_id, violations)
3622 },
3623 FetchResponseMsg::ProcessRequestBody(..) | FetchResponseMsg::ProcessRequestEOF(..) => {
3624 },
3625 }
3626 }
3627
3628 fn handle_fetch_metadata(
3629 &self,
3630 id: PipelineId,
3631 request_id: RequestId,
3632 fetch_metadata: Result<FetchMetadata, NetworkError>,
3633 ) {
3634 match fetch_metadata {
3635 Ok(_) => (),
3636 Err(NetworkError::Crash(..)) => (),
3637 Err(ref e) => {
3638 warn!("Network error: {:?}", e);
3639 },
3640 };
3641
3642 let mut incomplete_parser_contexts = self.incomplete_parser_contexts.0.borrow_mut();
3643 let parser = incomplete_parser_contexts
3644 .iter_mut()
3645 .find(|&&mut (pipeline_id, _)| pipeline_id == id);
3646 if let Some(&mut (_, ref mut ctxt)) = parser {
3647 ctxt.process_response(request_id, fetch_metadata);
3648 }
3649 }
3650
3651 fn handle_fetch_chunk(&self, pipeline_id: PipelineId, request_id: RequestId, chunk: Vec<u8>) {
3652 let mut incomplete_parser_contexts = self.incomplete_parser_contexts.0.borrow_mut();
3653 let parser = incomplete_parser_contexts
3654 .iter_mut()
3655 .find(|&&mut (parser_pipeline_id, _)| parser_pipeline_id == pipeline_id);
3656 if let Some(&mut (_, ref mut ctxt)) = parser {
3657 ctxt.process_response_chunk(request_id, chunk);
3658 }
3659 }
3660
3661 fn handle_fetch_eof(
3662 &self,
3663 id: PipelineId,
3664 request_id: RequestId,
3665 eof: Result<ResourceFetchTiming, NetworkError>,
3666 ) {
3667 let idx = self
3668 .incomplete_parser_contexts
3669 .0
3670 .borrow()
3671 .iter()
3672 .position(|&(pipeline_id, _)| pipeline_id == id);
3673
3674 if let Some(idx) = idx {
3675 let (_, mut ctxt) = self.incomplete_parser_contexts.0.borrow_mut().remove(idx);
3676 ctxt.process_response_eof(request_id, eof);
3677 }
3678 }
3679
3680 fn handle_csp_violations(&self, id: PipelineId, _: RequestId, violations: Vec<Violation>) {
3681 if let Some(global) = self.documents.borrow().find_global(id) {
3682 global.report_csp_violations(violations, None, None);
3684 }
3685 }
3686
3687 fn handle_navigation_redirect(&self, id: PipelineId, metadata: &Metadata) {
3688 assert!(metadata.location_url.is_some());
3692
3693 let mut incomplete_loads = self.incomplete_loads.borrow_mut();
3694 let Some(incomplete_load) = incomplete_loads
3695 .iter_mut()
3696 .find(|incomplete_load| incomplete_load.pipeline_id == id)
3697 else {
3698 return;
3699 };
3700
3701 incomplete_load.url_list.push(metadata.final_url.clone());
3704
3705 let mut request_builder = incomplete_load.request_builder();
3706 request_builder.referrer = metadata
3707 .referrer
3708 .clone()
3709 .map(Referrer::ReferrerUrl)
3710 .unwrap_or(Referrer::NoReferrer);
3711 request_builder.referrer_policy = metadata.referrer_policy;
3712
3713 let headers = metadata
3714 .headers
3715 .as_ref()
3716 .map(|headers| headers.clone().into_inner())
3717 .unwrap_or_default();
3718
3719 let response_init = Some(ResponseInit {
3720 url: metadata.final_url.clone(),
3721 location_url: metadata.location_url.clone(),
3722 headers,
3723 referrer: metadata.referrer.clone(),
3724 status_code: metadata
3725 .status
3726 .try_code()
3727 .map(|code| code.as_u16())
3728 .unwrap_or(200),
3729 });
3730
3731 incomplete_load.canceller = FetchCanceller::new(
3732 request_builder.id,
3733 self.resource_threads.core_thread.clone(),
3734 );
3735 NavigationListener::new(request_builder, self.senders.self_sender.clone())
3736 .initiate_fetch(&self.resource_threads.core_thread, response_init);
3737 }
3738
3739 fn start_page_load_about_blank(&self, mut incomplete: InProgressLoad) {
3742 let url = ServoUrl::parse("about:blank").unwrap();
3743 let mut context = ParserContext::new(
3744 incomplete.webview_id,
3745 incomplete.pipeline_id,
3746 url.clone(),
3747 incomplete.load_data.creation_sandboxing_flag_set,
3748 );
3749
3750 let mut meta = Metadata::default(url);
3751 meta.set_content_type(Some(&mime::TEXT_HTML));
3752 meta.set_referrer_policy(incomplete.load_data.referrer_policy);
3753
3754 let chunk = match incomplete.load_data.js_eval_result {
3757 Some(JsEvalResult::Ok(ref mut content)) => std::mem::take(content),
3758 Some(JsEvalResult::NoContent) => {
3759 meta.status = http::StatusCode::NO_CONTENT.into();
3760 vec![]
3761 },
3762 None => vec![],
3763 };
3764
3765 let policy_container = incomplete.load_data.policy_container.clone();
3766 self.incomplete_loads.borrow_mut().push(incomplete);
3767
3768 let dummy_request_id = RequestId::default();
3769 context.process_response(dummy_request_id, Ok(FetchMetadata::Unfiltered(meta)));
3770 context.set_policy_container(policy_container.as_ref());
3771 context.process_response_chunk(dummy_request_id, chunk);
3772 context.process_response_eof(
3773 dummy_request_id,
3774 Ok(ResourceFetchTiming::new(ResourceTimingType::None)),
3775 );
3776 }
3777
3778 fn page_load_about_srcdoc(&self, mut incomplete: InProgressLoad) {
3780 let url = ServoUrl::parse("about:srcdoc").unwrap();
3781 let mut meta = Metadata::default(url.clone());
3782 meta.set_content_type(Some(&mime::TEXT_HTML));
3783 meta.set_referrer_policy(incomplete.load_data.referrer_policy);
3784
3785 let srcdoc = std::mem::take(&mut incomplete.load_data.srcdoc);
3786 let chunk = srcdoc.into_bytes();
3787
3788 let policy_container = incomplete.load_data.policy_container.clone();
3789 let creation_sandboxing_flag_set = incomplete.load_data.creation_sandboxing_flag_set;
3790
3791 let webview_id = incomplete.webview_id;
3792 let pipeline_id = incomplete.pipeline_id;
3793 self.incomplete_loads.borrow_mut().push(incomplete);
3794
3795 let mut context =
3796 ParserContext::new(webview_id, pipeline_id, url, creation_sandboxing_flag_set);
3797 let dummy_request_id = RequestId::default();
3798
3799 context.process_response(dummy_request_id, Ok(FetchMetadata::Unfiltered(meta)));
3800 context.set_policy_container(policy_container.as_ref());
3801 context.process_response_chunk(dummy_request_id, chunk);
3802 context.process_response_eof(
3803 dummy_request_id,
3804 Ok(ResourceFetchTiming::new(ResourceTimingType::None)),
3805 );
3806 }
3807
3808 fn handle_css_error_reporting(
3809 &self,
3810 pipeline_id: PipelineId,
3811 filename: String,
3812 line: u32,
3813 column: u32,
3814 msg: String,
3815 ) {
3816 let sender = match self.senders.devtools_server_sender {
3817 Some(ref sender) => sender,
3818 None => return,
3819 };
3820
3821 if let Some(global) = self.documents.borrow().find_global(pipeline_id) {
3822 if global.live_devtools_updates() {
3823 let css_error = CSSError {
3824 filename,
3825 line,
3826 column,
3827 msg,
3828 };
3829 let message = ScriptToDevtoolsControlMsg::ReportCSSError(pipeline_id, css_error);
3830 sender.send(message).unwrap();
3831 }
3832 }
3833 }
3834
3835 fn handle_reload(&self, pipeline_id: PipelineId, can_gc: CanGc) {
3836 let window = self.documents.borrow().find_window(pipeline_id);
3837 if let Some(window) = window {
3838 window.Location().reload_without_origin_check(can_gc);
3839 }
3840 }
3841
3842 fn handle_paint_metric(
3843 &self,
3844 pipeline_id: PipelineId,
3845 metric_type: ProgressiveWebMetricType,
3846 metric_value: CrossProcessInstant,
3847 first_reflow: bool,
3848 can_gc: CanGc,
3849 ) {
3850 match self.documents.borrow().find_document(pipeline_id) {
3851 Some(document) => {
3852 document.handle_paint_metric(metric_type, metric_value, first_reflow, can_gc)
3853 },
3854 None => warn!(
3855 "Received paint metric ({metric_type:?}) for unknown document: {pipeline_id:?}"
3856 ),
3857 }
3858 }
3859
3860 fn handle_media_session_action(
3861 &self,
3862 pipeline_id: PipelineId,
3863 action: MediaSessionActionType,
3864 can_gc: CanGc,
3865 ) {
3866 if let Some(window) = self.documents.borrow().find_window(pipeline_id) {
3867 let media_session = window.Navigator().MediaSession();
3868 media_session.handle_action(action, can_gc);
3869 } else {
3870 warn!("No MediaSession for this pipeline ID");
3871 };
3872 }
3873
3874 pub(crate) fn enqueue_microtask(job: Microtask) {
3875 with_script_thread(|script_thread| {
3876 script_thread
3877 .microtask_queue
3878 .enqueue(job, script_thread.get_cx());
3879 });
3880 }
3881
3882 fn perform_a_microtask_checkpoint(&self, can_gc: CanGc) {
3883 if self.can_continue_running_inner() {
3885 let globals = self
3886 .documents
3887 .borrow()
3888 .iter()
3889 .map(|(_id, document)| DomRoot::from_ref(document.window().upcast()))
3890 .collect();
3891
3892 self.microtask_queue.checkpoint(
3893 self.get_cx(),
3894 |id| self.documents.borrow().find_global(id),
3895 globals,
3896 can_gc,
3897 )
3898 }
3899 }
3900
3901 fn handle_evaluate_javascript(
3902 &self,
3903 webview_id: WebViewId,
3904 pipeline_id: PipelineId,
3905 evaluation_id: JavaScriptEvaluationId,
3906 script: String,
3907 can_gc: CanGc,
3908 ) {
3909 let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
3910 let _ = self.senders.pipeline_to_constellation_sender.send((
3911 webview_id,
3912 pipeline_id,
3913 ScriptToConstellationMessage::FinishJavaScriptEvaluation(
3914 evaluation_id,
3915 Err(JavaScriptEvaluationError::WebViewNotReady),
3916 ),
3917 ));
3918 return;
3919 };
3920
3921 let global_scope = window.as_global_scope();
3922 let realm = enter_realm(global_scope);
3923 let context = window.get_cx();
3924
3925 rooted!(in(*context) let mut return_value = UndefinedValue());
3926 if let Err(err) = global_scope.evaluate_js_on_global_with_result(
3927 &script,
3928 return_value.handle_mut(),
3929 ScriptFetchOptions::default_classic_script(global_scope),
3930 global_scope.api_base_url(),
3931 can_gc,
3932 None, ) {
3934 _ = self.senders.pipeline_to_constellation_sender.send((
3935 webview_id,
3936 pipeline_id,
3937 ScriptToConstellationMessage::FinishJavaScriptEvaluation(evaluation_id, Err(err)),
3938 ));
3939 return;
3940 };
3941
3942 let result = jsval_to_webdriver(
3943 context,
3944 global_scope,
3945 return_value.handle(),
3946 (&realm).into(),
3947 can_gc,
3948 );
3949 let _ = self.senders.pipeline_to_constellation_sender.send((
3950 webview_id,
3951 pipeline_id,
3952 ScriptToConstellationMessage::FinishJavaScriptEvaluation(evaluation_id, result),
3953 ));
3954 }
3955
3956 fn handle_refresh_cursor(&self, pipeline_id: PipelineId) {
3957 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
3958 return;
3959 };
3960 document.event_handler().handle_refresh_cursor();
3961 }
3962
3963 pub(crate) fn is_servo_privileged(url: ServoUrl) -> bool {
3964 with_script_thread(|script_thread| script_thread.privileged_urls.contains(&url))
3965 }
3966
3967 fn handle_request_screenshot_readiness(
3968 &self,
3969 webview_id: WebViewId,
3970 pipeline_id: PipelineId,
3971 can_gc: CanGc,
3972 ) {
3973 let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
3974 let _ = self.senders.pipeline_to_constellation_sender.send((
3975 webview_id,
3976 pipeline_id,
3977 ScriptToConstellationMessage::RespondToScreenshotReadinessRequest(
3978 ScreenshotReadinessResponse::NoLongerActive,
3979 ),
3980 ));
3981 return;
3982 };
3983 window.request_screenshot_readiness(can_gc);
3984 }
3985
3986 fn handle_embedder_control_response(
3987 &self,
3988 id: EmbedderControlId,
3989 response: EmbedderControlResponse,
3990 can_gc: CanGc,
3991 ) {
3992 let Some(document) = self.documents.borrow().find_document(id.pipeline_id) else {
3993 return;
3994 };
3995 document
3996 .embedder_controls()
3997 .handle_embedder_control_response(id, response, can_gc);
3998 }
3999}
4000
4001impl Drop for ScriptThread {
4002 fn drop(&mut self) {
4003 SCRIPT_THREAD_ROOT.with(|root| {
4004 root.set(None);
4005 });
4006 }
4007}