use std::borrow::Cow;
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet};
use std::default::Default;
use std::option::Option;
use std::rc::Rc;
use std::result::Result;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant, SystemTime};
use background_hang_monitor_api::{
BackgroundHangMonitor, BackgroundHangMonitorExitSignal, HangAnnotation, MonitoredComponentId,
MonitoredComponentType,
};
use base::cross_process_instant::CrossProcessInstant;
use base::id::{
BrowsingContextId, HistoryStateId, PipelineId, PipelineNamespace, TopLevelBrowsingContextId,
};
use base::Epoch;
use canvas_traits::webgl::WebGLPipeline;
use chrono::{DateTime, Local};
use crossbeam_channel::unbounded;
use devtools_traits::{
CSSError, DevtoolScriptControlMsg, DevtoolsPageInfo, NavigationState,
ScriptToDevtoolsControlMsg, WorkerId,
};
use embedder_traits::EmbedderMsg;
use euclid::default::{Point2D, Rect};
use fonts::SystemFontServiceProxy;
use headers::{HeaderMapExt, LastModified, ReferrerPolicy as ReferrerPolicyHeader};
use html5ever::{local_name, namespace_url, ns};
use hyper_serde::Serde;
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use js::glue::GetWindowProxyClass;
use js::jsapi::{
JSContext as UnsafeJSContext, JSTracer, JS_AddInterruptCallback, SetWindowProxyClass,
};
use js::jsval::UndefinedValue;
use js::rust::ParentRuntime;
use media::WindowGLContext;
use metrics::{PaintTimeMetrics, MAX_TASK_NS};
use mime::{self, Mime};
use net_traits::image_cache::{ImageCache, PendingImageResponse};
use net_traits::request::{
CredentialsMode, Destination, RedirectMode, RequestBuilder, RequestId, RequestMode,
};
use net_traits::storage_thread::StorageType;
use net_traits::{
FetchMetadata, FetchResponseListener, FetchResponseMsg, Metadata, NetworkError,
ResourceFetchTiming, ResourceThreads, ResourceTimingType,
};
use percent_encoding::percent_decode;
use profile_traits::mem::ReportsChan;
use profile_traits::time::ProfilerCategory;
use profile_traits::time_profile;
use script_layout_interface::{
node_id_from_scroll_id, LayoutConfig, LayoutFactory, ReflowGoal, ScriptThreadFactory,
};
use script_traits::webdriver_msg::WebDriverScriptCommand;
use script_traits::{
CompositorEvent, ConstellationControlMsg, DiscardBrowsingContext, DocumentActivity,
EventResult, InitialScriptState, JsEvalResult, LoadData, LoadOrigin, MediaSessionActionType,
MouseButton, MouseEventType, NavigationHistoryBehavior, NewLayoutInfo, Painter,
ProgressiveWebMetricType, ScriptMsg, ScriptToConstellationChan, ScrollState,
StructuredSerializedData, Theme, TouchEventType, TouchId, UntrustedNodeAddress,
UpdatePipelineIdReason, WheelDelta, WindowSizeData, WindowSizeType,
};
use servo_atoms::Atom;
use servo_config::opts;
use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
use style::dom::OpaqueNode;
use style::thread_state::{self, ThreadState};
use timers::{TimerEventRequest, TimerScheduler};
use url::Position;
#[cfg(feature = "webgpu")]
use webgpu::{WebGPUDevice, WebGPUMsg};
use webrender_api::DocumentId;
use webrender_traits::CrossProcessCompositorApi;
use crate::document_collection::DocumentCollection;
use crate::document_loader::DocumentLoader;
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::DocumentBinding::{
DocumentMethods, DocumentReadyState,
};
use crate::dom::bindings::codegen::Bindings::NavigatorBinding::NavigatorMethods;
use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use crate::dom::bindings::conversions::{
ConversionResult, FromJSValConvertible, StringificationBehavior,
};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::DomObject;
use crate::dom::bindings::root::{
Dom, DomRoot, MutNullableDom, RootCollection, ThreadLocalStackRoots,
};
use crate::dom::bindings::settings_stack::AutoEntryScript;
use crate::dom::bindings::str::DOMString;
use crate::dom::bindings::trace::{HashMapTracedValues, JSTraceable};
use crate::dom::customelementregistry::{
CallbackReaction, CustomElementDefinition, CustomElementReactionStack,
};
use crate::dom::document::{
Document, DocumentSource, FocusType, HasBrowsingContext, IsHTMLDocument, TouchEventResult,
};
use crate::dom::element::Element;
use crate::dom::globalscope::GlobalScope;
use crate::dom::htmlanchorelement::HTMLAnchorElement;
use crate::dom::htmliframeelement::HTMLIFrameElement;
use crate::dom::mutationobserver::MutationObserver;
use crate::dom::node::{Node, NodeTraits, ShadowIncluding};
use crate::dom::performanceentry::PerformanceEntry;
use crate::dom::performancepainttiming::PerformancePaintTiming;
use crate::dom::servoparser::{ParserContext, ServoParser};
#[cfg(feature = "webgpu")]
use crate::dom::webgpu::identityhub::IdentityHub;
use crate::dom::window::Window;
use crate::dom::windowproxy::{CreatorBrowsingContextInfo, WindowProxy};
use crate::dom::worklet::WorkletThreadPool;
use crate::dom::workletglobalscope::WorkletGlobalScopeInit;
use crate::fetch::FetchCanceller;
use crate::messaging::{
MainThreadScriptChan, MainThreadScriptMsg, MixedMessage, ScriptThreadReceivers,
ScriptThreadSenders,
};
use crate::microtask::{Microtask, MicrotaskQueue};
use crate::realms::enter_realm;
use crate::script_module::ScriptFetchOptions;
use crate::script_runtime::{
CanGc, CommonScriptMsg, JSContext, Runtime, ScriptChan, ScriptThreadEventCategory,
ThreadSafeJSContext,
};
use crate::task_queue::TaskQueue;
use crate::task_source::{TaskSource, TaskSourceName};
use crate::{devtools, webdriver_handlers};
thread_local!(static SCRIPT_THREAD_ROOT: Cell<Option<*const ScriptThread>> = const { Cell::new(None) });
fn with_optional_script_thread<R>(f: impl FnOnce(Option<&ScriptThread>) -> R) -> R {
SCRIPT_THREAD_ROOT.with(|root| {
f(root
.get()
.and_then(|script_thread| unsafe { script_thread.as_ref() }))
})
}
pub(crate) fn with_script_thread<R: Default>(f: impl FnOnce(&ScriptThread) -> R) -> R {
with_optional_script_thread(|script_thread| script_thread.map(f).unwrap_or_default())
}
pub unsafe fn trace_thread(tr: *mut JSTracer) {
with_script_thread(|script_thread| {
debug!("tracing fields of ScriptThread");
script_thread.trace(tr);
})
}
#[derive(JSTraceable)]
struct InProgressLoad {
#[no_trace]
pipeline_id: PipelineId,
#[no_trace]
browsing_context_id: BrowsingContextId,
#[no_trace]
top_level_browsing_context_id: TopLevelBrowsingContextId,
#[no_trace]
parent_info: Option<PipelineId>,
#[no_trace]
opener: Option<BrowsingContextId>,
#[no_trace]
window_size: WindowSizeData,
#[no_trace]
activity: DocumentActivity,
throttled: bool,
#[no_trace]
url: ServoUrl,
#[no_trace]
origin: MutableOrigin,
#[no_trace]
navigation_start: CrossProcessInstant,
canceller: FetchCanceller,
inherited_secure_context: Option<bool>,
}
impl InProgressLoad {
#[allow(clippy::too_many_arguments)]
fn new(
id: PipelineId,
browsing_context_id: BrowsingContextId,
top_level_browsing_context_id: TopLevelBrowsingContextId,
parent_info: Option<PipelineId>,
opener: Option<BrowsingContextId>,
window_size: WindowSizeData,
url: ServoUrl,
origin: MutableOrigin,
inherited_secure_context: Option<bool>,
) -> InProgressLoad {
let navigation_start = CrossProcessInstant::now();
InProgressLoad {
pipeline_id: id,
browsing_context_id,
top_level_browsing_context_id,
parent_info,
opener,
window_size,
activity: DocumentActivity::FullyActive,
throttled: false,
url,
origin,
navigation_start,
canceller: Default::default(),
inherited_secure_context,
}
}
}
pub struct IncompleteParserContexts(RefCell<Vec<(PipelineId, ParserContext)>>);
unsafe_no_jsmanaged_fields!(TaskQueue<MainThreadScriptMsg>);
#[derive(JSTraceable)]
#[allow(crown::unrooted_must_root)]
pub struct ScriptThread {
last_render_opportunity_time: DomRefCell<Option<Instant>>,
documents: DomRefCell<DocumentCollection>,
window_proxies: DomRefCell<HashMapTracedValues<BrowsingContextId, Dom<WindowProxy>>>,
incomplete_loads: DomRefCell<Vec<InProgressLoad>>,
incomplete_parser_contexts: IncompleteParserContexts,
#[no_trace]
image_cache: Arc<dyn ImageCache>,
receivers: ScriptThreadReceivers,
senders: ScriptThreadSenders,
#[no_trace]
resource_threads: ResourceThreads,
task_queue: TaskQueue<MainThreadScriptMsg>,
#[no_trace]
background_hang_monitor: Box<dyn BackgroundHangMonitor>,
closing: Arc<AtomicBool>,
#[no_trace]
timer_scheduler: RefCell<TimerScheduler>,
#[no_trace]
system_font_service: Arc<SystemFontServiceProxy>,
js_runtime: Rc<Runtime>,
topmost_mouse_over_target: MutNullableDom<Element>,
#[no_trace]
closed_pipelines: DomRefCell<HashSet<PipelineId>>,
microtask_queue: Rc<MicrotaskQueue>,
mutation_observer_microtask_queued: Cell<bool>,
mutation_observers: DomRefCell<Vec<Dom<MutationObserver>>>,
#[no_trace]
webgl_chan: Option<WebGLPipeline>,
#[no_trace]
#[cfg(feature = "webxr")]
webxr_registry: Option<webxr_api::Registry>,
worklet_thread_pool: DomRefCell<Option<Rc<WorkletThreadPool>>>,
docs_with_no_blocking_loads: DomRefCell<HashSet<Dom<Document>>>,
custom_element_reaction_stack: CustomElementReactionStack,
#[no_trace]
webrender_document: DocumentId,
#[no_trace]
compositor_api: CrossProcessCompositorApi,
profile_script_events: bool,
print_pwm: bool,
relayout_event: bool,
prepare_for_screenshot: bool,
unminify_js: bool,
local_script_source: Option<String>,
unminify_css: bool,
userscripts_path: Option<String>,
headless: bool,
replace_surrogates: bool,
user_agent: Cow<'static, str>,
#[no_trace]
player_context: WindowGLContext,
node_ids: DomRefCell<HashSet<String>>,
is_user_interacting: Cell<bool>,
#[no_trace]
#[cfg(feature = "webgpu")]
gpu_id_hub: Arc<IdentityHub>,
inherited_secure_context: Option<bool>,
#[no_trace]
layout_factory: Arc<dyn LayoutFactory>,
}
struct BHMExitSignal {
closing: Arc<AtomicBool>,
js_context: ThreadSafeJSContext,
}
impl BackgroundHangMonitorExitSignal for BHMExitSignal {
fn signal_to_exit(&self) {
self.closing.store(true, Ordering::SeqCst);
self.js_context.request_interrupt_callback();
}
}
#[allow(unsafe_code)]
unsafe extern "C" fn interrupt_callback(_cx: *mut UnsafeJSContext) -> bool {
let res = ScriptThread::can_continue_running();
if !res {
ScriptThread::prepare_for_shutdown();
}
res
}
struct ScriptMemoryFailsafe<'a> {
owner: Option<&'a ScriptThread>,
}
impl<'a> ScriptMemoryFailsafe<'a> {
fn neuter(&mut self) {
self.owner = None;
}
fn new(owner: &'a ScriptThread) -> ScriptMemoryFailsafe<'a> {
ScriptMemoryFailsafe { owner: Some(owner) }
}
}
impl Drop for ScriptMemoryFailsafe<'_> {
#[allow(crown::unrooted_must_root)]
fn drop(&mut self) {
if let Some(owner) = self.owner {
for (_, document) in owner.documents.borrow().iter() {
document.window().clear_js_runtime_for_script_deallocation();
}
}
}
}
impl ScriptThreadFactory for ScriptThread {
fn create(
state: InitialScriptState,
layout_factory: Arc<dyn LayoutFactory>,
system_font_service: Arc<SystemFontServiceProxy>,
load_data: LoadData,
user_agent: Cow<'static, str>,
) {
thread::Builder::new()
.name(format!("Script{:?}", state.id))
.spawn(move || {
thread_state::initialize(ThreadState::SCRIPT | ThreadState::LAYOUT);
PipelineNamespace::install(state.pipeline_namespace_id);
TopLevelBrowsingContextId::install(state.top_level_browsing_context_id);
let roots = RootCollection::new();
let _stack_roots = ThreadLocalStackRoots::new(&roots);
let id = state.id;
let browsing_context_id = state.browsing_context_id;
let top_level_browsing_context_id = state.top_level_browsing_context_id;
let parent_info = state.parent_info;
let opener = state.opener;
let secure = load_data.inherited_secure_context;
let memory_profiler_sender = state.memory_profiler_sender.clone();
let window_size = state.window_size;
let script_thread =
ScriptThread::new(state, layout_factory, system_font_service, user_agent);
SCRIPT_THREAD_ROOT.with(|root| {
root.set(Some(&script_thread as *const _));
});
let mut failsafe = ScriptMemoryFailsafe::new(&script_thread);
let origin = MutableOrigin::new(load_data.url.origin());
let new_load = InProgressLoad::new(
id,
browsing_context_id,
top_level_browsing_context_id,
parent_info,
opener,
window_size,
load_data.url.clone(),
origin,
secure,
);
script_thread.pre_page_load(new_load, load_data);
let reporter_name = format!("script-reporter-{:?}", id);
memory_profiler_sender.run_with_memory_reporting(
|| {
script_thread.start(CanGc::note());
let _ = script_thread
.senders
.content_process_shutdown_sender
.send(());
},
reporter_name,
script_thread.senders.self_sender.0.clone(),
CommonScriptMsg::CollectReports,
);
failsafe.neuter();
})
.expect("Thread spawning failed");
}
}
impl ScriptThread {
pub fn runtime_handle() -> ParentRuntime {
with_optional_script_thread(|script_thread| {
script_thread.unwrap().js_runtime.prepare_for_new_child()
})
}
pub fn can_continue_running() -> bool {
with_script_thread(|script_thread| script_thread.can_continue_running_inner())
}
pub fn prepare_for_shutdown() {
with_script_thread(|script_thread| {
script_thread.prepare_for_shutdown_inner();
})
}
pub fn set_mutation_observer_microtask_queued(value: bool) {
with_script_thread(|script_thread| {
script_thread.mutation_observer_microtask_queued.set(value);
})
}
pub fn is_mutation_observer_microtask_queued() -> bool {
with_script_thread(|script_thread| script_thread.mutation_observer_microtask_queued.get())
}
pub fn add_mutation_observer(observer: &MutationObserver) {
with_script_thread(|script_thread| {
script_thread
.mutation_observers
.borrow_mut()
.push(Dom::from_ref(observer));
})
}
pub fn get_mutation_observers() -> Vec<DomRoot<MutationObserver>> {
with_script_thread(|script_thread| {
script_thread
.mutation_observers
.borrow()
.iter()
.map(|o| DomRoot::from_ref(&**o))
.collect()
})
}
pub fn mark_document_with_no_blocked_loads(doc: &Document) {
with_script_thread(|script_thread| {
script_thread
.docs_with_no_blocking_loads
.borrow_mut()
.insert(Dom::from_ref(doc));
})
}
pub fn page_headers_available(
id: &PipelineId,
metadata: Option<Metadata>,
can_gc: CanGc,
) -> Option<DomRoot<ServoParser>> {
with_script_thread(|script_thread| {
script_thread.handle_page_headers_available(id, metadata, can_gc)
})
}
pub fn process_event(msg: CommonScriptMsg) -> bool {
with_script_thread(|script_thread| {
if !script_thread.can_continue_running_inner() {
return false;
}
script_thread.handle_msg_from_script(MainThreadScriptMsg::Common(msg));
true
})
}
pub(crate) fn schedule_timer(&self, request: TimerEventRequest) {
self.timer_scheduler.borrow_mut().schedule_timer(request);
}
pub fn await_stable_state(task: Microtask) {
with_script_thread(|script_thread| {
script_thread
.microtask_queue
.enqueue(task, script_thread.get_cx());
});
}
pub fn check_load_origin(source: &LoadOrigin, target: &ImmutableOrigin) -> bool {
match (source, target) {
(LoadOrigin::Constellation, _) | (LoadOrigin::WebDriver, _) => {
true
},
(_, ImmutableOrigin::Opaque(_)) => {
true
},
(LoadOrigin::Script(source_origin), _) => source_origin == target,
}
}
pub fn navigate(
browsing_context: BrowsingContextId,
pipeline_id: PipelineId,
mut load_data: LoadData,
history_handling: NavigationHistoryBehavior,
) {
with_script_thread(|script_thread| {
let is_javascript = load_data.url.scheme() == "javascript";
if is_javascript {
let window = match script_thread.documents.borrow().find_window(pipeline_id) {
None => return,
Some(window) => window,
};
let global = window.upcast::<GlobalScope>();
let trusted_global = Trusted::new(global);
let sender = script_thread
.senders
.pipeline_to_constellation_sender
.clone();
let task = task!(navigate_javascript: move || {
if let Some(window) = trusted_global.root().downcast::<Window>() {
if ScriptThread::check_load_origin(&load_data.load_origin, &window.get_url().origin()) {
ScriptThread::eval_js_url(&trusted_global.root(), &mut load_data, CanGc::note());
sender
.send((pipeline_id, ScriptMsg::LoadUrl(load_data, history_handling)))
.unwrap();
}
}
});
global
.task_manager()
.dom_manipulation_task_source()
.queue(task)
.expect("Enqueing navigate js task on the DOM manipulation task source failed");
} else {
if let Some(ref sender) = script_thread.senders.devtools_server_sender {
let _ = sender.send(ScriptToDevtoolsControlMsg::Navigate(
browsing_context,
NavigationState::Start(load_data.url.clone()),
));
}
script_thread
.senders
.pipeline_to_constellation_sender
.send((pipeline_id, ScriptMsg::LoadUrl(load_data, history_handling)))
.expect("Sending a LoadUrl message to the constellation failed");
}
});
}
pub fn process_attach_layout(new_layout_info: NewLayoutInfo, origin: MutableOrigin) {
with_script_thread(|script_thread| {
let pipeline_id = Some(new_layout_info.new_pipeline_id);
script_thread.profile_event(
ScriptThreadEventCategory::AttachLayout,
pipeline_id,
|| {
script_thread.handle_new_layout(new_layout_info, origin);
},
)
});
}
pub fn get_top_level_for_browsing_context(
sender_pipeline: PipelineId,
browsing_context_id: BrowsingContextId,
) -> Option<TopLevelBrowsingContextId> {
with_script_thread(|script_thread| {
script_thread.ask_constellation_for_top_level_info(sender_pipeline, browsing_context_id)
})
}
pub fn find_document(id: PipelineId) -> Option<DomRoot<Document>> {
with_script_thread(|script_thread| script_thread.documents.borrow().find_document(id))
}
pub fn set_user_interacting(interacting: bool) {
with_script_thread(|script_thread| {
script_thread.is_user_interacting.set(interacting);
});
}
pub fn is_user_interacting() -> bool {
with_script_thread(|script_thread| script_thread.is_user_interacting.get())
}
pub fn get_fully_active_document_ids() -> HashSet<PipelineId> {
with_script_thread(|script_thread| {
script_thread
.documents
.borrow()
.iter()
.filter_map(|(id, document)| {
if document.is_fully_active() {
Some(id)
} else {
None
}
})
.fold(HashSet::new(), |mut set, id| {
let _ = set.insert(id);
set
})
})
}
pub fn find_window_proxy(id: BrowsingContextId) -> Option<DomRoot<WindowProxy>> {
with_script_thread(|script_thread| {
script_thread
.window_proxies
.borrow()
.get(&id)
.map(|context| DomRoot::from_ref(&**context))
})
}
pub fn find_window_proxy_by_name(name: &DOMString) -> Option<DomRoot<WindowProxy>> {
with_script_thread(|script_thread| {
for (_, proxy) in script_thread.window_proxies.borrow().iter() {
if proxy.get_name() == *name {
return Some(DomRoot::from_ref(&**proxy));
}
}
None
})
}
pub fn worklet_thread_pool() -> Rc<WorkletThreadPool> {
with_optional_script_thread(|script_thread| {
let script_thread = script_thread.unwrap();
script_thread
.worklet_thread_pool
.borrow_mut()
.get_or_insert_with(|| {
let init = WorkletGlobalScopeInit {
to_script_thread_sender: script_thread.senders.self_sender.0.clone(),
resource_threads: script_thread.resource_threads.clone(),
mem_profiler_chan: script_thread.senders.memory_profiler_sender.clone(),
time_profiler_chan: script_thread.senders.time_profiler_sender.clone(),
devtools_chan: script_thread.senders.devtools_server_sender.clone(),
to_constellation_sender: script_thread
.senders
.pipeline_to_constellation_sender
.clone(),
image_cache: script_thread.image_cache.clone(),
is_headless: script_thread.headless,
user_agent: script_thread.user_agent.clone(),
#[cfg(feature = "webgpu")]
gpu_id_hub: script_thread.gpu_id_hub.clone(),
inherited_secure_context: script_thread.inherited_secure_context,
};
Rc::new(WorkletThreadPool::spawn(init))
})
.clone()
})
}
fn handle_register_paint_worklet(
&self,
pipeline_id: PipelineId,
name: Atom,
properties: Vec<Atom>,
painter: Box<dyn Painter>,
) {
let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
warn!("Paint worklet registered after pipeline {pipeline_id} closed.");
return;
};
window
.layout_mut()
.register_paint_worklet_modules(name, properties, painter);
}
pub fn push_new_element_queue() {
with_script_thread(|script_thread| {
script_thread
.custom_element_reaction_stack
.push_new_element_queue();
})
}
pub fn pop_current_element_queue(can_gc: CanGc) {
with_script_thread(|script_thread| {
script_thread
.custom_element_reaction_stack
.pop_current_element_queue(can_gc);
})
}
pub fn enqueue_callback_reaction(
element: &Element,
reaction: CallbackReaction,
definition: Option<Rc<CustomElementDefinition>>,
) {
with_script_thread(|script_thread| {
script_thread
.custom_element_reaction_stack
.enqueue_callback_reaction(element, reaction, definition);
})
}
pub fn enqueue_upgrade_reaction(element: &Element, definition: Rc<CustomElementDefinition>) {
with_script_thread(|script_thread| {
script_thread
.custom_element_reaction_stack
.enqueue_upgrade_reaction(element, definition);
})
}
pub fn invoke_backup_element_queue(can_gc: CanGc) {
with_script_thread(|script_thread| {
script_thread
.custom_element_reaction_stack
.invoke_backup_element_queue(can_gc);
})
}
pub fn save_node_id(node_id: String) {
with_script_thread(|script_thread| {
script_thread.node_ids.borrow_mut().insert(node_id);
})
}
pub fn has_node_id(node_id: &str) -> bool {
with_script_thread(|script_thread| script_thread.node_ids.borrow().contains(node_id))
}
pub(crate) fn new(
state: InitialScriptState,
layout_factory: Arc<dyn LayoutFactory>,
system_font_service: Arc<SystemFontServiceProxy>,
user_agent: Cow<'static, str>,
) -> ScriptThread {
let opts = opts::get();
let prepare_for_screenshot =
opts.output_file.is_some() || opts.exit_after_load || opts.webdriver_port.is_some();
let (self_sender, self_receiver) = unbounded();
let self_sender = MainThreadScriptChan(self_sender.clone());
let runtime = Runtime::new(Some(TaskSource {
sender: self_sender.as_boxed(),
pipeline_id: state.id,
name: TaskSourceName::Networking,
canceller: Default::default(),
}));
let cx = runtime.cx();
unsafe {
SetWindowProxyClass(cx, GetWindowProxyClass());
JS_AddInterruptCallback(cx, Some(interrupt_callback));
}
let constellation_receiver =
ROUTER.route_ipc_receiver_to_new_crossbeam_receiver(state.constellation_receiver);
let devtools_server_sender = state.devtools_server_sender;
let (ipc_devtools_sender, ipc_devtools_receiver) = ipc::channel().unwrap();
let devtools_server_receiver = devtools_server_sender
.as_ref()
.map(|_| ROUTER.route_ipc_receiver_to_new_crossbeam_receiver(ipc_devtools_receiver))
.unwrap_or_else(crossbeam_channel::never);
let (image_cache_sender, image_cache_receiver) = unbounded();
let task_queue = TaskQueue::new(self_receiver, self_sender.0.clone());
let closing = Arc::new(AtomicBool::new(false));
let background_hang_monitor_exit_signal = BHMExitSignal {
closing: closing.clone(),
js_context: runtime.thread_safe_js_context(),
};
let background_hang_monitor = state.background_hang_monitor_register.register_component(
MonitoredComponentId(state.id, MonitoredComponentType::Script),
Duration::from_millis(1000),
Duration::from_millis(5000),
Some(Box::new(background_hang_monitor_exit_signal)),
);
let receivers = ScriptThreadReceivers {
constellation_receiver,
image_cache_receiver,
devtools_server_receiver,
#[cfg(feature = "webgpu")]
webgpu_receiver: RefCell::new(crossbeam_channel::never()),
};
let senders = ScriptThreadSenders {
self_sender,
bluetooth_sender: state.bluetooth_sender,
constellation_sender: state.constellation_sender,
pipeline_to_constellation_sender: state.pipeline_to_constellation_sender.sender.clone(),
layout_to_constellation_ipc_sender: state.layout_to_constellation_ipc_sender,
image_cache_sender,
time_profiler_sender: state.time_profiler_sender,
memory_profiler_sender: state.memory_profiler_sender,
devtools_server_sender,
devtools_client_to_script_thread_sender: ipc_devtools_sender,
content_process_shutdown_sender: state.content_process_shutdown_sender,
};
ScriptThread {
documents: DomRefCell::new(DocumentCollection::default()),
last_render_opportunity_time: Default::default(),
window_proxies: DomRefCell::new(HashMapTracedValues::new()),
incomplete_loads: DomRefCell::new(vec![]),
incomplete_parser_contexts: IncompleteParserContexts(RefCell::new(vec![])),
senders,
receivers,
image_cache: state.image_cache.clone(),
resource_threads: state.resource_threads,
task_queue,
background_hang_monitor,
closing,
timer_scheduler: Default::default(),
microtask_queue: runtime.microtask_queue.clone(),
js_runtime: Rc::new(runtime),
topmost_mouse_over_target: MutNullableDom::new(Default::default()),
closed_pipelines: DomRefCell::new(HashSet::new()),
mutation_observer_microtask_queued: Default::default(),
mutation_observers: Default::default(),
system_font_service,
webgl_chan: state.webgl_chan,
#[cfg(feature = "webxr")]
webxr_registry: state.webxr_registry,
worklet_thread_pool: Default::default(),
docs_with_no_blocking_loads: Default::default(),
custom_element_reaction_stack: CustomElementReactionStack::new(),
webrender_document: state.webrender_document,
compositor_api: state.compositor_api,
profile_script_events: opts.debug.profile_script_events,
print_pwm: opts.print_pwm,
relayout_event: opts.debug.relayout_event,
prepare_for_screenshot,
unminify_js: opts.unminify_js,
local_script_source: opts.local_script_source.clone(),
unminify_css: opts.unminify_css,
userscripts_path: opts.userscripts.clone(),
headless: opts.headless,
replace_surrogates: opts.debug.replace_surrogates,
user_agent,
player_context: state.player_context,
node_ids: Default::default(),
is_user_interacting: Cell::new(false),
#[cfg(feature = "webgpu")]
gpu_id_hub: Arc::new(IdentityHub::default()),
inherited_secure_context: state.inherited_secure_context,
layout_factory,
}
}
#[allow(unsafe_code)]
pub fn get_cx(&self) -> JSContext {
unsafe { JSContext::from_ptr(self.js_runtime.cx()) }
}
fn can_continue_running_inner(&self) -> bool {
if self.closing.load(Ordering::SeqCst) {
return false;
}
true
}
fn prepare_for_shutdown_inner(&self) {
let docs = self.documents.borrow();
for (_, document) in docs.iter() {
document
.window()
.task_manager()
.cancel_all_tasks_and_ignore_future_tasks();
}
}
pub fn start(&self, can_gc: CanGc) {
debug!("Starting script thread.");
while self.handle_msgs(can_gc) {
debug!("Running script thread.");
}
debug!("Stopped script thread.");
}
fn process_mouse_move_event(
&self,
document: &Document,
window: &Window,
point: Point2D<f32>,
node_address: Option<UntrustedNodeAddress>,
pressed_mouse_buttons: u16,
can_gc: CanGc,
) {
let prev_mouse_over_target = self.topmost_mouse_over_target.get();
unsafe {
document.handle_mouse_move_event(
point,
&self.topmost_mouse_over_target,
node_address,
pressed_mouse_buttons,
can_gc,
)
}
if self.topmost_mouse_over_target.get() == prev_mouse_over_target {
return;
}
let mut state_already_changed = false;
if let Some(target) = self.topmost_mouse_over_target.get() {
if let Some(anchor) = target
.upcast::<Node>()
.inclusive_ancestors(ShadowIncluding::No)
.filter_map(DomRoot::downcast::<HTMLAnchorElement>)
.next()
{
let status = anchor
.upcast::<Element>()
.get_attribute(&ns!(), &local_name!("href"))
.and_then(|href| {
let value = href.value();
let url = document.url();
url.join(&value).map(|url| url.to_string()).ok()
});
let event = EmbedderMsg::Status(status);
window.send_to_embedder(event);
state_already_changed = true;
}
}
if !state_already_changed {
if let Some(target) = prev_mouse_over_target {
if target
.upcast::<Node>()
.inclusive_ancestors(ShadowIncluding::No)
.filter_map(DomRoot::downcast::<HTMLAnchorElement>)
.next()
.is_some()
{
let event = EmbedderMsg::Status(None);
window.send_to_embedder(event);
}
}
}
}
fn process_pending_compositor_events(&self, pipeline_id: PipelineId, can_gc: CanGc) {
let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
warn!("Processing pending compositor events for closed pipeline {pipeline_id}.");
return;
};
if document.window().Closed() {
warn!("Compositor event sent to a pipeline with a closed window {pipeline_id}.");
return;
}
ScriptThread::set_user_interacting(true);
let window = document.window();
let _realm = enter_realm(document.window());
for event in document.take_pending_compositor_events().into_iter() {
match event {
CompositorEvent::ResizeEvent(new_size, size_type) => {
window.add_resize_event(new_size, size_type);
},
CompositorEvent::MouseButtonEvent(
event_type,
button,
point,
node_address,
point_in_node,
pressed_mouse_buttons,
) => {
self.handle_mouse_button_event(
pipeline_id,
event_type,
button,
point,
node_address,
point_in_node,
pressed_mouse_buttons,
can_gc,
);
},
CompositorEvent::MouseMoveEvent(point, node_address, pressed_mouse_buttons) => {
self.process_mouse_move_event(
&document,
window,
point,
node_address,
pressed_mouse_buttons,
can_gc,
);
},
CompositorEvent::TouchEvent(event_type, identifier, point, node_address) => {
let touch_result = self.handle_touch_event(
pipeline_id,
event_type,
identifier,
point,
node_address,
can_gc,
);
match (event_type, touch_result) {
(TouchEventType::Down, TouchEventResult::Processed(handled)) => {
let result = if handled {
EventResult::DefaultAllowed
} else {
EventResult::DefaultPrevented
};
let message = ScriptMsg::TouchEventProcessed(result);
self.senders
.pipeline_to_constellation_sender
.send((pipeline_id, message))
.unwrap();
},
_ => {
},
}
},
CompositorEvent::WheelEvent(delta, point, node_address) => {
self.handle_wheel_event(pipeline_id, delta, point, node_address, can_gc);
},
CompositorEvent::KeyboardEvent(key_event) => {
document.dispatch_key_event(key_event, can_gc);
},
CompositorEvent::IMEDismissedEvent => {
document.ime_dismissed(can_gc);
},
CompositorEvent::CompositionEvent(composition_event) => {
document.dispatch_composition_event(composition_event, can_gc);
},
CompositorEvent::GamepadEvent(gamepad_event) => {
let global = window.upcast::<GlobalScope>();
global.handle_gamepad_event(gamepad_event);
},
}
}
ScriptThread::set_user_interacting(false);
}
pub(crate) fn update_the_rendering(&self, requested_by_compositor: bool, can_gc: CanGc) {
*self.last_render_opportunity_time.borrow_mut() = Some(Instant::now());
if !self.can_continue_running_inner() {
return;
}
let should_run_rafs = self
.documents
.borrow()
.iter()
.any(|(_, doc)| doc.has_received_raf_tick());
let any_animations_running = self
.documents
.borrow()
.iter()
.any(|(_, document)| document.animations().running_animation_count() != 0);
if !requested_by_compositor && any_animations_running {
return;
}
let documents_in_order = self.documents.borrow().documents_in_order();
for pipeline_id in documents_in_order.iter() {
let document = self
.documents
.borrow()
.find_document(*pipeline_id)
.expect("Got pipeline for Document not managed by this ScriptThread.");
self.process_pending_compositor_events(*pipeline_id, can_gc);
if document.window().run_the_resize_steps(can_gc) {
document
.window()
.evaluate_media_queries_and_report_changes(can_gc);
document.react_to_environment_changes()
}
document.update_animations_and_send_events(can_gc);
if should_run_rafs {
document.run_the_animation_frame_callbacks();
}
let _realm = enter_realm(&*document);
let mut depth = Default::default();
while document.gather_active_resize_observations_at_depth(&depth, can_gc) {
depth = document.broadcast_active_resize_observations(can_gc);
}
if document.has_skipped_resize_observations() {
document.deliver_resize_loop_error_notification(can_gc);
}
#[cfg(feature = "webgpu")]
document.update_rendering_of_webgpu_canvases();
let window = document.window();
if document.is_fully_active() {
window.reflow(ReflowGoal::UpdateTheRendering, can_gc);
}
}
self.perform_a_microtask_checkpoint(can_gc);
self.schedule_rendering_opportunity_if_necessary();
}
fn schedule_rendering_opportunity_if_necessary(&self) {
if self.documents.borrow().iter().any(|(_, document)| {
document.animations().running_animation_count() != 0 ||
document.has_active_request_animation_frame_callbacks()
}) {
return;
}
let Some((_, document)) = self.documents.borrow().iter().find(|(_, document)| {
!document.window().layout_blocked() && document.needs_reflow().is_some()
}) else {
return;
};
let _realm = enter_realm(&*document);
let rendering_task_source = document.window().task_manager().rendering_task_source();
let _ =
rendering_task_source.queue_unconditionally(task!(update_the_rendering: move || { }));
}
fn handle_msgs(&self, can_gc: CanGc) -> bool {
let mut sequential = vec![];
self.background_hang_monitor.notify_wait();
debug!("Waiting for event.");
let mut event = self
.receivers
.recv(&self.task_queue, &self.timer_scheduler.borrow());
let mut compositor_requested_update_the_rendering = false;
loop {
debug!("Handling event: {event:?}");
self.timer_scheduler
.borrow_mut()
.dispatch_completed_timers();
let _realm = event.pipeline_id().map(|id| {
let global = self.documents.borrow().find_global(id);
global.map(|global| enter_realm(&*global))
});
match event {
MixedMessage::FromConstellation(ConstellationControlMsg::AttachLayout(
new_layout_info,
)) => {
let pipeline_id = new_layout_info.new_pipeline_id;
self.profile_event(
ScriptThreadEventCategory::AttachLayout,
Some(pipeline_id),
|| {
let not_an_about_blank_and_about_srcdoc_load =
new_layout_info.load_data.url.as_str() != "about:blank" &&
new_layout_info.load_data.url.as_str() != "about:srcdoc";
let origin = if not_an_about_blank_and_about_srcdoc_load {
MutableOrigin::new(new_layout_info.load_data.url.origin())
} else if let Some(parent) =
new_layout_info.parent_info.and_then(|pipeline_id| {
self.documents.borrow().find_document(pipeline_id)
})
{
parent.origin().clone()
} else if let Some(creator) = new_layout_info
.load_data
.creator_pipeline_id
.and_then(|pipeline_id| {
self.documents.borrow().find_document(pipeline_id)
})
{
creator.origin().clone()
} else {
MutableOrigin::new(ImmutableOrigin::new_opaque())
};
self.handle_new_layout(new_layout_info, origin);
},
)
},
MixedMessage::FromConstellation(ConstellationControlMsg::Resize(
id,
size,
size_type,
)) => {
self.handle_resize_message(id, size, size_type);
},
MixedMessage::FromConstellation(ConstellationControlMsg::Viewport(id, rect)) => {
self.profile_event(ScriptThreadEventCategory::SetViewport, Some(id), || {
self.handle_viewport(id, rect);
})
},
MixedMessage::FromConstellation(ConstellationControlMsg::TickAllAnimations(
pipeline_id,
tick_type,
)) => {
if let Some(document) = self.documents.borrow().find_document(pipeline_id) {
document.note_pending_animation_tick(tick_type);
compositor_requested_update_the_rendering = true;
} else {
warn!(
"Trying to note pending animation tick for closed pipeline {}.",
pipeline_id
)
}
},
MixedMessage::FromConstellation(ConstellationControlMsg::SendEvent(id, event)) => {
self.handle_event(id, event)
},
MixedMessage::FromScript(MainThreadScriptMsg::Common(CommonScriptMsg::Task(
_,
_,
_,
TaskSourceName::Rendering,
))) => {
},
MixedMessage::FromScript(MainThreadScriptMsg::Inactive) => {
},
MixedMessage::FromConstellation(ConstellationControlMsg::ExitFullScreen(id)) => {
self.profile_event(ScriptThreadEventCategory::ExitFullscreen, Some(id), || {
self.handle_exit_fullscreen(id, can_gc);
})
},
_ => {
sequential.push(event);
},
}
match self.receivers.try_recv(&self.task_queue) {
Some(new_event) => event = new_event,
None => break,
}
}
debug!("Processing events.");
for msg in sequential {
debug!("Processing event {:?}.", msg);
let category = self.categorize_msg(&msg);
let pipeline_id = msg.pipeline_id();
let _realm = pipeline_id.and_then(|id| {
let global = self.documents.borrow().find_global(id);
global.map(|global| enter_realm(&*global))
});
if self.closing.load(Ordering::SeqCst) {
match msg {
MixedMessage::FromConstellation(ConstellationControlMsg::ExitScriptThread) => {
self.handle_exit_script_thread_msg(can_gc);
return false;
},
MixedMessage::FromConstellation(ConstellationControlMsg::ExitPipeline(
pipeline_id,
discard_browsing_context,
)) => {
self.handle_exit_pipeline_msg(
pipeline_id,
discard_browsing_context,
can_gc,
);
},
_ => {},
}
continue;
}
let exiting = self.profile_event(category, pipeline_id, move || {
match msg {
MixedMessage::FromConstellation(ConstellationControlMsg::ExitScriptThread) => {
self.handle_exit_script_thread_msg(can_gc);
return true;
},
MixedMessage::FromConstellation(inner_msg) => {
self.handle_msg_from_constellation(inner_msg, can_gc)
},
MixedMessage::FromScript(inner_msg) => self.handle_msg_from_script(inner_msg),
MixedMessage::FromDevtools(inner_msg) => {
self.handle_msg_from_devtools(inner_msg, can_gc)
},
MixedMessage::FromImageCache(inner_msg) => {
self.handle_msg_from_image_cache(inner_msg)
},
#[cfg(feature = "webgpu")]
MixedMessage::FromWebGPUServer(inner_msg) => {
self.handle_msg_from_webgpu_server(inner_msg, can_gc)
},
MixedMessage::TimerFired => {},
}
false
});
if exiting {
return false;
}
self.perform_a_microtask_checkpoint(can_gc);
}
{
let mut docs = self.docs_with_no_blocking_loads.borrow_mut();
for document in docs.iter() {
let _realm = enter_realm(&**document);
document.maybe_queue_document_completion();
}
docs.clear();
}
self.update_the_rendering(compositor_requested_update_the_rendering, can_gc);
true
}
fn categorize_msg(&self, msg: &MixedMessage) -> ScriptThreadEventCategory {
match *msg {
MixedMessage::FromConstellation(ref inner_msg) => match *inner_msg {
ConstellationControlMsg::SendEvent(_, _) => ScriptThreadEventCategory::DomEvent,
_ => ScriptThreadEventCategory::ConstellationMsg,
},
MixedMessage::FromDevtools(_) => ScriptThreadEventCategory::DevtoolsMsg,
MixedMessage::FromImageCache(_) => ScriptThreadEventCategory::ImageCacheMsg,
MixedMessage::FromScript(ref inner_msg) => match *inner_msg {
MainThreadScriptMsg::Common(CommonScriptMsg::Task(category, ..)) => category,
MainThreadScriptMsg::RegisterPaintWorklet { .. } => {
ScriptThreadEventCategory::WorkletEvent
},
_ => ScriptThreadEventCategory::ScriptEvent,
},
#[cfg(feature = "webgpu")]
MixedMessage::FromWebGPUServer(_) => ScriptThreadEventCategory::WebGPUMsg,
MixedMessage::TimerFired => ScriptThreadEventCategory::TimerEvent,
}
}
fn profile_event<F, R>(
&self,
category: ScriptThreadEventCategory,
pipeline_id: Option<PipelineId>,
f: F,
) -> R
where
F: FnOnce() -> R,
{
self.background_hang_monitor
.notify_activity(HangAnnotation::Script(category.into()));
let start = Instant::now();
let value = if self.profile_script_events {
let profiler_chan = self.senders.time_profiler_sender.clone();
match category {
ScriptThreadEventCategory::AttachLayout => {
time_profile!(ProfilerCategory::ScriptAttachLayout, None, profiler_chan, f)
},
ScriptThreadEventCategory::ConstellationMsg => time_profile!(
ProfilerCategory::ScriptConstellationMsg,
None,
profiler_chan,
f
),
ScriptThreadEventCategory::DevtoolsMsg => {
time_profile!(ProfilerCategory::ScriptDevtoolsMsg, None, profiler_chan, f)
},
ScriptThreadEventCategory::DocumentEvent => time_profile!(
ProfilerCategory::ScriptDocumentEvent,
None,
profiler_chan,
f
),
ScriptThreadEventCategory::DomEvent => {
time_profile!(ProfilerCategory::ScriptDomEvent, None, profiler_chan, f)
},
ScriptThreadEventCategory::FileRead => {
time_profile!(ProfilerCategory::ScriptFileRead, None, profiler_chan, f)
},
ScriptThreadEventCategory::FormPlannedNavigation => time_profile!(
ProfilerCategory::ScriptPlannedNavigation,
None,
profiler_chan,
f
),
ScriptThreadEventCategory::HistoryEvent => {
time_profile!(ProfilerCategory::ScriptHistoryEvent, None, profiler_chan, f)
},
ScriptThreadEventCategory::ImageCacheMsg => time_profile!(
ProfilerCategory::ScriptImageCacheMsg,
None,
profiler_chan,
f
),
ScriptThreadEventCategory::InputEvent => {
time_profile!(ProfilerCategory::ScriptInputEvent, None, profiler_chan, f)
},
ScriptThreadEventCategory::NetworkEvent => {
time_profile!(ProfilerCategory::ScriptNetworkEvent, None, profiler_chan, f)
},
ScriptThreadEventCategory::PortMessage => {
time_profile!(ProfilerCategory::ScriptPortMessage, None, profiler_chan, f)
},
ScriptThreadEventCategory::Resize => {
time_profile!(ProfilerCategory::ScriptResize, None, profiler_chan, f)
},
ScriptThreadEventCategory::ScriptEvent => {
time_profile!(ProfilerCategory::ScriptEvent, None, profiler_chan, f)
},
ScriptThreadEventCategory::SetScrollState => time_profile!(
ProfilerCategory::ScriptSetScrollState,
None,
profiler_chan,
f
),
ScriptThreadEventCategory::UpdateReplacedElement => time_profile!(
ProfilerCategory::ScriptUpdateReplacedElement,
None,
profiler_chan,
f
),
ScriptThreadEventCategory::StylesheetLoad => time_profile!(
ProfilerCategory::ScriptStylesheetLoad,
None,
profiler_chan,
f
),
ScriptThreadEventCategory::SetViewport => {
time_profile!(ProfilerCategory::ScriptSetViewport, None, profiler_chan, f)
},
ScriptThreadEventCategory::TimerEvent => {
time_profile!(ProfilerCategory::ScriptTimerEvent, None, profiler_chan, f)
},
ScriptThreadEventCategory::WebSocketEvent => time_profile!(
ProfilerCategory::ScriptWebSocketEvent,
None,
profiler_chan,
f
),
ScriptThreadEventCategory::WorkerEvent => {
time_profile!(ProfilerCategory::ScriptWorkerEvent, None, profiler_chan, f)
},
ScriptThreadEventCategory::WorkletEvent => {
time_profile!(ProfilerCategory::ScriptWorkletEvent, None, profiler_chan, f)
},
ScriptThreadEventCategory::ServiceWorkerEvent => time_profile!(
ProfilerCategory::ScriptServiceWorkerEvent,
None,
profiler_chan,
f
),
ScriptThreadEventCategory::EnterFullscreen => time_profile!(
ProfilerCategory::ScriptEnterFullscreen,
None,
profiler_chan,
f
),
ScriptThreadEventCategory::ExitFullscreen => time_profile!(
ProfilerCategory::ScriptExitFullscreen,
None,
profiler_chan,
f
),
ScriptThreadEventCategory::PerformanceTimelineTask => time_profile!(
ProfilerCategory::ScriptPerformanceEvent,
None,
profiler_chan,
f
),
ScriptThreadEventCategory::Rendering => {
time_profile!(ProfilerCategory::ScriptRendering, None, profiler_chan, f)
},
#[cfg(feature = "webgpu")]
ScriptThreadEventCategory::WebGPUMsg => {
time_profile!(ProfilerCategory::ScriptWebGPUMsg, None, profiler_chan, f)
},
}
} else {
f()
};
let task_duration = start.elapsed();
for (doc_id, doc) in self.documents.borrow().iter() {
if let Some(pipeline_id) = pipeline_id {
if pipeline_id == doc_id && task_duration.as_nanos() > MAX_TASK_NS.into() {
if self.print_pwm {
println!(
"Task took longer than max allowed ({:?}) {:?}",
category,
task_duration.as_nanos()
);
}
doc.start_tti();
}
}
doc.record_tti_if_necessary();
}
value
}
fn handle_msg_from_constellation(&self, msg: ConstellationControlMsg, can_gc: CanGc) {
match msg {
ConstellationControlMsg::StopDelayingLoadEventsMode(pipeline_id) => {
self.handle_stop_delaying_load_events_mode(pipeline_id)
},
ConstellationControlMsg::NavigationResponse(pipeline_id, fetch_data) => {
match fetch_data {
FetchResponseMsg::ProcessResponse(request_id, metadata) => {
self.handle_fetch_metadata(pipeline_id, request_id, metadata)
},
FetchResponseMsg::ProcessResponseChunk(request_id, chunk) => {
self.handle_fetch_chunk(pipeline_id, request_id, chunk)
},
FetchResponseMsg::ProcessResponseEOF(request_id, eof) => {
self.handle_fetch_eof(pipeline_id, request_id, eof)
},
_ => unreachable!(),
};
},
ConstellationControlMsg::NavigateIframe(
parent_pipeline_id,
browsing_context_id,
load_data,
history_handling,
) => self.handle_navigate_iframe(
parent_pipeline_id,
browsing_context_id,
load_data,
history_handling,
can_gc,
),
ConstellationControlMsg::UnloadDocument(pipeline_id) => {
self.handle_unload_document(pipeline_id, can_gc)
},
ConstellationControlMsg::ResizeInactive(id, new_size) => {
self.handle_resize_inactive_msg(id, new_size)
},
ConstellationControlMsg::ThemeChange(_, theme) => {
self.handle_theme_change_msg(theme);
},
ConstellationControlMsg::GetTitle(pipeline_id) => {
self.handle_get_title_msg(pipeline_id)
},
ConstellationControlMsg::SetDocumentActivity(pipeline_id, activity) => {
self.handle_set_document_activity_msg(pipeline_id, activity)
},
ConstellationControlMsg::SetThrottled(pipeline_id, throttled) => {
self.handle_set_throttled_msg(pipeline_id, throttled)
},
ConstellationControlMsg::SetThrottledInContainingIframe(
parent_pipeline_id,
browsing_context_id,
throttled,
) => self.handle_set_throttled_in_containing_iframe_msg(
parent_pipeline_id,
browsing_context_id,
throttled,
),
ConstellationControlMsg::PostMessage {
target: target_pipeline_id,
source: source_pipeline_id,
source_browsing_context,
target_origin: origin,
source_origin,
data,
} => self.handle_post_message_msg(
target_pipeline_id,
source_pipeline_id,
source_browsing_context,
origin,
source_origin,
data,
),
ConstellationControlMsg::UpdatePipelineId(
parent_pipeline_id,
browsing_context_id,
top_level_browsing_context_id,
new_pipeline_id,
reason,
) => self.handle_update_pipeline_id(
parent_pipeline_id,
browsing_context_id,
top_level_browsing_context_id,
new_pipeline_id,
reason,
can_gc,
),
ConstellationControlMsg::UpdateHistoryState(pipeline_id, history_state_id, url) => {
self.handle_update_history_state_msg(pipeline_id, history_state_id, url, can_gc)
},
ConstellationControlMsg::RemoveHistoryStates(pipeline_id, history_states) => {
self.handle_remove_history_states(pipeline_id, history_states)
},
ConstellationControlMsg::FocusIFrame(parent_pipeline_id, frame_id) => {
self.handle_focus_iframe_msg(parent_pipeline_id, frame_id, can_gc)
},
ConstellationControlMsg::WebDriverScriptCommand(pipeline_id, msg) => {
self.handle_webdriver_msg(pipeline_id, msg, can_gc)
},
ConstellationControlMsg::WebFontLoaded(pipeline_id, success) => {
self.handle_web_font_loaded(pipeline_id, success)
},
ConstellationControlMsg::DispatchIFrameLoadEvent {
target: browsing_context_id,
parent: parent_id,
child: child_id,
} => self.handle_iframe_load_event(parent_id, browsing_context_id, child_id, can_gc),
ConstellationControlMsg::DispatchStorageEvent(
pipeline_id,
storage,
url,
key,
old_value,
new_value,
) => self.handle_storage_event(pipeline_id, storage, url, key, old_value, new_value),
ConstellationControlMsg::ReportCSSError(pipeline_id, filename, line, column, msg) => {
self.handle_css_error_reporting(pipeline_id, filename, line, column, msg)
},
ConstellationControlMsg::Reload(pipeline_id) => self.handle_reload(pipeline_id, can_gc),
ConstellationControlMsg::ExitPipeline(pipeline_id, discard_browsing_context) => {
self.handle_exit_pipeline_msg(pipeline_id, discard_browsing_context, can_gc)
},
ConstellationControlMsg::PaintMetric(pipeline_id, metric_type, metric_value) => {
self.handle_paint_metric(pipeline_id, metric_type, metric_value, can_gc)
},
ConstellationControlMsg::MediaSessionAction(pipeline_id, action) => {
self.handle_media_session_action(pipeline_id, action, can_gc)
},
#[cfg(feature = "webgpu")]
ConstellationControlMsg::SetWebGPUPort(port) => {
*self.receivers.webgpu_receiver.borrow_mut() =
ROUTER.route_ipc_receiver_to_new_crossbeam_receiver(port);
},
msg @ ConstellationControlMsg::AttachLayout(..) |
msg @ ConstellationControlMsg::Viewport(..) |
msg @ ConstellationControlMsg::Resize(..) |
msg @ ConstellationControlMsg::ExitFullScreen(..) |
msg @ ConstellationControlMsg::SendEvent(..) |
msg @ ConstellationControlMsg::TickAllAnimations(..) |
msg @ ConstellationControlMsg::ExitScriptThread => {
panic!("should have handled {:?} already", msg)
},
ConstellationControlMsg::SetScrollStates(pipeline_id, scroll_states) => {
self.handle_set_scroll_states_msg(pipeline_id, scroll_states)
},
ConstellationControlMsg::SetEpochPaintTime(pipeline_id, epoch, time) => {
self.handle_set_epoch_paint_time(pipeline_id, epoch, time)
},
}
}
fn handle_set_scroll_states_msg(
&self,
pipeline_id: PipelineId,
scroll_states: Vec<ScrollState>,
) {
let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
warn!("Received scroll states for closed pipeline {pipeline_id}");
return;
};
self.profile_event(
ScriptThreadEventCategory::SetScrollState,
Some(pipeline_id),
|| {
window.layout_mut().set_scroll_states(&scroll_states);
let mut scroll_offsets = HashMap::new();
for scroll_state in scroll_states.into_iter() {
let scroll_offset = scroll_state.scroll_offset;
if scroll_state.scroll_id.is_root() {
window.update_viewport_for_scroll(-scroll_offset.x, -scroll_offset.y);
} else if let Some(node_id) =
node_id_from_scroll_id(scroll_state.scroll_id.0 as usize)
{
scroll_offsets.insert(OpaqueNode(node_id), -scroll_offset);
}
}
window.set_scroll_offsets(scroll_offsets)
},
)
}
fn handle_set_epoch_paint_time(
&self,
pipeline_id: PipelineId,
epoch: Epoch,
time: CrossProcessInstant,
) {
let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
warn!("Received set epoch paint time message for closed pipeline {pipeline_id}.");
return;
};
window.layout_mut().set_epoch_paint_time(epoch, time);
}
#[cfg(feature = "webgpu")]
fn handle_msg_from_webgpu_server(&self, msg: WebGPUMsg, can_gc: CanGc) {
match msg {
WebGPUMsg::FreeAdapter(id) => self.gpu_id_hub.free_adapter_id(id),
WebGPUMsg::FreeDevice {
device_id,
pipeline_id,
} => {
self.gpu_id_hub.free_device_id(device_id);
if let Some(global) = self.documents.borrow().find_global(pipeline_id) {
global.remove_gpu_device(WebGPUDevice(device_id));
} },
WebGPUMsg::FreeBuffer(id) => self.gpu_id_hub.free_buffer_id(id),
WebGPUMsg::FreePipelineLayout(id) => self.gpu_id_hub.free_pipeline_layout_id(id),
WebGPUMsg::FreeComputePipeline(id) => self.gpu_id_hub.free_compute_pipeline_id(id),
WebGPUMsg::FreeBindGroup(id) => self.gpu_id_hub.free_bind_group_id(id),
WebGPUMsg::FreeBindGroupLayout(id) => self.gpu_id_hub.free_bind_group_layout_id(id),
WebGPUMsg::FreeCommandBuffer(id) => self
.gpu_id_hub
.free_command_buffer_id(id.into_command_encoder_id()),
WebGPUMsg::FreeSampler(id) => self.gpu_id_hub.free_sampler_id(id),
WebGPUMsg::FreeShaderModule(id) => self.gpu_id_hub.free_shader_module_id(id),
WebGPUMsg::FreeRenderBundle(id) => self.gpu_id_hub.free_render_bundle_id(id),
WebGPUMsg::FreeRenderPipeline(id) => self.gpu_id_hub.free_render_pipeline_id(id),
WebGPUMsg::FreeTexture(id) => self.gpu_id_hub.free_texture_id(id),
WebGPUMsg::FreeTextureView(id) => self.gpu_id_hub.free_texture_view_id(id),
WebGPUMsg::FreeComputePass(id) => self.gpu_id_hub.free_compute_pass_id(id),
WebGPUMsg::FreeRenderPass(id) => self.gpu_id_hub.free_render_pass_id(id),
WebGPUMsg::Exit => {
*self.receivers.webgpu_receiver.borrow_mut() = crossbeam_channel::never()
},
WebGPUMsg::DeviceLost {
pipeline_id,
device,
reason,
msg,
} => {
let global = self.documents.borrow().find_global(pipeline_id).unwrap();
global.gpu_device_lost(device, reason, msg);
},
WebGPUMsg::UncapturedError {
device,
pipeline_id,
error,
} => {
let global = self.documents.borrow().find_global(pipeline_id).unwrap();
let _ac = enter_realm(&*global);
global.handle_uncaptured_gpu_error(device, error, can_gc);
},
_ => {},
}
}
fn handle_msg_from_script(&self, msg: MainThreadScriptMsg) {
match msg {
MainThreadScriptMsg::Common(CommonScriptMsg::Task(_, task, pipeline_id, _)) => {
let _realm = pipeline_id.and_then(|id| {
let global = self.documents.borrow().find_global(id);
global.map(|global| enter_realm(&*global))
});
task.run_box()
},
MainThreadScriptMsg::Common(CommonScriptMsg::CollectReports(chan)) => {
self.collect_reports(chan)
},
MainThreadScriptMsg::WorkletLoaded(pipeline_id) => {
self.handle_worklet_loaded(pipeline_id)
},
MainThreadScriptMsg::RegisterPaintWorklet {
pipeline_id,
name,
properties,
painter,
} => self.handle_register_paint_worklet(pipeline_id, name, properties, painter),
MainThreadScriptMsg::Inactive => {},
MainThreadScriptMsg::WakeUp => {},
}
}
fn handle_msg_from_devtools(&self, msg: DevtoolScriptControlMsg, can_gc: CanGc) {
let documents = self.documents.borrow();
match msg {
DevtoolScriptControlMsg::EvaluateJS(id, s, reply) => match documents.find_window(id) {
Some(window) => {
let global = window.upcast::<GlobalScope>();
let _aes = AutoEntryScript::new(global);
devtools::handle_evaluate_js(global, s, reply, can_gc)
},
None => warn!("Message sent to closed pipeline {}.", id),
},
DevtoolScriptControlMsg::GetRootNode(id, reply) => {
devtools::handle_get_root_node(&documents, id, reply)
},
DevtoolScriptControlMsg::GetDocumentElement(id, reply) => {
devtools::handle_get_document_element(&documents, id, reply)
},
DevtoolScriptControlMsg::GetChildren(id, node_id, reply) => {
devtools::handle_get_children(&documents, id, node_id, reply)
},
DevtoolScriptControlMsg::GetAttributeStyle(id, node_id, reply) => {
devtools::handle_get_attribute_style(&documents, id, node_id, reply, can_gc)
},
DevtoolScriptControlMsg::GetStylesheetStyle(
id,
node_id,
selector,
stylesheet,
reply,
) => devtools::handle_get_stylesheet_style(
&documents, id, node_id, selector, stylesheet, reply, can_gc,
),
DevtoolScriptControlMsg::GetSelectors(id, node_id, reply) => {
devtools::handle_get_selectors(&documents, id, node_id, reply)
},
DevtoolScriptControlMsg::GetComputedStyle(id, node_id, reply) => {
devtools::handle_get_computed_style(&documents, id, node_id, reply, can_gc)
},
DevtoolScriptControlMsg::GetLayout(id, node_id, reply) => {
devtools::handle_get_layout(&documents, id, node_id, reply, can_gc)
},
DevtoolScriptControlMsg::ModifyAttribute(id, node_id, modifications) => {
devtools::handle_modify_attribute(&documents, id, node_id, modifications, can_gc)
},
DevtoolScriptControlMsg::ModifyRule(id, node_id, modifications) => {
devtools::handle_modify_rule(&documents, id, node_id, modifications, can_gc)
},
DevtoolScriptControlMsg::WantsLiveNotifications(id, to_send) => match documents
.find_window(id)
{
Some(window) => devtools::handle_wants_live_notifications(window.upcast(), to_send),
None => warn!("Message sent to closed pipeline {}.", id),
},
DevtoolScriptControlMsg::SetTimelineMarkers(id, marker_types, reply) => {
devtools::handle_set_timeline_markers(&documents, id, marker_types, reply)
},
DevtoolScriptControlMsg::DropTimelineMarkers(id, marker_types) => {
devtools::handle_drop_timeline_markers(&documents, id, marker_types)
},
DevtoolScriptControlMsg::RequestAnimationFrame(id, name) => {
devtools::handle_request_animation_frame(&documents, id, name)
},
DevtoolScriptControlMsg::Reload(id) => devtools::handle_reload(&documents, id, can_gc),
DevtoolScriptControlMsg::GetCssDatabase(reply) => {
devtools::handle_get_css_database(reply)
},
}
}
fn handle_msg_from_image_cache(&self, (id, response): (PipelineId, PendingImageResponse)) {
let window = self.documents.borrow().find_window(id);
if let Some(ref window) = window {
window.pending_image_notification(response);
}
}
fn handle_webdriver_msg(
&self,
pipeline_id: PipelineId,
msg: WebDriverScriptCommand,
can_gc: CanGc,
) {
match msg {
WebDriverScriptCommand::ExecuteScript(script, reply) => {
let window = self.documents.borrow().find_window(pipeline_id);
return webdriver_handlers::handle_execute_script(window, script, reply, can_gc);
},
WebDriverScriptCommand::ExecuteAsyncScript(script, reply) => {
let window = self.documents.borrow().find_window(pipeline_id);
return webdriver_handlers::handle_execute_async_script(
window, script, reply, can_gc,
);
},
_ => (),
}
let documents = self.documents.borrow();
match msg {
WebDriverScriptCommand::AddCookie(params, reply) => {
webdriver_handlers::handle_add_cookie(&documents, pipeline_id, params, reply)
},
WebDriverScriptCommand::DeleteCookies(reply) => {
webdriver_handlers::handle_delete_cookies(&documents, pipeline_id, reply)
},
WebDriverScriptCommand::FindElementCSS(selector, reply) => {
webdriver_handlers::handle_find_element_css(
&documents,
pipeline_id,
selector,
reply,
)
},
WebDriverScriptCommand::FindElementLinkText(selector, partial, reply) => {
webdriver_handlers::handle_find_element_link_text(
&documents,
pipeline_id,
selector,
partial,
reply,
)
},
WebDriverScriptCommand::FindElementTagName(selector, reply) => {
webdriver_handlers::handle_find_element_tag_name(
&documents,
pipeline_id,
selector,
reply,
)
},
WebDriverScriptCommand::FindElementsCSS(selector, reply) => {
webdriver_handlers::handle_find_elements_css(
&documents,
pipeline_id,
selector,
reply,
)
},
WebDriverScriptCommand::FindElementsLinkText(selector, partial, reply) => {
webdriver_handlers::handle_find_elements_link_text(
&documents,
pipeline_id,
selector,
partial,
reply,
)
},
WebDriverScriptCommand::FindElementsTagName(selector, reply) => {
webdriver_handlers::handle_find_elements_tag_name(
&documents,
pipeline_id,
selector,
reply,
)
},
WebDriverScriptCommand::FindElementElementCSS(selector, element_id, reply) => {
webdriver_handlers::handle_find_element_element_css(
&documents,
pipeline_id,
element_id,
selector,
reply,
)
},
WebDriverScriptCommand::FindElementElementLinkText(
selector,
element_id,
partial,
reply,
) => webdriver_handlers::handle_find_element_element_link_text(
&documents,
pipeline_id,
element_id,
selector,
partial,
reply,
),
WebDriverScriptCommand::FindElementElementTagName(selector, element_id, reply) => {
webdriver_handlers::handle_find_element_element_tag_name(
&documents,
pipeline_id,
element_id,
selector,
reply,
)
},
WebDriverScriptCommand::FindElementElementsCSS(selector, element_id, reply) => {
webdriver_handlers::handle_find_element_elements_css(
&documents,
pipeline_id,
element_id,
selector,
reply,
)
},
WebDriverScriptCommand::FindElementElementsLinkText(
selector,
element_id,
partial,
reply,
) => webdriver_handlers::handle_find_element_elements_link_text(
&documents,
pipeline_id,
element_id,
selector,
partial,
reply,
),
WebDriverScriptCommand::FindElementElementsTagName(selector, element_id, reply) => {
webdriver_handlers::handle_find_element_elements_tag_name(
&documents,
pipeline_id,
element_id,
selector,
reply,
)
},
WebDriverScriptCommand::FocusElement(element_id, reply) => {
webdriver_handlers::handle_focus_element(
&documents,
pipeline_id,
element_id,
reply,
can_gc,
)
},
WebDriverScriptCommand::ElementClick(element_id, reply) => {
webdriver_handlers::handle_element_click(
&documents,
pipeline_id,
element_id,
reply,
can_gc,
)
},
WebDriverScriptCommand::GetActiveElement(reply) => {
webdriver_handlers::handle_get_active_element(&documents, pipeline_id, reply)
},
WebDriverScriptCommand::GetPageSource(reply) => {
webdriver_handlers::handle_get_page_source(&documents, pipeline_id, reply, can_gc)
},
WebDriverScriptCommand::GetCookies(reply) => {
webdriver_handlers::handle_get_cookies(&documents, pipeline_id, reply)
},
WebDriverScriptCommand::GetCookie(name, reply) => {
webdriver_handlers::handle_get_cookie(&documents, pipeline_id, name, reply)
},
WebDriverScriptCommand::GetElementTagName(node_id, reply) => {
webdriver_handlers::handle_get_name(&documents, pipeline_id, node_id, reply)
},
WebDriverScriptCommand::GetElementAttribute(node_id, name, reply) => {
webdriver_handlers::handle_get_attribute(
&documents,
pipeline_id,
node_id,
name,
reply,
)
},
WebDriverScriptCommand::GetElementProperty(node_id, name, reply) => {
webdriver_handlers::handle_get_property(
&documents,
pipeline_id,
node_id,
name,
reply,
)
},
WebDriverScriptCommand::GetElementCSS(node_id, name, reply) => {
webdriver_handlers::handle_get_css(
&documents,
pipeline_id,
node_id,
name,
reply,
can_gc,
)
},
WebDriverScriptCommand::GetElementRect(node_id, reply) => {
webdriver_handlers::handle_get_rect(&documents, pipeline_id, node_id, reply, can_gc)
},
WebDriverScriptCommand::GetBoundingClientRect(node_id, reply) => {
webdriver_handlers::handle_get_bounding_client_rect(
&documents,
pipeline_id,
node_id,
reply,
can_gc,
)
},
WebDriverScriptCommand::GetElementText(node_id, reply) => {
webdriver_handlers::handle_get_text(&documents, pipeline_id, node_id, reply)
},
WebDriverScriptCommand::GetElementInViewCenterPoint(node_id, reply) => {
webdriver_handlers::handle_get_element_in_view_center_point(
&documents,
pipeline_id,
node_id,
reply,
can_gc,
)
},
WebDriverScriptCommand::GetBrowsingContextId(webdriver_frame_id, reply) => {
webdriver_handlers::handle_get_browsing_context_id(
&documents,
pipeline_id,
webdriver_frame_id,
reply,
)
},
WebDriverScriptCommand::GetUrl(reply) => {
webdriver_handlers::handle_get_url(&documents, pipeline_id, reply)
},
WebDriverScriptCommand::IsEnabled(element_id, reply) => {
webdriver_handlers::handle_is_enabled(&documents, pipeline_id, element_id, reply)
},
WebDriverScriptCommand::IsSelected(element_id, reply) => {
webdriver_handlers::handle_is_selected(&documents, pipeline_id, element_id, reply)
},
WebDriverScriptCommand::GetTitle(reply) => {
webdriver_handlers::handle_get_title(&documents, pipeline_id, reply)
},
_ => (),
}
}
pub(crate) fn handle_resize_message(
&self,
id: PipelineId,
size: WindowSizeData,
size_type: WindowSizeType,
) {
self.profile_event(ScriptThreadEventCategory::Resize, Some(id), || {
let window = self.documents.borrow().find_window(id);
if let Some(ref window) = window {
window.add_resize_event(size, size_type);
return;
}
let mut loads = self.incomplete_loads.borrow_mut();
if let Some(ref mut load) = loads.iter_mut().find(|load| load.pipeline_id == id) {
load.window_size = size;
}
})
}
fn handle_theme_change_msg(&self, theme: Theme) {
for (_, document) in self.documents.borrow().iter() {
document.window().handle_theme_change(theme);
}
}
fn handle_exit_fullscreen(&self, id: PipelineId, can_gc: CanGc) {
let document = self.documents.borrow().find_document(id);
if let Some(document) = document {
let _ac = enter_realm(&*document);
document.exit_fullscreen(can_gc);
}
}
fn handle_viewport(&self, id: PipelineId, rect: Rect<f32>) {
let document = self.documents.borrow().find_document(id);
if let Some(document) = document {
document.window().set_page_clip_rect_with_new_viewport(rect);
return;
}
let loads = self.incomplete_loads.borrow();
if loads.iter().any(|load| load.pipeline_id == id) {
return;
}
warn!("Page rect message sent to nonexistent pipeline");
}
fn handle_new_layout(&self, new_layout_info: NewLayoutInfo, origin: MutableOrigin) {
let NewLayoutInfo {
parent_info,
new_pipeline_id,
browsing_context_id,
top_level_browsing_context_id,
opener,
load_data,
window_size,
} = new_layout_info;
let new_load = InProgressLoad::new(
new_pipeline_id,
browsing_context_id,
top_level_browsing_context_id,
parent_info,
opener,
window_size,
load_data.url.clone(),
origin,
load_data.inherited_secure_context,
);
if load_data.url.as_str() == "about:blank" {
self.start_page_load_about_blank(new_load, load_data);
} else if load_data.url.as_str() == "about:srcdoc" {
self.page_load_about_srcdoc(new_load, load_data);
} else {
self.pre_page_load(new_load, load_data);
}
}
fn collect_reports(&self, reports_chan: ReportsChan) {
let documents = self.documents.borrow();
let urls = itertools::join(documents.iter().map(|(_, d)| d.url().to_string()), ", ");
let mut reports = self.get_cx().get_reports(format!("url({})", urls));
for (_, document) in documents.iter() {
document.window().layout().collect_reports(&mut reports);
}
reports_chan.send(reports);
}
fn handle_set_throttled_in_containing_iframe_msg(
&self,
parent_pipeline_id: PipelineId,
browsing_context_id: BrowsingContextId,
throttled: bool,
) {
let iframe = self
.documents
.borrow()
.find_iframe(parent_pipeline_id, browsing_context_id);
if let Some(iframe) = iframe {
iframe.set_throttled(throttled);
}
}
fn handle_set_throttled_msg(&self, id: PipelineId, throttled: bool) {
self.senders
.pipeline_to_constellation_sender
.send((id, ScriptMsg::SetThrottledComplete(throttled)))
.unwrap();
let window = self.documents.borrow().find_window(id);
match window {
Some(window) => {
window.set_throttled(throttled);
return;
},
None => {
let mut loads = self.incomplete_loads.borrow_mut();
if let Some(ref mut load) = loads.iter_mut().find(|load| load.pipeline_id == id) {
load.throttled = throttled;
return;
}
},
}
warn!("SetThrottled sent to nonexistent pipeline");
}
fn handle_set_document_activity_msg(&self, id: PipelineId, activity: DocumentActivity) {
debug!(
"Setting activity of {} to be {:?} in {:?}.",
id,
activity,
thread::current().name()
);
let document = self.documents.borrow().find_document(id);
if let Some(document) = document {
document.set_activity(activity);
return;
}
let mut loads = self.incomplete_loads.borrow_mut();
if let Some(ref mut load) = loads.iter_mut().find(|load| load.pipeline_id == id) {
load.activity = activity;
return;
}
warn!("change of activity sent to nonexistent pipeline");
}
fn handle_focus_iframe_msg(
&self,
parent_pipeline_id: PipelineId,
browsing_context_id: BrowsingContextId,
can_gc: CanGc,
) {
let document = self
.documents
.borrow()
.find_document(parent_pipeline_id)
.unwrap();
let iframes = document.iframes();
if let Some(iframe) = iframes.get(browsing_context_id) {
document.request_focus(Some(iframe.element.upcast()), FocusType::Parent, can_gc);
}
}
fn handle_post_message_msg(
&self,
pipeline_id: PipelineId,
source_pipeline_id: PipelineId,
source_browsing_context: TopLevelBrowsingContextId,
origin: Option<ImmutableOrigin>,
source_origin: ImmutableOrigin,
data: StructuredSerializedData,
) {
let window = self.documents.borrow().find_window(pipeline_id);
match window {
None => warn!("postMessage after target pipeline {} closed.", pipeline_id),
Some(window) => {
let source = match self.remote_window_proxy(
&window.global(),
source_browsing_context,
source_pipeline_id,
None,
) {
None => {
return warn!(
"postMessage after source pipeline {} closed.",
source_pipeline_id,
);
},
Some(source) => source,
};
window.post_message(origin, source_origin, &source, data)
},
}
}
fn handle_stop_delaying_load_events_mode(&self, pipeline_id: PipelineId) {
let window = self.documents.borrow().find_window(pipeline_id);
if let Some(window) = window {
match window.undiscarded_window_proxy() {
Some(window_proxy) => window_proxy.stop_delaying_load_events_mode(),
None => warn!(
"Attempted to take {} of 'delaying-load-events-mode' after having been discarded.",
pipeline_id
),
};
}
}
fn handle_unload_document(&self, pipeline_id: PipelineId, can_gc: CanGc) {
let document = self.documents.borrow().find_document(pipeline_id);
if let Some(document) = document {
document.unload(false, can_gc);
}
}
fn handle_update_pipeline_id(
&self,
parent_pipeline_id: PipelineId,
browsing_context_id: BrowsingContextId,
top_level_browsing_context_id: TopLevelBrowsingContextId,
new_pipeline_id: PipelineId,
reason: UpdatePipelineIdReason,
can_gc: CanGc,
) {
let frame_element = self
.documents
.borrow()
.find_iframe(parent_pipeline_id, browsing_context_id);
if let Some(frame_element) = frame_element {
frame_element.update_pipeline_id(new_pipeline_id, reason, can_gc);
}
if let Some(window) = self.documents.borrow().find_window(new_pipeline_id) {
let _ = self.local_window_proxy(
&window,
browsing_context_id,
top_level_browsing_context_id,
Some(parent_pipeline_id),
None,
);
}
}
fn handle_update_history_state_msg(
&self,
pipeline_id: PipelineId,
history_state_id: Option<HistoryStateId>,
url: ServoUrl,
can_gc: CanGc,
) {
let window = self.documents.borrow().find_window(pipeline_id);
match window {
None => {
warn!(
"update history state after pipeline {} closed.",
pipeline_id
);
},
Some(window) => window
.History()
.activate_state(history_state_id, url, can_gc),
}
}
fn handle_remove_history_states(
&self,
pipeline_id: PipelineId,
history_states: Vec<HistoryStateId>,
) {
let window = self.documents.borrow().find_window(pipeline_id);
match window {
None => {
warn!(
"update history state after pipeline {} closed.",
pipeline_id
);
},
Some(window) => window.History().remove_states(history_states),
}
}
fn handle_resize_inactive_msg(&self, id: PipelineId, new_size: WindowSizeData) {
let window = self.documents.borrow().find_window(id)
.expect("ScriptThread: received a resize msg for a pipeline not in this script thread. This is a bug.");
window.set_window_size(new_size);
}
fn handle_page_headers_available(
&self,
id: &PipelineId,
metadata: Option<Metadata>,
can_gc: CanGc,
) -> Option<DomRoot<ServoParser>> {
let idx = self
.incomplete_loads
.borrow()
.iter()
.position(|load| load.pipeline_id == *id);
match idx {
Some(idx) => {
let is20x = match metadata {
Some(ref metadata) => metadata.status.in_range(204..=205),
_ => false,
};
if is20x {
if let Some(window) = self.documents.borrow().find_window(*id) {
let window_proxy = window.window_proxy();
if window_proxy.parent().is_some() {
window_proxy.stop_delaying_load_events_mode();
}
}
self.senders
.pipeline_to_constellation_sender
.send((*id, ScriptMsg::AbortLoadUrl))
.unwrap();
return None;
};
let load = self.incomplete_loads.borrow_mut().remove(idx);
metadata.map(|meta| self.load(meta, load, can_gc))
},
None => {
assert!(self.closed_pipelines.borrow().contains(id));
None
},
}
}
fn handle_get_title_msg(&self, pipeline_id: PipelineId) {
let document = match self.documents.borrow().find_document(pipeline_id) {
Some(document) => document,
None => return warn!("Message sent to closed pipeline {}.", pipeline_id),
};
document.send_title_to_embedder();
}
fn handle_exit_pipeline_msg(
&self,
id: PipelineId,
discard_bc: DiscardBrowsingContext,
can_gc: CanGc,
) {
debug!("{id}: Starting pipeline exit.");
self.closed_pipelines.borrow_mut().insert(id);
let document = self.documents.borrow_mut().remove(id);
if let Some(document) = document {
debug_assert!(!self
.incomplete_loads
.borrow()
.iter()
.any(|load| load.pipeline_id == id));
if let Some(parser) = document.get_current_parser() {
parser.abort(can_gc);
}
debug!("{id}: Shutting down layout");
document.window().layout_mut().exit_now();
debug!("{id}: Sending PipelineExited message to constellation");
self.senders
.pipeline_to_constellation_sender
.send((id, ScriptMsg::PipelineExited))
.ok();
debug!("{id}: Clearing animations");
document.animations().clear();
if let Some(target) = self.topmost_mouse_over_target.get() {
if target.upcast::<Node>().owner_doc() == document {
self.topmost_mouse_over_target.set(None);
}
}
let window = document.window();
if discard_bc == DiscardBrowsingContext::Yes {
window.discard_browsing_context();
}
debug!("{id}: Clearing JavaScript runtime");
window.clear_js_runtime();
}
debug!("{id}: Finished pipeline exit");
}
fn handle_exit_script_thread_msg(&self, can_gc: CanGc) {
debug!("Exiting script thread.");
let mut pipeline_ids = Vec::new();
pipeline_ids.extend(
self.incomplete_loads
.borrow()
.iter()
.next()
.map(|load| load.pipeline_id),
);
pipeline_ids.extend(
self.documents
.borrow()
.iter()
.next()
.map(|(pipeline_id, _)| pipeline_id),
);
for pipeline_id in pipeline_ids {
self.handle_exit_pipeline_msg(pipeline_id, DiscardBrowsingContext::Yes, can_gc);
}
self.background_hang_monitor.unregister();
if opts::multiprocess() {
debug!("Exiting IPC router thread in script thread.");
ROUTER.shutdown();
}
debug!("Exited script thread.");
}
pub fn handle_tick_all_animations_for_testing(id: PipelineId) {
with_script_thread(|script_thread| {
let Some(document) = script_thread.documents.borrow().find_document(id) else {
warn!("Animation tick for tests for closed pipeline {id}.");
return;
};
document.maybe_mark_animating_nodes_as_dirty();
});
}
fn handle_web_font_loaded(&self, pipeline_id: PipelineId, _success: bool) {
let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
warn!("Web font loaded in closed pipeline {}.", pipeline_id);
return;
};
document.dirty_all_nodes();
}
fn handle_worklet_loaded(&self, pipeline_id: PipelineId) {
if let Some(document) = self.documents.borrow().find_document(pipeline_id) {
document.set_needs_paint(true)
}
}
fn handle_storage_event(
&self,
pipeline_id: PipelineId,
storage_type: StorageType,
url: ServoUrl,
key: Option<String>,
old_value: Option<String>,
new_value: Option<String>,
) {
let window = match self.documents.borrow().find_window(pipeline_id) {
None => return warn!("Storage event sent to closed pipeline {}.", pipeline_id),
Some(window) => window,
};
let storage = match storage_type {
StorageType::Local => window.LocalStorage(),
StorageType::Session => window.SessionStorage(),
};
storage.queue_storage_event(url, key, old_value, new_value);
}
fn handle_iframe_load_event(
&self,
parent_id: PipelineId,
browsing_context_id: BrowsingContextId,
child_id: PipelineId,
can_gc: CanGc,
) {
let iframe = self
.documents
.borrow()
.find_iframe(parent_id, browsing_context_id);
match iframe {
Some(iframe) => iframe.iframe_load_event_steps(child_id, can_gc),
None => warn!("Message sent to closed pipeline {}.", parent_id),
}
}
fn ask_constellation_for_browsing_context_info(
&self,
pipeline_id: PipelineId,
) -> Option<(BrowsingContextId, Option<PipelineId>)> {
let (result_sender, result_receiver) = ipc::channel().unwrap();
let msg = ScriptMsg::GetBrowsingContextInfo(pipeline_id, result_sender);
self.senders
.pipeline_to_constellation_sender
.send((pipeline_id, msg))
.expect("Failed to send to constellation.");
result_receiver
.recv()
.expect("Failed to get browsing context info from constellation.")
}
fn ask_constellation_for_top_level_info(
&self,
sender_pipeline: PipelineId,
browsing_context_id: BrowsingContextId,
) -> Option<TopLevelBrowsingContextId> {
let (result_sender, result_receiver) = ipc::channel().unwrap();
let msg = ScriptMsg::GetTopForBrowsingContext(browsing_context_id, result_sender);
self.senders
.pipeline_to_constellation_sender
.send((sender_pipeline, msg))
.expect("Failed to send to constellation.");
result_receiver
.recv()
.expect("Failed to get top-level id from constellation.")
}
fn remote_window_proxy(
&self,
global_to_clone: &GlobalScope,
top_level_browsing_context_id: TopLevelBrowsingContextId,
pipeline_id: PipelineId,
opener: Option<BrowsingContextId>,
) -> Option<DomRoot<WindowProxy>> {
let (browsing_context_id, parent_pipeline_id) =
self.ask_constellation_for_browsing_context_info(pipeline_id)?;
if let Some(window_proxy) = self.window_proxies.borrow().get(&browsing_context_id) {
return Some(DomRoot::from_ref(window_proxy));
}
let parent_browsing_context = parent_pipeline_id.and_then(|parent_id| {
self.remote_window_proxy(
global_to_clone,
top_level_browsing_context_id,
parent_id,
opener,
)
});
let opener_browsing_context = opener.and_then(ScriptThread::find_window_proxy);
let creator = CreatorBrowsingContextInfo::from(
parent_browsing_context.as_deref(),
opener_browsing_context.as_deref(),
);
let window_proxy = WindowProxy::new_dissimilar_origin(
global_to_clone,
browsing_context_id,
top_level_browsing_context_id,
parent_browsing_context.as_deref(),
opener,
creator,
);
self.window_proxies
.borrow_mut()
.insert(browsing_context_id, Dom::from_ref(&*window_proxy));
Some(window_proxy)
}
fn local_window_proxy(
&self,
window: &Window,
browsing_context_id: BrowsingContextId,
top_level_browsing_context_id: TopLevelBrowsingContextId,
parent_info: Option<PipelineId>,
opener: Option<BrowsingContextId>,
) -> DomRoot<WindowProxy> {
if let Some(window_proxy) = self.window_proxies.borrow().get(&browsing_context_id) {
return DomRoot::from_ref(window_proxy);
}
let iframe = parent_info.and_then(|parent_id| {
self.documents
.borrow()
.find_iframe(parent_id, browsing_context_id)
});
let parent_browsing_context = match (parent_info, iframe.as_ref()) {
(_, Some(iframe)) => Some(iframe.owner_window().window_proxy()),
(Some(parent_id), _) => self.remote_window_proxy(
window.upcast(),
top_level_browsing_context_id,
parent_id,
opener,
),
_ => None,
};
let opener_browsing_context = opener.and_then(ScriptThread::find_window_proxy);
let creator = CreatorBrowsingContextInfo::from(
parent_browsing_context.as_deref(),
opener_browsing_context.as_deref(),
);
let window_proxy = WindowProxy::new(
window,
browsing_context_id,
top_level_browsing_context_id,
iframe.as_deref().map(Castable::upcast),
parent_browsing_context.as_deref(),
opener,
creator,
);
self.window_proxies
.borrow_mut()
.insert(browsing_context_id, Dom::from_ref(&*window_proxy));
window_proxy
}
fn load(
&self,
metadata: Metadata,
incomplete: InProgressLoad,
can_gc: CanGc,
) -> DomRoot<ServoParser> {
let final_url = metadata.final_url.clone();
{
self.senders
.pipeline_to_constellation_sender
.send((
incomplete.pipeline_id,
ScriptMsg::SetFinalUrl(final_url.clone()),
))
.unwrap();
}
debug!(
"ScriptThread: loading {} on pipeline {:?}",
incomplete.url, incomplete.pipeline_id
);
let origin = if final_url.as_str() == "about:blank" || final_url.as_str() == "about:srcdoc"
{
incomplete.origin.clone()
} else {
MutableOrigin::new(final_url.origin())
};
let script_to_constellation_chan = ScriptToConstellationChan {
sender: self.senders.pipeline_to_constellation_sender.clone(),
pipeline_id: incomplete.pipeline_id,
};
let paint_time_metrics = PaintTimeMetrics::new(
incomplete.pipeline_id,
self.senders.time_profiler_sender.clone(),
self.senders.layout_to_constellation_ipc_sender.clone(),
self.senders.constellation_sender.clone(),
final_url.clone(),
incomplete.navigation_start,
);
let layout_config = LayoutConfig {
id: incomplete.pipeline_id,
url: final_url.clone(),
is_iframe: incomplete.parent_info.is_some(),
constellation_chan: self.senders.layout_to_constellation_ipc_sender.clone(),
script_chan: self.senders.constellation_sender.clone(),
image_cache: self.image_cache.clone(),
system_font_service: self.system_font_service.clone(),
resource_threads: self.resource_threads.clone(),
time_profiler_chan: self.senders.time_profiler_sender.clone(),
compositor_api: self.compositor_api.clone(),
paint_time_metrics,
window_size: incomplete.window_size,
};
let window = Window::new(
self.js_runtime.clone(),
self.senders.self_sender.clone(),
self.layout_factory.create(layout_config),
self.senders.image_cache_sender.clone(),
self.image_cache.clone(),
self.resource_threads.clone(),
self.senders.bluetooth_sender.clone(),
self.senders.memory_profiler_sender.clone(),
self.senders.time_profiler_sender.clone(),
self.senders.devtools_server_sender.clone(),
script_to_constellation_chan,
self.senders.constellation_sender.clone(),
incomplete.pipeline_id,
incomplete.parent_info,
incomplete.window_size,
origin.clone(),
final_url.clone(),
incomplete.navigation_start,
self.webgl_chan.as_ref().map(|chan| chan.channel()),
#[cfg(feature = "webxr")]
self.webxr_registry.clone(),
self.microtask_queue.clone(),
self.webrender_document,
self.compositor_api.clone(),
self.relayout_event,
self.prepare_for_screenshot,
self.unminify_js,
self.unminify_css,
self.local_script_source.clone(),
self.userscripts_path.clone(),
self.headless,
self.replace_surrogates,
self.user_agent.clone(),
self.player_context.clone(),
#[cfg(feature = "webgpu")]
self.gpu_id_hub.clone(),
incomplete.inherited_secure_context,
);
let _realm = enter_realm(&*window);
let window_proxy = self.local_window_proxy(
&window,
incomplete.browsing_context_id,
incomplete.top_level_browsing_context_id,
incomplete.parent_info,
incomplete.opener,
);
if window_proxy.parent().is_some() {
window_proxy.stop_delaying_load_events_mode();
}
window.init_window_proxy(&window_proxy);
let last_modified = metadata.headers.as_ref().and_then(|headers| {
headers.typed_get::<LastModified>().map(|tm| {
let tm: SystemTime = tm.into();
let local_time: DateTime<Local> = tm.into();
local_time.format("%m/%d/%Y %H:%M:%S").to_string()
})
});
let loader = DocumentLoader::new_with_threads(
self.resource_threads.clone(),
Some(final_url.clone()),
);
let content_type: Option<Mime> =
metadata.content_type.map(Serde::into_inner).map(Into::into);
let is_html_document = match content_type {
Some(ref mime)
if mime.type_() == mime::APPLICATION && mime.suffix() == Some(mime::XML) =>
{
IsHTMLDocument::NonHTMLDocument
},
Some(ref mime)
if (mime.type_() == mime::TEXT && mime.subtype() == mime::XML) ||
(mime.type_() == mime::APPLICATION && mime.subtype() == mime::XML) =>
{
IsHTMLDocument::NonHTMLDocument
},
_ => IsHTMLDocument::HTMLDocument,
};
let referrer = metadata
.referrer
.as_ref()
.map(|referrer| referrer.clone().into_string());
let is_initial_about_blank = final_url.as_str() == "about:blank";
let document = Document::new(
&window,
HasBrowsingContext::Yes,
Some(final_url.clone()),
origin,
is_html_document,
content_type,
last_modified,
incomplete.activity,
DocumentSource::FromParser,
loader,
referrer,
Some(metadata.status.raw_code()),
incomplete.canceller,
is_initial_about_blank,
can_gc,
);
let referrer_policy = metadata
.headers
.as_deref()
.and_then(|h| h.typed_get::<ReferrerPolicyHeader>())
.into();
document.set_referrer_policy(referrer_policy);
document.set_ready_state(DocumentReadyState::Loading, can_gc);
self.documents
.borrow_mut()
.insert(incomplete.pipeline_id, &document);
window.init_document(&document);
if let Some(frame) = window_proxy
.frame_element()
.and_then(|e| e.downcast::<HTMLIFrameElement>())
{
let parent_pipeline = frame.global().pipeline_id();
self.handle_update_pipeline_id(
parent_pipeline,
window_proxy.browsing_context_id(),
window_proxy.top_level_browsing_context_id(),
incomplete.pipeline_id,
UpdatePipelineIdReason::Navigation,
can_gc,
);
}
self.senders
.pipeline_to_constellation_sender
.send((incomplete.pipeline_id, ScriptMsg::ActivateDocument))
.unwrap();
if incomplete.top_level_browsing_context_id.0 == incomplete.browsing_context_id {
self.notify_devtools(
document.Title(),
final_url.clone(),
(incomplete.browsing_context_id, incomplete.pipeline_id, None),
);
}
document.set_https_state(metadata.https_state);
document.set_navigation_start(incomplete.navigation_start);
if is_html_document == IsHTMLDocument::NonHTMLDocument {
ServoParser::parse_xml_document(&document, None, final_url, can_gc);
} else {
ServoParser::parse_html_document(&document, None, final_url, can_gc);
}
if incomplete.activity == DocumentActivity::FullyActive {
window.resume();
} else {
window.suspend();
}
if incomplete.throttled {
window.set_throttled(true);
}
document.get_current_parser().unwrap()
}
fn notify_devtools(
&self,
title: DOMString,
url: ServoUrl,
(bc, p, w): (BrowsingContextId, PipelineId, Option<WorkerId>),
) {
if let Some(ref chan) = self.senders.devtools_server_sender {
let page_info = DevtoolsPageInfo {
title: String::from(title),
url,
};
chan.send(ScriptToDevtoolsControlMsg::NewGlobal(
(bc, p, w),
self.senders.devtools_client_to_script_thread_sender.clone(),
page_info.clone(),
))
.unwrap();
let state = NavigationState::Stop(p, page_info);
let _ = chan.send(ScriptToDevtoolsControlMsg::Navigate(bc, state));
}
}
fn handle_event(&self, pipeline_id: PipelineId, event: CompositorEvent) {
let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
warn!("Compositor event sent to closed pipeline {pipeline_id}.");
return;
};
document.note_pending_compositor_event(event);
}
#[allow(clippy::too_many_arguments)]
fn handle_mouse_button_event(
&self,
pipeline_id: PipelineId,
mouse_event_type: MouseEventType,
button: MouseButton,
point: Point2D<f32>,
node_address: Option<UntrustedNodeAddress>,
point_in_node: Option<Point2D<f32>>,
pressed_mouse_buttons: u16,
can_gc: CanGc,
) {
let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
warn!("Message sent to closed pipeline {pipeline_id}.");
return;
};
unsafe {
document.handle_mouse_button_event(
button,
point,
mouse_event_type,
node_address,
point_in_node,
pressed_mouse_buttons,
can_gc,
)
}
}
fn handle_touch_event(
&self,
pipeline_id: PipelineId,
event_type: TouchEventType,
identifier: TouchId,
point: Point2D<f32>,
node_address: Option<UntrustedNodeAddress>,
can_gc: CanGc,
) -> TouchEventResult {
let document = match self.documents.borrow().find_document(pipeline_id) {
Some(document) => document,
None => {
warn!("Message sent to closed pipeline {}.", pipeline_id);
return TouchEventResult::Processed(true);
},
};
unsafe { document.handle_touch_event(event_type, identifier, point, node_address, can_gc) }
}
fn handle_wheel_event(
&self,
pipeline_id: PipelineId,
wheel_delta: WheelDelta,
point: Point2D<f32>,
node_address: Option<UntrustedNodeAddress>,
can_gc: CanGc,
) {
let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
warn!("Message sent to closed pipeline {pipeline_id}.");
return;
};
unsafe { document.handle_wheel_event(wheel_delta, point, node_address, can_gc) };
}
fn handle_navigate_iframe(
&self,
parent_pipeline_id: PipelineId,
browsing_context_id: BrowsingContextId,
load_data: LoadData,
history_handling: NavigationHistoryBehavior,
can_gc: CanGc,
) {
let iframe = self
.documents
.borrow()
.find_iframe(parent_pipeline_id, browsing_context_id);
if let Some(iframe) = iframe {
iframe.navigate_or_reload_child_browsing_context(load_data, history_handling, can_gc);
}
}
pub fn eval_js_url(global_scope: &GlobalScope, load_data: &mut LoadData, can_gc: CanGc) {
let encoded = &load_data.url.clone()[Position::BeforePath..];
let script_source = percent_decode(encoded.as_bytes()).decode_utf8_lossy();
let _ac = enter_realm(global_scope);
rooted!(in(*GlobalScope::get_cx()) let mut jsval = UndefinedValue());
global_scope.evaluate_js_on_global_with_result(
&script_source,
jsval.handle_mut(),
ScriptFetchOptions::default_classic_script(global_scope),
global_scope.api_base_url(),
can_gc,
);
load_data.js_eval_result = if jsval.get().is_string() {
unsafe {
let strval = DOMString::from_jsval(
*GlobalScope::get_cx(),
jsval.handle(),
StringificationBehavior::Empty,
);
match strval {
Ok(ConversionResult::Success(s)) => {
Some(JsEvalResult::Ok(String::from(s).as_bytes().to_vec()))
},
_ => None,
}
}
} else {
Some(JsEvalResult::NoContent)
};
load_data.url = ServoUrl::parse("about:blank").unwrap();
}
fn pre_page_load(&self, mut incomplete: InProgressLoad, load_data: LoadData) {
let id = incomplete.pipeline_id;
let top_level_browsing_context_id = incomplete.top_level_browsing_context_id;
let req_init = RequestBuilder::new(load_data.url.clone(), load_data.referrer)
.method(load_data.method)
.destination(Destination::Document)
.mode(RequestMode::Navigate)
.credentials_mode(CredentialsMode::Include)
.use_url_credentials(true)
.pipeline_id(Some(id))
.target_browsing_context_id(Some(top_level_browsing_context_id))
.referrer_policy(load_data.referrer_policy)
.headers(load_data.headers)
.body(load_data.data)
.redirect_mode(RedirectMode::Manual)
.origin(incomplete.origin.immutable().clone())
.crash(load_data.crash);
let context = ParserContext::new(id, load_data.url);
self.incomplete_parser_contexts
.0
.borrow_mut()
.push((id, context));
let cancel_chan = incomplete.canceller.initialize();
self.senders
.pipeline_to_constellation_sender
.send((
id,
ScriptMsg::InitiateNavigateRequest(req_init, cancel_chan),
))
.unwrap();
self.incomplete_loads.borrow_mut().push(incomplete);
}
fn handle_fetch_metadata(
&self,
id: PipelineId,
request_id: RequestId,
fetch_metadata: Result<FetchMetadata, NetworkError>,
) {
match fetch_metadata {
Ok(_) => (),
Err(NetworkError::Crash(..)) => (),
Err(ref e) => {
warn!("Network error: {:?}", e);
},
};
let mut incomplete_parser_contexts = self.incomplete_parser_contexts.0.borrow_mut();
let parser = incomplete_parser_contexts
.iter_mut()
.find(|&&mut (pipeline_id, _)| pipeline_id == id);
if let Some(&mut (_, ref mut ctxt)) = parser {
ctxt.process_response(request_id, fetch_metadata);
}
}
fn handle_fetch_chunk(&self, pipeline_id: PipelineId, request_id: RequestId, chunk: Vec<u8>) {
let mut incomplete_parser_contexts = self.incomplete_parser_contexts.0.borrow_mut();
let parser = incomplete_parser_contexts
.iter_mut()
.find(|&&mut (parser_pipeline_id, _)| parser_pipeline_id == pipeline_id);
if let Some(&mut (_, ref mut ctxt)) = parser {
ctxt.process_response_chunk(request_id, chunk);
}
}
fn handle_fetch_eof(
&self,
id: PipelineId,
request_id: RequestId,
eof: Result<ResourceFetchTiming, NetworkError>,
) {
let idx = self
.incomplete_parser_contexts
.0
.borrow()
.iter()
.position(|&(pipeline_id, _)| pipeline_id == id);
if let Some(idx) = idx {
let (_, mut ctxt) = self.incomplete_parser_contexts.0.borrow_mut().remove(idx);
ctxt.process_response_eof(request_id, eof);
}
}
fn start_page_load_about_blank(&self, incomplete: InProgressLoad, load_data: LoadData) {
let id = incomplete.pipeline_id;
self.incomplete_loads.borrow_mut().push(incomplete);
let url = ServoUrl::parse("about:blank").unwrap();
let mut context = ParserContext::new(id, url.clone());
let mut meta = Metadata::default(url);
meta.set_content_type(Some(&mime::TEXT_HTML));
meta.set_referrer_policy(load_data.referrer_policy);
let chunk = match load_data.js_eval_result {
Some(JsEvalResult::Ok(content)) => content,
Some(JsEvalResult::NoContent) => {
meta.status = http::StatusCode::NO_CONTENT.into();
vec![]
},
None => vec![],
};
let dummy_request_id = RequestId::next();
context.process_response(dummy_request_id, Ok(FetchMetadata::Unfiltered(meta)));
context.process_response_chunk(dummy_request_id, chunk);
context.process_response_eof(
dummy_request_id,
Ok(ResourceFetchTiming::new(ResourceTimingType::None)),
);
}
fn page_load_about_srcdoc(&self, incomplete: InProgressLoad, load_data: LoadData) {
let id = incomplete.pipeline_id;
self.incomplete_loads.borrow_mut().push(incomplete);
let url = ServoUrl::parse("about:srcdoc").unwrap();
let mut context = ParserContext::new(id, url.clone());
let mut meta = Metadata::default(url);
meta.set_content_type(Some(&mime::TEXT_HTML));
meta.set_referrer_policy(load_data.referrer_policy);
let chunk = load_data.srcdoc.into_bytes();
let dummy_request_id = RequestId::next();
context.process_response(dummy_request_id, Ok(FetchMetadata::Unfiltered(meta)));
context.process_response_chunk(dummy_request_id, chunk);
context.process_response_eof(
dummy_request_id,
Ok(ResourceFetchTiming::new(ResourceTimingType::None)),
);
}
fn handle_css_error_reporting(
&self,
pipeline_id: PipelineId,
filename: String,
line: u32,
column: u32,
msg: String,
) {
let sender = match self.senders.devtools_server_sender {
Some(ref sender) => sender,
None => return,
};
if let Some(global) = self.documents.borrow().find_global(pipeline_id) {
if global.live_devtools_updates() {
let css_error = CSSError {
filename,
line,
column,
msg,
};
let message = ScriptToDevtoolsControlMsg::ReportCSSError(pipeline_id, css_error);
sender.send(message).unwrap();
}
}
}
fn handle_reload(&self, pipeline_id: PipelineId, can_gc: CanGc) {
let window = self.documents.borrow().find_window(pipeline_id);
if let Some(window) = window {
window.Location().reload_without_origin_check(can_gc);
}
}
fn handle_paint_metric(
&self,
pipeline_id: PipelineId,
metric_type: ProgressiveWebMetricType,
metric_value: CrossProcessInstant,
can_gc: CanGc,
) {
let window = self.documents.borrow().find_window(pipeline_id);
if let Some(window) = window {
let entry = PerformancePaintTiming::new(
window.upcast::<GlobalScope>(),
metric_type,
metric_value,
);
window
.Performance()
.queue_entry(entry.upcast::<PerformanceEntry>(), can_gc);
}
}
fn handle_media_session_action(
&self,
pipeline_id: PipelineId,
action: MediaSessionActionType,
can_gc: CanGc,
) {
if let Some(window) = self.documents.borrow().find_window(pipeline_id) {
let media_session = window.Navigator().MediaSession();
media_session.handle_action(action, can_gc);
} else {
warn!("No MediaSession for this pipeline ID");
};
}
pub fn enqueue_microtask(job: Microtask) {
with_script_thread(|script_thread| {
script_thread
.microtask_queue
.enqueue(job, script_thread.get_cx());
});
}
fn perform_a_microtask_checkpoint(&self, can_gc: CanGc) {
if self.can_continue_running_inner() {
let globals = self
.documents
.borrow()
.iter()
.map(|(_id, document)| DomRoot::from_ref(document.window().upcast()))
.collect();
self.microtask_queue.checkpoint(
self.get_cx(),
|id| self.documents.borrow().find_global(id),
globals,
can_gc,
)
}
}
}
impl Drop for ScriptThread {
fn drop(&mut self) {
SCRIPT_THREAD_ROOT.with(|root| {
root.set(None);
});
}
}