script: Refactor channels in ScriptThread into receivers and senders (#34776)

Create two new data structures in the `script` crate to hold senders and
receiver:

- `ScriptThreadSenders`: holds all outgoing channels from the
  `ScriptThread` including a channel to the `ScriptThread` itself. The
  ultimate goal with this is to reduce duplication by giving a boxed
  version of this this to `Window`s.
- `ScriptThradReceivers`: holds all incoming channels to the
  `ScriptThread`. This isn't cloenable like the senders. This is used to
  abstract away `recv()` and `try_recv()` methods used to make the
  `ScriptThread` event loop easier to read.

In addition:

- The many duplicated `ScriptThread` self-senders for the `TaskManager`
  have been removed and, in general, a lot of boilerplate is removed as
  well.
- Visibilty of all methods affected by this change is changed to
  `pub(crate)` in order to take advantage of dead code detection. Some
  dead code produced from macros is removed.
- Some conversion code is refactord into implementations of the `From`
  trait.
- The names of channels uses a standard "sender" and "receiver" naming
  as well as trying to be descriptive of where they go in `ScriptThread`
  as well as `InitialScriptState`

Signed-off-by: Martin Robinson <mrobinson@igalia.com>
This commit is contained in:
Martin Robinson 2024-12-26 04:34:54 +01:00 committed by GitHub
parent 1e95712772
commit 5f927a2c28
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
30 changed files with 732 additions and 902 deletions

View file

@ -518,20 +518,20 @@ impl UnprivilegedPipelineContent {
top_level_browsing_context_id: self.top_level_browsing_context_id,
parent_info: self.parent_pipeline_id,
opener: self.opener,
control_chan: self.script_chan.clone(),
control_port: self.script_port,
script_to_constellation_chan: self.script_to_constellation_chan.clone(),
constellation_sender: self.script_chan.clone(),
constellation_receiver: self.script_port,
pipeline_to_constellation_sender: self.script_to_constellation_chan.clone(),
background_hang_monitor_register: background_hang_monitor_register.clone(),
layout_to_constellation_chan: self.layout_to_constellation_chan.clone(),
bluetooth_thread: self.bluetooth_thread,
layout_to_constellation_ipc_sender: self.layout_to_constellation_chan.clone(),
bluetooth_sender: self.bluetooth_thread,
resource_threads: self.resource_threads,
image_cache: image_cache.clone(),
time_profiler_chan: self.time_profiler_chan.clone(),
mem_profiler_chan: self.mem_profiler_chan.clone(),
devtools_chan: self.devtools_ipc_sender,
time_profiler_sender: self.time_profiler_chan.clone(),
memory_profiler_sender: self.mem_profiler_chan.clone(),
devtools_server_sender: self.devtools_ipc_sender,
window_size: self.window_size,
pipeline_namespace_id: self.pipeline_namespace_id,
content_process_shutdown_chan,
content_process_shutdown_sender: content_process_shutdown_chan,
webgl_chan: self.webgl_chan,
webxr_registry: self.webxr_registry,
webrender_document: self.webrender_document,

View file

@ -35,7 +35,7 @@ impl ScriptChan for SendableWorkerScriptChan {
self.sender.send(msg).map_err(|_| ())
}
fn clone(&self) -> Box<dyn ScriptChan + Send> {
fn as_boxed(&self) -> Box<dyn ScriptChan + Send> {
Box::new(SendableWorkerScriptChan {
sender: self.sender.clone(),
worker: self.worker.clone(),
@ -62,7 +62,7 @@ impl ScriptChan for WorkerThreadWorkerChan {
self.sender.send(msg).map_err(|_| ())
}
fn clone(&self) -> Box<dyn ScriptChan + Send> {
fn as_boxed(&self) -> Box<dyn ScriptChan + Send> {
Box::new(WorkerThreadWorkerChan {
sender: self.sender.clone(),
worker: self.worker.clone(),

View file

@ -418,7 +418,7 @@ impl DedicatedWorkerGlobalScope {
worker_url,
devtools_mpsc_port,
runtime,
parent_sender.clone(),
parent_sender.as_boxed(),
own_sender,
receiver,
closing,

View file

@ -185,10 +185,11 @@ use crate::dom::windowproxy::WindowProxy;
use crate::dom::xpathevaluator::XPathEvaluator;
use crate::fetch::FetchCanceller;
use crate::iframe_collection::IFrameCollection;
use crate::messaging::MainThreadScriptMsg;
use crate::network_listener::{NetworkListener, PreInvoke};
use crate::realms::{enter_realm, AlreadyInRealm, InRealm};
use crate::script_runtime::{CanGc, CommonScriptMsg, ScriptThreadEventCategory};
use crate::script_thread::{with_script_thread, MainThreadScriptMsg, ScriptThread};
use crate::script_thread::{with_script_thread, ScriptThread};
use crate::stylesheet_set::StylesheetSetRef;
use crate::task::TaskBox;
use crate::task_source::{TaskSource, TaskSourceName};

View file

@ -127,6 +127,7 @@ use crate::dom::webgpu::identityhub::IdentityHub;
use crate::dom::window::Window;
use crate::dom::workerglobalscope::WorkerGlobalScope;
use crate::dom::workletglobalscope::WorkletGlobalScope;
use crate::messaging::MainThreadScriptChan;
use crate::microtask::{Microtask, MicrotaskQueue, UserMicrotask};
use crate::network_listener::{NetworkListener, PreInvoke};
use crate::realms::{enter_realm, AlreadyInRealm, InRealm};
@ -134,7 +135,7 @@ use crate::script_module::{DynamicModuleList, ModuleScript, ModuleTree, ScriptFe
use crate::script_runtime::{
CanGc, CommonScriptMsg, JSContext as SafeJSContext, ScriptChan, ScriptPort, ThreadSafeJSContext,
};
use crate::script_thread::{with_script_thread, MainThreadScriptChan, ScriptThread};
use crate::script_thread::{with_script_thread, ScriptThread};
use crate::security_manager::CSPViolationReporter;
use crate::task::TaskCanceller;
use crate::task_source::dom_manipulation::DOMManipulationTaskSource;
@ -2581,7 +2582,9 @@ impl GlobalScope {
/// `ScriptChan` to send messages to the event loop of this global scope.
pub fn script_chan(&self) -> Box<dyn ScriptChan + Send> {
if let Some(window) = self.downcast::<Window>() {
return MainThreadScriptChan(window.main_thread_script_chan().clone()).clone();
return Box::new(
MainThreadScriptChan(window.main_thread_script_chan().clone()).clone(),
);
}
if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
return worker.script_chan();

View file

@ -86,7 +86,7 @@ pub struct PaintWorkletGlobalScope {
impl PaintWorkletGlobalScope {
#[allow(unsafe_code)]
pub fn new(
pub(crate) fn new(
runtime: &Runtime,
pipeline_id: PipelineId,
base_url: ServoUrl,

View file

@ -143,7 +143,7 @@ impl ScriptChan for ServiceWorkerChan {
.map_err(|_| ())
}
fn clone(&self) -> Box<dyn ScriptChan + Send> {
fn as_boxed(&self) -> Box<dyn ScriptChan + Send> {
Box::new(ServiceWorkerChan {
sender: self.sender.clone(),
})

View file

@ -31,7 +31,7 @@ pub struct TestWorkletGlobalScope {
impl TestWorkletGlobalScope {
#[allow(unsafe_code)]
pub fn new(
pub(crate) fn new(
runtime: &Runtime,
pipeline_id: PipelineId,
base_url: ServoUrl,

View file

@ -145,15 +145,15 @@ use crate::dom::windowproxy::{WindowProxy, WindowProxyHandler};
use crate::dom::worklet::Worklet;
use crate::dom::workletglobalscope::WorkletGlobalScopeType;
use crate::layout_image::fetch_image_for_layout;
use crate::messaging::{
ImageCacheMsg, MainThreadScriptChan, MainThreadScriptMsg, SendableMainThreadScriptChan,
};
use crate::microtask::MicrotaskQueue;
use crate::realms::{enter_realm, InRealm};
use crate::script_runtime::{
CanGc, CommonScriptMsg, JSContext, Runtime, ScriptChan, ScriptPort, ScriptThreadEventCategory,
};
use crate::script_thread::{
ImageCacheMsg, MainThreadScriptChan, MainThreadScriptMsg, ScriptThread,
SendableMainThreadScriptChan,
};
use crate::script_thread::ScriptThread;
use crate::task_manager::TaskManager;
use crate::task_source::{TaskSource, TaskSourceName};
use crate::timers::{IsInterval, TimerCallback};
@ -453,7 +453,7 @@ impl Window {
self.js_runtime.borrow()
}
pub fn main_thread_script_chan(&self) -> &Sender<MainThreadScriptMsg> {
pub(crate) fn main_thread_script_chan(&self) -> &Sender<MainThreadScriptMsg> {
&self.script_chan.0
}
@ -2683,7 +2683,7 @@ impl Window {
impl Window {
#[allow(unsafe_code)]
#[allow(clippy::too_many_arguments)]
pub fn new(
pub(crate) fn new(
runtime: Rc<Runtime>,
script_chan: MainThreadScriptChan,
task_manager: TaskManager,

View file

@ -49,9 +49,10 @@ use crate::dom::workletglobalscope::{
WorkletGlobalScope, WorkletGlobalScopeInit, WorkletGlobalScopeType, WorkletTask,
};
use crate::fetch::load_whole_resource;
use crate::messaging::MainThreadScriptMsg;
use crate::realms::InRealm;
use crate::script_runtime::{CanGc, CommonScriptMsg, Runtime, ScriptThreadEventCategory};
use crate::script_thread::{MainThreadScriptMsg, ScriptThread};
use crate::script_thread::ScriptThread;
use crate::task::TaskBox;
use crate::task_source::TaskSourceName;
@ -277,7 +278,7 @@ impl Drop for WorkletThreadPool {
impl WorkletThreadPool {
/// Create a new thread pool and spawn the threads.
/// When the thread pool is dropped, the threads will be asked to quit.
pub fn spawn(global_init: WorkletGlobalScopeInit) -> WorkletThreadPool {
pub(crate) fn spawn(global_init: WorkletGlobalScopeInit) -> WorkletThreadPool {
let primary_role = WorkletThreadRole::new(false, false);
let hot_backup_role = WorkletThreadRole::new(true, false);
let cold_backup_role = WorkletThreadRole::new(false, true);

View file

@ -27,9 +27,9 @@ use crate::dom::testworkletglobalscope::{TestWorkletGlobalScope, TestWorkletTask
#[cfg(feature = "webgpu")]
use crate::dom::webgpu::identityhub::IdentityHub;
use crate::dom::worklet::WorkletExecutor;
use crate::messaging::MainThreadScriptMsg;
use crate::script_module::ScriptFetchOptions;
use crate::script_runtime::{CanGc, JSContext};
use crate::script_thread::MainThreadScriptMsg;
#[dom_struct]
/// <https://drafts.css-houdini.org/worklets/#workletglobalscope>
@ -49,7 +49,7 @@ pub struct WorkletGlobalScope {
impl WorkletGlobalScope {
/// Create a new heap-allocated `WorkletGlobalScope`.
pub fn new(
pub(crate) fn new(
scope_type: WorkletGlobalScopeType,
runtime: &Runtime,
pipeline_id: PipelineId,
@ -76,7 +76,7 @@ impl WorkletGlobalScope {
}
/// Create a new stack-allocated `WorkletGlobalScope`.
pub fn new_inherited(
pub(crate) fn new_inherited(
pipeline_id: PipelineId,
base_url: ServoUrl,
executor: WorkletExecutor,
@ -172,7 +172,7 @@ impl WorkletGlobalScope {
/// Resources required by workletglobalscopes
#[derive(Clone)]
pub struct WorkletGlobalScopeInit {
pub(crate) struct WorkletGlobalScopeInit {
/// Channel to the main script thread
pub to_script_thread_sender: Sender<MainThreadScriptMsg>,
/// Channel to a resource thread

View file

@ -61,6 +61,9 @@ pub mod layout_dom;
#[warn(deprecated)]
mod mem;
#[warn(deprecated)]
#[allow(unsafe_code)]
pub mod messaging;
#[warn(deprecated)]
mod microtask;
#[warn(deprecated)]
mod network_listener;

View file

@ -0,0 +1,398 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::cell::RefCell;
use std::option::Option;
use std::result::Result;
use base::id::PipelineId;
use bluetooth_traits::BluetoothRequest;
use crossbeam_channel::{select, Receiver, Sender};
use devtools_traits::{DevtoolScriptControlMsg, ScriptToDevtoolsControlMsg};
use ipc_channel::ipc::IpcSender;
use net_traits::image_cache::PendingImageResponse;
use profile_traits::mem::{self as profile_mem, OpaqueSender};
use profile_traits::time::{self as profile_time};
use script_traits::{ConstellationControlMsg, LayoutMsg, Painter, ScriptMsg};
use servo_atoms::Atom;
use timers::TimerScheduler;
#[cfg(feature = "webgpu")]
use webgpu::WebGPUMsg;
use crate::dom::serviceworker::TrustedServiceWorkerAddress;
use crate::dom::worker::TrustedWorkerAddress;
use crate::script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort};
use crate::task_queue::{QueuedTask, QueuedTaskConversion, TaskQueue};
use crate::task_source::TaskSourceName;
pub(crate) type ImageCacheMsg = (PipelineId, PendingImageResponse);
#[derive(Debug)]
pub(crate) enum MixedMessage {
FromConstellation(ConstellationControlMsg),
FromScript(MainThreadScriptMsg),
FromDevtools(DevtoolScriptControlMsg),
FromImageCache((PipelineId, PendingImageResponse)),
#[cfg(feature = "webgpu")]
FromWebGPUServer(WebGPUMsg),
TimerFired,
}
impl MixedMessage {
pub(crate) fn pipeline_id(&self) -> Option<PipelineId> {
match self {
MixedMessage::FromConstellation(ref inner_msg) => match *inner_msg {
ConstellationControlMsg::StopDelayingLoadEventsMode(id) => Some(id),
ConstellationControlMsg::NavigationResponse(id, _) => Some(id),
ConstellationControlMsg::AttachLayout(ref new_layout_info) => new_layout_info
.parent_info
.or(Some(new_layout_info.new_pipeline_id)),
ConstellationControlMsg::Resize(id, ..) => Some(id),
ConstellationControlMsg::ThemeChange(id, ..) => Some(id),
ConstellationControlMsg::ResizeInactive(id, ..) => Some(id),
ConstellationControlMsg::UnloadDocument(id) => Some(id),
ConstellationControlMsg::ExitPipeline(id, ..) => Some(id),
ConstellationControlMsg::ExitScriptThread => None,
ConstellationControlMsg::SendEvent(id, ..) => Some(id),
ConstellationControlMsg::Viewport(id, ..) => Some(id),
ConstellationControlMsg::GetTitle(id) => Some(id),
ConstellationControlMsg::SetDocumentActivity(id, ..) => Some(id),
ConstellationControlMsg::SetThrottled(id, ..) => Some(id),
ConstellationControlMsg::SetThrottledInContainingIframe(id, ..) => Some(id),
ConstellationControlMsg::NavigateIframe(id, ..) => Some(id),
ConstellationControlMsg::PostMessage { target: id, .. } => Some(id),
ConstellationControlMsg::UpdatePipelineId(_, _, _, id, _) => Some(id),
ConstellationControlMsg::UpdateHistoryState(id, ..) => Some(id),
ConstellationControlMsg::RemoveHistoryStates(id, ..) => Some(id),
ConstellationControlMsg::FocusIFrame(id, ..) => Some(id),
ConstellationControlMsg::WebDriverScriptCommand(id, ..) => Some(id),
ConstellationControlMsg::TickAllAnimations(id, ..) => Some(id),
ConstellationControlMsg::WebFontLoaded(id, ..) => Some(id),
ConstellationControlMsg::DispatchIFrameLoadEvent {
target: _,
parent: id,
child: _,
} => Some(id),
ConstellationControlMsg::DispatchStorageEvent(id, ..) => Some(id),
ConstellationControlMsg::ReportCSSError(id, ..) => Some(id),
ConstellationControlMsg::Reload(id, ..) => Some(id),
ConstellationControlMsg::PaintMetric(id, ..) => Some(id),
ConstellationControlMsg::ExitFullScreen(id, ..) => Some(id),
ConstellationControlMsg::MediaSessionAction(..) => None,
#[cfg(feature = "webgpu")]
ConstellationControlMsg::SetWebGPUPort(..) => None,
ConstellationControlMsg::SetScrollStates(id, ..) => Some(id),
ConstellationControlMsg::SetEpochPaintTime(id, ..) => Some(id),
},
MixedMessage::FromScript(ref inner_msg) => match *inner_msg {
MainThreadScriptMsg::Common(CommonScriptMsg::Task(_, _, pipeline_id, _)) => {
pipeline_id
},
MainThreadScriptMsg::Common(CommonScriptMsg::CollectReports(_)) => None,
MainThreadScriptMsg::WorkletLoaded(pipeline_id) => Some(pipeline_id),
MainThreadScriptMsg::RegisterPaintWorklet { pipeline_id, .. } => Some(pipeline_id),
MainThreadScriptMsg::Inactive => None,
MainThreadScriptMsg::WakeUp => None,
},
MixedMessage::FromImageCache((pipeline_id, _)) => Some(*pipeline_id),
MixedMessage::FromDevtools(_) | MixedMessage::TimerFired => None,
#[cfg(feature = "webgpu")]
MixedMessage::FromWebGPUServer(..) => None,
}
}
}
/// Messages used to control the script event loop.
#[derive(Debug)]
pub(crate) enum MainThreadScriptMsg {
/// Common variants associated with the script messages
Common(CommonScriptMsg),
/// Notifies the script thread that a new worklet has been loaded, and thus the page should be
/// reflowed.
WorkletLoaded(PipelineId),
/// Notifies the script thread that a new paint worklet has been registered.
RegisterPaintWorklet {
pipeline_id: PipelineId,
name: Atom,
properties: Vec<Atom>,
painter: Box<dyn Painter>,
},
/// A task related to a not fully-active document has been throttled.
Inactive,
/// Wake-up call from the task queue.
WakeUp,
}
impl QueuedTaskConversion for MainThreadScriptMsg {
fn task_source_name(&self) -> Option<&TaskSourceName> {
let script_msg = match self {
MainThreadScriptMsg::Common(script_msg) => script_msg,
_ => return None,
};
match script_msg {
CommonScriptMsg::Task(_category, _boxed, _pipeline_id, task_source) => {
Some(task_source)
},
_ => None,
}
}
fn pipeline_id(&self) -> Option<PipelineId> {
let script_msg = match self {
MainThreadScriptMsg::Common(script_msg) => script_msg,
_ => return None,
};
match script_msg {
CommonScriptMsg::Task(_category, _boxed, pipeline_id, _task_source) => *pipeline_id,
_ => None,
}
}
fn into_queued_task(self) -> Option<QueuedTask> {
let script_msg = match self {
MainThreadScriptMsg::Common(script_msg) => script_msg,
_ => return None,
};
let (category, boxed, pipeline_id, task_source) = match script_msg {
CommonScriptMsg::Task(category, boxed, pipeline_id, task_source) => {
(category, boxed, pipeline_id, task_source)
},
_ => return None,
};
Some((None, category, boxed, pipeline_id, task_source))
}
fn from_queued_task(queued_task: QueuedTask) -> Self {
let (_worker, category, boxed, pipeline_id, task_source) = queued_task;
let script_msg = CommonScriptMsg::Task(category, boxed, pipeline_id, task_source);
MainThreadScriptMsg::Common(script_msg)
}
fn inactive_msg() -> Self {
MainThreadScriptMsg::Inactive
}
fn wake_up_msg() -> Self {
MainThreadScriptMsg::WakeUp
}
fn is_wake_up(&self) -> bool {
matches!(self, MainThreadScriptMsg::WakeUp)
}
}
impl OpaqueSender<CommonScriptMsg> for Box<dyn ScriptChan + Send> {
fn send(&self, msg: CommonScriptMsg) {
ScriptChan::send(&**self, msg).unwrap();
}
}
impl ScriptPort for Receiver<CommonScriptMsg> {
fn recv(&self) -> Result<CommonScriptMsg, ()> {
self.recv().map_err(|_| ())
}
}
impl ScriptPort for Receiver<MainThreadScriptMsg> {
fn recv(&self) -> Result<CommonScriptMsg, ()> {
match self.recv() {
Ok(MainThreadScriptMsg::Common(script_msg)) => Ok(script_msg),
Ok(_) => panic!("unexpected main thread event message!"),
Err(_) => Err(()),
}
}
}
impl ScriptPort for Receiver<(TrustedWorkerAddress, CommonScriptMsg)> {
fn recv(&self) -> Result<CommonScriptMsg, ()> {
self.recv().map(|(_, msg)| msg).map_err(|_| ())
}
}
impl ScriptPort for Receiver<(TrustedWorkerAddress, MainThreadScriptMsg)> {
fn recv(&self) -> Result<CommonScriptMsg, ()> {
match self.recv().map(|(_, msg)| msg) {
Ok(MainThreadScriptMsg::Common(script_msg)) => Ok(script_msg),
Ok(_) => panic!("unexpected main thread event message!"),
Err(_) => Err(()),
}
}
}
impl ScriptPort for Receiver<(TrustedServiceWorkerAddress, CommonScriptMsg)> {
fn recv(&self) -> Result<CommonScriptMsg, ()> {
self.recv().map(|(_, msg)| msg).map_err(|_| ())
}
}
/// Encapsulates internal communication of shared messages within the script thread.
#[derive(Clone, JSTraceable)]
pub(crate) struct SendableMainThreadScriptChan(#[no_trace] pub Sender<CommonScriptMsg>);
impl ScriptChan for SendableMainThreadScriptChan {
fn send(&self, msg: CommonScriptMsg) -> Result<(), ()> {
self.0.send(msg).map_err(|_| ())
}
fn as_boxed(&self) -> Box<dyn ScriptChan + Send> {
Box::new(SendableMainThreadScriptChan((self.0).clone()))
}
}
/// Encapsulates internal communication of main thread messages within the script thread.
#[derive(Clone, JSTraceable)]
pub(crate) struct MainThreadScriptChan(#[no_trace] pub Sender<MainThreadScriptMsg>);
impl ScriptChan for MainThreadScriptChan {
fn send(&self, msg: CommonScriptMsg) -> Result<(), ()> {
self.0
.send(MainThreadScriptMsg::Common(msg))
.map_err(|_| ())
}
fn as_boxed(&self) -> Box<dyn ScriptChan + Send> {
Box::new(MainThreadScriptChan((self.0).clone()))
}
}
impl OpaqueSender<CommonScriptMsg> for Sender<MainThreadScriptMsg> {
fn send(&self, msg: CommonScriptMsg) {
self.send(MainThreadScriptMsg::Common(msg)).unwrap()
}
}
#[derive(Clone, JSTraceable)]
pub(crate) struct ScriptThreadSenders {
/// A channel to hand out to script thread-based entities that need to be able to enqueue
/// events in the event queue.
pub self_sender: MainThreadScriptChan,
/// A handle to the bluetooth thread.
#[no_trace]
pub bluetooth_sender: IpcSender<BluetoothRequest>,
/// A [`Sender`] that sends messages to the `Constellation`.
#[no_trace]
pub constellation_sender: IpcSender<ConstellationControlMsg>,
/// A [`Sender`] that sends messages to the `Constellation` associated with
/// particular pipelines.
#[no_trace]
pub pipeline_to_constellation_sender: IpcSender<(PipelineId, ScriptMsg)>,
/// A sender for layout to communicate to the constellation.
#[no_trace]
pub layout_to_constellation_ipc_sender: IpcSender<LayoutMsg>,
/// The [`Sender`] on which messages can be sent to the `ImageCache`.
#[no_trace]
pub image_cache_sender: Sender<ImageCacheMsg>,
/// For providing contact with the time profiler.
#[no_trace]
pub time_profiler_sender: profile_time::ProfilerChan,
/// For providing contact with the memory profiler.
#[no_trace]
pub memory_profiler_sender: profile_mem::ProfilerChan,
/// For providing instructions to an optional devtools server.
#[no_trace]
pub devtools_server_sender: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
#[no_trace]
pub devtools_client_to_script_thread_sender: IpcSender<DevtoolScriptControlMsg>,
#[no_trace]
pub content_process_shutdown_sender: Sender<()>,
}
#[derive(JSTraceable)]
pub(crate) struct ScriptThreadReceivers {
/// A [`Receiver`] that receives messages from the constellation.
#[no_trace]
pub constellation_receiver: Receiver<ConstellationControlMsg>,
/// The [`Receiver`] which receives incoming messages from the `ImageCache`.
#[no_trace]
pub image_cache_receiver: Receiver<ImageCacheMsg>,
/// For receiving commands from an optional devtools server. Will be ignored if
/// no such server exists.
#[no_trace]
pub devtools_server_receiver: Receiver<DevtoolScriptControlMsg>,
/// Receiver to receive commands from optional WebGPU server.
#[no_trace]
#[cfg(feature = "webgpu")]
pub webgpu_receiver: RefCell<Receiver<WebGPUMsg>>,
}
impl ScriptThreadReceivers {
/// Block until a message is received by any of the receivers of this [`ScriptThreadReceivers`]
/// or the given [`TaskQueue`] or [`TimerScheduler`]. Return the first message received.
pub(crate) fn recv(
&self,
task_queue: &TaskQueue<MainThreadScriptMsg>,
timer_scheduler: &TimerScheduler,
) -> MixedMessage {
select! {
recv(task_queue.select()) -> msg => {
task_queue.take_tasks(msg.unwrap());
let event = task_queue
.recv()
.expect("Spurious wake-up of the event-loop, task-queue has no tasks available");
MixedMessage::FromScript(event)
},
recv(self.constellation_receiver) -> msg => MixedMessage::FromConstellation(msg.unwrap()),
recv(self.devtools_server_receiver) -> msg => MixedMessage::FromDevtools(msg.unwrap()),
recv(self.image_cache_receiver) -> msg => MixedMessage::FromImageCache(msg.unwrap()),
recv(timer_scheduler.wait_channel()) -> _ => MixedMessage::TimerFired,
recv({
#[cfg(feature = "webgpu")]
{
self.webgpu_receiver.borrow()
}
#[cfg(not(feature = "webgpu"))]
{
&crossbeam_channel::never::<()>()
}
}) -> msg => {
#[cfg(feature = "webgpu")]
{
MixedMessage::FromWebGPUServer(msg.unwrap())
}
#[cfg(not(feature = "webgpu"))]
{
unreachable!("This should never be hit when webgpu is disabled");
}
}
}
}
/// Try to receive a from any of the receivers of this [`ScriptThreadReceivers`] or the given
/// [`TaskQueue`]. Return `None` if no messages are ready to be received.
pub(crate) fn try_recv(
&self,
task_queue: &TaskQueue<MainThreadScriptMsg>,
) -> Option<MixedMessage> {
if let Ok(message) = self.constellation_receiver.try_recv() {
return MixedMessage::FromConstellation(message).into();
}
if let Ok(message) = task_queue.take_tasks_and_recv() {
return MixedMessage::FromScript(message).into();
}
if let Ok(message) = self.devtools_server_receiver.try_recv() {
return MixedMessage::FromDevtools(message).into();
}
if let Ok(message) = self.image_cache_receiver.try_recv() {
return MixedMessage::FromImageCache(message).into();
}
#[cfg(feature = "webgpu")]
if let Ok(message) = self.webgpu_receiver.borrow().try_recv() {
return MixedMessage::FromWebGPUServer(message).into();
}
None
}
}

View file

@ -18,6 +18,7 @@ use std::sync::Mutex;
use std::time::{Duration, Instant};
use std::{fmt, os, ptr, thread};
use background_hang_monitor_api::ScriptHangAnnotation;
use base::id::PipelineId;
use content_security_policy::{CheckResult, PolicyDisposition};
use js::conversions::jsstr_to_string;
@ -50,6 +51,7 @@ use js::rust::{
use malloc_size_of::MallocSizeOfOps;
use profile_traits::mem::{Report, ReportKind, ReportsChan};
use profile_traits::path;
use profile_traits::time::ProfilerCategory;
use servo_config::{opts, pref};
use style::thread_state::{self, ThreadState};
@ -126,8 +128,8 @@ pub trait ScriptChan: JSTraceable {
/// Send a message to the associated event loop.
#[allow(clippy::result_unit_err)]
fn send(&self, msg: CommonScriptMsg) -> Result<(), ()>;
/// Clone this handle.
fn clone(&self) -> Box<dyn ScriptChan + Send>;
/// Return a cloned version of this sender in a [`Box`].
fn as_boxed(&self) -> Box<dyn ScriptChan + Send>;
}
#[derive(Clone, Copy, Debug, Eq, Hash, JSTraceable, PartialEq)]
@ -162,6 +164,92 @@ pub enum ScriptThreadEventCategory {
WebGPUMsg,
}
impl From<ScriptThreadEventCategory> for ProfilerCategory {
fn from(category: ScriptThreadEventCategory) -> Self {
match category {
ScriptThreadEventCategory::AttachLayout => ProfilerCategory::ScriptAttachLayout,
ScriptThreadEventCategory::ConstellationMsg => ProfilerCategory::ScriptConstellationMsg,
ScriptThreadEventCategory::DevtoolsMsg => ProfilerCategory::ScriptDevtoolsMsg,
ScriptThreadEventCategory::DocumentEvent => ProfilerCategory::ScriptDocumentEvent,
ScriptThreadEventCategory::DomEvent => ProfilerCategory::ScriptDomEvent,
ScriptThreadEventCategory::EnterFullscreen => ProfilerCategory::ScriptEnterFullscreen,
ScriptThreadEventCategory::ExitFullscreen => ProfilerCategory::ScriptExitFullscreen,
ScriptThreadEventCategory::FileRead => ProfilerCategory::ScriptFileRead,
ScriptThreadEventCategory::FormPlannedNavigation => {
ProfilerCategory::ScriptPlannedNavigation
},
ScriptThreadEventCategory::HistoryEvent => ProfilerCategory::ScriptHistoryEvent,
ScriptThreadEventCategory::ImageCacheMsg => ProfilerCategory::ScriptImageCacheMsg,
ScriptThreadEventCategory::InputEvent => ProfilerCategory::ScriptInputEvent,
ScriptThreadEventCategory::NetworkEvent => ProfilerCategory::ScriptNetworkEvent,
ScriptThreadEventCategory::PerformanceTimelineTask => {
ProfilerCategory::ScriptPerformanceEvent
},
ScriptThreadEventCategory::PortMessage => ProfilerCategory::ScriptPortMessage,
ScriptThreadEventCategory::Resize => ProfilerCategory::ScriptResize,
ScriptThreadEventCategory::ScriptEvent => ProfilerCategory::ScriptEvent,
ScriptThreadEventCategory::ServiceWorkerEvent => {
ProfilerCategory::ScriptServiceWorkerEvent
},
ScriptThreadEventCategory::SetScrollState => ProfilerCategory::ScriptSetScrollState,
ScriptThreadEventCategory::SetViewport => ProfilerCategory::ScriptSetViewport,
ScriptThreadEventCategory::StylesheetLoad => ProfilerCategory::ScriptStylesheetLoad,
ScriptThreadEventCategory::TimerEvent => ProfilerCategory::ScriptTimerEvent,
ScriptThreadEventCategory::UpdateReplacedElement => {
ProfilerCategory::ScriptUpdateReplacedElement
},
ScriptThreadEventCategory::WebSocketEvent => ProfilerCategory::ScriptWebSocketEvent,
ScriptThreadEventCategory::WorkerEvent => ProfilerCategory::ScriptWorkerEvent,
ScriptThreadEventCategory::WorkletEvent => ProfilerCategory::ScriptWorkletEvent,
#[cfg(feature = "webgpu")]
ScriptThreadEventCategory::WebGPUMsg => ProfilerCategory::ScriptWebGPUMsg,
}
}
}
impl From<ScriptThreadEventCategory> for ScriptHangAnnotation {
fn from(category: ScriptThreadEventCategory) -> Self {
match category {
ScriptThreadEventCategory::AttachLayout => ScriptHangAnnotation::AttachLayout,
ScriptThreadEventCategory::ConstellationMsg => ScriptHangAnnotation::ConstellationMsg,
ScriptThreadEventCategory::DevtoolsMsg => ScriptHangAnnotation::DevtoolsMsg,
ScriptThreadEventCategory::DocumentEvent => ScriptHangAnnotation::DocumentEvent,
ScriptThreadEventCategory::DomEvent => ScriptHangAnnotation::DomEvent,
ScriptThreadEventCategory::FileRead => ScriptHangAnnotation::FileRead,
ScriptThreadEventCategory::FormPlannedNavigation => {
ScriptHangAnnotation::FormPlannedNavigation
},
ScriptThreadEventCategory::HistoryEvent => ScriptHangAnnotation::HistoryEvent,
ScriptThreadEventCategory::ImageCacheMsg => ScriptHangAnnotation::ImageCacheMsg,
ScriptThreadEventCategory::InputEvent => ScriptHangAnnotation::InputEvent,
ScriptThreadEventCategory::NetworkEvent => ScriptHangAnnotation::NetworkEvent,
ScriptThreadEventCategory::Resize => ScriptHangAnnotation::Resize,
ScriptThreadEventCategory::ScriptEvent => ScriptHangAnnotation::ScriptEvent,
ScriptThreadEventCategory::SetScrollState => ScriptHangAnnotation::SetScrollState,
ScriptThreadEventCategory::SetViewport => ScriptHangAnnotation::SetViewport,
ScriptThreadEventCategory::StylesheetLoad => ScriptHangAnnotation::StylesheetLoad,
ScriptThreadEventCategory::TimerEvent => ScriptHangAnnotation::TimerEvent,
ScriptThreadEventCategory::UpdateReplacedElement => {
ScriptHangAnnotation::UpdateReplacedElement
},
ScriptThreadEventCategory::WebSocketEvent => ScriptHangAnnotation::WebSocketEvent,
ScriptThreadEventCategory::WorkerEvent => ScriptHangAnnotation::WorkerEvent,
ScriptThreadEventCategory::WorkletEvent => ScriptHangAnnotation::WorkletEvent,
ScriptThreadEventCategory::ServiceWorkerEvent => {
ScriptHangAnnotation::ServiceWorkerEvent
},
ScriptThreadEventCategory::EnterFullscreen => ScriptHangAnnotation::EnterFullscreen,
ScriptThreadEventCategory::ExitFullscreen => ScriptHangAnnotation::ExitFullscreen,
ScriptThreadEventCategory::PerformanceTimelineTask => {
ScriptHangAnnotation::PerformanceTimelineTask
},
ScriptThreadEventCategory::PortMessage => ScriptHangAnnotation::PortMessage,
#[cfg(feature = "webgpu")]
ScriptThreadEventCategory::WebGPUMsg => ScriptHangAnnotation::WebGPUMsg,
}
}
}
/// An interface for receiving ScriptMsg values in an event loop. Used for synchronous DOM
/// APIs that need to abstract over multiple kinds of event loops (worker/main thread) with
/// different Receiver interfaces.

File diff suppressed because it is too large Load diff

View file

@ -6,7 +6,10 @@ use std::collections::HashMap;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use base::id::PipelineId;
use crate::dom::bindings::cell::DomRefCell;
use crate::messaging::MainThreadScriptChan;
use crate::task::TaskCanceller;
use crate::task_source::dom_manipulation::DOMManipulationTaskSource;
use crate::task_source::file_reading::FileReadingTaskSource;
@ -24,15 +27,20 @@ use crate::task_source::websocket::WebsocketTaskSource;
use crate::task_source::TaskSourceName;
macro_rules! task_source_functions {
($self:ident,$with_canceller:ident,$task_source:ident,$task_source_type:ident,$task_source_name:ident) => {
pub fn $with_canceller(&$self) -> ($task_source_type, TaskCanceller) {
($self:ident, $task_source:ident, $task_source_type:ident, $task_source_name:ident) => {
pub(crate) fn $task_source(&$self) -> $task_source_type {
$self.$task_source.clone()
}
};
($self:ident, $with_canceller:ident, $task_source:ident, $task_source_type:ident, $task_source_name:ident) => {
pub(crate) fn $with_canceller(&$self) -> ($task_source_type, TaskCanceller) {
($self.$task_source.clone(), $self.task_canceller(TaskSourceName::$task_source_name))
}
pub fn $task_source(&$self) -> $task_source_type {
pub(crate) fn $task_source(&$self) -> $task_source_type {
$self.$task_source.clone()
}
}
};
}
#[derive(JSTraceable, MallocSizeOf)]
@ -69,35 +77,27 @@ pub struct TaskManager {
impl TaskManager {
#[allow(clippy::too_many_arguments)]
pub fn new(
dom_manipulation_task_source: DOMManipulationTaskSource,
file_reading_task_source: FileReadingTaskSource,
gamepad_task_source: GamepadTaskSource,
history_traversal_task_source: HistoryTraversalTaskSource,
media_element_task_source: MediaElementTaskSource,
networking_task_source: NetworkingTaskSource,
performance_timeline_task_source: PerformanceTimelineTaskSource,
port_message_queue: PortMessageQueue,
user_interaction_task_source: UserInteractionTaskSource,
remote_event_task_source: RemoteEventTaskSource,
rendering_task_source: RenderingTaskSource,
timer_task_source: TimerTaskSource,
websocket_task_source: WebsocketTaskSource,
) -> Self {
pub(crate) fn new(sender: Box<MainThreadScriptChan>, pipeline_id: PipelineId) -> Self {
TaskManager {
dom_manipulation_task_source,
file_reading_task_source,
gamepad_task_source,
history_traversal_task_source,
media_element_task_source,
networking_task_source,
performance_timeline_task_source,
port_message_queue,
user_interaction_task_source,
remote_event_task_source,
rendering_task_source,
timer_task_source,
websocket_task_source,
dom_manipulation_task_source: DOMManipulationTaskSource(sender.clone(), pipeline_id),
file_reading_task_source: FileReadingTaskSource(sender.clone(), pipeline_id),
gamepad_task_source: GamepadTaskSource(sender.clone(), pipeline_id),
history_traversal_task_source: HistoryTraversalTaskSource(
sender.0.clone(),
pipeline_id,
),
media_element_task_source: MediaElementTaskSource(sender.0.clone(), pipeline_id),
networking_task_source: NetworkingTaskSource(sender.clone(), pipeline_id),
performance_timeline_task_source: PerformanceTimelineTaskSource(
sender.clone(),
pipeline_id,
),
port_message_queue: PortMessageQueue(sender.clone(), pipeline_id),
user_interaction_task_source: UserInteractionTaskSource(sender.0.clone(), pipeline_id),
remote_event_task_source: RemoteEventTaskSource(sender.clone(), pipeline_id),
rendering_task_source: RenderingTaskSource(sender.clone(), pipeline_id),
timer_task_source: TimerTaskSource(sender.clone(), pipeline_id),
websocket_task_source: WebsocketTaskSource(sender.clone(), pipeline_id),
task_cancellers: Default::default(),
}
}
@ -110,13 +110,7 @@ impl TaskManager {
DOMManipulation
);
task_source_functions!(
self,
gamepad_task_source_with_canceller,
gamepad_task_source,
GamepadTaskSource,
Gamepad
);
task_source_functions!(self, gamepad_task_source, GamepadTaskSource, Gamepad);
task_source_functions!(
self,
@ -128,7 +122,6 @@ impl TaskManager {
task_source_functions!(
self,
user_interaction_task_source_with_canceller,
user_interaction_task_source,
UserInteractionTaskSource,
UserInteraction
@ -144,7 +137,6 @@ impl TaskManager {
task_source_functions!(
self,
file_reading_task_source_with_canceller,
file_reading_task_source,
FileReadingTaskSource,
FileReading
@ -152,59 +144,25 @@ impl TaskManager {
task_source_functions!(
self,
history_traversal_task_source_with_canceller,
history_traversal_task_source,
HistoryTraversalTaskSource,
HistoryTraversal
);
task_source_functions!(
self,
performance_timeline_task_source_with_canceller,
performance_timeline_task_source,
PerformanceTimelineTaskSource,
PerformanceTimeline
);
task_source_functions!(
self,
port_message_queue_with_canceller,
port_message_queue,
PortMessageQueue,
PortMessage
);
task_source_functions!(self, port_message_queue, PortMessageQueue, PortMessage);
task_source_functions!(
self,
remote_event_task_source_with_canceller,
remote_event_task_source,
RemoteEventTaskSource,
RemoteEvent
);
task_source_functions!(
self,
rendering_task_source_with_canceller,
rendering_task_source,
RenderingTaskSource,
Rendering
);
task_source_functions!(self, rendering_task_source, RenderingTaskSource, Rendering);
task_source_functions!(
self,
timer_task_source_with_canceller,
timer_task_source,
TimerTaskSource,
Timer
);
task_source_functions!(self, timer_task_source, TimerTaskSource, Timer);
task_source_functions!(
self,
websocket_task_source_with_canceller,
websocket_task_source,
WebsocketTaskSource,
Websocket
);
task_source_functions!(self, websocket_task_source, WebsocketTaskSource, Websocket);
pub fn task_canceller(&self, name: TaskSourceName) -> TaskCanceller {
let mut flags = self.task_cancellers.borrow_mut();

View file

@ -22,7 +22,7 @@ pub struct DOMManipulationTaskSource(pub Box<dyn ScriptChan + Send>, #[no_trace]
impl Clone for DOMManipulationTaskSource {
fn clone(&self) -> DOMManipulationTaskSource {
DOMManipulationTaskSource(self.0.clone(), self.1)
DOMManipulationTaskSource(self.0.as_boxed(), self.1)
}
}

View file

@ -18,7 +18,7 @@ pub struct FileReadingTaskSource(
impl Clone for FileReadingTaskSource {
fn clone(&self) -> FileReadingTaskSource {
FileReadingTaskSource(self.0.clone(), self.1)
FileReadingTaskSource(self.0.as_boxed(), self.1)
}
}

View file

@ -19,7 +19,7 @@ pub struct GamepadTaskSource(
impl Clone for GamepadTaskSource {
fn clone(&self) -> GamepadTaskSource {
GamepadTaskSource(self.0.clone(), self.1)
GamepadTaskSource(self.0.as_boxed(), self.1)
}
}

View file

@ -5,13 +5,13 @@
use base::id::PipelineId;
use crossbeam_channel::Sender;
use crate::messaging::MainThreadScriptMsg;
use crate::script_runtime::{CommonScriptMsg, ScriptThreadEventCategory};
use crate::script_thread::MainThreadScriptMsg;
use crate::task::{TaskCanceller, TaskOnce};
use crate::task_source::{TaskSource, TaskSourceName};
#[derive(Clone, JSTraceable)]
pub struct HistoryTraversalTaskSource(
pub(crate) struct HistoryTraversalTaskSource(
#[no_trace] pub Sender<MainThreadScriptMsg>,
#[no_trace] pub PipelineId,
);

View file

@ -14,13 +14,13 @@ use crate::dom::bindings::refcounted::Trusted;
use crate::dom::event::SimpleEventTask;
use crate::dom::eventtarget::EventTarget;
use crate::dom::window::Window;
use crate::messaging::MainThreadScriptMsg;
use crate::script_runtime::{CommonScriptMsg, ScriptThreadEventCategory};
use crate::script_thread::MainThreadScriptMsg;
use crate::task::{TaskCanceller, TaskOnce};
use crate::task_source::{TaskSource, TaskSourceName};
#[derive(Clone, JSTraceable)]
pub struct MediaElementTaskSource(
pub(crate) struct MediaElementTaskSource(
#[no_trace] pub Sender<MainThreadScriptMsg>,
#[no_trace] pub PipelineId,
);

View file

@ -16,7 +16,7 @@ pub struct NetworkingTaskSource(
impl Clone for NetworkingTaskSource {
fn clone(&self) -> NetworkingTaskSource {
NetworkingTaskSource(self.0.clone(), self.1)
NetworkingTaskSource(self.0.as_boxed(), self.1)
}
}

View file

@ -25,7 +25,7 @@ pub struct PerformanceTimelineTaskSource(
impl Clone for PerformanceTimelineTaskSource {
fn clone(&self) -> PerformanceTimelineTaskSource {
PerformanceTimelineTaskSource(self.0.clone(), self.1)
PerformanceTimelineTaskSource(self.0.as_boxed(), self.1)
}
}

View file

@ -18,7 +18,7 @@ pub struct PortMessageQueue(
impl Clone for PortMessageQueue {
fn clone(&self) -> PortMessageQueue {
PortMessageQueue(self.0.clone(), self.1)
PortMessageQueue(self.0.as_boxed(), self.1)
}
}

View file

@ -16,7 +16,7 @@ pub struct RemoteEventTaskSource(
impl Clone for RemoteEventTaskSource {
fn clone(&self) -> RemoteEventTaskSource {
RemoteEventTaskSource(self.0.clone(), self.1)
RemoteEventTaskSource(self.0.as_boxed(), self.1)
}
}

View file

@ -16,7 +16,7 @@ pub struct RenderingTaskSource(pub Box<dyn ScriptChan + Send>, #[no_trace] pub P
impl Clone for RenderingTaskSource {
fn clone(&self) -> RenderingTaskSource {
RenderingTaskSource(self.0.clone(), self.1)
RenderingTaskSource(self.0.as_boxed(), self.1)
}
}

View file

@ -19,7 +19,7 @@ pub struct TimerTaskSource(
impl Clone for TimerTaskSource {
fn clone(&self) -> TimerTaskSource {
TimerTaskSource(self.0.clone(), self.1)
TimerTaskSource(self.0.as_boxed(), self.1)
}
}

View file

@ -14,8 +14,8 @@ use crate::dom::bindings::refcounted::Trusted;
use crate::dom::event::{EventBubbles, EventCancelable, EventTask};
use crate::dom::eventtarget::EventTarget;
use crate::dom::window::Window;
use crate::messaging::MainThreadScriptMsg;
use crate::script_runtime::{CommonScriptMsg, ScriptThreadEventCategory};
use crate::script_thread::MainThreadScriptMsg;
use crate::task::{TaskCanceller, TaskOnce};
use crate::task_source::{TaskSource, TaskSourceName};

View file

@ -16,7 +16,7 @@ pub struct WebsocketTaskSource(
impl Clone for WebsocketTaskSource {
fn clone(&self) -> WebsocketTaskSource {
WebsocketTaskSource(self.0.clone(), self.1)
WebsocketTaskSource(self.0.as_boxed(), self.1)
}
}

View file

@ -616,33 +616,33 @@ pub struct InitialScriptState {
/// Loading into a Secure Context
pub inherited_secure_context: Option<bool>,
/// A channel with which messages can be sent to us (the script thread).
pub control_chan: IpcSender<ConstellationControlMsg>,
pub constellation_sender: IpcSender<ConstellationControlMsg>,
/// A port on which messages sent by the constellation to script can be received.
pub control_port: IpcReceiver<ConstellationControlMsg>,
pub constellation_receiver: IpcReceiver<ConstellationControlMsg>,
/// A channel on which messages can be sent to the constellation from script.
pub script_to_constellation_chan: ScriptToConstellationChan,
pub pipeline_to_constellation_sender: ScriptToConstellationChan,
/// A handle to register script-(and associated layout-)threads for hang monitoring.
pub background_hang_monitor_register: Box<dyn BackgroundHangMonitorRegister>,
/// A sender layout to communicate to the constellation.
pub layout_to_constellation_chan: IpcSender<LayoutMsg>,
pub layout_to_constellation_ipc_sender: IpcSender<LayoutMsg>,
/// A channel to the resource manager thread.
pub resource_threads: ResourceThreads,
/// A channel to the bluetooth thread.
pub bluetooth_thread: IpcSender<BluetoothRequest>,
pub bluetooth_sender: IpcSender<BluetoothRequest>,
/// The image cache for this script thread.
pub image_cache: Arc<dyn ImageCache>,
/// A channel to the time profiler thread.
pub time_profiler_chan: profile_traits::time::ProfilerChan,
pub time_profiler_sender: profile_traits::time::ProfilerChan,
/// A channel to the memory profiler thread.
pub mem_profiler_chan: mem::ProfilerChan,
pub memory_profiler_sender: mem::ProfilerChan,
/// A channel to the developer tools, if applicable.
pub devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
pub devtools_server_sender: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
/// Information about the initial window size.
pub window_size: WindowSizeData,
/// The ID of the pipeline namespace for this script thread.
pub pipeline_namespace_id: PipelineNamespaceId,
/// A ping will be sent on this channel once the script thread shuts down.
pub content_process_shutdown_chan: Sender<()>,
pub content_process_shutdown_sender: Sender<()>,
/// A channel to the WebGL thread used in this pipeline.
pub webgl_chan: Option<WebGLPipeline>,
/// The XR device registry