script: Do not run layout in a thread (#31346)

* script: Do not run layout in a thread

Instead of spawning a thread for layout that almost always runs
synchronously with script, simply run layout in the script thread.

This is a resurrection of #28708, taking just the bits that remove the
layout thread. It's a complex change and thus is just a first step
toward cleaning up the interface between script and layout. Messages are
still passed from script to layout via a `process()` method and script
proxies some messages to layout from other threads as well.

Big changes:

1. Layout is created in the script thread on Document load, thus every
   live document is guaranteed to have a layout. This isn't completely
   hidden in the interface, but we can safely `unwrap()` on a Document's
   layout.
2. Layout configuration is abstracted away into a LayoutConfig struct
   and the LayoutFactory is a struct passed around by the Constellation.
   This is to avoid having to monomorphize the entire script thread
   for each layout.
3. Instead of having the Constellation block on the layout thread to
   figure out the current epoch and whether there are pending web fonts
   loading, updates are sent synchronously to the Constellation when
   rendering to a screenshot. This practically only used by the WPT.

A couple tests start to fail, which is probably inevitable since removing
the layout thread has introduced timing changes in "exit after load" and
screenshot behavior.

Co-authored-by: Josh Matthews <josh@joshmatthews.net>

* Update test expectations

* Fix some issues found during review

* Clarify some comments

* Address review comments

---------

Co-authored-by: Josh Matthews <josh@joshmatthews.net>
This commit is contained in:
Martin Robinson 2024-02-23 09:14:10 +01:00 committed by GitHub
parent 4849ba901e
commit 9c0561536d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
44 changed files with 636 additions and 1253 deletions

View file

@ -53,6 +53,7 @@ euclid = { workspace = true }
fnv = { workspace = true }
fxhash = { workspace = true }
gfx_traits = { workspace = true }
gfx = { path = "../gfx" }
headers = { workspace = true }
html5ever = { workspace = true }
http = { workspace = true }

View file

@ -30,7 +30,7 @@ pub struct DomRefCell<T> {
impl<T> DomRefCell<T> {
/// Return a reference to the contents.
///
/// For use in the layout thread only.
/// For use in layout only.
#[allow(unsafe_code)]
pub unsafe fn borrow_for_layout(&self) -> &T {
assert_in_layout();

View file

@ -320,7 +320,7 @@ pub struct Document {
/// This field is set to the document itself for inert documents.
/// <https://html.spec.whatwg.org/multipage/#appropriate-template-contents-owner-document>
appropriate_template_contents_owner_document: MutNullableDom<Document>,
/// Information on elements needing restyle to ship over to the layout thread when the
/// Information on elements needing restyle to ship over to layout when the
/// time comes.
pending_restyles: DomRefCell<HashMap<Dom<Element>, NoTrace<PendingRestyle>>>,
/// This flag will be true if layout suppressed a reflow attempt that was
@ -367,7 +367,7 @@ pub struct Document {
spurious_animation_frames: Cell<u8>,
/// Track the total number of elements in this DOM's tree.
/// This is sent to the layout thread every time a reflow is done;
/// This is sent to layout every time a reflow is done;
/// layout uses this to determine if the gains from parallel layout will be worth the overhead.
///
/// See also: <https://github.com/servo/servo/issues/10110>
@ -827,10 +827,9 @@ impl Document {
let old_mode = self.quirks_mode.replace(new_mode);
if old_mode != new_mode {
match self.window.layout_chan() {
Some(chan) => chan.send(Msg::SetQuirksMode(new_mode)).unwrap(),
None => warn!("Layout channel unavailable"),
}
let _ = self
.window
.with_layout(move |layout| layout.process(Msg::SetQuirksMode(new_mode)));
}
}
@ -2092,7 +2091,7 @@ impl Document {
},
LoadType::PageSource(_) => {
if self.has_browsing_context && self.is_fully_active() {
// Note: if the document is not fully active, the layout thread will have exited already.
// Note: if the document is not fully active, layout will have exited already.
// The underlying problem might actually be that layout exits while it should be kept alive.
// See https://github.com/servo/servo/issues/22507
@ -2264,7 +2263,7 @@ impl Document {
None => false,
};
// Note: if the document is not fully active, the layout thread will have exited already,
// Note: if the document is not fully active, layout will have exited already,
// and this method will panic.
// The underlying problem might actually be that layout exits while it should be kept alive.
// See https://github.com/servo/servo/issues/22507
@ -3441,12 +3440,11 @@ impl Document {
/// Flushes the stylesheet list, and returns whether any stylesheet changed.
pub fn flush_stylesheets_for_reflow(&self) -> bool {
// NOTE(emilio): The invalidation machinery is used on the replicated
// list on the layout thread.
// list in layout.
//
// FIXME(emilio): This really should differentiate between CSSOM changes
// and normal stylesheets additions / removals, because in the last case
// the layout thread already has that information and we could avoid
// dirtying the whole thing.
// layout already has that information and we could avoid dirtying the whole thing.
let mut stylesheets = self.stylesheets.borrow_mut();
let have_changed = stylesheets.has_changed();
stylesheets.flush_without_invalidation();
@ -3830,15 +3828,14 @@ impl Document {
})
.cloned();
match self.window.layout_chan() {
Some(chan) => chan
.send(Msg::AddStylesheet(
sheet.clone(),
insertion_point.as_ref().map(|s| s.sheet.clone()),
))
.unwrap(),
None => return warn!("Layout channel unavailable"),
}
let cloned_stylesheet = sheet.clone();
let insertion_point2 = insertion_point.clone();
let _ = self.window.with_layout(move |layout| {
layout.process(Msg::AddStylesheet(
cloned_stylesheet,
insertion_point2.as_ref().map(|s| s.sheet.clone()),
));
});
DocumentOrShadowRoot::add_stylesheet(
owner,
@ -3851,15 +3848,15 @@ impl Document {
/// Remove a stylesheet owned by `owner` from the list of document sheets.
#[allow(crown::unrooted_must_root)] // Owner needs to be rooted already necessarily.
pub fn remove_stylesheet(&self, owner: &Element, s: &Arc<Stylesheet>) {
match self.window.layout_chan() {
Some(chan) => chan.send(Msg::RemoveStylesheet(s.clone())).unwrap(),
None => return warn!("Layout channel unavailable"),
}
pub fn remove_stylesheet(&self, owner: &Element, stylesheet: &Arc<Stylesheet>) {
let cloned_stylesheet = stylesheet.clone();
let _ = self
.window
.with_layout(|layout| layout.process(Msg::RemoveStylesheet(cloned_stylesheet)));
DocumentOrShadowRoot::remove_stylesheet(
owner,
s,
stylesheet,
StylesheetSetRef::Document(&mut *self.stylesheets.borrow_mut()),
)
}

View file

@ -93,7 +93,7 @@ impl DocumentOrShadowRoot {
return vec![];
};
self.window.layout().nodes_from_point_response()
self.window.layout_rpc().nodes_from_point_response()
}
#[allow(unsafe_code)]

View file

@ -457,7 +457,7 @@ impl HTMLElementMethods for HTMLElement {
window.layout_reflow(QueryMsg::ElementInnerTextQuery(
node.to_trusted_node_address(),
));
DOMString::from(window.layout().element_inner_text())
DOMString::from(window.layout_rpc().element_inner_text())
}
// https://html.spec.whatwg.org/multipage/#the-innertext-idl-attribute

View file

@ -7,7 +7,6 @@ use std::cell::Cell;
use bitflags::bitflags;
use dom_struct::dom_struct;
use html5ever::{local_name, namespace_url, ns, LocalName, Prefix};
use ipc_channel::ipc;
use js::rust::HandleObject;
use msg::constellation_msg::{BrowsingContextId, PipelineId, TopLevelBrowsingContextId};
use profile_traits::ipc as ProfiledIpc;
@ -200,8 +199,6 @@ impl HTMLIFrameElement {
match pipeline_type {
PipelineType::InitialAboutBlank => {
let (pipeline_sender, pipeline_receiver) = ipc::channel().unwrap();
self.about_blank_pipeline_id.set(Some(new_pipeline_id));
let load_info = IFrameLoadInfoWithData {
@ -213,7 +210,7 @@ impl HTMLIFrameElement {
};
global_scope
.script_to_constellation_chan()
.send(ScriptMsg::ScriptNewIFrame(load_info, pipeline_sender))
.send(ScriptMsg::ScriptNewIFrame(load_info))
.unwrap();
let new_layout_info = NewLayoutInfo {
@ -223,7 +220,6 @@ impl HTMLIFrameElement {
top_level_browsing_context_id: top_level_browsing_context_id,
opener: None,
load_data: load_data,
pipeline_port: pipeline_receiver,
window_size,
};

View file

@ -197,7 +197,7 @@
//! Layout code can access the DOM through the
//! [`LayoutDom`](bindings/root/struct.LayoutDom.html) smart pointer. This does not
//! keep the DOM object alive; we ensure that no DOM code (Garbage Collection
//! in particular) runs while the layout thread is accessing the DOM.
//! in particular) runs while layout is accessing the DOM.
//!
//! Methods accessible to layout are implemented on `LayoutDom<Foo>` using
//! `LayoutFooHelpers` traits.

View file

@ -10,7 +10,7 @@ use std::default::Default;
use std::io::{stderr, stdout, Write};
use std::ptr::NonNull;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::atomic::Ordering;
use std::sync::{Arc, Mutex};
use std::{cmp, env, mem};
@ -26,7 +26,7 @@ use dom_struct::dom_struct;
use embedder_traits::{EmbedderMsg, PromptDefinition, PromptOrigin, PromptResult};
use euclid::default::{Point2D as UntypedPoint2D, Rect as UntypedRect};
use euclid::{Point2D, Rect, Scale, Size2D, Vector2D};
use ipc_channel::ipc::IpcSender;
use ipc_channel::ipc::{self, IpcSender};
use ipc_channel::router::ROUTER;
use js::conversions::ToJSValConvertible;
use js::jsapi::{GCReason, Heap, JSAutoRealm, JSObject, StackFormat, JSPROP_ENUMERATE, JS_GC};
@ -47,13 +47,13 @@ use num_traits::ToPrimitive;
use parking_lot::Mutex as ParkMutex;
use profile_traits::ipc as ProfiledIpc;
use profile_traits::mem::ProfilerChan as MemProfilerChan;
use profile_traits::time::{ProfilerChan as TimeProfilerChan, ProfilerMsg};
use profile_traits::time::ProfilerChan as TimeProfilerChan;
use script_layout_interface::message::{Msg, QueryMsg, Reflow, ReflowGoal, ScriptReflow};
use script_layout_interface::rpc::{
ContentBoxResponse, ContentBoxesResponse, LayoutRPC, NodeScrollIdResponse,
ResolvedStyleResponse, TextIndexResponse,
};
use script_layout_interface::{PendingImageState, TrustedNodeAddress};
use script_layout_interface::{Layout, PendingImageState, TrustedNodeAddress};
use script_traits::webdriver_msg::{WebDriverJSError, WebDriverJSResult};
use script_traits::{
ConstellationControlMsg, DocumentState, HistoryEntryReplacement, LoadData, ScriptMsg,
@ -237,19 +237,6 @@ pub struct Window {
#[ignore_malloc_size_of = "Rc<T> is hard"]
js_runtime: DomRefCell<Option<Rc<Runtime>>>,
/// A handle for communicating messages to the layout thread.
///
/// This channel shouldn't be accessed directly, but through `Window::layout_chan()`,
/// which returns `None` if there's no layout thread anymore.
#[ignore_malloc_size_of = "channels are hard"]
#[no_trace]
layout_chan: Sender<Msg>,
/// A handle to perform RPC calls into the layout, quickly.
#[ignore_malloc_size_of = "trait objects are hard"]
#[no_trace]
layout_rpc: Box<dyn LayoutRPC + Send + 'static>,
/// The current size of the window, in pixels.
#[no_trace]
window_size: Cell<WindowSizeData>,
@ -339,10 +326,6 @@ pub struct Window {
/// It is used to avoid sending idle message more than once, which is unneccessary.
has_sent_idle_message: Cell<bool>,
/// Flag that indicates if the layout thread is busy handling a request.
#[ignore_malloc_size_of = "Arc<T> is hard"]
layout_is_busy: Arc<AtomicBool>,
/// Emits notifications when there is a relayout.
relayout_event: bool,
@ -519,8 +502,8 @@ impl Window {
}
pub fn pending_image_notification(&self, response: PendingImageResponse) {
//XXXjdm could be more efficient to send the responses to the layout thread,
// rather than making the layout thread talk to the image cache to
//XXXjdm could be more efficient to send the responses to layout,
// rather than making layout talk to the image cache to
// obtain the same data.
let mut images = self.pending_layout_images.borrow_mut();
let nodes = images.entry(response.id);
@ -1676,7 +1659,7 @@ impl Window {
// objects removed from the tree that haven't been collected
// yet). There should not be any such DOM nodes with layout
// data, but if there are, then when they are dropped, they
// will attempt to send a message to the closed layout thread.
// will attempt to send a message to layout.
// This causes memory safety issues, because the DOM node uses
// the layout channel from its window, and the window has
// already been GC'd. For nodes which do not have a live
@ -1803,18 +1786,14 @@ impl Window {
ScriptThread::handle_tick_all_animations_for_testing(pipeline_id);
}
/// Reflows the page unconditionally if possible and not suppressed. This
/// method will wait for the layout thread to complete (but see the `TODO`
/// below). If there is no window size yet, the page is presumed invisible
/// and no reflow is performed. If reflow is suppressed, no reflow will be
/// performed for ForDisplay goals.
///
/// TODO(pcwalton): Only wait for style recalc, since we have
/// off-main-thread layout.
/// Reflows the page unconditionally if possible and not suppressed. This method will wait for
/// the layout to complete. If there is no window size yet, the page is presumed invisible and
/// no reflow is performed. If reflow is suppressed, no reflow will be performed for ForDisplay
/// goals.
///
/// Returns true if layout actually happened, false otherwise.
#[allow(unsafe_code)]
pub fn force_reflow(
pub(crate) fn force_reflow(
&self,
reflow_goal: ReflowGoal,
reason: ReflowReason,
@ -1905,14 +1884,7 @@ impl Window {
animations: document.animations().sets.clone(),
};
match self.layout_chan() {
Some(layout_chan) => layout_chan
.send(Msg::Reflow(reflow))
.expect("Layout thread disconnected"),
None => return false,
};
debug!("script: layout forked");
let _ = self.with_layout(move |layout| layout.process(Msg::Reflow(reflow)));
let complete = match join_port.try_recv() {
Err(TryRecvError::Empty) => {
@ -1921,11 +1893,11 @@ impl Window {
},
Ok(reflow_complete) => reflow_complete,
Err(TryRecvError::Disconnected) => {
panic!("Layout thread failed while script was waiting for a result.");
panic!("Layout failed while script was waiting for a result.");
},
};
debug!("script: layout joined");
debug!("script: layout complete");
// Pending reflows require display, so only reset the pending reflow count if this reflow
// was to be displayed.
@ -1968,17 +1940,12 @@ impl Window {
}
document.update_animations_post_reflow();
self.update_constellation_epoch();
true
}
/// Reflows the page if it's possible to do so and the page is dirty. This
/// method will wait for the layout thread to complete (but see the `TODO`
/// below). If there is no window size yet, the page is presumed invisible
/// and no reflow is performed.
///
/// TODO(pcwalton): Only wait for style recalc, since we have
/// off-main-thread layout.
/// Reflows the page if it's possible to do so and the page is dirty.
///
/// Returns true if layout actually happened, false otherwise.
/// This return value is useful for script queries, that wait for a lock
@ -2032,12 +1999,24 @@ impl Window {
elem.has_class(&atom!("reftest-wait"), CaseSensitivity::CaseSensitive)
});
let pending_web_fonts = self
.with_layout(move |layout| layout.waiting_for_web_fonts_to_load())
.unwrap();
let has_sent_idle_message = self.has_sent_idle_message.get();
let is_ready_state_complete = document.ReadyState() == DocumentReadyState::Complete;
let pending_images = self.pending_layout_images.borrow().is_empty();
let pending_images = !self.pending_layout_images.borrow().is_empty();
if !has_sent_idle_message && is_ready_state_complete && !reftest_wait && pending_images
if !has_sent_idle_message &&
is_ready_state_complete &&
!reftest_wait &&
!pending_images &&
!pending_web_fonts
{
debug!(
"{:?}: Sending DocumentState::Idle to Constellation",
self.pipeline_id()
);
let event = ScriptMsg::SetDocumentState(DocumentState::Idle);
self.send_to_constellation(event);
self.has_sent_idle_message.set(true);
@ -2047,13 +2026,28 @@ impl Window {
issued_reflow
}
pub fn layout_reflow(&self, query_msg: QueryMsg) -> bool {
if self.layout_is_busy.load(Ordering::Relaxed) {
let url = self.get_url().into_string();
self.time_profiler_chan()
.send(ProfilerMsg::BlockedLayoutQuery(url));
/// If writing a screenshot, synchronously update the layout epoch that it set
/// in the constellation.
pub(crate) fn update_constellation_epoch(&self) {
if !self.prepare_for_screenshot {
return;
}
let epoch = self
.with_layout(move |layout| layout.current_epoch())
.unwrap();
debug!(
"{:?}: Updating constellation epoch: {epoch:?}",
self.pipeline_id()
);
let (sender, receiver) = ipc::channel().expect("Failed to create IPC channel!");
let event = ScriptMsg::SetLayoutEpoch(epoch, sender);
self.send_to_constellation(event);
receiver.recv().unwrap();
}
pub fn layout_reflow(&self, query_msg: QueryMsg) -> bool {
self.reflow(
ReflowGoal::LayoutQuery(query_msg, time::precise_time_ns()),
ReflowReason::Query,
@ -2069,18 +2063,18 @@ impl Window {
)) {
return None;
}
self.layout_rpc.resolved_font_style()
self.layout_rpc().resolved_font_style()
}
pub fn layout(&self) -> &dyn LayoutRPC {
&*self.layout_rpc
pub fn layout_rpc(&self) -> Box<dyn LayoutRPC> {
self.with_layout(|layout| layout.rpc()).unwrap()
}
pub fn content_box_query(&self, node: &Node) -> Option<UntypedRect<Au>> {
if !self.layout_reflow(QueryMsg::ContentBoxQuery(node.to_opaque())) {
return None;
}
let ContentBoxResponse(rect) = self.layout_rpc.content_box();
let ContentBoxResponse(rect) = self.layout_rpc().content_box();
rect
}
@ -2088,7 +2082,7 @@ impl Window {
if !self.layout_reflow(QueryMsg::ContentBoxesQuery(node.to_opaque())) {
return vec![];
}
let ContentBoxesResponse(rects) = self.layout_rpc.content_boxes();
let ContentBoxesResponse(rects) = self.layout_rpc().content_boxes();
rects
}
@ -2096,7 +2090,7 @@ impl Window {
if !self.layout_reflow(QueryMsg::ClientRectQuery(node.to_opaque())) {
return Rect::zero();
}
self.layout_rpc.node_geometry().client_rect
self.layout_rpc().node_geometry().client_rect
}
/// Find the scroll area of the given node, if it is not None. If the node
@ -2106,7 +2100,7 @@ impl Window {
if !self.layout_reflow(QueryMsg::ScrollingAreaQuery(opaque)) {
return Rect::zero();
}
self.layout_rpc.scrolling_area().client_rect
self.layout_rpc().scrolling_area().client_rect
}
pub fn scroll_offset_query(&self, node: &Node) -> Vector2D<f32, LayoutPixel> {
@ -2129,7 +2123,7 @@ impl Window {
.borrow_mut()
.insert(node.to_opaque(), Vector2D::new(x_ as f32, y_ as f32));
let NodeScrollIdResponse(scroll_id) = self.layout_rpc.node_scroll_id();
let NodeScrollIdResponse(scroll_id) = self.layout_rpc().node_scroll_id();
// Step 12
self.perform_a_scroll(
@ -2150,7 +2144,7 @@ impl Window {
if !self.layout_reflow(QueryMsg::ResolvedStyleQuery(element, pseudo, property)) {
return DOMString::new();
}
let ResolvedStyleResponse(resolved) = self.layout_rpc.resolved_style();
let ResolvedStyleResponse(resolved) = self.layout_rpc().resolved_style();
DOMString::from(resolved)
}
@ -2161,7 +2155,7 @@ impl Window {
if !self.layout_reflow(QueryMsg::InnerWindowDimensionsQuery(browsing_context)) {
return None;
}
self.layout_rpc.inner_window_dimensions()
self.layout_rpc().inner_window_dimensions()
}
#[allow(unsafe_code)]
@ -2172,7 +2166,7 @@ impl Window {
// FIXME(nox): Layout can reply with a garbage value which doesn't
// actually correspond to an element, that's unsound.
let response = self.layout_rpc.offset_parent();
let response = self.layout_rpc().offset_parent();
let element = response.node_address.and_then(|parent_node_address| {
let node = unsafe { from_untrusted_node_address(parent_node_address) };
DomRoot::downcast(node)
@ -2188,7 +2182,7 @@ impl Window {
if !self.layout_reflow(QueryMsg::TextIndexQuery(node.to_opaque(), point_in_node)) {
return TextIndexResponse(None);
}
self.layout_rpc.text_index()
self.layout_rpc().text_index()
}
#[allow(unsafe_code)]
@ -2313,12 +2307,8 @@ impl Window {
self.Document().url()
}
pub fn layout_chan(&self) -> Option<&Sender<Msg>> {
if self.is_alive() {
Some(&self.layout_chan)
} else {
None
}
pub fn with_layout<'a, T>(&self, call: impl FnOnce(&mut dyn Layout) -> T) -> Result<T, ()> {
ScriptThread::with_layout(self.pipeline_id(), call)
}
pub fn windowproxy_handler(&self) -> WindowProxyHandler {
@ -2539,7 +2529,6 @@ impl Window {
constellation_chan: ScriptToConstellationChan,
control_chan: IpcSender<ConstellationControlMsg>,
scheduler_chan: IpcSender<TimerSchedulerMsg>,
layout_chan: Sender<Msg>,
pipelineid: PipelineId,
parent_info: Option<PipelineId>,
window_size: WindowSizeData,
@ -2552,7 +2541,6 @@ impl Window {
microtask_queue: Rc<MicrotaskQueue>,
webrender_document: DocumentId,
webrender_api_sender: WebrenderIpcSender,
layout_is_busy: Arc<AtomicBool>,
relayout_event: bool,
prepare_for_screenshot: bool,
unminify_js: bool,
@ -2565,11 +2553,6 @@ impl Window {
gpu_id_hub: Arc<ParkMutex<Identities>>,
inherited_secure_context: Option<bool>,
) -> DomRoot<Self> {
let layout_rpc: Box<dyn LayoutRPC + Send> = {
let (rpc_send, rpc_recv) = unbounded();
layout_chan.send(Msg::GetRPC(rpc_send)).unwrap();
rpc_recv.recv().unwrap()
};
let error_reporter = CSSErrorReporter {
pipelineid,
script_chan: Arc::new(Mutex::new(control_chan)),
@ -2615,8 +2598,6 @@ impl Window {
bluetooth_extra_permission_data: BluetoothExtraPermissionData::new(),
page_clip_rect: Cell::new(MaxRect::max_rect()),
resize_event: Default::default(),
layout_chan,
layout_rpc,
window_size: Cell::new(window_size),
current_viewport: Cell::new(Rect::zero()),
suppress_reflow: Cell::new(true),
@ -2640,7 +2621,6 @@ impl Window {
exists_mut_observer: Cell::new(false),
webrender_api_sender,
has_sent_idle_message: Cell::new(false),
layout_is_busy,
relayout_event,
prepare_for_screenshot,
unminify_js,

View file

@ -323,7 +323,6 @@ impl WindowProxy {
new_pipeline_id: new_pipeline_id,
};
let (pipeline_sender, pipeline_receiver) = ipc::channel().unwrap();
let new_layout_info = NewLayoutInfo {
parent_info: None,
new_pipeline_id: new_pipeline_id,
@ -331,10 +330,9 @@ impl WindowProxy {
top_level_browsing_context_id: new_top_level_browsing_context_id,
opener: Some(self.browsing_context_id),
load_data: load_data,
pipeline_port: pipeline_receiver,
window_size: window.window_size(),
};
let constellation_msg = ScriptMsg::ScriptNewAuxiliary(load_info, pipeline_sender);
let constellation_msg = ScriptMsg::ScriptNewAuxiliary(load_info);
window.send_to_constellation(constellation_msg);
ScriptThread::process_attach_layout(new_layout_info, document.origin().clone());
let msg = EmbedderMsg::WebViewOpened(new_top_level_browsing_context_id);

View file

@ -234,7 +234,7 @@ impl PendingTasksStruct {
/// when a worklet adds a module. It is dropped when the script thread
/// is dropped, and asks each of the worklet threads to quit.
///
/// The layout thread can end up blocking on the primary worklet thread
/// Layout can end up blocking on the primary worklet thread
/// (e.g. when invoking a paint callback), so it is important to avoid
/// deadlock by making sure the primary worklet thread doesn't end up
/// blocking waiting on layout. In particular, since the constellation

View file

@ -2,10 +2,9 @@
* 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/. */
//! Infrastructure to initiate network requests for images needed by the layout
//! thread. The script thread needs to be responsible for them because there's
//! no guarantee that the responsible nodes will still exist in the future if the
//! layout thread holds on to them during asynchronous operations.
//! Infrastructure to initiate network requests for images needed by layout. The script thread needs
//! to be responsible for them because there's no guarantee that the responsible nodes will still
//! exist in the future if layout holds on to them during asynchronous operations.
use std::sync::{Arc, Mutex};

View file

@ -2,8 +2,8 @@
* 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/. */
//! The script thread is the thread that owns the DOM in memory, runs JavaScript, and spawns parsing
//! and layout threads. It's in charge of processing events for all same-origin pages in a frame
//! The script thread is the thread that owns the DOM in memory, runs JavaScript, and triggers
//! layout. It's in charge of processing events for all same-origin pages in a frame
//! tree, and manages the entire lifetime of pages in the frame tree from initial request to
//! teardown.
//!
@ -41,6 +41,7 @@ use devtools_traits::{
use embedder_traits::EmbedderMsg;
use euclid::default::{Point2D, Rect};
use euclid::Vector2D;
use gfx::font_cache_thread::FontCacheThread;
use headers::{HeaderMapExt, LastModified, ReferrerPolicy as ReferrerPolicyHeader};
use html5ever::{local_name, namespace_url, ns};
use hyper_serde::Serde;
@ -56,10 +57,9 @@ use media::WindowGLContext;
use metrics::{PaintTimeMetrics, MAX_TASK_NS};
use mime::{self, Mime};
use msg::constellation_msg::{
BackgroundHangMonitor, BackgroundHangMonitorExitSignal, BackgroundHangMonitorRegister,
BrowsingContextId, HangAnnotation, HistoryStateId, MonitoredComponentId,
MonitoredComponentType, PipelineId, PipelineNamespace, ScriptHangAnnotation,
TopLevelBrowsingContextId,
BackgroundHangMonitor, BackgroundHangMonitorExitSignal, BrowsingContextId, HangAnnotation,
HistoryStateId, MonitoredComponentId, MonitoredComponentType, PipelineId, PipelineNamespace,
ScriptHangAnnotation, TopLevelBrowsingContextId,
};
use net_traits::image_cache::{ImageCache, PendingImageResponse};
use net_traits::request::{CredentialsMode, Destination, RedirectMode, RequestBuilder};
@ -72,7 +72,8 @@ use parking_lot::Mutex;
use percent_encoding::percent_decode;
use profile_traits::mem::{self as profile_mem, OpaqueSender, ReportsChan};
use profile_traits::time::{self as profile_time, profile, ProfilerCategory};
use script_layout_interface::message::{self, LayoutThreadInit, Msg, ReflowGoal};
use script_layout_interface::message::{Msg, ReflowGoal};
use script_layout_interface::{Layout, LayoutConfig, LayoutFactory, ScriptThreadFactory};
use script_traits::webdriver_msg::WebDriverScriptCommand;
use script_traits::CompositorEvent::{
CompositionEvent, GamepadEvent, IMEDismissedEvent, KeyboardEvent, MouseButtonEvent,
@ -81,8 +82,8 @@ use script_traits::CompositorEvent::{
use script_traits::{
AnimationTickType, CompositorEvent, ConstellationControlMsg, DiscardBrowsingContext,
DocumentActivity, EventResult, HistoryEntryReplacement, InitialScriptState, JsEvalResult,
LayoutMsg, LoadData, LoadOrigin, MediaSessionActionType, MouseButton, MouseEventType,
NewLayoutInfo, Painter, ProgressiveWebMetricType, ScriptMsg, ScriptThreadFactory,
LayoutControlMsg, LayoutMsg, LoadData, LoadOrigin, MediaSessionActionType, MouseButton,
MouseEventType, NewLayoutInfo, Painter, ProgressiveWebMetricType, ScriptMsg,
ScriptToConstellationChan, StructuredSerializedData, TimerSchedulerMsg, TouchEventType,
TouchId, UntrustedNodeAddress, UpdatePipelineIdReason, WebrenderIpcSender, WheelDelta,
WindowSizeData, WindowSizeType,
@ -202,9 +203,6 @@ struct InProgressLoad {
/// The current window size associated with this pipeline.
#[no_trace]
window_size: WindowSizeData,
/// Channel to the layout thread associated with this pipeline.
#[no_trace]
layout_chan: Sender<message::Msg>,
/// The activity level of the document (inactive, active or fully active).
#[no_trace]
activity: DocumentActivity,
@ -222,8 +220,6 @@ struct InProgressLoad {
navigation_start_precise: u64,
/// For cancelling the fetch
canceller: FetchCanceller,
/// Flag for sharing with the layout thread that is not yet created.
layout_is_busy: Arc<AtomicBool>,
/// If inheriting the security context
inherited_secure_context: Option<bool>,
}
@ -236,11 +232,9 @@ impl InProgressLoad {
top_level_browsing_context_id: TopLevelBrowsingContextId,
parent_info: Option<PipelineId>,
opener: Option<BrowsingContextId>,
layout_chan: Sender<message::Msg>,
window_size: WindowSizeData,
url: ServoUrl,
origin: MutableOrigin,
layout_is_busy: Arc<AtomicBool>,
inherited_secure_context: Option<bool>,
) -> InProgressLoad {
let duration = SystemTime::now()
@ -248,18 +242,12 @@ impl InProgressLoad {
.unwrap_or_default();
let navigation_start = duration.as_millis();
let navigation_start_precise = precise_time_ns();
layout_chan
.send(message::Msg::SetNavigationStart(
navigation_start_precise as u64,
))
.unwrap();
InProgressLoad {
pipeline_id: id,
browsing_context_id: browsing_context_id,
top_level_browsing_context_id: top_level_browsing_context_id,
parent_info: parent_info,
opener: opener,
layout_chan: layout_chan,
window_size: window_size,
activity: DocumentActivity::FullyActive,
is_visible: true,
@ -268,7 +256,6 @@ impl InProgressLoad {
navigation_start: navigation_start as u64,
navigation_start_precise: navigation_start_precise,
canceller: Default::default(),
layout_is_busy: layout_is_busy,
inherited_secure_context: inherited_secure_context,
}
}
@ -554,9 +541,6 @@ pub struct ScriptThread {
/// A queue of tasks to be executed in this script-thread.
task_queue: TaskQueue<MainThreadScriptMsg>,
/// A handle to register associated layout threads for hang-monitoring.
#[no_trace]
background_hang_monitor_register: Box<dyn BackgroundHangMonitorRegister>,
/// The dedicated means of communication with the background-hang-monitor for this script-thread.
#[no_trace]
background_hang_monitor: Box<dyn BackgroundHangMonitor>,
@ -596,7 +580,7 @@ pub struct ScriptThread {
#[no_trace]
control_chan: IpcSender<ConstellationControlMsg>,
/// The port on which the constellation and layout threads can communicate with the
/// The port on which the constellation and layout can communicate with the
/// script thread.
#[no_trace]
control_port: Receiver<ConstellationControlMsg>,
@ -605,10 +589,14 @@ pub struct ScriptThread {
#[no_trace]
script_sender: IpcSender<(PipelineId, ScriptMsg)>,
/// A sender for new layout threads to communicate to the constellation.
/// A sender for layout to communicate to the constellation.
#[no_trace]
layout_to_constellation_chan: IpcSender<LayoutMsg>,
/// The font cache thread to use for layout that happens in this [`ScriptThread`].
#[no_trace]
font_cache_thread: FontCacheThread,
/// The port on which we receive messages from the image cache
#[no_trace]
image_cache_port: Receiver<ImageCacheMsg>,
@ -738,6 +726,14 @@ pub struct ScriptThread {
// Secure context
inherited_secure_context: Option<bool>,
/// The layouts that we control.
#[no_trace]
layouts: RefCell<HashMap<PipelineId, Box<dyn Layout>>>,
/// A factory for making new layouts. This allows layout to depend on script.
#[no_trace]
layout_factory: Arc<dyn LayoutFactory>,
}
struct BHMExitSignal {
@ -791,21 +787,18 @@ impl<'a> Drop for ScriptMemoryFailsafe<'a> {
}
impl ScriptThreadFactory for ScriptThread {
type Message = message::Msg;
fn create(
state: InitialScriptState,
layout_factory: Arc<dyn LayoutFactory>,
font_cache_thread: FontCacheThread,
load_data: LoadData,
user_agent: Cow<'static, str>,
) -> (Sender<message::Msg>, Receiver<message::Msg>) {
) {
let (script_chan, script_port) = unbounded();
let (sender, receiver) = unbounded();
let layout_chan = sender.clone();
thread::Builder::new()
.name(format!("Script{:?}", state.id))
.spawn(move || {
thread_state::initialize(ThreadState::SCRIPT);
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();
@ -818,10 +811,15 @@ impl ScriptThreadFactory for ScriptThread {
let secure = load_data.inherited_secure_context.clone();
let mem_profiler_chan = state.mem_profiler_chan.clone();
let window_size = state.window_size;
let layout_is_busy = state.layout_is_busy.clone();
let script_thread =
ScriptThread::new(state, script_port, script_chan.clone(), user_agent);
let script_thread = ScriptThread::new(
state,
script_port,
script_chan.clone(),
layout_factory,
font_cache_thread,
user_agent,
);
SCRIPT_THREAD_ROOT.with(|root| {
root.set(Some(&script_thread as *const _));
@ -836,11 +834,9 @@ impl ScriptThreadFactory for ScriptThread {
top_level_browsing_context_id,
parent_info,
opener,
layout_chan,
window_size,
load_data.url.clone(),
origin,
layout_is_busy,
secure,
);
script_thread.pre_page_load(new_load, load_data);
@ -860,12 +856,26 @@ impl ScriptThreadFactory for ScriptThread {
failsafe.neuter();
})
.expect("Thread spawning failed");
(sender, receiver)
}
}
impl ScriptThread {
pub fn with_layout<'a, T>(
pipeline_id: PipelineId,
call: impl FnOnce(&mut dyn Layout) -> T,
) -> Result<T, ()> {
SCRIPT_THREAD_ROOT.with(|root| {
let script_thread = unsafe { &*root.get().unwrap() };
let mut layouts = script_thread.layouts.borrow_mut();
if let Some(ref mut layout) = layouts.get_mut(&pipeline_id) {
Ok(call(&mut ***layout))
} else {
warn!("No layout found for {}", pipeline_id);
Err(())
}
})
}
pub fn runtime_handle() -> ParentRuntime {
SCRIPT_THREAD_ROOT.with(|root| {
let script_thread = unsafe { &*root.get().unwrap() };
@ -1201,12 +1211,8 @@ impl ScriptThread {
},
};
match window.layout_chan() {
Some(chan) => chan
.send(Msg::RegisterPaint(name, properties, painter))
.unwrap(),
None => warn!("Layout channel unavailable"),
}
let _ = window
.with_layout(|layout| layout.process(Msg::RegisterPaint(name, properties, painter)));
}
pub fn push_new_element_queue() {
@ -1292,6 +1298,8 @@ impl ScriptThread {
state: InitialScriptState,
port: Receiver<MainThreadScriptMsg>,
chan: Sender<MainThreadScriptMsg>,
layout_factory: Arc<dyn LayoutFactory>,
font_cache_thread: FontCacheThread,
user_agent: Cow<'static, str>,
) -> ScriptThread {
let opts = opts::get();
@ -1351,7 +1359,6 @@ impl ScriptThread {
task_queue,
background_hang_monitor_register: state.background_hang_monitor_register,
background_hang_monitor,
closing,
@ -1394,6 +1401,7 @@ impl ScriptThread {
mutation_observers: Default::default(),
layout_to_constellation_chan: state.layout_to_constellation_chan,
font_cache_thread,
webgl_chan: state.webgl_chan,
webxr_registry: state.webxr_registry,
@ -1426,6 +1434,8 @@ impl ScriptThread {
gpu_id_hub: Arc::new(Mutex::new(Identities::new())),
webgpu_port: RefCell::new(None),
inherited_secure_context: state.inherited_secure_context,
layouts: Default::default(),
layout_factory,
}
}
@ -1847,6 +1857,8 @@ impl ScriptThread {
ExitFullScreen(id, ..) => Some(id),
MediaSessionAction(..) => None,
SetWebGPUPort(..) => None,
ForLayoutFromConstellation(_, id) => Some(id),
ForLayoutFromFontCache(id) => Some(id),
},
MixedMessage::FromDevtools(_) => None,
MixedMessage::FromScript(ref inner_msg) => match *inner_msg {
@ -2081,9 +2093,23 @@ impl ScriptThread {
msg @ ConstellationControlMsg::ExitScriptThread => {
panic!("should have handled {:?} already", msg)
},
ConstellationControlMsg::ForLayoutFromConstellation(msg, pipeline_id) => {
self.handle_layout_message(msg, pipeline_id)
},
ConstellationControlMsg::ForLayoutFromFontCache(pipeline_id) => {
self.handle_font_cache(pipeline_id)
},
}
}
fn handle_layout_message(&self, msg: LayoutControlMsg, pipeline_id: PipelineId) {
let _ = Self::with_layout(pipeline_id, |layout| layout.handle_constellation_msg(msg));
}
fn handle_font_cache(&self, pipeline_id: PipelineId) {
let _ = Self::with_layout(pipeline_id, |layout| layout.handle_font_cache_msg());
}
fn handle_msg_from_webgpu_server(&self, msg: WebGPUMsg) {
match msg {
WebGPUMsg::FreeAdapter(id) => self.gpu_id_hub.lock().kill_adapter_id(id),
@ -2509,55 +2535,8 @@ impl ScriptThread {
opener,
load_data,
window_size,
pipeline_port,
} = new_layout_info;
let layout_pair = unbounded();
let layout_chan = layout_pair.0.clone();
let layout_is_busy = Arc::new(AtomicBool::new(false));
let msg = message::Msg::CreateLayoutThread(LayoutThreadInit {
id: new_pipeline_id,
url: load_data.url.clone(),
is_parent: false,
layout_pair: layout_pair,
pipeline_port: pipeline_port,
background_hang_monitor_register: self.background_hang_monitor_register.clone(),
constellation_chan: self.layout_to_constellation_chan.clone(),
script_chan: self.control_chan.clone(),
image_cache: self.image_cache.clone(),
paint_time_metrics: PaintTimeMetrics::new(
new_pipeline_id,
self.time_profiler_chan.clone(),
self.layout_to_constellation_chan.clone(),
self.control_chan.clone(),
load_data.url.clone(),
),
layout_is_busy: layout_is_busy.clone(),
window_size,
});
// Pick a layout thread, any layout thread
let current_layout_chan: Option<Sender<Msg>> = self
.documents
.borrow()
.iter()
.next()
.and_then(|(_, document)| document.window().layout_chan().cloned())
.or_else(|| {
self.incomplete_loads
.borrow()
.first()
.map(|load| load.layout_chan.clone())
});
match current_layout_chan {
None => panic!("Layout attached to empty script thread."),
// Tell the layout thread factory to actually spawn the thread.
Some(layout_chan) => layout_chan.send(msg).unwrap(),
};
// Kick off the fetch for the new resource.
let new_load = InProgressLoad::new(
new_pipeline_id,
@ -2565,11 +2544,9 @@ impl ScriptThread {
top_level_browsing_context_id,
parent_info,
opener,
layout_chan,
window_size,
load_data.url.clone(),
origin,
layout_is_busy.clone(),
load_data.inherited_secure_context.clone(),
);
if load_data.url.as_str() == "about:blank" {
@ -2926,60 +2903,37 @@ impl ScriptThread {
/// Handles a request to exit a pipeline and shut down layout.
fn handle_exit_pipeline_msg(&self, id: PipelineId, discard_bc: DiscardBrowsingContext) {
debug!("Exiting pipeline {}.", id);
debug!("{id}: Starting pipeline exit.");
self.closed_pipelines.borrow_mut().insert(id);
// Check if the exit message is for an in progress load.
let idx = self
.incomplete_loads
.borrow()
.iter()
.position(|load| load.pipeline_id == id);
let document = self.documents.borrow_mut().remove(id);
// Abort the parser, if any,
// to prevent any further incoming networking messages from being handled.
if let Some(document) = document.as_ref() {
let document = self.documents.borrow_mut().remove(id);
if let Some(document) = document {
// We should never have a pipeline that's still an incomplete load, but also has a Document.
debug_assert!(!self
.incomplete_loads
.borrow()
.iter()
.any(|load| load.pipeline_id == id));
if let Some(parser) = document.get_current_parser() {
parser.abort();
}
}
// We should never have a pipeline that's still an incomplete load,
// but also has a Document.
debug_assert!(idx.is_none() || document.is_none());
debug!("{id}: Shutting down layout");
let _ = document.window().with_layout(|layout| {
layout.process(Msg::ExitNow);
});
// Remove any incomplete load.
let chan = if let Some(idx) = idx {
let load = self.incomplete_loads.borrow_mut().remove(idx);
load.layout_chan.clone()
} else if let Some(ref document) = document {
match document.window().layout_chan() {
Some(chan) => chan.clone(),
None => return warn!("Layout channel unavailable"),
}
} else {
return warn!("Exiting nonexistant pipeline {}.", id);
};
debug!("{id}: Sending PipelineExited message to constellation");
self.script_sender
.send((id, ScriptMsg::PipelineExited))
.ok();
// We shut down layout before removing the document,
// since layout might still be in the middle of laying it out.
debug!("preparing to shut down layout for page {}", id);
let (response_chan, response_port) = unbounded();
chan.send(message::Msg::PrepareToExit(response_chan)).ok();
let _ = response_port.recv();
debug!("shutting down layout for page {}", id);
chan.send(message::Msg::ExitNow).ok();
self.script_sender
.send((id, ScriptMsg::PipelineExited))
.ok();
// Now that layout is shut down, it's OK to remove the document.
if let Some(document) = document {
// Clear any active animations and unroot all of the associated DOM objects.
debug!("{id}: Clearing animations");
document.animations().clear();
// We don't want to dispatch `mouseout` event pointing to non-existing element
@ -2995,10 +2949,12 @@ impl ScriptThread {
if discard_bc == DiscardBrowsingContext::Yes {
window.discard_browsing_context();
}
debug!("{id}: Clearing JavaScript runtime");
window.clear_js_runtime();
}
debug!("Exited pipeline {}.", id);
debug!("{id}: Finished pipeline exit");
}
/// Handles a request to exit the script thread and shut down layout.
@ -3045,7 +3001,7 @@ impl ScriptThread {
});
}
/// Handles when layout thread finishes all animation in one tick
/// Handles when layout finishes all animation in one tick
fn handle_tick_all_animations(&self, id: PipelineId, tick_type: AnimationTickType) {
let document = match self.documents.borrow().find_document(id) {
Some(document) => document,
@ -3255,13 +3211,6 @@ impl ScriptThread {
fn load(&self, metadata: Metadata, incomplete: InProgressLoad) -> DomRoot<ServoParser> {
let final_url = metadata.final_url.clone();
{
// send the final url to the layout thread.
incomplete
.layout_chan
.send(message::Msg::SetFinalUrl(final_url.clone()))
.unwrap();
// update the pipeline url
self.script_sender
.send((
incomplete.pipeline_id,
@ -3304,6 +3253,33 @@ impl ScriptThread {
self.websocket_task_source(incomplete.pipeline_id),
);
let paint_time_metrics = PaintTimeMetrics::new(
incomplete.pipeline_id,
self.time_profiler_chan.clone(),
self.layout_to_constellation_chan.clone(),
self.control_chan.clone(),
final_url.clone(),
incomplete.navigation_start_precise,
);
let layout_config = LayoutConfig {
id: incomplete.pipeline_id,
url: final_url.clone(),
is_iframe: incomplete.parent_info.is_some(),
constellation_chan: self.layout_to_constellation_chan.clone(),
script_chan: self.control_chan.clone(),
image_cache: self.image_cache.clone(),
font_cache_thread: self.font_cache_thread.clone(),
time_profiler_chan: self.time_profiler_chan.clone(),
webrender_api_sender: self.webrender_api_sender.clone(),
paint_time_metrics,
window_size: incomplete.window_size.clone(),
};
self.layouts.borrow_mut().insert(
incomplete.pipeline_id,
self.layout_factory.create(layout_config),
);
// Create the window and document objects.
let window = Window::new(
self.js_runtime.clone(),
@ -3319,7 +3295,6 @@ impl ScriptThread {
script_to_constellation_chan,
self.control_chan.clone(),
self.scheduler_chan.clone(),
incomplete.layout_chan,
incomplete.pipeline_id,
incomplete.parent_info,
incomplete.window_size,
@ -3332,7 +3307,6 @@ impl ScriptThread {
self.microtask_queue.clone(),
self.webrender_document,
self.webrender_api_sender.clone(),
incomplete.layout_is_busy,
self.relayout_event,
self.prepare_for_screenshot,
self.unminify_js,