Skip to content

Truly independent web browser

LibCompositing+LibWebView+Compositor: Add an overlay of layers and tiles

Aliaksandr Kalenik1a475b41340e
diff --git a/Libraries/LibCompositing/Rust/src/display_list/layers/planning.rs b/Libraries/LibCompositing/Rust/src/display_list/layers/planning.rs
index fc358153af0..7c1101e5ab8 100644
--- a/Libraries/LibCompositing/Rust/src/display_list/layers/planning.rs
+++ b/Libraries/LibCompositing/Rust/src/display_list/layers/planning.rs
@@ -158,7 +158,7 @@ impl std::fmt::Display for WhyEffectIsComposited {
}
/// A plan of the layers of a list: the stack the compositor composites frames from, and where the parts of the list
-/// are placed among the spaces of the stack, which only the dump and the tests read.
+/// are placed among the spaces of the stack, which only the dump, the overlay of layers and the tests read.
#[derive(Clone, Debug, PartialEq)]
pub struct PlannedLayers {
pub stack: LayerStack,
diff --git a/Libraries/LibCompositing/Rust/src/display_list/layers/planning/lines_of_plan.rs b/Libraries/LibCompositing/Rust/src/display_list/layers/planning/lines_of_plan.rs
index 691f53aba3e..9c4ad8dda2f 100644
--- a/Libraries/LibCompositing/Rust/src/display_list/layers/planning/lines_of_plan.rs
+++ b/Libraries/LibCompositing/Rust/src/display_list/layers/planning/lines_of_plan.rs
@@ -4,12 +4,13 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! The lines the dump tells of a plan, and the layers the dump names for each record.
+//! The lines the dump and the overlay of layers tell of a plan, and the layers the dump names for each record.
use super::{AnimatedNode, PlacedEffect, PlannedLayers, WhyEffectIsComposited, for_each_layer_records_go_into};
use crate::display_list::commands::EffectNodeIndex;
use crate::display_list::layers::{
- CompositedEffect, LayerContent, LayerIndex, VisualContextNodeNamer, WindowServerPresentationOfMedia, media_name,
+ CompositedEffect, LayerContent, LayerIndex, NodeNamesFromIndices, VisualContextNodeNamer,
+ WindowServerPresentationOfMedia, media_name, wire,
};
use crate::display_list::reach::Reach;
use crate::display_list::storage::ListPosition;
@@ -95,6 +96,21 @@ impl PlannedLayers {
.map(|(content, why_no_layer)| format!("no layer for {}: {why_no_layer}", media_name(*content)))
}
+ /// The lines the overlay of layers shows of the stack past its layers, which WebContent sends with the plan: those
+ /// of the effects the compositor composites, of the canvases, videos and nested contexts without layers, and of the
+ /// effects that read only their own layer, with nodes named by their indices, as many and as long as a plan holds.
+ /// A stack of one layer that replays the whole list has none.
+ pub fn note_lines_for_layers_overlay(&self) -> Vec<String> {
+ if self.stack.replays_whole_list() {
+ return Vec::new();
+ }
+ wire::note_lines_a_plan_holds(
+ self.lines_of_composited_effects(&NodeNamesFromIndices)
+ .chain(self.lines_of_media_without_layers())
+ .chain(self.lines_of_effects_reading_only_own_layer(&NodeNamesFromIndices)),
+ )
+ }
+
/// What the dump says of each node the compositor animates whose content was not given layers of its own, and why.
pub fn lines_of_animations_without_layers<'a>(
&'a self,
diff --git a/Libraries/LibCompositing/Rust/src/display_list/layers/wire.rs b/Libraries/LibCompositing/Rust/src/display_list/layers/wire.rs
index ecad0f36f71..eb1b64b1d12 100644
--- a/Libraries/LibCompositing/Rust/src/display_list/layers/wire.rs
+++ b/Libraries/LibCompositing/Rust/src/display_list/layers/wire.rs
@@ -5,7 +5,8 @@
*/
//! A plan of the layers of a list as it goes from WebContent to the compositor: what of its stack the compositor cannot
-//! work out of the list and the tree, and the checks that a plan from another process passes before anything reads it.
+//! work out of the list and the tree, the notes the overlay of layers shows, and the checks that a plan from another
+//! process passes before anything reads it.
use super::{
BandOfPlan, BarrierOfPlan, COORDINATE_LIMIT_IN_DEVICE_PIXELS, CutOfPlan, LayerContent, LayerIdentity, LayerStack,
@@ -37,6 +38,22 @@ const MAXIMUM_NODE_COUNT_OF_RECEIVED_STACK: usize = 1 << 16;
const MAXIMUM_BAND_COUNT_OF_RECEIVED_STACK: usize = 1 << 16;
const MAXIMUM_CUT_COUNT_OF_RECEIVED_BAND: usize = 256;
const MAXIMUM_SPAN_COUNT_OF_RECEIVED_BAND: usize = 1 << 20;
+// The most note lines a plan holds, and the most bytes a line holds. A plan holds only the first lines, each cut to that
+// length, so that no plan exceeds the caps.
+const MAXIMUM_NOTE_LINE_COUNT_OF_PLAN: usize = 1 << 10;
+const MAXIMUM_NOTE_LINE_LENGTH_OF_PLAN: usize = 1 << 10;
+
+/// The note lines a plan holds of `lines`: as many of the first lines as a plan holds, each cut at a character boundary
+/// to the length a plan holds.
+pub(super) fn note_lines_a_plan_holds(lines: impl Iterator<Item = String>) -> Vec<String> {
+ lines
+ .take(MAXIMUM_NOTE_LINE_COUNT_OF_PLAN)
+ .map(|mut line| {
+ line.truncate(line.floor_char_boundary(MAXIMUM_NOTE_LINE_LENGTH_OF_PLAN));
+ line
+ })
+ .collect()
+}
/// A stack decoded from another process: why it is one layer that replays the whole list, or the plan of a stack of
/// more layers. Nothing reads it until `validated_stack` checks it and works out the stack.
@@ -47,12 +64,14 @@ enum StackOnWire {
}
/// A plan of the layers of a list as WebContent sends it to the compositor: the stack, the display list it was planned
-/// for, and the viewport, in device pixels, it was planned within.
+/// for, the viewport, in device pixels, it was planned within, and what the overlay of layers tells of the stack past
+/// its layers.
#[derive(Clone, Debug, PartialEq)]
pub struct LayerPlan {
pub display_list_id: u64,
pub viewport_rect: IntRect,
pub stack: LayerStack,
+ pub note_lines: Vec<String>,
}
/// A plan of layers decoded from another process, whose stack nothing reads until it is checked.
@@ -61,16 +80,19 @@ pub struct UnvalidatedLayerPlan {
pub display_list_id: u64,
pub viewport_rect: IntRect,
stack: StackOnWire,
+ note_lines: Vec<String>,
}
impl UnvalidatedLayerPlan {
/// The plan, once its stack passes `validated_stack` for `list` under `tree` within the viewport the plan
- /// names. The receiver makes sure that `list` is the list that `display_list_id` names.
+ /// names. The receiver makes sure that `list` is the list that `display_list_id` names. The note lines go unchecked:
+ /// decoding bounds their count and length, and only the overlay of layers shows them.
pub fn validated(self, list: &DisplayListStorage, tree: &VisualContextTree) -> Result<LayerPlan, &'static str> {
Ok(LayerPlan {
display_list_id: self.display_list_id,
viewport_rect: self.viewport_rect,
stack: validated_stack(self.stack, list, tree, self.viewport_rect)?,
+ note_lines: self.note_lines,
})
}
}
@@ -411,22 +433,35 @@ impl Encode for LayerStack {
}
}
+fn decode_note_lines(decoder: &mut Decoder<'_>) -> Result<Vec<String>, DecodeError> {
+ let count = decoder.decode_size()?;
+ if count > MAXIMUM_NOTE_LINE_COUNT_OF_PLAN || count > decoder.remaining_bytes() / String::MIN_ENCODED_SIZE {
+ return Err(DecodeError::SizeTooLarge(count));
+ }
+ (0..count)
+ .map(|_| decoder.decode_with_max_size(MAXIMUM_NOTE_LINE_LENGTH_OF_PLAN))
+ .collect()
+}
+
impl Encode for LayerPlan {
fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {
encoder.encode(&self.display_list_id)?;
encoder.encode(&self.viewport_rect)?;
- encoder.encode(&self.stack)
+ encoder.encode(&self.stack)?;
+ encoder.encode(&self.note_lines)
}
}
impl Decode for UnvalidatedLayerPlan {
- const MIN_ENCODED_SIZE: usize = size_of::<u64>() + IntRect::MIN_ENCODED_SIZE + StackOnWire::MIN_ENCODED_SIZE;
+ const MIN_ENCODED_SIZE: usize =
+ size_of::<u64>() + IntRect::MIN_ENCODED_SIZE + StackOnWire::MIN_ENCODED_SIZE + Vec::<String>::MIN_ENCODED_SIZE;
fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
Ok(Self {
display_list_id: decoder.decode()?,
viewport_rect: decoder.decode()?,
stack: decoder.decode()?,
+ note_lines: decode_note_lines(decoder)?,
})
}
}
@@ -1274,6 +1309,7 @@ mod tests {
display_list_id: 42,
viewport_rect: VIEWPORT,
stack: planned.stack.clone(),
+ note_lines: planned.note_lines_for_layers_overlay(),
}
}
@@ -1566,6 +1602,62 @@ mod tests {
}
}
+ // The overlay of layers showed these lines of the plans of these pages before the plan carried them as text.
+ #[test]
+ fn the_note_lines_of_a_plan_are_the_lines_the_overlay_of_layers_showed() {
+ let lines_of = |page: Page| page.planned().note_lines_for_layers_overlay();
+ assert_eq!(
+ lines_of(page_with_nested_composited_effects()),
+ [
+ "composited e1 space=document: the compositor animates it",
+ "composited e2 space=document inside e1: the compositor animates it",
+ ]
+ );
+ assert_eq!(
+ lines_of(page_with_spinner_holding_the_root_group()),
+ ["composited e0 space=animated@s1 in viewport: it applies over a transform the compositor animates"]
+ );
+ assert_eq!(
+ lines_of(page_with_nine_canvases()),
+ ["no layer for canvas: past the most media that get layers"]
+ );
+ assert_eq!(
+ lines_of(page_with_two_fading_siblings()),
+ [
+ "composited e1 space=document: the compositor animates it",
+ "composited e2 space=document: the compositor animates it",
+ ]
+ );
+ assert_eq!(
+ lines_of(page_with_frosted_glass()),
+ [
+ "composited e2 space=document reads=[73,73 254x154]: it reads what its own layer does not hold",
+ "e1 is not composited: it reads only its own layer",
+ ]
+ );
+ assert!(lines_of(page_under_translucent_root()).is_empty());
+ assert!(lines_of(plain_page()).is_empty());
+ }
+
+ #[test]
+ fn note_lines_past_what_a_plan_holds_are_cut() {
+ // The last character that fits is cut in two at the length a line holds, so the line ends before it.
+ let long_line = format!("a{}", "é".repeat(MAXIMUM_NOTE_LINE_LENGTH_OF_PLAN));
+ let lines = note_lines_a_plan_holds(std::iter::repeat_n(long_line, MAXIMUM_NOTE_LINE_COUNT_OF_PLAN + 1));
+ assert_eq!(lines.len(), MAXIMUM_NOTE_LINE_COUNT_OF_PLAN);
+ assert!(
+ lines
+ .iter()
+ .all(|line| line.len() == MAXIMUM_NOTE_LINE_LENGTH_OF_PLAN - 1)
+ );
+ let page = plain_page();
+ let sent = LayerPlan {
+ note_lines: lines,
+ ..plan_sent_of(&page.planned())
+ };
+ assert_eq!(decoded_and_validated_plan(&page, &encoded(&sent)), Ok(sent));
+ }
+
#[test]
fn every_reason_and_kind_round_trips() {
fn round_trip<T: Encode + Decode + PartialEq + std::fmt::Debug>(value: T) {
@@ -1621,6 +1713,23 @@ mod tests {
Err(DecodeError::SizeTooLarge(_))
));
let page = page_with_two_canvases();
+ let plan_with_note_lines = |note_lines: Vec<String>| {
+ encoded(&LayerPlan {
+ note_lines,
+ ..plan_sent_of(&page.planned())
+ })
+ };
+ let too_many_lines = vec![String::new(); MAXIMUM_NOTE_LINE_COUNT_OF_PLAN + 1];
+ let too_long_line = vec!["x".repeat(MAXIMUM_NOTE_LINE_LENGTH_OF_PLAN + 1)];
+ for bytes in [
+ plan_with_note_lines(too_many_lines),
+ plan_with_note_lines(too_long_line),
+ ] {
+ assert!(matches!(
+ Decoder::new(&bytes, []).decode::<UnvalidatedLayerPlan>(),
+ Err(DecodeError::SizeTooLarge(_))
+ ));
+ }
// A count of many spans that the bytes cannot hold is refused too.
let mut bytes = encoded(&plan_sent_of(&page.planned()));
bytes.truncate(bytes.len() / 2);
@@ -2116,6 +2225,7 @@ mod tests {
for run_index in 0..list.run_count() {
planned_with_stack.layers_of_record(list.span_of_run(run_index).begin);
}
+ planned_with_stack.note_lines_for_layers_overlay();
for layer_index in 0..stack.layers.len() {
stack.space_holds_content_that_moves_within_it(stack.space_of_layer(LayerIndex(layer_index)));
}
diff --git a/Libraries/LibCompositing/Types.h b/Libraries/LibCompositing/Types.h
index 87c525f79d9..8d04c7ef408 100644
--- a/Libraries/LibCompositing/Types.h
+++ b/Libraries/LibCompositing/Types.h
@@ -11,12 +11,14 @@
#include <AK/EnumBits.h>
#include <AK/Math.h>
#include <AK/Optional.h>
+#include <AK/String.h>
#include <AK/Time.h>
#include <AK/Types.h>
#include <AK/Vector.h>
#include <LibCompositing/Export.h>
#include <LibCompositing/Scrolling/AsyncScrollingState.h>
#include <LibCompositing/Scrolling/ScrollSnapSelection.h>
+#include <LibGfx/Rect.h>
#include <LibIPC/Forward.h>
#include <LibWebCommon/Page/CompositorContextId.h>
#include <LibWebCommon/Page/InputEvent.h>
@@ -311,6 +313,56 @@ struct ScrollRequest {
}
};
+enum class VisualContextNodeKind : u8 {
+ Spatial,
+ Effect,
+};
+
+// A node of the visual context tree that the name of a layer mentions, with the element whose box owns it. The
+// compositor names the node, and the view asks the page for the element.
+struct CompositorLayerNodeDescription {
+ VisualContextNodeKind kind { VisualContextNodeKind::Spatial };
+ u32 index { 0 };
+ String element;
+
+ bool operator==(CompositorLayerNodeDescription const&) const = default;
+};
+
+struct CompositorLayerDescription {
+ u64 id { 0 };
+ String name;
+ String details;
+ u32 rgb_of_outline { 0 };
+ bool hidden { false };
+ // In the device pixels of the viewport: what of the layer's outline the frame shows.
+ Gfx::IntRect visible_rect_in_viewport;
+ Vector<CompositorLayerNodeDescription> nodes;
+ u64 tiles_rastered_since_reset { 0 };
+ String raster_causes_since_reset;
+
+ bool operator==(CompositorLayerDescription const&) const = default;
+};
+
+struct CompositorTileHighlightDescription {
+ String raster_cause;
+ u32 rgb { 0 };
+
+ bool operator==(CompositorTileHighlightDescription const&) const = default;
+};
+
+struct CompositorLayersDescription {
+ // From the base layer up.
+ Vector<CompositorLayerDescription> layers;
+ Vector<String> notes;
+ String summary_of_last_frame;
+ Vector<CompositorTileHighlightDescription> tile_highlights;
+ String summary_since_reset;
+ // The tree whose nodes the layers name, which the page names the elements of only while it holds the same tree.
+ u64 visual_context_tree_structural_epoch { 0 };
+
+ bool operator==(CompositorLayersDescription const&) const = default;
+};
+
// AD-HOC: Wheel events carry no gesture phase information, so a wheel gesture is considered finished once no input of
// it has moved a scrolling box for this long. The side that scrolled the gesture's steps decides when its
// input ran out: the compositor reports the end of a gesture whose steps it chained, and the main thread
diff --git a/Libraries/LibCompositing/Types.ipc b/Libraries/LibCompositing/Types.ipc
index 06750d01af7..64dcbb2168e 100644
--- a/Libraries/LibCompositing/Types.ipc
+++ b/Libraries/LibCompositing/Types.ipc
@@ -7,6 +7,7 @@
#include <LibCompositing/Types.h>
#include <LibCompositing/WebGL/Types.h>
+#include <LibGfx/Rect.h>
[ExistingCpp]
enum Compositing::WindowResizingInProgress : u8 {
@@ -201,3 +202,45 @@ struct Compositing::WheelStepLetThrough {
Web::ScrollGesturePhase scroll_gesture_phase;
Vector<Web::AsyncScrollNodeStableID> scroll_chain;
}
+
+[ExistingCpp]
+enum Compositing::VisualContextNodeKind : u8 {
+ Spatial,
+ Effect,
+}
+
+[ExistingCpp, RustDerive=Eq]
+struct Compositing::CompositorLayerNodeDescription {
+ Compositing::VisualContextNodeKind kind;
+ u32 index;
+ String element;
+}
+
+[ExistingCpp, RustDerive=Eq+Default]
+struct Compositing::CompositorLayerDescription {
+ u64 id;
+ String name;
+ String details;
+ u32 rgb_of_outline;
+ bool hidden;
+ Gfx::IntRect visible_rect_in_viewport;
+ Vector<Compositing::CompositorLayerNodeDescription> nodes;
+ u64 tiles_rastered_since_reset;
+ String raster_causes_since_reset;
+}
+
+[ExistingCpp, RustDerive=Eq+Default]
+struct Compositing::CompositorTileHighlightDescription {
+ String raster_cause;
+ u32 rgb;
+}
+
+[ExistingCpp, RustDerive=Eq+Default]
+struct Compositing::CompositorLayersDescription {
+ Vector<Compositing::CompositorLayerDescription> layers;
+ Vector<String> notes;
+ String summary_of_last_frame;
+ Vector<Compositing::CompositorTileHighlightDescription> tile_highlights;
+ String summary_since_reset;
+ u64 visual_context_tree_structural_epoch;
+}
diff --git a/Libraries/LibCompositing/UIOverlays.cpp b/Libraries/LibCompositing/UIOverlays.cpp
index 7dfa341fbaa..92fbb65ddc1 100644
--- a/Libraries/LibCompositing/UIOverlays.cpp
+++ b/Libraries/LibCompositing/UIOverlays.cpp
@@ -85,11 +85,35 @@ ErrorOr<Compositing::PictureInPictureControlsState> decode(Decoder& decoder)
};
}
+template<>
+ErrorOr<void> encode(Encoder& encoder, Compositing::CompositorLayersOverlayState const& state)
+{
+ TRY(encoder.encode(state.font_family));
+ TRY(encoder.encode(state.hidden_layer_ids));
+ TRY(encoder.encode(state.selected_layer_ids));
+ TRY(encoder.encode(state.hovered_layer_id));
+ TRY(encoder.encode(state.raster_count_reset_generation));
+ return {};
+}
+
+template<>
+ErrorOr<Compositing::CompositorLayersOverlayState> decode(Decoder& decoder)
+{
+ return Compositing::CompositorLayersOverlayState {
+ .font_family = TRY(decoder.decode<Optional<String>>()),
+ .hidden_layer_ids = TRY(decoder.decode<Vector<u64>>()),
+ .selected_layer_ids = TRY(decoder.decode<Vector<u64>>()),
+ .hovered_layer_id = TRY(decoder.decode<Optional<u64>>()),
+ .raster_count_reset_generation = TRY(decoder.decode<u64>()),
+ };
+}
+
template<>
ErrorOr<void> encode(Encoder& encoder, Compositing::UIOverlays const& overlays)
{
TRY(encoder.encode(overlays.paused_debugger));
TRY(encoder.encode(overlays.picture_in_picture_controls));
+ TRY(encoder.encode(overlays.compositor_layers));
return {};
}
@@ -99,6 +123,7 @@ ErrorOr<Compositing::UIOverlays> decode(Decoder& decoder)
return Compositing::UIOverlays {
.paused_debugger = TRY(decoder.decode<Optional<Compositing::PausedDebuggerOverlayState>>()),
.picture_in_picture_controls = TRY(decoder.decode<Optional<Compositing::PictureInPictureControlsState>>()),
+ .compositor_layers = TRY(decoder.decode<Optional<Compositing::CompositorLayersOverlayState>>()),
};
}
diff --git a/Libraries/LibCompositing/UIOverlays.h b/Libraries/LibCompositing/UIOverlays.h
index 91df00405a6..a4f153e5bb2 100644
--- a/Libraries/LibCompositing/UIOverlays.h
+++ b/Libraries/LibCompositing/UIOverlays.h
@@ -8,6 +8,7 @@
#include <AK/Optional.h>
#include <AK/String.h>
+#include <AK/Vector.h>
#include <LibCompositing/Export.h>
#include <LibCompositing/PausedDebuggerOverlay.h>
#include <LibCompositing/PictureInPictureControls.h>
@@ -31,11 +32,24 @@ struct PictureInPictureControlsState {
bool operator==(PictureInPictureControlsState const&) const = default;
};
+struct CompositorLayersOverlayState {
+ Optional<String> font_family;
+ Vector<u64> hidden_layer_ids;
+ // The layers the overlay shows the tiles of.
+ Vector<u64> selected_layer_ids;
+ Optional<u64> hovered_layer_id;
+ // Each new value zeroes the counts of tiles rastered.
+ u64 raster_count_reset_generation { 0 };
+
+ bool operator==(CompositorLayersOverlayState const&) const = default;
+};
+
// What the browser draws over a context's page, on top of anything the page draws, with each overlay the view has
// present. The browser handles their input before the page sees any of it.
struct UIOverlays {
Optional<PausedDebuggerOverlayState> paused_debugger;
Optional<PictureInPictureControlsState> picture_in_picture_controls;
+ Optional<CompositorLayersOverlayState> compositor_layers;
bool operator==(UIOverlays const&) const = default;
};
@@ -113,6 +127,11 @@ COMPOSITING_API ErrorOr<void> encode(Encoder&, Compositing::PictureInPictureCont
template<>
COMPOSITING_API ErrorOr<Compositing::PictureInPictureControlsState> decode(Decoder&);
+template<>
+COMPOSITING_API ErrorOr<void> encode(Encoder&, Compositing::CompositorLayersOverlayState const&);
+template<>
+COMPOSITING_API ErrorOr<Compositing::CompositorLayersOverlayState> decode(Decoder&);
+
template<>
COMPOSITING_API ErrorOr<void> encode(Encoder&, Compositing::UIOverlays const&);
template<>
diff --git a/Libraries/LibWeb/Rust/src/painting/presentation.rs b/Libraries/LibWeb/Rust/src/painting/presentation.rs
index 1a50fe46f2a..dd45db6b2af 100644
--- a/Libraries/LibWeb/Rust/src/painting/presentation.rs
+++ b/Libraries/LibWeb/Rust/src/painting/presentation.rs
@@ -797,6 +797,7 @@ fn layer_plan_made_from(display_list_id: u64, inputs: InputsOfLayerPlan) -> Laye
plan: Arc::new(LayerPlan {
display_list_id,
viewport_rect: inputs.viewport_rect(),
+ note_lines: planned.note_lines_for_layers_overlay(),
stack: planned.stack,
}),
inputs,
diff --git a/Libraries/LibWebView/CompositorPresentationClient.cpp b/Libraries/LibWebView/CompositorPresentationClient.cpp
index e8e37a7a5ce..162b3045915 100644
--- a/Libraries/LibWebView/CompositorPresentationClient.cpp
+++ b/Libraries/LibWebView/CompositorPresentationClient.cpp
@@ -129,6 +129,12 @@ void CompositorPresentationClient::did_consume_input_event(Web::CompositorContex
page->did_consume_input_event_in_compositor(event_id);
}
+void CompositorPresentationClient::did_update_compositor_layers(Web::CompositorContextId context_id, Compositing::CompositorLayersDescription layers)
+{
+ if (auto* page = page_for_compositor_context_id(context_id))
+ page->did_update_compositor_layers(layers);
+}
+
void CompositorPresentationClient::did_not_dispatch_input_event(Web::CompositorContextId context_id, u64 event_id)
{
if (auto* page = page_for_compositor_context_id(context_id))
diff --git a/Libraries/LibWebView/CompositorPresentationClient.h b/Libraries/LibWebView/CompositorPresentationClient.h
index 14511c75b54..93374bc390f 100644
--- a/Libraries/LibWebView/CompositorPresentationClient.h
+++ b/Libraries/LibWebView/CompositorPresentationClient.h
@@ -45,6 +45,7 @@ private:
virtual void did_present_frame(Web::CompositorContextId, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, i32 bitmap_id, double device_pixel_ratio) override;
virtual void did_present_frame_in_remote_layer(Web::CompositorContextId, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, double device_pixel_ratio) override;
virtual void did_consume_input_event(Web::CompositorContextId, u64 event_id) override;
+ virtual void did_update_compositor_layers(Web::CompositorContextId, Compositing::CompositorLayersDescription) override;
virtual void did_not_dispatch_input_event(Web::CompositorContextId, u64 event_id) override;
virtual void did_dispatch_input_event(Web::CompositorContextId, u64 event_id, bool performed_default_action) override;
virtual void did_take_frame_snapshot(u64 request_id, Optional<Gfx::ShareableBitmap>) override;
diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cpp
index 6882431ab30..921c7f9f72b 100644
--- a/Libraries/LibWebView/ViewImplementation.cpp
+++ b/Libraries/LibWebView/ViewImplementation.cpp
@@ -2766,6 +2766,12 @@ void ViewImplementation::update_ui_overlays()
Application::the().update_compositor_ui_overlays(page().compositor_context_id(), overlays);
}
+void ViewImplementation::did_update_compositor_layers(Badge<WebContentPage>, Compositing::CompositorLayersDescription const& layers)
+{
+ if (on_compositor_layers_change)
+ on_compositor_layers_change(layers);
+}
+
void ViewImplementation::update_debugger_blackboxing(Utf16String url, Vector<DebuggerBlackboxRange> ranges, DebuggerBlackboxingOperation operation)
{
page().async_update_debugger_blackboxing(move(url), move(ranges), operation);
diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.h
index ef58676a231..16efbc41097 100644
--- a/Libraries/LibWebView/ViewImplementation.h
+++ b/Libraries/LibWebView/ViewImplementation.h
@@ -370,6 +370,7 @@ public:
bool take_input_to_open_link_in_new_tab(Badge<WebContentPage>, WebContentPage const&);
void did_lose_input_event_endpoint(Badge<WebContentPage>, WebContentPage&);
void did_consume_input_event_in_compositor(Badge<WebContentPage>, u64 event_id);
+ void did_update_compositor_layers(Badge<WebContentPage>, Compositing::CompositorLayersDescription const&);
void did_not_dispatch_input_event_through_compositor(Badge<WebContentPage>, u64 event_id);
void did_dispatch_input_event_through_compositor(Badge<WebContentPage>, u64 event_id, bool performed_default_action);
void discard_input_events_routed_through_lost_compositor(Badge<Application>);
@@ -655,6 +656,7 @@ public:
Function<void()> on_ready_to_paint;
Function<void(TabPerformanceStats const&)> on_performance_stats;
+ Function<void(Compositing::CompositorLayersDescription const&)> on_compositor_layers_change;
Function<String(Web::HTML::ActivateTab, Web::HTML::WebViewHints, CanonicalTraversable&)> on_new_web_view;
Function<void()> on_activate_tab;
Function<void()> on_close;
diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cpp
index 2215c3ca24a..36746a86896 100644
--- a/Libraries/LibWebView/WebContentPage.cpp
+++ b/Libraries/LibWebView/WebContentPage.cpp
@@ -545,6 +545,12 @@ void WebContentPage::did_consume_input_event_in_compositor(u64 event_id)
}
}
+void WebContentPage::did_update_compositor_layers(Compositing::CompositorLayersDescription const& layers)
+{
+ if (displays_tab())
+ view().did_update_compositor_layers({}, layers);
+}
+
void WebContentPage::did_not_dispatch_input_event_through_compositor(u64 event_id)
{
dbgln_if(COMPOSITOR_DEBUG, "[Compositor] UI compositor did not dispatch input event {} for page {}; sending it to WebContent directly", event_id, m_id);
diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.h
index 073ef89fe2f..aa495acb9e1 100644
--- a/Libraries/LibWebView/WebContentPage.h
+++ b/Libraries/LibWebView/WebContentPage.h
@@ -171,6 +171,7 @@ public:
// Returns whether the event was posted; a page without a compositor sends it to WebContent itself.
bool handle_and_dispatch_mouse_event_in_compositor(Web::MouseEvent const&);
void did_consume_input_event_in_compositor(u64 event_id);
+ void did_update_compositor_layers(Compositing::CompositorLayersDescription const&);
void did_not_dispatch_input_event_through_compositor(u64 event_id);
void did_dispatch_input_event_through_compositor(u64 event_id, bool performed_default_action);
void did_present_bitmap(Gfx::IntRect content_rect, Gfx::IntRect damage_rect, i32 bitmap_id, double device_pixel_ratio);
diff --git a/Services/Compositor/CompositorCore.cpp b/Services/Compositor/CompositorCore.cpp
index fda383eac4e..073bea46570 100644
--- a/Services/Compositor/CompositorCore.cpp
+++ b/Services/Compositor/CompositorCore.cpp
@@ -53,12 +53,12 @@ static void destroy_timer(void* host, u64 timer_number)
static_cast<CompositorCoreHost*>(host)->destroy_timer(timer_number);
}
-static void shape_overlay_label(void* host, u64 context_id, bool has_font_family, ReadonlyBytes font_family, double device_pixel_ratio, ReadonlyBytes text, void* receiver, void (*receive)(void*, RustFFI::FfiOverlayLabel const*))
+static void shape_overlay_label(void* host, u64 context_id, bool has_font_family, ReadonlyBytes font_family, float font_size_in_points, double device_pixel_ratio, ReadonlyBytes text, void* receiver, void (*receive)(void*, RustFFI::FfiOverlayLabel const*))
{
Optional<StringView> font_family_view;
if (has_font_family)
font_family_view = StringView { font_family };
- auto label = static_cast<CompositorCoreHost*>(host)->shape_overlay_label(Web::CompositorContextId { context_id }, font_family_view, device_pixel_ratio, StringView { text });
+ auto label = static_cast<CompositorCoreHost*>(host)->shape_overlay_label(Web::CompositorContextId { context_id }, font_family_view, font_size_in_points, device_pixel_ratio, StringView { text });
if (!label.has_value())
return;
RustFFI::FfiOverlayLabel ffi_label {
@@ -168,7 +168,9 @@ void CompositorCore::set_ui_overlays(Web::CompositorContextId context_id, Compos
{
auto const& paused_debugger = overlays.paused_debugger;
auto const& picture_in_picture_controls = overlays.picture_in_picture_controls;
+ auto const& compositor_layers = overlays.compositor_layers;
auto font_family = paused_debugger.has_value() && paused_debugger->font_family.has_value() ? paused_debugger->font_family->bytes() : ReadonlyBytes {};
+ auto compositor_layers_font_family = compositor_layers.has_value() && compositor_layers->font_family.has_value() ? compositor_layers->font_family->bytes() : ReadonlyBytes {};
RustFFI::FfiUIOverlays ffi_overlays {
.has_paused_debugger = paused_debugger.has_value(),
.paused_debugger_has_font_family = paused_debugger.has_value() && paused_debugger->font_family.has_value(),
@@ -179,6 +181,14 @@ void CompositorCore::set_ui_overlays(Web::CompositorContextId context_id, Compos
.picture_in_picture_controls_shown = picture_in_picture_controls.has_value() && picture_in_picture_controls->shown,
.picture_in_picture_controls_has_hovered_control = picture_in_picture_controls.has_value() && picture_in_picture_controls->hovered_control.has_value(),
.picture_in_picture_controls_hovered_control = picture_in_picture_controls.has_value() && picture_in_picture_controls->hovered_control.has_value() ? to_underlying(*picture_in_picture_controls->hovered_control) : u8 { 0 },
+ .has_compositor_layers = compositor_layers.has_value(),
+ .compositor_layers_has_font_family = compositor_layers.has_value() && compositor_layers->font_family.has_value(),
+ .compositor_layers_font_family = compositor_layers_font_family,
+ .compositor_layers_hidden_layer_ids = compositor_layers.has_value() ? compositor_layers->hidden_layer_ids.span() : ReadonlySpan<u64> {},
+ .compositor_layers_selected_layer_ids = compositor_layers.has_value() ? compositor_layers->selected_layer_ids.span() : ReadonlySpan<u64> {},
+ .compositor_layers_has_hovered_layer_id = compositor_layers.has_value() && compositor_layers->hovered_layer_id.has_value(),
+ .compositor_layers_hovered_layer_id = compositor_layers.has_value() ? compositor_layers->hovered_layer_id.value_or(0) : 0,
+ .compositor_layers_raster_count_reset_generation = compositor_layers.has_value() ? compositor_layers->raster_count_reset_generation : 0,
};
RustFFI::compositor_core_set_ui_overlays(m_core, context_id.value(), &ffi_overlays, now().nanoseconds());
}
diff --git a/Services/Compositor/CompositorCoreHost.h b/Services/Compositor/CompositorCoreHost.h
index c54fdb18606..7202d371ccd 100644
--- a/Services/Compositor/CompositorCoreHost.h
+++ b/Services/Compositor/CompositorCoreHost.h
@@ -52,7 +52,7 @@ public:
// The timer is not set again.
virtual void destroy_timer(u64 timer_number) = 0;
// In the font family given, or the default one. Empty where no font draws the label.
- virtual Optional<OverlayLabel> shape_overlay_label(Web::CompositorContextId, Optional<StringView> font_family, double device_pixel_ratio, StringView text) = 0;
+ virtual Optional<OverlayLabel> shape_overlay_label(Web::CompositorContextId, Optional<StringView> font_family, float font_size_in_points, double device_pixel_ratio, StringView text) = 0;
};
}
diff --git a/Services/Compositor/CompositorPresentationClient.ipc b/Services/Compositor/CompositorPresentationClient.ipc
index 890d021bfc9..6db41808417 100644
--- a/Services/Compositor/CompositorPresentationClient.ipc
+++ b/Services/Compositor/CompositorPresentationClient.ipc
@@ -16,4 +16,5 @@ endpoint CompositorPresentationClient
[RustSender] did_consume_input_event(Web::CompositorContextId context_id, u64 event_id) =|
[RustSender] did_not_dispatch_input_event(Web::CompositorContextId context_id, u64 event_id) =|
[RustSender] did_dispatch_input_event(Web::CompositorContextId context_id, u64 event_id, bool performed_default_action) =|
+ [RustSender] did_update_compositor_layers(Web::CompositorContextId context_id, Compositing::CompositorLayersDescription layers) =|
}
diff --git a/Services/Compositor/CompositorState.cpp b/Services/Compositor/CompositorState.cpp
index 825a5dcd952..0cfb4006039 100644
--- a/Services/Compositor/CompositorState.cpp
+++ b/Services/Compositor/CompositorState.cpp
@@ -675,12 +675,12 @@ void CompositorState::viewport_size_updated(Web::CompositorContextId context_id,
m_core.viewport_size_updated(context_id, viewport_size, device_pixel_ratio, window_resize_in_progress);
}
-Optional<OverlayLabel> CompositorState::shape_overlay_label(Web::CompositorContextId context_id, Optional<StringView> font_family, double device_pixel_ratio, StringView text)
+Optional<OverlayLabel> CompositorState::shape_overlay_label(Web::CompositorContextId context_id, Optional<StringView> font_family, float font_size_in_points, double device_pixel_ratio, StringView text)
{
auto* context = presented_context_if_present(context_id);
if (!context)
return {};
- return context->raster_targets.shape_overlay_label(font_family, device_pixel_ratio, text);
+ return context->raster_targets.shape_overlay_label(font_family, font_size_in_points, device_pixel_ratio, text);
}
void CompositorState::set_ui_overlays(Web::CompositorContextId context_id, Compositing::UIOverlays overlays)
diff --git a/Services/Compositor/CompositorState.h b/Services/Compositor/CompositorState.h
index da380ae9a3f..e5e404429f9 100644
--- a/Services/Compositor/CompositorState.h
+++ b/Services/Compositor/CompositorState.h
@@ -185,7 +185,7 @@ private:
virtual void set_timer(u64 timer_number, AK::Duration delay) override;
virtual void cancel_timer(u64 timer_number) override;
virtual void destroy_timer(u64 timer_number) override;
- virtual Optional<OverlayLabel> shape_overlay_label(Web::CompositorContextId, Optional<StringView> font_family, double device_pixel_ratio, StringView text) override;
+ virtual Optional<OverlayLabel> shape_overlay_label(Web::CompositorContextId, Optional<StringView> font_family, float font_size_in_points, double device_pixel_ratio, StringView text) override;
// What the compositor keeps of a context to paint and present its frames.
struct PresentedContext {
diff --git a/Services/Compositor/ContextRasterTargets.cpp b/Services/Compositor/ContextRasterTargets.cpp
index 3d3ff708177..f89e1d3e542 100644
--- a/Services/Compositor/ContextRasterTargets.cpp
+++ b/Services/Compositor/ContextRasterTargets.cpp
@@ -29,13 +29,26 @@ void ContextRasterTargets::retain_only_image_frames(ReadonlySpan<u64> image_fram
m_raster_cache.forget_image_frames(m_image_frames.retain_only(image_frame_ids));
}
-Optional<OverlayLabel> ContextRasterTargets::shape_overlay_label(Optional<StringView> font_family, double device_pixel_ratio, StringView text)
+static RefPtr<Gfx::Font> fallback_font_of_overlay_labels(float font_size_in_points)
+{
+ static Optional<FlyString> s_system_sans_serif_family;
+ auto& font_database = Gfx::FontDatabase::the();
+ if (!s_system_sans_serif_family.has_value())
+ s_system_sans_serif_family = font_database.resolve_generic_family("sans-serif"sv, 400, 0);
+ if (s_system_sans_serif_family.has_value()) {
+ if (auto font = font_database.get(*s_system_sans_serif_family, font_size_in_points, 400, Gfx::FontWidth::Normal, 0))
+ return font;
+ }
+ return font_database.get("SerenitySans"_fly_string, font_size_in_points, 400, Gfx::FontWidth::Normal, 0);
+}
+
+Optional<OverlayLabel> ContextRasterTargets::shape_overlay_label(Optional<StringView> font_family, float font_size_in_points, double device_pixel_ratio, StringView text)
{
RefPtr<Gfx::Font> font;
if (font_family.has_value())
- font = Gfx::FontDatabase::the().get(MUST(FlyString::from_utf8(*font_family)), 12, 400, Gfx::FontWidth::Normal, 0);
+ font = Gfx::FontDatabase::the().get(MUST(FlyString::from_utf8(*font_family)), font_size_in_points, 400, Gfx::FontWidth::Normal, 0);
if (!font)
- font = Gfx::FontDatabase::the().get("SerenitySans"_fly_string, 12, 400, Gfx::FontWidth::Normal, 0);
+ font = fallback_font_of_overlay_labels(font_size_in_points);
if (!font)
return {};
auto skia_font = Compositor::skia_font(*font, static_cast<float>(device_pixel_ratio));
diff --git a/Services/Compositor/ContextRasterTargets.h b/Services/Compositor/ContextRasterTargets.h
index 2f0ca40ff7e..95fbfe167c7 100644
--- a/Services/Compositor/ContextRasterTargets.h
+++ b/Services/Compositor/ContextRasterTargets.h
@@ -52,7 +52,7 @@ public:
DrawnFonts const& overlay_fonts() const { return m_overlay_fonts; }
DisplayListRasterCache& overlay_raster_cache() { return m_overlay_raster_cache; }
// Shapes a label of the overlays, in a font that the overlays' fonts then hold.
- Optional<OverlayLabel> shape_overlay_label(Optional<StringView> font_family, double device_pixel_ratio, StringView text);
+ Optional<OverlayLabel> shape_overlay_label(Optional<StringView> font_family, float font_size_in_points, double device_pixel_ratio, StringView text);
// The video sinks that the display list of the context draws. Answers whether these are other sinks than before.
bool set_drawn_video_sinks(ReadonlySpan<u64> handles);
diff --git a/Services/Compositor/Rust/src/context_scene.rs b/Services/Compositor/Rust/src/context_scene.rs
index aca327d2ed2..61fcfd01723 100644
--- a/Services/Compositor/Rust/src/context_scene.rs
+++ b/Services/Compositor/Rust/src/context_scene.rs
@@ -28,6 +28,8 @@ pub struct ReceivedLayerPlan {
/// The spatial nodes whose scroll offset the plan reads. It holds wherever the compositor scrolls or moves the
/// other nodes to, which include the anchors of its spaces. Empty for a plan of one layer.
pub nodes_whose_scroll_offset_plan_reads: Rc<[u32]>,
+ /// What the overlay of layers tells of the stack past its layers, as WebContent wrote it.
+ pub note_lines: Rc<[String]>,
}
#[derive(Default)]
@@ -220,6 +222,7 @@ impl ContextScene {
viewport_rect: layer_plan.viewport_rect,
stack: Rc::new(layer_plan.stack),
nodes_whose_scroll_offset_plan_reads,
+ note_lines: layer_plan.note_lines.into(),
});
Ok(())
}
@@ -433,6 +436,7 @@ mod tests {
display_list_id,
viewport_rect: VIEWPORT,
stack,
+ note_lines: Vec::new(),
})))
.unwrap();
let (bytes, _) = encoder.finish();
diff --git a/Services/Compositor/Rust/src/context_state/frames_and_viewport.rs b/Services/Compositor/Rust/src/context_state/frames_and_viewport.rs
index 9c0601aeafe..e989d1d840e 100644
--- a/Services/Compositor/Rust/src/context_state/frames_and_viewport.rs
+++ b/Services/Compositor/Rust/src/context_state/frames_and_viewport.rs
@@ -229,16 +229,17 @@ impl ContextState {
|| (only_the_pixel_ratio_changed && ui_overlays.picture_in_picture_controls.is_some())
}
- /// Returns false, changing nothing, for the overlays already shown.
- pub fn set_ui_overlays(&mut self, ui_overlays: UIOverlays, now: MonotonicTime) -> bool {
+ pub fn set_ui_overlays(&mut self, ui_overlays: UIOverlays, now: MonotonicTime) -> UIOverlaysChange {
let shows_paused_debugger = ui_overlays.paused_debugger.is_some();
- if !self.overlays.set_ui_overlays(ui_overlays, now) {
- return false;
- }
- if shows_paused_debugger {
+ let change = self.overlays.set_ui_overlays(ui_overlays, now);
+ if change == UIOverlaysChange::RepaintsEverything && shows_paused_debugger {
self.end_keyboard_scroll_gesture();
}
- true
+ change
+ }
+
+ pub fn set_compositor_layers_overlay_needs_frames_until(&mut self, until: Option<MonotonicTime>) {
+ self.overlays.set_compositor_layers_overlay_needs_frames_until(until);
}
/// What the fades of the overlays repaint of the viewport as they advance to the frame.
@@ -247,6 +248,11 @@ impl ContextState {
.advance_fades(frame_time, self.viewport_size, self.device_pixel_ratio)
}
+ /// Whether the compositor layers overlay needs the frame, which rasters no tile again for that.
+ pub fn compositor_layers_overlay_needs_frame(&mut self, frame_time: MonotonicTime) -> bool {
+ self.overlays.compositor_layers_overlay_needs_frame(frame_time)
+ }
+
pub fn viewport_rect(&self) -> IntRect {
IntRect::new(0, 0, self.viewport_size.width, self.viewport_size.height)
}
diff --git a/Services/Compositor/Rust/src/context_state/mod.rs b/Services/Compositor/Rust/src/context_state/mod.rs
index bba4d68e76a..3a0cc7a0074 100644
--- a/Services/Compositor/Rust/src/context_state/mod.rs
+++ b/Services/Compositor/Rust/src/context_state/mod.rs
@@ -20,7 +20,7 @@ use crate::frame_inputs::FrameInputs;
use crate::host::{ContextTimer, Host, PendingFrame, PresentationId, WebContentClientId};
use crate::input_event::is_keyboard_scroll_key;
use crate::keyboard_scroll_controller::{KeyRelease, KeyStep, KeyboardScrollController};
-use crate::overlays::{ContextOverlays, UIOverlays};
+use crate::overlays::{ContextOverlays, UIOverlays, UIOverlaysChange};
use crate::scroll_fling_controller::ScrollFlingController;
use crate::scroll_snap_controller::{ScrollSnapController, SnapScrollStart, StepDecision};
use crate::scrollbar_controller::{Drag, ScrollbarController};
@@ -579,7 +579,7 @@ impl ContextState {
|| self.elastic_overscroll_controller.has_rebound()
|| self.visual_animations_need_frame(now)
|| self.scrollbar_controller.fades_need_frame(now)
- || self.overlays.fades_need_frame()
+ || self.overlays.fades_or_compositor_layers_overlay_need_frame()
}
pub fn has_active_scroll_fling(&self) -> bool {
self.scroll_fling_controller.is_active()
diff --git a/Services/Compositor/Rust/src/context_state/scrolling.rs b/Services/Compositor/Rust/src/context_state/scrolling.rs
index b3137a8548f..66fd65deef0 100644
--- a/Services/Compositor/Rust/src/context_state/scrolling.rs
+++ b/Services/Compositor/Rust/src/context_state/scrolling.rs
@@ -1139,6 +1139,7 @@ mod tests {
_: u64,
_: bool,
_: ak::Span<'_, u8>,
+ _: f32,
_: f64,
_: ak::Span<'_, u8>,
_: *mut c_void,
diff --git a/Services/Compositor/Rust/src/core/mod.rs b/Services/Compositor/Rust/src/core/mod.rs
index 672f76ba9c9..7abfcb8d434 100644
--- a/Services/Compositor/Rust/src/core/mod.rs
+++ b/Services/Compositor/Rust/src/core/mod.rs
@@ -18,7 +18,7 @@ use crate::host::{
ContextTimer, DisplayTickInputs, DisplayTickResult, Host, PendingFrame, PresentRequest, PresentScheduling,
PresentationId, Timer, WebContentClientId,
};
-use crate::overlays::UIOverlays;
+use crate::overlays::{UIOverlays, UIOverlaysChange};
use crate::presenting::ContextPresenting;
use crate::raster_host::RasterHost;
use crate::remote_layers::RemoteLayers;
@@ -336,12 +336,24 @@ impl CompositorCore {
let Some(context) = self.context_if_present(context_id) else {
return;
};
- if context.borrow_mut().set_ui_overlays(ui_overlays, now) {
- self.request_present_repainting_everything(context_id, context);
+ let change = context.borrow_mut().set_ui_overlays(ui_overlays, now);
+ match change {
+ UIOverlaysChange::Nothing => {}
+ UIOverlaysChange::OnlyCompositorLayers => self.request_present_keeping_tiles(context_id),
+ UIOverlaysChange::RepaintsEverything => self.request_present_repainting_everything(context_id, context),
}
self.finish_entry(now);
}
+ fn request_present_keeping_tiles(&self, context_id: CompositorContextId) {
+ self.present_requests.borrow_mut().push(PresentRequest {
+ context_id,
+ viewport_rect: None,
+ forced_damage_rect: Default::default(),
+ scheduling: PresentScheduling::OnNextDisplayTick,
+ });
+ }
+
// A frame at the viewport rect the context is presented at, which repaints all of it.
fn request_present_repainting_everything(&self, context_id: CompositorContextId, context: &RefCell<ContextState>) {
self.present_requests.borrow_mut().push(PresentRequest {
@@ -1032,6 +1044,14 @@ impl CompositorCore {
scheduling: PresentScheduling::WithDisplayTickInProgress,
});
}
+ if context.borrow_mut().compositor_layers_overlay_needs_frame(frame_time) {
+ self.present_requests.borrow_mut().push(PresentRequest {
+ context_id,
+ viewport_rect: None,
+ forced_damage_rect: Default::default(),
+ scheduling: PresentScheduling::WithDisplayTickInProgress,
+ });
+ }
}
DisplayTickResult {
presents_on_display,
diff --git a/Services/Compositor/Rust/src/core/presenting.rs b/Services/Compositor/Rust/src/core/presenting.rs
index 60c74ac6db5..423ae9645a2 100644
--- a/Services/Compositor/Rust/src/core/presenting.rs
+++ b/Services/Compositor/Rust/src/core/presenting.rs
@@ -429,9 +429,27 @@ impl CompositorCore {
};
let environment = self.environment(context_id, now, &nested_contexts);
let mut presenting = presenting.borrow_mut();
- let Some(prepared_frame) =
- presenting.prepare_frame(&environment, pending_frame, display_list.as_ref(), frame_inputs)
- else {
+ let prepared_frame = presenting.prepare_frame(&environment, pending_frame, display_list.as_ref(), frame_inputs);
+ if let Some(presentation_id) = bound_presentation
+ && let Some(layers) = presenting.take_description_of_layers_to_publish(now)
+ {
+ self.host.post_to_presentation(
+ presentation_id,
+ compositor_presentation_client::messages::DidUpdateCompositorLayers { context_id, layers },
+ );
+ }
+ // If the frame was not painted, as while the stores are not valid, the overlay is still that of an earlier
+ // frame, which can need frames until a time that is past.
+ let layer_overlay_needs_frames_until = presenting
+ .layer_overlay_needs_frames_until()
+ .filter(|&until| until > now);
+ context
+ .borrow_mut()
+ .set_compositor_layers_overlay_needs_frames_until(layer_overlay_needs_frames_until);
+ if layer_overlay_needs_frames_until.is_some() {
+ self.host.request_display_ticks(context_id);
+ }
+ let Some(prepared_frame) = prepared_frame else {
return;
};
diff --git a/Services/Compositor/Rust/src/ffi.rs b/Services/Compositor/Rust/src/ffi.rs
index 93e20e91da4..c4a96cd0401 100644
--- a/Services/Compositor/Rust/src/ffi.rs
+++ b/Services/Compositor/Rust/src/ffi.rs
@@ -12,8 +12,8 @@ use crate::core::presenting::{GpuBackend, PresentationCapabilities};
use crate::core::{CompositorCore, ContextOwnerCheckResult};
use crate::host::{FfiCompositorCoreHost, Host, PresentationId, WebContentClientId};
use crate::overlays::{
- PausedDebuggerOverlayAction, PausedDebuggerOverlayState, PictureInPictureControl, PictureInPictureControlsState,
- UIOverlays,
+ CompositorLayersOverlayState, PausedDebuggerOverlayAction, PausedDebuggerOverlayState, PictureInPictureControl,
+ PictureInPictureControlsState, UIOverlays,
};
use crate::raster_host::{FfiRasterHost, RasterHost};
use crate::surfaces::painting_surface::PaintingSurface;
@@ -522,6 +522,14 @@ pub struct FfiUIOverlays<'a> {
pub picture_in_picture_controls_shown: bool,
pub picture_in_picture_controls_has_hovered_control: bool,
pub picture_in_picture_controls_hovered_control: u8,
+ pub has_compositor_layers: bool,
+ pub compositor_layers_has_font_family: bool,
+ pub compositor_layers_font_family: ak::Span<'a, u8>,
+ pub compositor_layers_hidden_layer_ids: ak::Span<'a, u64>,
+ pub compositor_layers_selected_layer_ids: ak::Span<'a, u64>,
+ pub compositor_layers_has_hovered_layer_id: bool,
+ pub compositor_layers_hovered_layer_id: u64,
+ pub compositor_layers_raster_count_reset_generation: u64,
}
#[unsafe(no_mangle)]
@@ -587,6 +595,17 @@ pub extern "C" fn compositor_core_set_ui_overlays(
UIOverlays {
paused_debugger,
picture_in_picture_controls,
+ compositor_layers: ui_overlays.has_compositor_layers.then(|| CompositorLayersOverlayState {
+ font_family: ui_overlays.compositor_layers_has_font_family.then(|| {
+ String::from_utf8_lossy(ui_overlays.compositor_layers_font_family.as_slice()).into_owned()
+ }),
+ hidden_layer_ids: ui_overlays.compositor_layers_hidden_layer_ids.as_slice().to_vec(),
+ selected_layer_ids: ui_overlays.compositor_layers_selected_layer_ids.as_slice().to_vec(),
+ hovered_layer_id: ui_overlays
+ .compositor_layers_has_hovered_layer_id
+ .then_some(ui_overlays.compositor_layers_hovered_layer_id),
+ raster_count_reset_generation: ui_overlays.compositor_layers_raster_count_reset_generation,
+ }),
},
MonotonicTime::from_nanoseconds(now_nanoseconds),
);
diff --git a/Services/Compositor/Rust/src/host.rs b/Services/Compositor/Rust/src/host.rs
index 923a1c4b76b..3346bb436cf 100644
--- a/Services/Compositor/Rust/src/host.rs
+++ b/Services/Compositor/Rust/src/host.rs
@@ -140,13 +140,14 @@ pub struct FfiCompositorCoreHost {
pub cancel_timer: unsafe extern "C" fn(*mut c_void, u64),
/// The timer is not set again, so the host forgets it.
pub destroy_timer: unsafe extern "C" fn(*mut c_void, u64),
- /// Arguments: the context, whether a font family is given, the font family, the device pixel ratio, the text, and
- /// what receives the shaped label, which is not called where no font draws the label.
+ /// Arguments: the context, whether a font family is given, the font family, the font size in points, the device
+ /// pixel ratio, the text, and what receives the shaped label, which is not called where no font draws the label.
pub shape_overlay_label: unsafe extern "C" fn(
*mut c_void,
u64,
bool,
ak::Span<'_, u8>,
+ f32,
f64,
ak::Span<'_, u8>,
*mut c_void,
@@ -300,6 +301,7 @@ impl OverlayLabelShaper for ContextOverlayLabelShaper<'_> {
fn shape_overlay_label(
&self,
font_family: Option<&str>,
+ font_size_in_points: f32,
device_pixel_ratio: f64,
text: &str,
) -> Option<OverlayLabel> {
@@ -324,6 +326,7 @@ impl OverlayLabelShaper for ContextOverlayLabelShaper<'_> {
self.context_id.0,
font_family.is_some(),
ak::Span::new(font_family.unwrap_or_default().as_bytes()),
+ font_size_in_points,
device_pixel_ratio,
ak::Span::new(text.as_bytes()),
(&raw mut label).cast(),
diff --git a/Services/Compositor/Rust/src/overlays.rs b/Services/Compositor/Rust/src/overlays.rs
index 33b4283f15c..d345a62dd65 100644
--- a/Services/Compositor/Rust/src/overlays.rs
+++ b/Services/Compositor/Rust/src/overlays.rs
@@ -56,11 +56,35 @@ pub struct PictureInPictureControlsState {
pub hovered_control: Option<PictureInPictureControl>,
}
+/// The layers the frames are composited from and the tiles each holds, drawn by the compositor that knows them.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct CompositorLayersOverlayState {
+ pub font_family: Option<String>,
+ /// The layers the frames leave out, by the ids the descriptions the compositor publishes give them.
+ pub hidden_layer_ids: Vec<u64>,
+ /// The layers the overlay shows the tiles of.
+ pub selected_layer_ids: Vec<u64>,
+ /// The layer the overlay marks out, as the pointer is over it in the window or on the page.
+ pub hovered_layer_id: Option<u64>,
+ /// Each new value zeroes the counts of tiles rastered.
+ pub raster_count_reset_generation: u64,
+}
+
/// What the browser draws over a context's page, with each overlay the view has present.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct UIOverlays {
pub paused_debugger: Option<PausedDebuggerOverlayState>,
pub picture_in_picture_controls: Option<PictureInPictureControlsState>,
+ pub compositor_layers: Option<CompositorLayersOverlayState>,
+}
+
+/// What a new set of overlays changes of the frames.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum UIOverlaysChange {
+ Nothing,
+ /// The compositor layers overlay is drawn over tiles that stay as they are, so the frame rasters nothing for it.
+ OnlyCompositorLayers,
+ RepaintsEverything,
}
/// A label of an overlay as the host shapes it: the font it resolved, in the overlays' resources, and where each glyph
@@ -79,17 +103,20 @@ pub struct OverlayLabel {
pub font_ascent: f32,
}
-/// Shapes the label of an overlay, in the font family given or the default one, at a device pixel ratio.
+/// Shapes the label of an overlay, in the font family given or the default one, at a font size and a device pixel
+/// ratio.
pub trait OverlayLabelShaper {
fn shape_overlay_label(
&self,
font_family: Option<&str>,
+ font_size_in_points: f32,
device_pixel_ratio: f64,
text: &str,
) -> Option<OverlayLabel>;
}
const PAUSED_DEBUGGER_LABEL: &str = "Paused in debugger";
+const PAUSED_DEBUGGER_LABEL_FONT_SIZE_IN_POINTS: f32 = 12.0;
#[derive(Default)]
pub struct ContextOverlays {
@@ -97,6 +124,7 @@ pub struct ContextOverlays {
picture_in_picture_controls_fade: OverlayFade,
// The label of the paused debugger overlay, for the font family and device pixel ratio it was shaped for.
paused_debugger_label: Option<(Option<String>, f64, Option<OverlayLabel>)>,
+ compositor_layers_overlay_needs_frames_until: Option<MonotonicTime>,
}
impl ContextOverlays {
@@ -104,23 +132,45 @@ impl ContextOverlays {
&self.ui_overlays
}
- /// Returns false, changing nothing, for the overlays already shown.
- pub fn set_ui_overlays(&mut self, ui_overlays: UIOverlays, now: MonotonicTime) -> bool {
+ pub fn set_ui_overlays(&mut self, ui_overlays: UIOverlays, now: MonotonicTime) -> UIOverlaysChange {
if self.ui_overlays == ui_overlays {
- return false;
+ return UIOverlaysChange::Nothing;
}
+ let only_compositor_layers_changed = UIOverlays {
+ compositor_layers: self.ui_overlays.compositor_layers.clone(),
+ ..ui_overlays.clone()
+ } == self.ui_overlays;
self.ui_overlays = ui_overlays;
+ if only_compositor_layers_changed {
+ return UIOverlaysChange::OnlyCompositorLayers;
+ }
let shows_picture_in_picture_controls = self
.ui_overlays
.picture_in_picture_controls
.is_some_and(|controls| controls.shown);
self.picture_in_picture_controls_fade
.fade_to(if shows_picture_in_picture_controls { 1.0 } else { 0.0 }, now);
- true
+ UIOverlaysChange::RepaintsEverything
+ }
+
+ pub fn set_compositor_layers_overlay_needs_frames_until(&mut self, until: Option<MonotonicTime>) {
+ self.compositor_layers_overlay_needs_frames_until = until;
+ }
+
+ pub fn fades_or_compositor_layers_overlay_need_frame(&self) -> bool {
+ self.picture_in_picture_controls_fade.is_fading() || self.compositor_layers_overlay_needs_frames_until.is_some()
}
- pub fn fades_need_frame(&self) -> bool {
- self.picture_in_picture_controls_fade.is_fading()
+ /// Answers whether the compositor layers overlay needs a frame: until one is presented at the end of the time it
+ /// needs them for, which no longer shows a highlight.
+ pub fn compositor_layers_overlay_needs_frame(&mut self, frame_time: MonotonicTime) -> bool {
+ let Some(until) = self.compositor_layers_overlay_needs_frames_until else {
+ return false;
+ };
+ if frame_time >= until {
+ self.compositor_layers_overlay_needs_frames_until = None;
+ }
+ true
}
/// Advances the fades to a frame, answering what of the viewport they repaint.
@@ -195,6 +245,7 @@ impl ContextOverlays {
ui_overlay_records: AlignedRecords::new(&ui_overlay_records.finish().bytes),
picture_in_picture_controls,
bounds: bounds.intersected(viewport_rect),
+ compositor_layers: self.ui_overlays.compositor_layers.clone(),
}
}
@@ -213,6 +264,7 @@ impl ContextOverlays {
if !is_cached {
let label = label_shaper.shape_overlay_label(
paused_debugger.font_family.as_deref(),
+ PAUSED_DEBUGGER_LABEL_FONT_SIZE_IN_POINTS,
device_pixel_ratio,
PAUSED_DEBUGGER_LABEL,
);
@@ -263,6 +315,8 @@ pub struct OverlayPicture {
ui_overlay_records: AlignedRecords,
picture_in_picture_controls: Option<PictureInPictureControlsPicture>,
pub bounds: IntRect,
+ /// The compositor records that overlay once it has rastered the frame's tiles, which it shows.
+ pub compositor_layers: Option<CompositorLayersOverlayState>,
}
thread_local! {
@@ -279,6 +333,24 @@ thread_local! {
});
}
+/// Records drawn over a frame in the space of the viewport, as the overlays of the browser are.
+pub struct OverlayRecords(AlignedRecords);
+
+impl OverlayRecords {
+ pub(crate) fn record(record: impl FnOnce(&mut OverlayRecorder<'_>)) -> Self {
+ let mut builder = DisplayListBuilder::new();
+ record(&mut OverlayRecorder {
+ builder: &mut builder,
+ clip_of_appended_commands: None,
+ });
+ Self(AlignedRecords::new(&builder.finish().bytes))
+ }
+
+ pub fn paint(&self, painter: &mut impl ReplayPainter) {
+ replay_overlay_records(&self.0, painter);
+ }
+}
+
fn replay_overlay_records(records: &AlignedRecords, painter: &mut impl ReplayPainter) {
OVERLAY_TREE.with(|tree| {
let list = ListReplay::new(tree);
@@ -338,13 +410,30 @@ fn presented_compositor_scrollbar(scrollbar: &ScrollbarOfFrame) -> PresentedScro
}
/// The records of one overlay, with the payload of each command laid out after the command as the painter reads it.
-struct OverlayRecorder<'a> {
+pub(crate) struct OverlayRecorder<'a> {
builder: &'a mut DisplayListBuilder,
+ clip_of_appended_commands: Option<IntRect>,
}
impl OverlayRecorder<'_> {
fn append<C: DisplayListCommand>(&mut self, command: &C, inline_data: &[u8]) {
- self.builder.append(command, inline_data, ContextRef::default());
+ match self.clip_of_appended_commands {
+ Some(clip) => self.builder.append_with_inline_clips(
+ command,
+ inline_data,
+ ContextRef::default(),
+ &[PendingInlineClip::intersecting_device_rect(clip)],
+ ),
+ None => self.builder.append(command, inline_data, ContextRef::default()),
+ }
+ }
+
+ /// Clips what `record` appends to `clip`.
+ pub(crate) fn clipped_to(&mut self, clip: IntRect, record: impl FnOnce(&mut Self)) {
+ let outer_clip = self.clip_of_appended_commands;
+ self.clip_of_appended_commands = Some(outer_clip.map_or(clip, |outer_clip| outer_clip.intersected(clip)));
+ record(self);
+ self.clip_of_appended_commands = outer_clip;
}
// The span of `data` placed after a command of type `C`, at an offset aligned for the data, with the padding
@@ -366,7 +455,7 @@ impl OverlayRecorder<'_> {
(span, inline_data)
}
- fn fill_rect(&mut self, rect: IntRect, color: Color) {
+ pub(crate) fn fill_rect(&mut self, rect: IntRect, color: Color) {
self.append(
&FillRect {
rect,
@@ -442,7 +531,7 @@ impl OverlayRecorder<'_> {
);
}
- fn draw_label(&mut self, label: &OverlayLabel, baseline_origin: FloatPoint, color: Color, scale: f32) {
+ pub(crate) fn draw_label(&mut self, label: &OverlayLabel, baseline_origin: FloatPoint, color: Color, scale: f32) {
if label.glyph_ids.is_empty() {
return;
}
@@ -606,7 +695,10 @@ fn record_paused_debugger_overlay(
state: &PausedDebuggerOverlayState,
label: Option<&OverlayLabel>,
) {
- let mut recorder = OverlayRecorder { builder };
+ let mut recorder = OverlayRecorder {
+ builder,
+ clip_of_appended_commands: None,
+ };
let geometry: PausedDebuggerOverlayGeometry = paused_debugger_overlay_geometry(viewport_size, device_pixel_ratio);
let radius = 1.0f32.max((4.0 * device_pixel_ratio) as f32);
@@ -774,7 +866,10 @@ fn record_picture_in_picture_controls(
device_pixel_ratio: f64,
state: &PictureInPictureControlsState,
) -> IntRect {
- let mut recorder = OverlayRecorder { builder };
+ let mut recorder = OverlayRecorder {
+ builder,
+ clip_of_appended_commands: None,
+ };
let geometry = picture_in_picture_controls_geometry(viewport_size, device_pixel_ratio);
// The icons are stroked on a grid of 16 units, and drawn at the given size in points.
diff --git a/Services/Compositor/Rust/src/presenting/damage.rs b/Services/Compositor/Rust/src/presenting/damage.rs
index d69dc7a90d6..5ea2ab921ad 100644
--- a/Services/Compositor/Rust/src/presenting/damage.rs
+++ b/Services/Compositor/Rust/src/presenting/damage.rs
@@ -298,7 +298,9 @@ impl ContextPresenting {
self.raster_rect_of(forced_damage_rect.united(scrolled_compositor_scrollbars.intersected(viewport_rect)));
let damage_of_layers_moved_by_animated_transforms =
self.damage_of_layers_moved_by_animated_transforms(&layer_update, raster_rect);
- let repaints_everything = invalidates_every_tile || damage_of_layers_moved_by_animated_transforms.is_none();
+ let repaints_everything = invalidates_every_tile
+ || damage_of_layers_moved_by_animated_transforms.is_none()
+ || self.layer_overlay.repaints_everything();
let stale_rect = stale_rect.united(damage_of_layers_moved_by_animated_transforms.unwrap_or_default());
FrameDamage {
rect_in_raster_device_pixels: if repaints_everything {
diff --git a/Services/Compositor/Rust/src/presenting/layer_overlay.rs b/Services/Compositor/Rust/src/presenting/layer_overlay.rs
new file mode 100644
index 00000000000..c356ba72d0c
--- /dev/null
+++ b/Services/Compositor/Rust/src/presenting/layer_overlay.rs
@@ -0,0 +1,1446 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The compositor layers overlay: over each frame, the outline of each layer the frame is composited from and the tiles
+//! rastered lately, highlighted by why they were and fading out. Each layer selected in the compositor layers window
+//! shows the tiles it holds and how often each was rastered, and the layer the pointer is over in the window is marked
+//! out. What it shows of a frame is worked out into a plain model first, which is both drawn and described to the
+//! compositor layers window.
+
+use crate::overlays::{
+ CompositorLayersOverlayState, OverlayLabel, OverlayLabelShaper, OverlayRecorder, OverlayRecords,
+};
+use libcompositing_rust::display_list::layers::{LayerIdentity, SpaceToFrame};
+use libcompositing_rust::display_list::tiles::TileCoord;
+use libcompositing_rust::ipc_types::{
+ Compositing_CompositorLayerDescription as CompositorLayerDescription,
+ Compositing_CompositorLayerNodeDescription as CompositorLayerNodeDescription,
+ Compositing_CompositorLayersDescription as CompositorLayersDescription,
+ Compositing_CompositorTileHighlightDescription as CompositorTileHighlightDescription,
+ Compositing_VisualContextNodeKind as VisualContextNodeKind,
+};
+use libcompositing_rust::time::{Duration, MonotonicTime};
+use libgfx_rust::{Color, FloatPoint, IntPoint, IntRect, IntSize};
+use std::collections::{BTreeMap, HashMap, HashSet, btree_map};
+use std::hash::{DefaultHasher, Hash, Hasher};
+use std::rc::Rc;
+
+pub const RASTER_HIGHLIGHT_FADE_DURATION: Duration = Duration::from_milliseconds(500);
+const MAXIMUM_CACHED_LABEL_COUNT: usize = 4096;
+const LABEL_FONT_SIZE_IN_POINTS: f32 = 10.0;
+const SHORTEST_TIME_BETWEEN_PUBLISHED_DESCRIPTIONS: Duration = Duration::from_milliseconds(100);
+// The compositor layers window lists no more layers, and no longer names of them, than a person can read.
+const MAXIMUM_LISTED_LAYER_COUNT: usize = 256;
+const MAXIMUM_LISTED_LAYER_NAME_LENGTH: usize = 1024;
+// A frame labels at most this many tiles of the selected layers, so that layers of very many tiles shape and place few
+// labels, which the cache of labels holds.
+const MAXIMUM_LABELED_TILE_COUNT: usize = 1024;
+const BYTES_PER_PIXEL: u64 = 4;
+const RASTER_HIGHLIGHT_ALPHA_BEFORE_FADING: u8 = 115;
+const ONE_COLOR_TILE_TINT_ALPHA: u8 = 40;
+const TILE_GRID_ALPHA: u8 = 150;
+const OUTLINE_ALPHA_OF_UNMARKED_LAYER: u8 = 170;
+const FILL_ALPHA_OF_HOVERED_LAYER: u8 = 50;
+const LABEL_BACKGROUND_COLOR: Color = Color::from_rgba(16, 18, 24, 200);
+const LABEL_TEXT_COLOR: Color = Color::from_rgba(255, 255, 255, 255);
+const OUTLINE_HALO_COLOR: Color = Color::from_rgba(0, 0, 0, 150);
+
+/// Why a tile was rastered, as the compositor tells the cases apart.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum RasterCause {
+ /// The layer held no tile at the cell.
+ NewlyShown,
+ /// The tile held pixels of other content.
+ ContentHashChanged,
+ /// The frame made every tile stale, or rastering the tile failed before.
+ HeldPixelsInvalidated,
+ /// The tile held less of its cell than the frame shows.
+ HeldLessThanNeeded,
+ /// The tile's surface was on another backend than the frame's.
+ HeldOnAnotherBackend,
+ /// No surface could be had for the tile, so the frame was painted straight from the list where the tile shows.
+ PaintedStraightIntoTheFrame,
+}
+
+impl RasterCause {
+ pub const ALL: [RasterCause; 6] = [
+ RasterCause::NewlyShown,
+ RasterCause::ContentHashChanged,
+ RasterCause::HeldPixelsInvalidated,
+ RasterCause::HeldLessThanNeeded,
+ RasterCause::HeldOnAnotherBackend,
+ RasterCause::PaintedStraightIntoTheFrame,
+ ];
+
+ pub fn name(self) -> &'static str {
+ match self {
+ RasterCause::NewlyShown => "newly shown",
+ RasterCause::ContentHashChanged => "key changed",
+ RasterCause::HeldPixelsInvalidated => "held pixels invalidated",
+ RasterCause::HeldLessThanNeeded => "held less than needed",
+ RasterCause::HeldOnAnotherBackend => "held on another backend",
+ RasterCause::PaintedStraightIntoTheFrame => "painted straight into the frame",
+ }
+ }
+
+ pub fn highlight_color(self) -> Color {
+ match self {
+ RasterCause::NewlyShown => Color::from_rgb(34, 197, 94),
+ RasterCause::ContentHashChanged => Color::from_rgb(239, 68, 68),
+ RasterCause::HeldPixelsInvalidated => Color::from_rgb(245, 158, 11),
+ RasterCause::HeldLessThanNeeded => Color::from_rgb(59, 130, 246),
+ RasterCause::HeldOnAnotherBackend => Color::from_rgb(168, 85, 247),
+ RasterCause::PaintedStraightIntoTheFrame => Color::from_rgb(236, 72, 153),
+ }
+ }
+}
+
+/// How many tiles were rastered, by why.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct RasterCountsByCause([u64; RasterCause::ALL.len()]);
+
+impl RasterCountsByCause {
+ fn count(&mut self, cause: RasterCause) {
+ self.0[cause as usize] += 1;
+ }
+
+ pub fn total(&self) -> u64 {
+ self.0.iter().sum()
+ }
+
+ /// The causes counted, the most counted first, as "12 key changed, 3 newly shown".
+ fn text(&self) -> String {
+ let mut counted_causes: Vec<(u64, RasterCause)> = RasterCause::ALL
+ .iter()
+ .map(|&cause| (self.0[cause as usize], cause))
+ .filter(|&(count, _)| count != 0)
+ .collect();
+ counted_causes.sort_by(|(count, _), (other_count, _)| other_count.cmp(count));
+ counted_causes
+ .iter()
+ .map(|(count, cause)| format!("{count} {}", cause.name()))
+ .collect::<Vec<_>>()
+ .join(", ")
+ }
+}
+
+/// How a canvas, video or nested context layer reaches the screen.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum MediaPresentation {
+ ShownByWindowServer,
+ Replayed { why: String },
+}
+
+impl std::fmt::Display for MediaPresentation {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ MediaPresentation::ShownByWindowServer => formatter.write_str("shown by the window server"),
+ MediaPresentation::Replayed { why } => write!(formatter, "replayed: {why}"),
+ }
+ }
+}
+
+/// What a frame did to bring the tiles of its layers up to date.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct FrameWorkCounts {
+ pub tiles_rastered: u64,
+ pub shown_tiles_of_one_color: u64,
+ pub tiles_covered_by_opaque_tiles_above: u64,
+ pub cells_binned: u64,
+ pub chunks_placed: u64,
+ /// Whether the frame took a plan of layers into use that the frame before was not drawn with.
+ pub took_plan_into_use: bool,
+}
+
+/// The last time a tile was rastered, as the overlay shows it.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct LastRaster {
+ pub cause: RasterCause,
+ pub rect_in_layer_space: IntRect,
+ pub age: Duration,
+}
+
+impl LastRaster {
+ pub fn is_highlighted(&self) -> bool {
+ self.age < RASTER_HIGHLIGHT_FADE_DURATION
+ }
+
+ pub fn highlight_opacity(&self) -> f32 {
+ if !self.is_highlighted() {
+ return 0.0;
+ }
+ 1.0 - self.age.nanoseconds() as f32 / RASTER_HIGHLIGHT_FADE_DURATION.nanoseconds() as f32
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct ModelTile {
+ pub coord: TileCoord,
+ /// None where the layer holds no tile at the cell, as where a tile was painted straight into the frame.
+ pub held_part_of_cell: Option<IntRect>,
+ /// Whether the tile is of one color, which has no surface.
+ pub is_one_color: bool,
+ /// How often the tile was rastered while the layer kept it, since the counts were last zeroed.
+ pub raster_count: u32,
+ pub last_raster: Option<LastRaster>,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum ModelLayerContent {
+ /// By cell, the tiles the layer holds, and those highlighted where it holds none.
+ Painted { tiles: Vec<ModelTile> },
+ Media {
+ reach: IntRect,
+ presentation: MediaPresentation,
+ },
+}
+
+/// A node of the visual context tree that the name of a layer mentions, by its index in the tree.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum NamedVisualContextNode {
+ Spatial(u32),
+ Effect(u32),
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct ModelLayer {
+ pub identity: LayerIdentity,
+ /// What the display list dump calls the layer.
+ pub name: Rc<str>,
+ /// The nodes of the visual context tree that the name mentions, in the order it does, each once.
+ pub nodes_named: Rc<[NamedVisualContextNode]>,
+ /// Whether the frames leave the layer out, as the compositor layers window hides it.
+ pub hidden: bool,
+ /// From the raster coordinates of the layer's space into those of the frame.
+ pub space_to_frame: SpaceToFrame,
+ /// In the raster coordinates of the frame.
+ pub composite_clip: Option<IntRect>,
+ pub content: ModelLayerContent,
+ /// The tiles of the layer rastered since the counts were last zeroed.
+ pub raster_counts_since_reset: RasterCountsByCause,
+}
+
+impl ModelLayer {
+ fn color(&self) -> Color {
+ color_of_layer(&self.identity)
+ }
+
+ fn visible_rect_in_frame(&self, viewport_rect: IntRect) -> IntRect {
+ self.composite_clip
+ .map_or(viewport_rect, |clip| viewport_rect.intersected(clip))
+ }
+
+ fn rect_in_frame(&self, rect_in_layer_space: IntRect) -> IntRect {
+ self.space_to_frame.rect_in_frame(rect_in_layer_space)
+ }
+
+ fn bounds_in_layer_space(&self) -> IntRect {
+ match &self.content {
+ ModelLayerContent::Painted { tiles } => tiles
+ .iter()
+ .filter_map(|tile| tile.held_part_of_cell)
+ .fold(IntRect::default(), IntRect::united),
+ ModelLayerContent::Media { reach, .. } => *reach,
+ }
+ }
+
+ /// What of the layer's outline the frame shows.
+ fn shown_bounds_in_frame(&self, viewport_rect: IntRect) -> IntRect {
+ self.rect_in_frame(self.bounds_in_layer_space())
+ .intersected(self.visible_rect_in_frame(viewport_rect))
+ }
+}
+
+/// What the overlay shows over a frame.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct LayerOverlayModel {
+ pub viewport_rect: IntRect,
+ /// From the base layer up.
+ pub layers: Vec<ModelLayer>,
+ pub why_list_is_one_layer: Option<String>,
+ /// The layer stack's lines of composited effects, media without layers and effects reading only their own layer.
+ pub notes_of_layer_stack: Rc<[String]>,
+ pub work_counts_of_frame: FrameWorkCounts,
+ /// The structural epoch of the visual context tree whose nodes the layers name.
+ pub visual_context_tree_structural_epoch: u64,
+ /// The tiles rastered since the counts were last zeroed, of layers in the stack or not.
+ pub raster_counts_since_reset: RasterCountsByCause,
+ /// How many frames rastered tiles since the counts were last zeroed.
+ pub frames_rastering_since_reset: u64,
+}
+
+/// Per layer of a model, from the base layer up, given whether each is hidden, whether the layers window lists it: only
+/// those show the layer's name.
+pub fn layers_whose_names_are_shown(hidden_by_layer: &[bool]) -> Vec<bool> {
+ hidden_by_layer
+ .iter()
+ .enumerate()
+ .map(|(position, &hidden)| position < MAXIMUM_LISTED_LAYER_COUNT || hidden)
+ .collect()
+}
+
+/// The layers the compositor layers window selects and the pointer is over in it, by the ids the descriptions give them.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+struct MarkedLayers {
+ selected_layer_ids: Vec<u64>,
+ hovered_layer_id: Option<u64>,
+}
+
+impl MarkedLayers {
+ fn of_state(state_from_ui: &CompositorLayersOverlayState) -> Self {
+ Self {
+ selected_layer_ids: state_from_ui.selected_layer_ids.clone(),
+ hovered_layer_id: state_from_ui.hovered_layer_id,
+ }
+ }
+
+ fn selects(&self, layer: &ModelLayer) -> bool {
+ self.selected_layer_ids.contains(&id_of_layer(&layer.identity))
+ }
+
+ /// The selected layers the frames show, from the base layer up.
+ fn selected_layers<'a>(&self, model: &'a LayerOverlayModel) -> Vec<&'a ModelLayer> {
+ model
+ .layers
+ .iter()
+ .filter(|layer| !layer.hidden && self.selects(layer))
+ .collect()
+ }
+
+ /// The layer the pointer is over, unless it is selected, when it shows more of itself already.
+ fn hovered_layer<'a>(&self, model: &'a LayerOverlayModel) -> Option<&'a ModelLayer> {
+ let hovered_layer_id = self.hovered_layer_id?;
+ model
+ .layers
+ .iter()
+ .find(|layer| !layer.hidden && !self.selects(layer) && id_of_layer(&layer.identity) == hovered_layer_id)
+ }
+
+ fn marks(&self, layer: &ModelLayer) -> bool {
+ self.selects(layer) || self.hovered_layer_id == Some(id_of_layer(&layer.identity))
+ }
+}
+
+/// What a frame of the overlay labels: the names of the selected layers and of the layer the pointer is over, where the
+/// frame shows them, and the tiles of the selected layers that the frame shows, up to as many as a frame labels.
+struct LabelsOfFrame<'a> {
+ named_layers: Vec<&'a ModelLayer>,
+ labeled_tiles_of_selected_layers: Vec<(&'a ModelLayer, Vec<&'a ModelTile>)>,
+}
+
+fn labels_of_model<'a>(model: &'a LayerOverlayModel, marked: &MarkedLayers) -> LabelsOfFrame<'a> {
+ let selected_layers = marked.selected_layers(model);
+ let named_layers = selected_layers
+ .iter()
+ .copied()
+ .chain(marked.hovered_layer(model))
+ .collect();
+ let mut labeled_tile_count = 0;
+ let labeled_tiles_of_selected_layers = selected_layers
+ .into_iter()
+ .rev()
+ .map(|layer| {
+ let mut labeled_tiles = Vec::new();
+ if let ModelLayerContent::Painted { tiles } = &layer.content {
+ let visible_rect = layer.visible_rect_in_frame(model.viewport_rect);
+ for tile in tiles {
+ if labeled_tile_count == MAXIMUM_LABELED_TILE_COUNT {
+ break;
+ }
+ let shown = tile.held_part_of_cell.is_some_and(|held_part_of_cell| {
+ !layer
+ .rect_in_frame(held_part_of_cell)
+ .intersected(visible_rect)
+ .is_empty()
+ });
+ if shown {
+ labeled_tile_count += 1;
+ labeled_tiles.push(tile);
+ }
+ }
+ }
+ (layer, labeled_tiles)
+ })
+ .collect();
+ LabelsOfFrame {
+ named_layers,
+ labeled_tiles_of_selected_layers,
+ }
+}
+
+fn count_with_noun(count: u64, singular_noun: &str, plural_noun: &str) -> String {
+ if count == 1 {
+ format!("1 {singular_noun}")
+ } else {
+ format!("{count} {plural_noun}")
+ }
+}
+
+fn memory_size_text(bytes: u64) -> String {
+ const MEBIBYTE: u64 = 1024 * 1024;
+ if bytes < MEBIBYTE {
+ return format!("{} KiB", bytes.div_ceil(1024));
+ }
+ format!("{:.1} MiB", bytes as f64 / MEBIBYTE as f64)
+}
+
+impl LayerOverlayModel {
+ fn details_of_layer(layer: &ModelLayer) -> String {
+ match &layer.content {
+ ModelLayerContent::Painted { tiles } => {
+ let held_tile_count = tiles.iter().filter(|tile| tile.held_part_of_cell.is_some()).count() as u64;
+ let one_color_tile_count = tiles.iter().filter(|tile| tile.is_one_color).count();
+ let bytes_held_by_tile_surfaces: u64 = tiles
+ .iter()
+ .filter(|tile| !tile.is_one_color)
+ .filter_map(|tile| tile.held_part_of_cell)
+ .map(|held_part| held_part.width.max(0) as u64 * held_part.height.max(0) as u64 * BYTES_PER_PIXEL)
+ .sum();
+ format!(
+ "{} ({one_color_tile_count} of one color), {}",
+ count_with_noun(held_tile_count, "tile", "tiles"),
+ memory_size_text(bytes_held_by_tile_surfaces)
+ )
+ }
+ ModelLayerContent::Media { presentation, .. } => presentation.to_string(),
+ }
+ }
+
+ fn summary_of_last_frame(&self) -> String {
+ let counts = self.work_counts_of_frame;
+ format!(
+ "last frame: {} rastered, {} of one color, {} covered, {} binned, {} placed, {}",
+ count_with_noun(counts.tiles_rastered, "tile", "tiles"),
+ counts.shown_tiles_of_one_color,
+ counts.tiles_covered_by_opaque_tiles_above,
+ count_with_noun(counts.cells_binned, "tile", "tiles"),
+ count_with_noun(counts.chunks_placed, "chunk", "chunks"),
+ if counts.took_plan_into_use {
+ "a new plan was taken into use"
+ } else {
+ "the stack was kept"
+ }
+ )
+ }
+
+ fn summary_since_reset(&self) -> String {
+ let tiles_rastered = self.raster_counts_since_reset.total();
+ if tiles_rastered == 0 {
+ return "since reset: nothing rastered".into();
+ }
+ format!(
+ "since reset: {} rastered by {} ({})",
+ count_with_noun(tiles_rastered, "tile", "tiles"),
+ count_with_noun(self.frames_rastering_since_reset, "frame", "frames"),
+ self.raster_counts_since_reset.text()
+ )
+ }
+
+ pub fn description_for_layers_window(&self) -> CompositorLayersDescription {
+ let rgb_of_color =
+ |color: Color| u32::from(color.red()) << 16 | u32::from(color.green()) << 8 | u32::from(color.blue());
+ let mut notes: Vec<String> = Vec::new();
+ if let Some(why) = &self.why_list_is_one_layer {
+ notes.push(format!("single layer: {why}"));
+ }
+ // The window forgets a hidden layer it is not told of, so hidden layers past those it lists are listed too.
+ let listed_layers: Vec<&ModelLayer> = self
+ .layers
+ .iter()
+ .enumerate()
+ .filter(|(position, layer)| *position < MAXIMUM_LISTED_LAYER_COUNT || layer.hidden)
+ .map(|(_, layer)| layer)
+ .collect();
+ let unlisted_layer_count = self.layers.len() - listed_layers.len();
+ if unlisted_layer_count != 0 {
+ notes.push(format!(
+ "not listed: {} above these",
+ count_with_noun(unlisted_layer_count as u64, "layer", "layers")
+ ));
+ }
+ notes.extend(self.notes_of_layer_stack.iter().cloned());
+ CompositorLayersDescription {
+ layers: listed_layers
+ .into_iter()
+ .map(|layer| CompositorLayerDescription {
+ id: id_of_layer(&layer.identity),
+ name: layer.name[..layer.name.floor_char_boundary(MAXIMUM_LISTED_LAYER_NAME_LENGTH)].into(),
+ details: Self::details_of_layer(layer).into(),
+ rgb_of_outline: rgb_of_color(layer.color()),
+ hidden: layer.hidden,
+ visible_rect_in_viewport: layer.shown_bounds_in_frame(self.viewport_rect),
+ nodes: layer
+ .nodes_named
+ .iter()
+ .map(|node| {
+ let (kind, index) = match *node {
+ NamedVisualContextNode::Spatial(index) => (VisualContextNodeKind::Spatial, index),
+ NamedVisualContextNode::Effect(index) => (VisualContextNodeKind::Effect, index),
+ };
+ CompositorLayerNodeDescription {
+ kind,
+ index,
+ element: Default::default(),
+ }
+ })
+ .collect(),
+ tiles_rastered_since_reset: layer.raster_counts_since_reset.total(),
+ raster_causes_since_reset: layer.raster_counts_since_reset.text().into(),
+ })
+ .collect(),
+ notes: notes.into_iter().map(Into::into).collect(),
+ summary_of_last_frame: self.summary_of_last_frame().into(),
+ tile_highlights: RasterCause::ALL
+ .iter()
+ .map(|cause| CompositorTileHighlightDescription {
+ raster_cause: cause.name().to_owned().into(),
+ rgb: rgb_of_color(cause.highlight_color()),
+ })
+ .collect(),
+ summary_since_reset: self.summary_since_reset().into(),
+ visual_context_tree_structural_epoch: self.visual_context_tree_structural_epoch,
+ }
+ }
+}
+
+fn tile_label_text(tile: &ModelTile) -> String {
+ format!("{},{} x{}", tile.coord.column, tile.coord.row, tile.raster_count)
+}
+
+fn layer_label_text(layer: &ModelLayer) -> String {
+ match &layer.content {
+ ModelLayerContent::Painted { .. } => layer.name.to_string(),
+ ModelLayerContent::Media { presentation, .. } => format!("{}: {presentation}", layer.name),
+ }
+}
+
+/// Names the layer in the descriptions the compositor publishes, for as long as its identity stays.
+fn id_of_layer(identity: &LayerIdentity) -> u64 {
+ let mut hasher = DefaultHasher::new();
+ identity.hash(&mut hasher);
+ hasher.finish()
+}
+
+/// A color of the layer's own, which stays as long as its identity does, wherever the layer is in the stack.
+fn color_of_layer(identity: &LayerIdentity) -> Color {
+ let hash = id_of_layer(identity);
+ let hue = (hash % 360) as f32;
+ let lighter_shade_tells_apart_similar_hues = hash & (1 << 40) != 0;
+ let lightness = if lighter_shade_tells_apart_similar_hues {
+ 0.62
+ } else {
+ 0.5
+ };
+ color_of_hsl(hue, 0.9, lightness)
+}
+
+fn color_of_hsl(hue_in_degrees: f32, saturation: f32, lightness: f32) -> Color {
+ let chroma = (1.0 - (2.0 * lightness - 1.0).abs()) * saturation;
+ let sector = hue_in_degrees / 60.0;
+ let second_largest_component = chroma * (1.0 - (sector % 2.0 - 1.0).abs());
+ let (red, green, blue) = match sector as u32 {
+ 0 => (chroma, second_largest_component, 0.0),
+ 1 => (second_largest_component, chroma, 0.0),
+ 2 => (0.0, chroma, second_largest_component),
+ 3 => (0.0, second_largest_component, chroma),
+ 4 => (second_largest_component, 0.0, chroma),
+ _ => (chroma, 0.0, second_largest_component),
+ };
+ let lightness_added_to_each_component = lightness - chroma / 2.0;
+ let channel = |component: f32| {
+ ((component + lightness_added_to_each_component) * 255.0)
+ .round()
+ .clamp(0.0, 255.0) as u8
+ };
+ Color::from_rgb(channel(red), channel(green), channel(blue))
+}
+
+#[derive(Clone, Copy, Debug)]
+struct RasterHistoryOfTile {
+ raster_count: u32,
+ last_cause: RasterCause,
+ last_rect_in_layer_space: IntRect,
+ last_rastered_at: MonotonicTime,
+}
+
+#[derive(Default)]
+struct ShapedLabelCache {
+ font_family: Option<String>,
+ device_pixel_ratio: f64,
+ label_by_text: HashMap<String, Option<OverlayLabel>>,
+}
+
+impl ShapedLabelCache {
+ fn shape_labels_not_cached_yet(
+ &mut self,
+ texts: &[String],
+ font_family: Option<&str>,
+ device_pixel_ratio: f64,
+ shaper: &dyn OverlayLabelShaper,
+ ) {
+ if self.font_family.as_deref() != font_family
+ || self.device_pixel_ratio != device_pixel_ratio
+ || self.label_by_text.len() > MAXIMUM_CACHED_LABEL_COUNT
+ {
+ self.label_by_text.clear();
+ self.font_family = font_family.map(str::to_owned);
+ self.device_pixel_ratio = device_pixel_ratio;
+ }
+ for text in texts {
+ if self.label_by_text.contains_key(text) {
+ continue;
+ }
+ let label = shaper.shape_overlay_label(font_family, LABEL_FONT_SIZE_IN_POINTS, device_pixel_ratio, text);
+ self.label_by_text.insert(text.clone(), label);
+ }
+ }
+
+ fn label_of_text(&self, text: &str) -> Option<&OverlayLabel> {
+ self.label_by_text.get(text)?.as_ref()
+ }
+}
+
+/// The overlay as of the frame painted last, and how it is drawn over that frame.
+pub struct LayerOverlayFrame {
+ pub model: LayerOverlayModel,
+ pub records: OverlayRecords,
+ /// Until when some tile stays highlighted.
+ pub highlights_fade_until: Option<MonotonicTime>,
+}
+
+/// What the overlay keeps while it is switched on: how often each tile was rastered, and why last, how many tiles of
+/// each layer were rastered since the window last zeroed the counts, and what the compositor layers window was told
+/// last. A layer keeps the raster history of a tile while the layer holds the tile or the tile is highlighted. A frame
+/// that does neither drops that history, and the count starts again from zero.
+#[derive(Default)]
+pub struct LayerOverlay {
+ state_from_ui: CompositorLayersOverlayState,
+ raster_history_of_tiles_by_layer: HashMap<LayerIdentity, BTreeMap<TileCoord, RasterHistoryOfTile>>,
+ raster_counts_since_reset_by_layer: HashMap<LayerIdentity, RasterCountsByCause>,
+ raster_counts_since_reset: RasterCountsByCause,
+ frames_rastering_since_reset: u64,
+ painted_at_of_latest_frame_counted: Option<MonotonicTime>,
+ shaped_labels: ShapedLabelCache,
+ latest_frame: Option<LayerOverlayFrame>,
+ publish_time_and_description_published_last: Option<(MonotonicTime, CompositorLayersDescription)>,
+ unpublished_description_waits_until: Option<MonotonicTime>,
+}
+
+impl LayerOverlay {
+ /// Takes in that a frame painted at `painted_at` rastered the tile at `coord` of the layer, or painted it straight
+ /// into the frame.
+ pub fn record_raster(
+ &mut self,
+ layer_identity: LayerIdentity,
+ coord: TileCoord,
+ cause: RasterCause,
+ rect_in_layer_space: IntRect,
+ painted_at: MonotonicTime,
+ ) {
+ let history = self
+ .raster_history_of_tiles_by_layer
+ .entry(layer_identity)
+ .or_default()
+ .entry(coord)
+ .or_insert(RasterHistoryOfTile {
+ raster_count: 0,
+ last_cause: cause,
+ last_rect_in_layer_space: rect_in_layer_space,
+ last_rastered_at: painted_at,
+ });
+ if cause != RasterCause::PaintedStraightIntoTheFrame {
+ history.raster_count += 1;
+ }
+ history.last_cause = cause;
+ history.last_rect_in_layer_space = rect_in_layer_space;
+ history.last_rastered_at = painted_at;
+ self.raster_counts_since_reset_by_layer
+ .entry(layer_identity)
+ .or_default()
+ .count(cause);
+ self.raster_counts_since_reset.count(cause);
+ }
+
+ fn take_state_from_ui(&mut self, state_from_ui: &CompositorLayersOverlayState) {
+ if self.state_from_ui == *state_from_ui {
+ return;
+ }
+ if self.state_from_ui.raster_count_reset_generation != state_from_ui.raster_count_reset_generation {
+ self.reset_raster_counts();
+ }
+ self.state_from_ui = state_from_ui.clone();
+ }
+
+ fn reset_raster_counts(&mut self) {
+ self.raster_counts_since_reset_by_layer.clear();
+ self.raster_counts_since_reset = RasterCountsByCause::default();
+ self.frames_rastering_since_reset = 0;
+ for history in self
+ .raster_history_of_tiles_by_layer
+ .values_mut()
+ .flat_map(|raster_history_of_tiles| raster_history_of_tiles.values_mut())
+ {
+ history.raster_count = 0;
+ }
+ }
+
+ pub fn latest_frame(&self) -> Option<&LayerOverlayFrame> {
+ self.latest_frame.as_ref()
+ }
+
+ /// Works out the overlay of a frame painted at `painted_at` from the layers of the frame and the tiles rastered so
+ /// far, and records how it is drawn.
+ pub fn update_with_frame(
+ &mut self,
+ mut model: LayerOverlayModel,
+ painted_at: MonotonicTime,
+ device_pixel_ratio: f64,
+ shaper: &dyn OverlayLabelShaper,
+ ) -> &LayerOverlayFrame {
+ let highlights_fade_until = self.merge_raster_history_into(&mut model.layers, painted_at);
+ self.merge_raster_counts_since_reset_into(&mut model, painted_at);
+ let records = self.record_drawing_of_model(&model, device_pixel_ratio, shaper);
+ self.latest_frame.insert(LayerOverlayFrame {
+ model,
+ records,
+ highlights_fade_until,
+ })
+ }
+
+ pub fn hides_layer(&self, identity: &LayerIdentity) -> bool {
+ self.state_from_ui.hidden_layer_ids.contains(&id_of_layer(identity))
+ }
+
+ /// What the compositor layers window is to show of the frame painted last, unless it shows that already or was
+ /// told what changed too short a time ago, when a later frame tells it.
+ pub fn take_description_to_publish(&mut self, now: MonotonicTime) -> Option<CompositorLayersDescription> {
+ let description = self.latest_frame.as_ref()?.model.description_for_layers_window();
+ self.unpublished_description_waits_until = None;
+ if let Some((published_at, published)) = &self.publish_time_and_description_published_last {
+ if *published == description {
+ return None;
+ }
+ let earliest_next_publish_time = *published_at + SHORTEST_TIME_BETWEEN_PUBLISHED_DESCRIPTIONS;
+ if now < earliest_next_publish_time {
+ self.unpublished_description_waits_until = Some(earliest_next_publish_time);
+ return None;
+ }
+ }
+ self.publish_time_and_description_published_last = Some((now, description.clone()));
+ Some(description)
+ }
+
+ /// Until when frames are needed without anything else changing: while a highlight fades, and until the compositor
+ /// layers window can be told what changed.
+ pub fn needs_frames_until(&self) -> Option<MonotonicTime> {
+ let highlights_fade_until = self.latest_frame.as_ref().and_then(|frame| frame.highlights_fade_until);
+ highlights_fade_until.max(self.unpublished_description_waits_until)
+ }
+
+ /// Gives the tiles of the layers of a frame painted at `painted_at` their raster history, adds the tiles that are
+ /// highlighted where a layer holds none, and keeps the raster history of only those tiles. Answers until when some
+ /// tile stays highlighted.
+ fn merge_raster_history_into(
+ &mut self,
+ layers: &mut [ModelLayer],
+ painted_at: MonotonicTime,
+ ) -> Option<MonotonicTime> {
+ let mut highlights_fade_until: Option<MonotonicTime> = None;
+ // The history that the layers of the frame do not take is of layers that left the stack, and is dropped.
+ let mut raster_history_of_tiles_by_layer = std::mem::take(&mut self.raster_history_of_tiles_by_layer);
+ let mut kept_raster_history_of_tiles_by_layer = HashMap::with_capacity(layers.len());
+ for layer in layers {
+ let ModelLayerContent::Painted { tiles } = &mut layer.content else {
+ continue;
+ };
+ let Some(mut raster_history_of_tiles) = raster_history_of_tiles_by_layer.remove(&layer.identity) else {
+ continue;
+ };
+ let mut tile_by_coord: BTreeMap<TileCoord, ModelTile> = std::mem::take(tiles)
+ .into_iter()
+ .map(|tile| (tile.coord, tile))
+ .collect();
+ raster_history_of_tiles.retain(|&coord, history| {
+ let last_raster = LastRaster {
+ cause: history.last_cause,
+ rect_in_layer_space: history.last_rect_in_layer_space,
+ age: painted_at - history.last_rastered_at,
+ };
+ if last_raster.is_highlighted() {
+ let fades_at = history.last_rastered_at + RASTER_HIGHLIGHT_FADE_DURATION;
+ highlights_fade_until = Some(highlights_fade_until.map_or(fades_at, |until| until.max(fades_at)));
+ }
+ let shows_cell_holding_no_tile = last_raster.is_highlighted();
+ let tile = match tile_by_coord.entry(coord) {
+ btree_map::Entry::Occupied(entry) => entry.into_mut(),
+ btree_map::Entry::Vacant(entry) if shows_cell_holding_no_tile => entry.insert(ModelTile {
+ coord,
+ held_part_of_cell: None,
+ is_one_color: false,
+ raster_count: 0,
+ last_raster: None,
+ }),
+ btree_map::Entry::Vacant(_) => return false,
+ };
+ tile.raster_count = history.raster_count;
+ tile.last_raster = Some(last_raster);
+ true
+ });
+ *tiles = tile_by_coord.into_values().collect();
+ if !raster_history_of_tiles.is_empty() {
+ kept_raster_history_of_tiles_by_layer.insert(layer.identity, raster_history_of_tiles);
+ }
+ }
+ self.raster_history_of_tiles_by_layer = kept_raster_history_of_tiles_by_layer;
+ highlights_fade_until
+ }
+
+ /// Gives the model of a frame painted at `painted_at` the counts of tiles rastered since the window last zeroed
+ /// them. The counts of a layer that left the stack stay only in those of all layers.
+ fn merge_raster_counts_since_reset_into(&mut self, model: &mut LayerOverlayModel, painted_at: MonotonicTime) {
+ // A frame is worked out again where presenting to the window server fails, and counts once.
+ if model.work_counts_of_frame.tiles_rastered != 0 && self.painted_at_of_latest_frame_counted != Some(painted_at)
+ {
+ self.frames_rastering_since_reset += 1;
+ self.painted_at_of_latest_frame_counted = Some(painted_at);
+ }
+ let identities_of_layers: HashSet<LayerIdentity> = model.layers.iter().map(|layer| layer.identity).collect();
+ self.raster_counts_since_reset_by_layer
+ .retain(|identity, _| identities_of_layers.contains(identity));
+ for layer in &mut model.layers {
+ layer.raster_counts_since_reset = self
+ .raster_counts_since_reset_by_layer
+ .get(&layer.identity)
+ .copied()
+ .unwrap_or_default();
+ }
+ model.raster_counts_since_reset = self.raster_counts_since_reset;
+ model.frames_rastering_since_reset = self.frames_rastering_since_reset;
+ }
+
+ fn record_drawing_of_model(
+ &mut self,
+ model: &LayerOverlayModel,
+ device_pixel_ratio: f64,
+ shaper: &dyn OverlayLabelShaper,
+ ) -> OverlayRecords {
+ let marked = MarkedLayers::of_state(&self.state_from_ui);
+ let labels = labels_of_model(model, &marked);
+ let mut label_texts: Vec<String> = labels
+ .named_layers
+ .iter()
+ .map(|layer| layer_label_text(layer))
+ .collect();
+ label_texts.extend(
+ labels
+ .labeled_tiles_of_selected_layers
+ .iter()
+ .flat_map(|(_, tiles)| tiles.iter().map(|tile| tile_label_text(tile))),
+ );
+ self.shaped_labels.shape_labels_not_cached_yet(
+ &label_texts,
+ self.state_from_ui.font_family.as_deref(),
+ device_pixel_ratio,
+ shaper,
+ );
+ let drawing = OverlayDrawing {
+ shaped_labels: &self.shaped_labels,
+ scale: device_pixel_ratio.max(1.0) as f32,
+ marked,
+ };
+ OverlayRecords::record(|recorder| drawing.draw(recorder, model))
+ }
+}
+
+struct OverlayDrawing<'a> {
+ shaped_labels: &'a ShapedLabelCache,
+ scale: f32,
+ marked: MarkedLayers,
+}
+
+impl OverlayDrawing<'_> {
+ fn device_pixels(&self, logical_pixels: f32) -> i32 {
+ (logical_pixels * self.scale).round().max(1.0) as i32
+ }
+
+ /// Draws the tiles rastered lately and a thin outline of each layer the frames show, then the layer the pointer is
+ /// over, filled, and the selected layers with the tiles they hold, all outlined boldly over the others and named.
+ fn draw(&self, recorder: &mut OverlayRecorder<'_>, model: &LayerOverlayModel) {
+ let viewport_rect = model.viewport_rect;
+ let shown_layers = || model.layers.iter().filter(|layer| !layer.hidden);
+ for layer in shown_layers() {
+ self.draw_raster_highlights_of_layer(recorder, layer, viewport_rect);
+ }
+ for layer in shown_layers().filter(|layer| !self.marked.marks(layer)) {
+ self.draw_thin_outline_of_layer(recorder, layer, viewport_rect);
+ }
+ if let Some(layer) = self.marked.hovered_layer(model) {
+ Self::fill_within(
+ recorder,
+ layer.shown_bounds_in_frame(viewport_rect),
+ layer.color().with_alpha(FILL_ALPHA_OF_HOVERED_LAYER),
+ viewport_rect,
+ );
+ self.draw_bold_outline_of_layer(recorder, layer, viewport_rect);
+ }
+ for layer in self.marked.selected_layers(model) {
+ self.draw_tiles_held_by_layer(recorder, layer, viewport_rect);
+ self.draw_bold_outline_of_layer(recorder, layer, viewport_rect);
+ }
+ let labels = labels_of_model(model, &self.marked);
+ let mut rects_of_drawn_labels = Vec::new();
+ for layer in &labels.named_layers {
+ self.draw_name_of_layer(recorder, layer, viewport_rect, &mut rects_of_drawn_labels);
+ }
+ for (layer, labeled_tiles) in &labels.labeled_tiles_of_selected_layers {
+ self.draw_tile_labels_of_layer(
+ recorder,
+ layer,
+ labeled_tiles,
+ viewport_rect,
+ &mut rects_of_drawn_labels,
+ );
+ }
+ }
+
+ fn fill_within(recorder: &mut OverlayRecorder<'_>, rect: IntRect, color: Color, within: IntRect) {
+ let rect = rect.intersected(within);
+ if !rect.is_empty() {
+ recorder.fill_rect(rect, color);
+ }
+ }
+
+ fn stroke_within(recorder: &mut OverlayRecorder<'_>, rect: IntRect, thickness: i32, color: Color, within: IntRect) {
+ if rect.is_empty() {
+ return;
+ }
+ let thickness = thickness.min(rect.width / 2).min(rect.height / 2).max(1);
+ let inner_height = rect.height - 2 * thickness;
+ for edge in [
+ IntRect::new(rect.x, rect.y, rect.width, thickness),
+ IntRect::new(rect.x, rect.bottom() - thickness, rect.width, thickness),
+ IntRect::new(rect.x, rect.y + thickness, thickness, inner_height),
+ IntRect::new(rect.right() - thickness, rect.y + thickness, thickness, inner_height),
+ ] {
+ Self::fill_within(recorder, edge, color, within);
+ }
+ }
+
+ fn draw_raster_highlights_of_layer(
+ &self,
+ recorder: &mut OverlayRecorder<'_>,
+ layer: &ModelLayer,
+ viewport_rect: IntRect,
+ ) {
+ let ModelLayerContent::Painted { tiles } = &layer.content else {
+ return;
+ };
+ let visible_rect = layer.visible_rect_in_frame(viewport_rect);
+ for tile in tiles {
+ let Some(last_raster) = tile.last_raster.filter(LastRaster::is_highlighted) else {
+ continue;
+ };
+ let alpha =
+ (f32::from(RASTER_HIGHLIGHT_ALPHA_BEFORE_FADING) * last_raster.highlight_opacity()).round() as u8;
+ Self::fill_within(
+ recorder,
+ layer.rect_in_frame(last_raster.rect_in_layer_space),
+ last_raster.cause.highlight_color().with_alpha(alpha),
+ visible_rect,
+ );
+ }
+ }
+
+ /// The grid of the tiles the layer holds, tinting those of one color.
+ fn draw_tiles_held_by_layer(&self, recorder: &mut OverlayRecorder<'_>, layer: &ModelLayer, viewport_rect: IntRect) {
+ let ModelLayerContent::Painted { tiles } = &layer.content else {
+ return;
+ };
+ let visible_rect = layer.visible_rect_in_frame(viewport_rect);
+ let color = layer.color();
+ for tile in tiles.iter().filter(|tile| tile.is_one_color) {
+ if let Some(held_part_of_cell) = tile.held_part_of_cell {
+ Self::fill_within(
+ recorder,
+ layer.rect_in_frame(held_part_of_cell),
+ color.with_alpha(ONE_COLOR_TILE_TINT_ALPHA),
+ visible_rect,
+ );
+ }
+ }
+ for held_part_of_cell in tiles.iter().filter_map(|tile| tile.held_part_of_cell) {
+ Self::stroke_within(
+ recorder,
+ layer.rect_in_frame(held_part_of_cell),
+ self.device_pixels(1.0),
+ color.with_alpha(TILE_GRID_ALPHA),
+ visible_rect,
+ );
+ }
+ }
+
+ fn draw_thin_outline_of_layer(
+ &self,
+ recorder: &mut OverlayRecorder<'_>,
+ layer: &ModelLayer,
+ viewport_rect: IntRect,
+ ) {
+ Self::stroke_within(
+ recorder,
+ layer.rect_in_frame(layer.bounds_in_layer_space()),
+ self.device_pixels(1.0),
+ layer.color().with_alpha(OUTLINE_ALPHA_OF_UNMARKED_LAYER),
+ layer.visible_rect_in_frame(viewport_rect),
+ );
+ }
+
+ fn draw_bold_outline_of_layer(
+ &self,
+ recorder: &mut OverlayRecorder<'_>,
+ layer: &ModelLayer,
+ viewport_rect: IntRect,
+ ) {
+ let visible_rect = layer.visible_rect_in_frame(viewport_rect);
+ let color = layer.color();
+ let bounds_in_frame = layer.rect_in_frame(layer.bounds_in_layer_space());
+ let halo_thickness = self.device_pixels(1.0);
+ Self::stroke_within(
+ recorder,
+ bounds_in_frame,
+ self.device_pixels(2.0) + 2 * halo_thickness,
+ OUTLINE_HALO_COLOR,
+ visible_rect,
+ );
+ Self::stroke_within(
+ recorder,
+ bounds_in_frame.inflated(-2 * halo_thickness, -2 * halo_thickness),
+ self.device_pixels(2.0),
+ color,
+ visible_rect,
+ );
+ }
+
+ fn label_size(&self, label: &OverlayLabel, has_swatch: bool) -> IntSize {
+ let text_height = (label.descent - label.ascent).ceil() as i32;
+ let swatch_width = if has_swatch {
+ text_height + self.device_pixels(3.0)
+ } else {
+ 0
+ };
+ IntSize {
+ width: label.width.ceil() as i32 + swatch_width + 2 * self.device_pixels(3.0),
+ height: text_height + 2 * self.device_pixels(1.0),
+ }
+ }
+
+ fn draw_label(
+ &self,
+ recorder: &mut OverlayRecorder<'_>,
+ label: &OverlayLabel,
+ top_left: IntPoint,
+ swatch: Option<Color>,
+ background: Option<Color>,
+ ) {
+ let size = self.label_size(label, swatch.is_some());
+ let text_height = (label.descent - label.ascent).ceil() as i32;
+ if let Some(background) = background {
+ recorder.fill_rect(
+ IntRect::new(top_left.x, top_left.y, size.width, size.height),
+ background,
+ );
+ }
+ let mut text_x = top_left.x + self.device_pixels(3.0);
+ if let Some(swatch) = swatch {
+ let swatch_rect = IntRect::new(text_x, top_left.y + self.device_pixels(1.0), text_height, text_height);
+ recorder.fill_rect(swatch_rect, swatch);
+ text_x += text_height + self.device_pixels(3.0);
+ }
+ let baseline = FloatPoint {
+ x: text_x as f32,
+ y: (top_left.y + self.device_pixels(1.0)) as f32 - label.ascent,
+ };
+ recorder.draw_label(label, baseline, LABEL_TEXT_COLOR, self.scale);
+ }
+
+ fn draw_name_of_layer(
+ &self,
+ recorder: &mut OverlayRecorder<'_>,
+ layer: &ModelLayer,
+ viewport_rect: IntRect,
+ rects_of_drawn_labels: &mut Vec<IntRect>,
+ ) {
+ let visible_rect = layer.visible_rect_in_frame(viewport_rect);
+ let visible_bounds = layer
+ .rect_in_frame(layer.bounds_in_layer_space())
+ .intersected(visible_rect);
+ let Some(label) = self.shaped_labels.label_of_text(&layer_label_text(layer)) else {
+ return;
+ };
+ if visible_bounds.is_empty() {
+ return;
+ }
+ let size = self.label_size(label, true);
+ let inset = self.device_pixels(3.0);
+ let mut rect = IntRect::new(
+ visible_bounds.x + inset,
+ visible_bounds.y + inset,
+ size.width,
+ size.height,
+ );
+ while rects_of_drawn_labels
+ .iter()
+ .any(|other| !other.intersected(rect).is_empty())
+ {
+ rect.y += size.height + self.device_pixels(1.0);
+ }
+ if !visible_bounds.contains_point(IntPoint { x: rect.x, y: rect.y }) {
+ return;
+ }
+ rects_of_drawn_labels.push(rect);
+ recorder.clipped_to(visible_rect, |recorder| {
+ self.draw_label(
+ recorder,
+ label,
+ IntPoint { x: rect.x, y: rect.y },
+ Some(layer.color()),
+ Some(LABEL_BACKGROUND_COLOR),
+ );
+ });
+ }
+
+ fn draw_tile_labels_of_layer(
+ &self,
+ recorder: &mut OverlayRecorder<'_>,
+ layer: &ModelLayer,
+ labeled_tiles: &[&ModelTile],
+ viewport_rect: IntRect,
+ rects_of_drawn_labels: &mut Vec<IntRect>,
+ ) {
+ let visible_rect = layer.visible_rect_in_frame(viewport_rect);
+ let inset = self.device_pixels(3.0);
+ recorder.clipped_to(visible_rect, |recorder| {
+ for tile in labeled_tiles {
+ let Some(held_part_of_cell) = tile.held_part_of_cell else {
+ continue;
+ };
+ let held_rect_in_frame = layer.rect_in_frame(held_part_of_cell);
+ let Some(label) = self.shaped_labels.label_of_text(&tile_label_text(tile)) else {
+ continue;
+ };
+ let size = self.label_size(label, false);
+ let rect = IntRect::new(
+ held_rect_in_frame.right() - size.width - inset,
+ held_rect_in_frame.bottom() - size.height - inset,
+ size.width,
+ size.height,
+ );
+ if !visible_rect.contains_rect(rect)
+ || rects_of_drawn_labels
+ .iter()
+ .any(|other| !other.intersected(rect).is_empty())
+ {
+ continue;
+ }
+ rects_of_drawn_labels.push(rect);
+ self.draw_label(
+ recorder,
+ label,
+ IntPoint { x: rect.x, y: rect.y },
+ None,
+ Some(LABEL_BACKGROUND_COLOR),
+ );
+ }
+ });
+ }
+}
+
+/// The overlay while it is switched on, and whether the frame painted last showed it, which the frame after then
+/// erases.
+#[derive(Default)]
+pub struct LayerOverlaySwitch {
+ overlay: Option<LayerOverlay>,
+ shown_by_latest_frame: bool,
+}
+
+impl LayerOverlaySwitch {
+ /// Switches the overlay on or off from the frame on, dropping all it kept as it is switched off.
+ pub fn switch_for_frame(&mut self, state_from_ui: Option<&CompositorLayersOverlayState>) {
+ let Some(state_from_ui) = state_from_ui else {
+ self.overlay = None;
+ return;
+ };
+ self.overlay.get_or_insert_default().take_state_from_ui(state_from_ui);
+ }
+
+ /// Whether the frame repaints all of the viewport, to draw the overlay over it or to erase it.
+ pub fn repaints_everything(&self) -> bool {
+ self.overlay.is_some() || self.shown_by_latest_frame
+ }
+
+ pub fn did_paint_frame(&mut self) {
+ self.shown_by_latest_frame = self.overlay.is_some();
+ }
+
+ pub fn overlay(&self) -> Option<&LayerOverlay> {
+ self.overlay.as_ref()
+ }
+
+ pub fn overlay_mut(&mut self) -> Option<&mut LayerOverlay> {
+ self.overlay.as_mut()
+ }
+
+ pub fn latest_frame(&self) -> Option<&LayerOverlayFrame> {
+ self.overlay.as_ref()?.latest_frame()
+ }
+
+ pub fn needs_frames_until(&self) -> Option<MonotonicTime> {
+ self.overlay.as_ref()?.needs_frames_until()
+ }
+
+ pub fn hides_layer(&self, identity: &LayerIdentity) -> bool {
+ self.overlay
+ .as_ref()
+ .is_some_and(|overlay| overlay.hides_layer(identity))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use libcompositing_rust::display_list::layers::PlacementNodeIdentity;
+
+ fn painted_layer_identity(node: u64) -> LayerIdentity {
+ LayerIdentity::Painted {
+ node: PlacementNodeIdentity(node),
+ band_ordinal_in_node: 0,
+ above_barrier: None,
+ }
+ }
+
+ fn painted_layer_holding(identity: LayerIdentity, held_coords: &[TileCoord]) -> ModelLayer {
+ ModelLayer {
+ identity,
+ name: "painted layer".into(),
+ nodes_named: Rc::default(),
+ hidden: false,
+ space_to_frame: SpaceToFrame::Offset(IntPoint::default()),
+ composite_clip: None,
+ raster_counts_since_reset: RasterCountsByCause::default(),
+ content: ModelLayerContent::Painted {
+ tiles: held_coords
+ .iter()
+ .map(|&coord| ModelTile {
+ coord,
+ held_part_of_cell: Some(coord.cell_rect()),
+ is_one_color: false,
+ raster_count: 0,
+ last_raster: None,
+ })
+ .collect(),
+ },
+ }
+ }
+
+ // A plan from another process can have many more layers than the window lists.
+ #[test]
+ fn only_the_layers_the_window_lists_show_their_names() {
+ let layer_count = MAXIMUM_LISTED_LAYER_COUNT + 100;
+ let topmost_hidden = layer_count - 10;
+ let hidden_by_layer: Vec<bool> = (0..layer_count).map(|position| position >= topmost_hidden).collect();
+ let shown = layers_whose_names_are_shown(&hidden_by_layer);
+ assert!(
+ shown
+ .iter()
+ .enumerate()
+ .all(|(position, &shown)| shown == (position < MAXIMUM_LISTED_LAYER_COUNT || hidden_by_layer[position]))
+ );
+ }
+
+ fn model_of(layers: Vec<ModelLayer>) -> LayerOverlayModel {
+ LayerOverlayModel {
+ viewport_rect: IntRect::new(0, 0, 800, 600),
+ layers,
+ why_list_is_one_layer: None,
+ notes_of_layer_stack: Rc::default(),
+ work_counts_of_frame: FrameWorkCounts::default(),
+ visual_context_tree_structural_epoch: 0,
+ raster_counts_since_reset: RasterCountsByCause::default(),
+ frames_rastering_since_reset: 0,
+ }
+ }
+
+ fn coords_with_raster_history(overlay: &LayerOverlay, identity: &LayerIdentity) -> Vec<TileCoord> {
+ overlay
+ .raster_history_of_tiles_by_layer
+ .get(identity)
+ .map_or_else(Vec::new, |history| history.keys().copied().collect())
+ }
+
+ // Per tile of the layer of a frame painted at `painted_at`, once it has its raster history: where it is, whether the
+ // layer holds it, and how often it was rastered. Answers too until when some tile stays highlighted.
+ fn tiles_with_raster_history(
+ overlay: &mut LayerOverlay,
+ painted_at: MonotonicTime,
+ layer: ModelLayer,
+ ) -> (Vec<(TileCoord, bool, u32)>, Option<MonotonicTime>) {
+ let mut layers = [layer];
+ let highlights_fade_until = overlay.merge_raster_history_into(&mut layers, painted_at);
+ let ModelLayerContent::Painted { tiles } = &layers[0].content else {
+ panic!("the layer is painted");
+ };
+ let tiles = tiles
+ .iter()
+ .map(|tile| (tile.coord, tile.held_part_of_cell.is_some(), tile.raster_count))
+ .collect();
+ (tiles, highlights_fade_until)
+ }
+
+ #[test]
+ fn raster_history_is_kept_only_for_tiles_held_or_highlighted() {
+ let layer = painted_layer_identity(1);
+ let held = TileCoord::new(0, 0);
+ let let_go = TileCoord::new(1, 0);
+ let rastered_at = MonotonicTime::from_nanoseconds(1_000_000_000);
+ let mut overlay = LayerOverlay::default();
+ for coord in [held, let_go] {
+ overlay.record_raster(layer, coord, RasterCause::NewlyShown, coord.cell_rect(), rastered_at);
+ }
+
+ // A tile the layer no longer holds shows while its highlight fades.
+ let while_fading = tiles_with_raster_history(
+ &mut overlay,
+ rastered_at + Duration::from_milliseconds(100),
+ painted_layer_holding(layer, &[held]),
+ );
+ assert_eq!(
+ while_fading,
+ (
+ vec![(held, true, 1), (let_go, false, 1)],
+ Some(rastered_at + RASTER_HIGHLIGHT_FADE_DURATION)
+ )
+ );
+ assert_eq!(coords_with_raster_history(&overlay, &layer), [held, let_go]);
+
+ // Once the highlight faded, only the tile the layer holds keeps its history.
+ let after_fading = tiles_with_raster_history(
+ &mut overlay,
+ rastered_at + RASTER_HIGHLIGHT_FADE_DURATION,
+ painted_layer_holding(layer, &[held]),
+ );
+ assert_eq!(after_fading, (vec![(held, true, 1)], None));
+ assert_eq!(coords_with_raster_history(&overlay, &layer), [held]);
+
+ // A tile the layer holds again after it let the tile go counts its rasters from zero.
+ let held_again = tiles_with_raster_history(
+ &mut overlay,
+ rastered_at + RASTER_HIGHLIGHT_FADE_DURATION,
+ painted_layer_holding(layer, &[held, let_go]),
+ );
+ assert_eq!(held_again.0, [(held, true, 1), (let_go, true, 0)]);
+
+ // A layer that left the stack keeps no history.
+ tiles_with_raster_history(
+ &mut overlay,
+ rastered_at + RASTER_HIGHLIGHT_FADE_DURATION,
+ painted_layer_holding(painted_layer_identity(2), &[held]),
+ );
+ assert!(overlay.raster_history_of_tiles_by_layer.is_empty());
+ }
+
+ struct LabelShaperCountingTexts(std::cell::RefCell<Vec<String>>);
+
+ impl OverlayLabelShaper for LabelShaperCountingTexts {
+ fn shape_overlay_label(&self, _: Option<&str>, _: f32, _: f64, text: &str) -> Option<OverlayLabel> {
+ self.0.borrow_mut().push(text.to_owned());
+ None
+ }
+ }
+
+ // A stack of many layers that each hold a tile the frame shows.
+ #[test]
+ fn a_frame_labels_only_the_selected_layers_their_tiles_and_the_hovered_layer() {
+ let layers = (0..100)
+ .map(|index| ModelLayer {
+ name: format!("layer {index}").into(),
+ ..painted_layer_holding(painted_layer_identity(index), &[TileCoord::new(0, 0)])
+ })
+ .collect();
+ let shaper = LabelShaperCountingTexts(std::cell::RefCell::new(Vec::new()));
+ let mut overlay = LayerOverlay::default();
+ overlay.take_state_from_ui(&CompositorLayersOverlayState {
+ selected_layer_ids: vec![
+ id_of_layer(&painted_layer_identity(40)),
+ id_of_layer(&painted_layer_identity(60)),
+ ],
+ hovered_layer_id: Some(id_of_layer(&painted_layer_identity(7))),
+ ..CompositorLayersOverlayState::default()
+ });
+ overlay.update_with_frame(model_of(layers), MonotonicTime::default(), 1.0, &shaper);
+ assert_eq!(*shaper.0.borrow(), ["layer 40", "layer 60", "layer 7", "0,0 x0"]);
+ }
+
+ #[test]
+ fn the_layers_window_is_told_of_no_more_layers_than_a_person_can_read() {
+ let long_name = format!("a{}", "é".repeat(MAXIMUM_LISTED_LAYER_NAME_LENGTH));
+ let model_with_layer_count = |layer_count: usize| LayerOverlayModel {
+ viewport_rect: IntRect::new(0, 0, 800, 600),
+ layers: (0..layer_count)
+ .map(|index| ModelLayer {
+ name: long_name.as_str().into(),
+ content: ModelLayerContent::Media {
+ reach: IntRect::new(0, 0, 10, 10),
+ presentation: MediaPresentation::ShownByWindowServer,
+ },
+ ..painted_layer_holding(painted_layer_identity(index as u64), &[])
+ })
+ .collect(),
+ notes_of_layer_stack: Rc::from(["a note of the plan".to_owned()]),
+ ..model_of(Vec::new())
+ };
+ let notes_of = |description: &CompositorLayersDescription| -> Vec<String> {
+ description
+ .notes
+ .iter()
+ .map(|note| note.as_str().unwrap().to_owned())
+ .collect()
+ };
+
+ let all_listed = model_with_layer_count(MAXIMUM_LISTED_LAYER_COUNT).description_for_layers_window();
+ assert_eq!(all_listed.layers.len(), MAXIMUM_LISTED_LAYER_COUNT);
+ assert_eq!(notes_of(&all_listed), ["a note of the plan"]);
+
+ let some_unlisted = model_with_layer_count(MAXIMUM_LISTED_LAYER_COUNT + 3).description_for_layers_window();
+ assert_eq!(some_unlisted.layers.len(), MAXIMUM_LISTED_LAYER_COUNT);
+ assert_eq!(
+ some_unlisted.layers.last().map(|layer| layer.id),
+ Some(id_of_layer(&painted_layer_identity(
+ MAXIMUM_LISTED_LAYER_COUNT as u64 - 1
+ )))
+ );
+ assert_eq!(
+ notes_of(&some_unlisted),
+ ["not listed: 3 layers above these", "a note of the plan"]
+ );
+ assert!(some_unlisted.layers.iter().all(|layer| {
+ let name = layer.name.as_str().unwrap();
+ name.len() == MAXIMUM_LISTED_LAYER_NAME_LENGTH - 1 && long_name.starts_with(name)
+ }));
+
+ // A layer hidden in the window stays listed where layers below it push it past those listed.
+ let mut with_hidden_layer_past_those_listed = model_with_layer_count(MAXIMUM_LISTED_LAYER_COUNT + 3);
+ with_hidden_layer_past_those_listed.layers[MAXIMUM_LISTED_LAYER_COUNT + 1].hidden = true;
+ let description = with_hidden_layer_past_those_listed.description_for_layers_window();
+ assert_eq!(description.layers.len(), MAXIMUM_LISTED_LAYER_COUNT + 1);
+ assert_eq!(
+ description.layers.last().map(|layer| (layer.id, layer.hidden)),
+ Some((
+ id_of_layer(&painted_layer_identity(MAXIMUM_LISTED_LAYER_COUNT as u64 + 1)),
+ true
+ ))
+ );
+ assert_eq!(notes_of(&description)[0], "not listed: 2 layers above these");
+ }
+}
diff --git a/Services/Compositor/Rust/src/presenting/layers.rs b/Services/Compositor/Rust/src/presenting/layers.rs
index d8f60193b4f..a6f9b4a5bb4 100644
--- a/Services/Compositor/Rust/src/presenting/layers.rs
+++ b/Services/Compositor/Rust/src/presenting/layers.rs
@@ -7,25 +7,29 @@
//! The layers a frame is painted in, each cached as tiles from one frame and one list to the next, and what of them the
//! window server shows above the frame by itself.
+use super::layer_overlay::{
+ FrameWorkCounts, LayerOverlayModel, MediaPresentation, ModelLayer, ModelLayerContent, NamedVisualContextNode,
+ RasterCountsByCause, layers_whose_names_are_shown,
+};
use super::tiles::{LayerTiles, LayerToRaster, TileDraw, TileShownInFrame, joined_rects_of_grid_given_row_by_row};
-use super::window_server::WindowServerLayers;
+use super::window_server::{WhyMediaIsReplayed, WindowServerLayers};
use super::{
ContextPresenting, FrameToPaint, NestedContexts, PresentingEnvironment, apply_raster_transform,
- composite_inside_effects_of_frame, inflated, paint_overlays, rect_of_size, replay_into, replay_with_scroll_offsets,
- size_of,
+ composite_inside_effects_of_frame, inflated, rect_of_size, replay_into, replay_with_scroll_offsets, size_of,
};
use crate::context_scene::ReceivedLayerPlan;
use crate::raster_host::LiveContent;
use crate::surfaces::painting_surface::PaintingSurface;
use libcompositing_rust::display_list::commands::{
- CanvasId, CompositorContextId, ImageFrameResourceId, VideoSinkHandle,
+ CanvasId, CompositorContextId, EffectNodeIndex, ImageFrameResourceId, SpatialNodeIndex, VideoSinkHandle,
};
use libcompositing_rust::display_list::effect_geometry::{
backdrop_filter_read_reach, composited_filter_read_reach_in_device_pixels, spreading_filter_of,
};
use libcompositing_rust::display_list::layers::{
- BandIndex, LayerContent, LayerIdentity, LayerIndex, LayerStack, LayeringObstacles, PlacementNodeIdentity,
- RasterSpaceIndex, SpaceToFrame, StackLayer, WhyListIsOneLayer, WindowServerPlacementsOfMedia,
+ BandIndex, LayerContent, LayerIdentity, LayerIndex, LayerStack, LayeringObstacles, NodeNamesFromIndices,
+ PlacementNodeIdentity, RasterSpaceIndex, SpaceToFrame, StackLayer, VisualContextNodeNamer, WhyListIsOneLayer,
+ WindowServerPlacementsOfMedia,
};
use libcompositing_rust::display_list::placement::{
RasterSpaceGeometry, RasterSpaces, WhatEverySpaceOfTreeShares, raster_scroll_offsets,
@@ -33,15 +37,15 @@ use libcompositing_rust::display_list::placement::{
use libcompositing_rust::display_list::reach::Reach;
use libcompositing_rust::display_list::replay::{CompositeClipsOfRaster, ReplaySelection};
use libcompositing_rust::display_list::tile_keys::{
- BandTileKeys, ContentHash, FrameStateReadByReplay, LayerRasterSettings, LiveContentVersions, TileKeyingOfList,
- TileKeyingOfRasterSpace,
+ BandTileKeys, ContentHash, FrameStateReadByReplay, LayerRasterSettings, LiveContentVersions, TileCoverage,
+ TileKeyingOfList, TileKeyingOfRasterSpace,
};
use libcompositing_rust::display_list::tiles::TILE_SIZE_IN_DEVICE_PIXELS;
use libcompositing_rust::scrolling::DisplayList;
use libcompositing_rust::visual_context::{VisualContextTree, WorldTransforms};
use libgfx_rust::{Color, CornerRadii, FloatMatrix4x4, FloatPoint, IntPoint, IntRect};
use std::borrow::Cow;
-use std::cell::OnceCell;
+use std::cell::{OnceCell, RefCell};
use std::collections::{HashMap, HashSet};
use std::rc::{Rc, Weak};
@@ -175,6 +179,7 @@ pub struct LayerUpdate {
shown_tiles_by_layer: Vec<Vec<TileShownInFrame>>,
composited_filter_read_reach_by_layer: Vec<i32>,
pub(super) frame_allows_lcd_text: bool,
+ work_counts: FrameWorkCounts,
}
impl LayerUpdate {
@@ -213,6 +218,39 @@ struct CachedRasterSpaceGeometry {
geometry: Rc<RasterSpaceGeometry>,
}
+#[derive(Clone)]
+struct NameOfLayerForOverlay {
+ name: Rc<str>,
+ nodes_named: Rc<[NamedVisualContextNode]>,
+}
+
+/// Names the nodes of the tree by their indices, as the overlay of layers does, noting each node it names once.
+#[derive(Default)]
+struct NodeNamesFromIndicesNotingNodes {
+ nodes_named: RefCell<Vec<NamedVisualContextNode>>,
+}
+
+impl NodeNamesFromIndicesNotingNodes {
+ fn note(&self, node: NamedVisualContextNode) {
+ let mut nodes_named = self.nodes_named.borrow_mut();
+ if !nodes_named.contains(&node) {
+ nodes_named.push(node);
+ }
+ }
+}
+
+impl VisualContextNodeNamer for NodeNamesFromIndicesNotingNodes {
+ fn name_of_spatial_node(&self, index: SpatialNodeIndex) -> String {
+ self.note(NamedVisualContextNode::Spatial(index.0));
+ NodeNamesFromIndices.name_of_spatial_node(index)
+ }
+
+ fn name_of_effect_node(&self, index: EffectNodeIndex) -> String {
+ self.note(NamedVisualContextNode::Effect(index.0));
+ NodeNamesFromIndices.name_of_effect_node(index)
+ }
+}
+
/// The stack that frames draw with, and what they keep of it from one frame to the next while they draw with the same
/// plan, whose trees hold the same nodes and differ only in their values.
struct StackOfFrames {
@@ -232,6 +270,9 @@ struct StackOfFrames {
/// By band index, the tile keys of the bands as the latest frame drawn with the stack keyed its tiles, painted or not,
/// or none for a band no frame has bound yet.
band_tile_keys: Vec<Option<BandTileKeysOfFrame>>,
+ /// What the layers overlay calls the layers whose names it shows, and the nodes of the tree each name mentions,
+ /// worked out by the first frame that shows each.
+ names_of_layers_for_overlay: RefCell<HashMap<LayerIndex, NameOfLayerForOverlay>>,
}
impl StackOfFrames {
@@ -268,6 +309,7 @@ impl StackOfFrames {
raster_spaces: None,
geometry_by_space,
what_every_space_of_tree_shares: None,
+ names_of_layers_for_overlay: RefCell::default(),
}
}
@@ -664,10 +706,12 @@ fn hide_tiles_covered_by_opaque_tiles_above(
compositing_of_layers: &[LayerCompositingInFrame],
read_reaches_of_composited_effects_in_frame: &[IntRect],
viewport_rect: IntRect,
-) {
+ is_hidden_from_view: impl Fn(&LayerIdentity) -> bool,
+) -> usize {
let composited_effect_reads_tested_against_tiles =
composited_effect_reads_tiles_are_tested_against(read_reaches_of_composited_effects_in_frame);
let mut opaque_rects_in_frame_above: Vec<IntRect> = Vec::new();
+ let mut hidden_tile_count = 0;
for compositing in compositing_of_layers.iter().rev() {
if opaque_rects_in_frame_above.len() > MAXIMUM_OPAQUE_RECTS_HIDING_TILES_BELOW {
break;
@@ -680,6 +724,7 @@ fn hide_tiles_covered_by_opaque_tiles_above(
let shown = &mut shown_tiles_by_layer[layer_index.0];
let every_backdrop_read_reach_is_known = shown.iter().all(|tile| tile.raster_margin_in_device_pixels.is_some());
if !opaque_rects_in_frame_above.is_empty() && every_backdrop_read_reach_is_known {
+ let tile_count_before = shown.len();
shown.retain(|tile| {
let needed_rect_in_frame = compositing.rect_in_frame(tile.part_of_cell_needed, viewport_rect);
let is_read_by_composited_effect = composited_effect_reads_tested_against_tiles
@@ -689,13 +734,15 @@ fn hide_tiles_covered_by_opaque_tiles_above(
|| is_read_by_composited_effect
|| !rect_is_covered_by_union_of(needed_rect_in_frame, &opaque_rects_in_frame_above)
});
+ hidden_tile_count += tile_count_before - shown.len();
}
let frame_holds_layer = !compositing.shown_by_window_server;
let is_inside_composited_effects = stack.layer_is_inside_composited_effects(layer_index);
let covers_layers_below = frame_holds_layer
&& !is_inside_composited_effects
&& compositing.rounded_composite_clips.is_empty()
- && matches!(compositing.space_to_frame, SpaceToFrame::Offset(_));
+ && matches!(compositing.space_to_frame, SpaceToFrame::Offset(_))
+ && !is_hidden_from_view(&compositing.identity);
if covers_layers_below {
let opaque_rects_in_frame = shown
.iter()
@@ -708,6 +755,7 @@ fn hide_tiles_covered_by_opaque_tiles_above(
);
}
}
+ hidden_tile_count
}
fn layer_allows_lcd_text(stack: &LayerStack, layer_index: LayerIndex, frame_allows_lcd_text: bool) -> bool {
@@ -893,10 +941,12 @@ impl ContextPresenting {
let one_layer = |layers: &mut ContextLayers| {
layers.one_layer_stack_of_frame(frame.display_list, tree, viewport_rect, why_list_is_one_layer)
};
- self.layers
- .take_stack_of_frame(layer_plan, frame.display_list, one_layer, raster_transform);
+ let took_another_stack =
+ self.layers
+ .take_stack_of_frame(layer_plan, frame.display_list, one_layer, raster_transform);
+ let took_plan_into_use = layer_plan.is_some() && took_another_stack;
let layer_update = self.layer_update_of_stack(env, frame, viewport_rect, live_content, frame_allows_lcd_text);
- let Some((layer_update, stale_rect)) = layer_update else {
+ let Some((mut layer_update, stale_rect)) = layer_update else {
// Frames draw the plan as one layer from now on. The budget does not hold a frame of one layer, so the frame
// is worked out once more at most.
self.layers.draw_plan_of_frames_as_one_layer();
@@ -909,6 +959,7 @@ impl ContextPresenting {
frame_allows_lcd_text,
);
};
+ layer_update.work_counts.took_plan_into_use = took_plan_into_use;
(layer_update, stale_rect)
}
@@ -1025,6 +1076,7 @@ impl ContextPresenting {
.collect();
let composited_filter_read_reach_by_layer = composited_filter_read_reach_by_layer(stack, tree, &geometries);
+ let mut work_counts = FrameWorkCounts::default();
let mut shown_tiles_by_layer: Vec<Vec<TileShownInFrame>> =
(0..stack.layers.len()).map(|_| Vec::new()).collect();
let mut frame_shows_too_many_tiles = false;
@@ -1057,7 +1109,7 @@ impl ContextPresenting {
tile_keys: tile_keying.bind_band(stack, band_index),
}),
};
- tile_keying.key_shown_tiles(
+ let keying_counts = tile_keying.key_shown_tiles(
&mut band_tile_keys.tile_keys,
stack,
band_index,
@@ -1075,6 +1127,7 @@ impl ContextPresenting {
viewport_rect,
),
);
+ work_counts.cells_binned += keying_counts.cells_binned as u64;
for tile in band_tile_keys
.tile_keys
.tiles_within(shown_rect)
@@ -1126,6 +1179,10 @@ impl ContextPresenting {
if frame_shows_too_many_tiles {
return None;
}
+ work_counts.chunks_placed = tile_keying_by_raster_space
+ .iter()
+ .map(|tile_keying| tile_keying.chunks_placed())
+ .sum();
let painted = self.painted_frame.as_ref().map(|painted_frame| &painted_frame.layers);
let composited_effects = composited_effects_of_frame(
@@ -1139,13 +1196,14 @@ impl ContextPresenting {
painted.map(|painted| &painted.content_hash_by_composited_node),
);
let mut stale_rect = composited_effects.stale_rect;
- hide_tiles_covered_by_opaque_tiles_above(
+ work_counts.tiles_covered_by_opaque_tiles_above = hide_tiles_covered_by_opaque_tiles_above(
stack,
&mut shown_tiles_by_layer,
&compositing_of_layers,
&composited_effects.read_reaches_in_frame,
viewport_rect,
- );
+ |identity| self.layer_overlay.hides_layer(identity),
+ ) as u64;
let mut media_replayed_by_identity = HashMap::new();
for compositing in &compositing_of_layers {
let layer_index = compositing.layer_index;
@@ -1167,6 +1225,10 @@ impl ContextPresenting {
media_replayed_by_identity.insert(layer.identity, media_replayed);
continue;
}
+ work_counts.shown_tiles_of_one_color += shown_tiles_by_layer[layer_index.0]
+ .iter()
+ .filter(|tile| matches!(tile.coverage, TileCoverage::OneColor(_)))
+ .count() as u64;
stale_rect = stale_rect.united(self.layers.tiles.stale_rect_of_layer(
&shown_tiles_by_layer[layer_index.0],
compositing,
@@ -1186,10 +1248,128 @@ impl ContextPresenting {
shown_tiles_by_layer,
composited_filter_read_reach_by_layer,
frame_allows_lcd_text,
+ work_counts,
};
Some((layer_update, stale_rect))
}
+ fn update_layer_overlay_with_frame(
+ &mut self,
+ env: &PresentingEnvironment<'_>,
+ frame: &FrameToPaint<'_>,
+ layer_update: &LayerUpdate,
+ window_server_shows_layers: bool,
+ some_tiles_were_painted_straight: bool,
+ live_content: &LiveContent,
+ ) {
+ if self.layer_overlay.overlay().is_none() {
+ return;
+ }
+ let stack_of_frames = self
+ .layers
+ .stack_of_frames
+ .as_ref()
+ .expect("a frame with layers has a stack");
+ let stack = &layer_update.layers.stack;
+ let hidden_by_layer: Vec<bool> = layer_update
+ .layers
+ .compositing_of_layers
+ .iter()
+ .map(|compositing| self.layer_overlay.hides_layer(&compositing.identity))
+ .collect();
+ let name_is_shown_by_layer = layers_whose_names_are_shown(&hidden_by_layer);
+ let mut names_of_layers = stack_of_frames.names_of_layers_for_overlay.borrow_mut();
+ let name_not_shown = NameOfLayerForOverlay {
+ name: Rc::from(""),
+ nodes_named: Rc::default(),
+ };
+ let why_context_shows_no_media = self.why_window_server_shows_no_media_of_this_context(env);
+ let layers = layer_update
+ .layers
+ .compositing_of_layers
+ .iter()
+ .enumerate()
+ .map(|(position, compositing)| {
+ let layer_index = compositing.layer_index;
+ let layer = &stack.layers[layer_index.0];
+ let content = match &layer.content {
+ LayerContent::Painted => ModelLayerContent::Painted {
+ tiles: self.layers.tiles.model_tiles_of(&compositing.identity),
+ },
+ LayerContent::Media { .. } => ModelLayerContent::Media {
+ reach: layer.reach,
+ presentation: if window_server_shows_layers && compositing.shown_by_window_server {
+ MediaPresentation::ShownByWindowServer
+ } else {
+ let why = why_context_shows_no_media
+ .or_else(|| {
+ self.why_window_server_does_not_show_media_layer(
+ env,
+ &layer_update.layers.window_server_placements_of_media,
+ layer_index,
+ layer,
+ live_content,
+ )
+ })
+ .unwrap_or(if some_tiles_were_painted_straight {
+ WhyMediaIsReplayed::TilesWerePaintedStraightIntoTheFrame
+ } else if stack.layer_is_inside_composited_effects(layer_index) {
+ WhyMediaIsReplayed::InsideAnEffectTheCompositorComposites
+ } else {
+ WhyMediaIsReplayed::UnderALayerTheFrameHolds
+ });
+ MediaPresentation::Replayed { why: why.to_string() }
+ },
+ },
+ };
+ let NameOfLayerForOverlay { name, nodes_named } = if name_is_shown_by_layer[position] {
+ names_of_layers
+ .entry(layer_index)
+ .or_insert_with(|| {
+ let node_namer = NodeNamesFromIndicesNotingNodes::default();
+ let name = Rc::from(stack.name_of_layer(layer_index, &node_namer));
+ NameOfLayerForOverlay {
+ name,
+ nodes_named: Rc::from(node_namer.nodes_named.into_inner()),
+ }
+ })
+ .clone()
+ } else {
+ name_not_shown.clone()
+ };
+ ModelLayer {
+ identity: compositing.identity,
+ name,
+ nodes_named,
+ hidden: hidden_by_layer[position],
+ space_to_frame: compositing.space_to_frame,
+ composite_clip: compositing.composite_clip,
+ content,
+ raster_counts_since_reset: RasterCountsByCause::default(),
+ }
+ })
+ .collect();
+ let model = LayerOverlayModel {
+ viewport_rect: self.raster_rect(),
+ layers,
+ why_list_is_one_layer: stack.why_list_is_one_layer.map(|why| why.to_string()),
+ notes_of_layer_stack: stack_of_frames
+ .layer_plan
+ .as_ref()
+ .map_or_else(Rc::default, |layer_plan| layer_plan.note_lines.clone()),
+ work_counts_of_frame: layer_update.work_counts,
+ visual_context_tree_structural_epoch: frame.frame_inputs.visual_context_tree.structural_epoch(),
+ raster_counts_since_reset: RasterCountsByCause::default(),
+ frames_rastering_since_reset: 0,
+ };
+ let painted_at = frame.frame_inputs.painted_at;
+ let device_pixel_ratio = self.device_pixel_ratio;
+ let shaper = env.host.overlay_label_shaper(env.context_id);
+ if let Some(overlay) = self.layer_overlay.overlay_mut() {
+ overlay.update_with_frame(model, painted_at, device_pixel_ratio, &shaper);
+ }
+ }
+
/// Takes in which layers left the stack with the frame painted, or that shows nothing new, whose tiles stay in the
/// pool for a while, and answers what the frame did with its layers.
pub(super) fn commit_layer_update(
@@ -1218,7 +1398,8 @@ impl ContextPresenting {
/// Paints the frame from its layers over `damage_rect`, and answers the rect it painted, which grows to the whole
/// raster where the frame has to hold what the window server was to show above it. Unless `paints_ui_overlays`
- /// is set, the frame leaves out the overlays of the browser.
+ /// is set, the frame leaves out the overlays of the browser and of the layers.
+ #[allow(clippy::too_many_arguments)]
pub(super) fn paint_layered_frame(
&mut self,
env: &PresentingEnvironment<'_>,
@@ -1226,6 +1407,7 @@ impl ContextPresenting {
frame: &FrameToPaint<'_>,
mut damage_rect: IntRect,
layer_update: &mut LayerUpdate,
+ live_content: &LiveContent,
paints_ui_overlays: bool,
) -> IntRect {
env.raster.start_raster_cache_frame(env.context_id);
@@ -1233,6 +1415,19 @@ impl ContextPresenting {
damage_rect = layer_update.damage_grown_over_what_composited_effects_read(damage_rect);
let rects_painted_straight = self.raster_tiles_of_layers(env, surface, frame, layer_update);
+ // The overlay goes into the surface the window server shows the overlays from, so it is worked out first,
+ // expecting presenting to the window server to succeed.
+ let expected_shown_by_window_server =
+ layer_update.shown_by_window_server() && rects_painted_straight.is_empty();
+ self.update_layer_overlay_with_frame(
+ env,
+ frame,
+ layer_update,
+ expected_shown_by_window_server,
+ !rects_painted_straight.is_empty(),
+ live_content,
+ );
+
if layer_update.shown_by_window_server() {
let presented_to_window_server = rects_painted_straight.is_empty()
&& self.present_painted_layers_to_window_server(env, &layer_update.layers, surface)
@@ -1244,6 +1439,16 @@ impl ContextPresenting {
damage_rect = self.raster_rect();
}
}
+ if layer_update.shown_by_window_server() != expected_shown_by_window_server {
+ self.update_layer_overlay_with_frame(
+ env,
+ frame,
+ layer_update,
+ layer_update.shown_by_window_server(),
+ !rects_painted_straight.is_empty(),
+ live_content,
+ );
+ }
self.composite_frame_from_layers(
env,
@@ -1254,6 +1459,7 @@ impl ContextPresenting {
&rects_painted_straight,
paints_ui_overlays,
);
+ self.layer_overlay.did_paint_frame();
damage_rect
}
@@ -1270,6 +1476,7 @@ impl ContextPresenting {
let viewport_rect = self.raster_rect();
let (raster_scale, raster_translation) = (self.raster_scale, self.raster_translation);
let surface_clear_color = frame.surface_clear_color();
+ let painted_at = frame.frame_inputs.painted_at;
let holder_count_by_content_hash = self.layers.tiles.holder_counts(&layer_update.shown_tiles_by_layer);
let stack_of_frames = self
.layers
@@ -1342,6 +1549,11 @@ impl ContextPresenting {
},
&holder_count_by_content_hash,
replay_tiles,
+ self.layer_overlay.overlay_mut().map(|overlay| {
+ move |coord, cause, rect| {
+ overlay.record_raster(compositing.identity, coord, cause, rect, painted_at);
+ }
+ }),
);
rects_painted_straight.extend(
rastered
@@ -1349,6 +1561,7 @@ impl ContextPresenting {
.into_iter()
.map(|rect_in_layer_space| compositing.rect_in_frame(rect_in_layer_space, viewport_rect)),
);
+ layer_update.work_counts.tiles_rastered += rastered.tile_count;
}
rects_painted_straight
}
@@ -1367,17 +1580,19 @@ impl ContextPresenting {
let raster = env.raster;
let save_count = raster.save(surface);
raster.clip_rect(surface, damage_rect);
- if let Some(base_layer_compositing) = layer_update.layers.compositing_of_layers.first()
- && self.layers.tiles.has_layer(&base_layer_compositing.identity)
- {
- // The base layer replaces what is below it, and nothing is below it outside its composite clip. Plans
- // clip no base layer, but the compositor does not trust a plan from WebContent.
- if base_layer_compositing.composite_clip.is_some() {
+ if let Some(base_layer_compositing) = layer_update.layers.compositing_of_layers.first() {
+ if self.layer_overlay.hides_layer(&base_layer_compositing.identity) {
raster.clear(surface, frame.surface_clear_color());
+ } else if self.layers.tiles.has_layer(&base_layer_compositing.identity) {
+ // The base layer replaces what is below it, and nothing is below it outside its composite clip. Plans
+ // clip no base layer, but the compositor does not trust a plan from WebContent.
+ if base_layer_compositing.composite_clip.is_some() {
+ raster.clear(surface, frame.surface_clear_color());
+ }
+ self.layers
+ .tiles
+ .copy_into(raster, surface, damage_rect, base_layer_compositing);
}
- self.layers
- .tiles
- .copy_into(raster, surface, damage_rect, base_layer_compositing);
}
self.composite_layers_above_base_of_stack(
env,
@@ -1406,7 +1621,7 @@ impl ContextPresenting {
raster.restore_to_count(surface, save_count);
}
self.apply_raster_transform(raster, surface);
- paint_overlays(env, surface, frame.frame_inputs, paints_ui_overlays);
+ self.paint_overlays(env, surface, frame.frame_inputs, paints_ui_overlays);
}
raster.restore_to_count(surface, save_count);
}
@@ -1451,6 +1666,7 @@ impl ContextPresenting {
.iter()
.skip(1)
.filter(|compositing| compositing.shown_by_window_server == composites_layers_the_window_server_shows)
+ .filter(|compositing| !self.layer_overlay.hides_layer(&compositing.identity))
{
let layer_index = compositing.layer_index;
let layer = compositing.layer_in(stack);
@@ -1609,6 +1825,7 @@ mod tests {
viewport_rect: VIEWPORT,
stack: Rc::new(one_layer_of(display_list, VIEWPORT)),
nodes_whose_scroll_offset_plan_reads: Rc::default(),
+ note_lines: Rc::default(),
};
let plan_received_again = ReceivedLayerPlan {
stack: Rc::new((*plan.stack).clone()),
@@ -1811,6 +2028,7 @@ mod tests {
},
read_reaches_of_composited_effects_in_frame,
frame_allows_lcd_text: false,
+ work_counts: FrameWorkCounts::default(),
}
}
diff --git a/Services/Compositor/Rust/src/presenting/mod.rs b/Services/Compositor/Rust/src/presenting/mod.rs
index 2ca5953b3c9..95c05759264 100644
--- a/Services/Compositor/Rust/src/presenting/mod.rs
+++ b/Services/Compositor/Rust/src/presenting/mod.rs
@@ -9,6 +9,7 @@
//! host.
mod damage;
+mod layer_overlay;
mod layers;
pub mod pacing;
mod tiles;
@@ -22,6 +23,7 @@ use crate::remote_layers::{ShowingLayer, WindowServerObject};
use crate::surfaces::painting_surface::PaintingSurface;
use crate::surfaces::presentable_surface::PresentableSurface;
use damage::{PaintedFrame, StoreDamage};
+use layer_overlay::LayerOverlaySwitch;
use layers::ContextLayers;
use libcompositing_rust::display_list::commands::CompositorContextId;
use libcompositing_rust::display_list::replay::{
@@ -29,6 +31,7 @@ use libcompositing_rust::display_list::replay::{
ResolvedCompositedContext, composite_inside_effects, replay_display_list,
};
use libcompositing_rust::host::FfiRasterPainter;
+use libcompositing_rust::ipc_types::Compositing_CompositorLayersDescription as CompositorLayersDescription;
use libcompositing_rust::scrolling::DisplayList;
use libcompositing_rust::time::{Duration, MonotonicTime};
use libgfx_rust::{Color, FloatMatrix4x4, FloatPoint, FloatRect, FloatSize, IntRect, IntSize, enclosing_int_rect};
@@ -109,6 +112,7 @@ fn screenshots_paint_from_layers() -> bool {
struct LayeredPaintState {
layers: ContextLayers,
painted_frame: Option<PaintedFrame>,
+ layer_overlay: LayerOverlaySwitch,
viewport_size: IntSize,
shown_in_remote_layer: bool,
backing_stores: BackingStores,
@@ -116,12 +120,13 @@ struct LayeredPaintState {
impl LayeredPaintState {
/// The state of a first frame of the screenshot's size that the window server and the presentation do not show:
- /// no layers, tiles or frame from before. Without published stores, the frame draws no LCD text, as a replay of
- /// the list into a screenshot does not.
+ /// no layers, tiles or frame from before, and no overlay of the layers. Without published stores, the frame draws
+ /// no LCD text, as a replay of the list into a screenshot does not.
fn of_screenshot(target_size: IntSize) -> Self {
Self {
layers: ContextLayers::default(),
painted_frame: None,
+ layer_overlay: LayerOverlaySwitch::default(),
viewport_size: target_size,
shown_in_remote_layer: false,
backing_stores: BackingStores::default(),
@@ -214,6 +219,7 @@ pub struct ContextPresenting {
painted_frame: Option<PaintedFrame>,
layers: ContextLayers,
+ layer_overlay: LayerOverlaySwitch,
}
impl ContextPresenting {
@@ -254,6 +260,7 @@ impl ContextPresenting {
raster_translation: FloatPoint::default(),
painted_frame: None,
layers: ContextLayers::default(),
+ layer_overlay: LayerOverlaySwitch::default(),
}
}
@@ -753,6 +760,13 @@ impl ContextPresenting {
}
let display_list = display_list.expect("a frame that can render has a display list");
let frame_inputs = frame_inputs.expect("a context with a display list has frame inputs");
+ self.layer_overlay.switch_for_frame(
+ frame_inputs
+ .overlays
+ .compositor_layers
+ .as_ref()
+ .filter(|_| self.presents_to_client),
+ );
let live_content = self.live_content(env, display_list);
let frame = FrameToPaint {
display_list,
@@ -793,7 +807,15 @@ impl ContextPresenting {
};
let store_rect = rect_of_size(store.size());
let repaint_rect = self.store_damage.take(bitmap_id, damage_rect, store_rect);
- let painted_rect = self.paint_layered_frame(env, &store, &frame, repaint_rect, &mut frame_damage.layers, true);
+ let painted_rect = self.paint_layered_frame(
+ env,
+ &store,
+ &frame,
+ repaint_rect,
+ &mut frame_damage.layers,
+ &live_content,
+ true,
+ );
// The other stores miss all of what this one now holds.
if painted_rect != repaint_rect {
damage_rect = rect_of_size(IntSize {
@@ -832,6 +854,8 @@ impl ContextPresenting {
return;
};
let frame_inputs = frame_inputs.expect("a context with a display list has frame inputs");
+ // What the parent draws of the frame can go into the parent's tiles, which the overlay must stay out of.
+ self.layer_overlay.switch_for_frame(None);
let pending_frame = match self.pending_present_frame {
Some(pending_frame) => pending_frame,
None => match self.presented_frame {
@@ -864,7 +888,15 @@ impl ContextPresenting {
} else {
rect_of_size(raster_size)
};
- let _ = self.paint_layered_frame(env, &surface, &frame, repaint_rect, &mut frame_damage.layers, true);
+ let _ = self.paint_layered_frame(
+ env,
+ &surface,
+ &frame,
+ repaint_rect,
+ &mut frame_damage.layers,
+ &live_content,
+ true,
+ );
self.remember_painted_frame(
env,
pending_frame.viewport_rect,
@@ -895,7 +927,7 @@ impl ContextPresenting {
if !screenshots_paint_from_layers() || !self.paint_screenshot_from_layers(env, target, &frame) {
let save_count = env.raster.save(target);
replay_into(env, target, &frame, ReplaySelection::default());
- paint_overlays(env, target, frame_inputs, false);
+ self.paint_overlays(env, target, frame_inputs, false);
env.raster.restore_to_count(target, save_count);
}
env.raster.flush(target);
@@ -925,6 +957,7 @@ impl ContextPresenting {
frame,
frame_damage.rect_in_raster_device_pixels,
&mut frame_damage.layers,
+ &live_content,
false,
);
});
@@ -944,12 +977,14 @@ impl ContextPresenting {
let LayeredPaintState {
layers,
painted_frame,
+ layer_overlay,
viewport_size,
shown_in_remote_layer,
backing_stores,
} = state;
std::mem::swap(&mut self.layers, layers);
std::mem::swap(&mut self.painted_frame, painted_frame);
+ std::mem::swap(&mut self.layer_overlay, layer_overlay);
std::mem::swap(&mut self.viewport_size, viewport_size);
std::mem::swap(&mut self.shown_in_remote_layer, shown_in_remote_layer);
std::mem::swap(&mut self.backing_stores, backing_stores);
@@ -1005,7 +1040,7 @@ impl ContextPresenting {
source_rect,
&painted_frame.layers,
);
- paint_overlays(&snapshot_env, &composited, &painted_frame.frame_inputs, true);
+ self.paint_overlays(&snapshot_env, &composited, &painted_frame.frame_inputs, true);
source = composited;
}
}
@@ -1034,6 +1069,38 @@ impl ContextPresenting {
// A blend or backdrop filter that reads the root group needs its original isolation from the canvas fill.
&& !tree.blend_mode_or_backdrop_filter_reads_root_group()
}
+
+ /// Paints what the compositor draws over the page: its scrollbars, and unless they are left out, the overlays of the
+ /// browser and of the layers.
+ fn paint_overlays(
+ &self,
+ env: &PresentingEnvironment<'_>,
+ target: &Rc<PaintingSurface>,
+ frame_inputs: &FrameInputs,
+ paints_ui_overlays: bool,
+ ) {
+ env.raster
+ .paint(env.context_id, target, PaintingResources::Overlays, false, |painter| {
+ frame_inputs.overlays.paint(painter, paints_ui_overlays);
+ });
+ let Some(layer_overlay_frame) = self.layer_overlay.latest_frame().filter(|_| paints_ui_overlays) else {
+ return;
+ };
+ env.raster
+ .paint(env.context_id, target, PaintingResources::Overlays, false, |painter| {
+ layer_overlay_frame.records.paint(painter);
+ });
+ }
+
+ /// Until when the compositor layers overlay needs frames without anything else changing.
+ pub fn layer_overlay_needs_frames_until(&self) -> Option<MonotonicTime> {
+ self.layer_overlay.needs_frames_until()
+ }
+
+ /// What the compositor layers window is to be told of the frame painted last, if anything.
+ pub fn take_description_of_layers_to_publish(&mut self, now: MonotonicTime) -> Option<CompositorLayersDescription> {
+ self.layer_overlay.overlay_mut()?.take_description_to_publish(now)
+ }
}
fn raster_transform_of(scale: FloatSize, translation: FloatPoint) -> FloatMatrix4x4 {
@@ -1138,17 +1205,3 @@ pub(crate) fn composite_inside_effects_of_frame(
);
});
}
-
-/// Paints what the compositor draws over the page: its scrollbars, and unless they are left out, the overlays of the
-/// browser.
-pub(crate) fn paint_overlays(
- env: &PresentingEnvironment<'_>,
- target: &Rc<PaintingSurface>,
- frame_inputs: &FrameInputs,
- paints_ui_overlays: bool,
-) {
- env.raster
- .paint(env.context_id, target, PaintingResources::Overlays, false, |painter| {
- frame_inputs.overlays.paint(painter, paints_ui_overlays);
- });
-}
diff --git a/Services/Compositor/Rust/src/presenting/tiles.rs b/Services/Compositor/Rust/src/presenting/tiles.rs
index c9b69db603e..c90e927878c 100644
--- a/Services/Compositor/Rust/src/presenting/tiles.rs
+++ b/Services/Compositor/Rust/src/presenting/tiles.rs
@@ -8,6 +8,7 @@
//! pixels of a tile are pooled under the tile's content hash, which hashes all they depend on, so a layer finds the
//! tiles another layer or an earlier stack rastered.
+use super::layer_overlay::{ModelTile, RasterCause};
use super::layers::LayerCompositingInFrame;
use super::{PresentingEnvironment, inflated, rect_of_size, size_of};
use crate::host::ContextTimer;
@@ -120,6 +121,7 @@ pub(super) struct LayerToRaster<'a> {
pub(super) struct RasteredLayer {
/// In the layer's space, where tiles are painted straight from the list into the frame instead.
pub(super) rects_painted_straight: Vec<IntRect>,
+ pub(super) tile_count: u64,
}
/// The tiles the layers of a context hold under the identities of the layers, and the pool of their pixels.
@@ -167,6 +169,21 @@ impl LayerTiles {
})
}
+ pub(super) fn model_tiles_of(&self, identity: &LayerIdentity) -> Vec<ModelTile> {
+ let Some(held) = self.held_by_layer.get(identity) else {
+ return Vec::new();
+ };
+ pooled_held_tiles(&held.by_cell, &self.pool)
+ .map(|(coord, tile)| ModelTile {
+ coord,
+ held_part_of_cell: Some(tile.held_part_of_cell),
+ is_one_color: tile.surface().is_none(),
+ raster_count: 0,
+ last_raster: None,
+ })
+ .collect()
+ }
+
pub(super) fn stale_rect_of_layer(
&self,
shown: &[TileShownInFrame],
@@ -407,7 +424,8 @@ impl LayerTiles {
}
/// Keeps the tiles the layer shows and those it may show again soon, and rasters the shown tiles that lack current
- /// pixels: `replay_tiles` replays the records of the tiles it is given into a target.
+ /// pixels: `replay_tiles` replays the records of the tiles it is given into a target, and `record_raster` hears of
+ /// each tile rastered or painted straight into the frame.
pub(super) fn raster_layer(
&mut self,
env: &PresentingEnvironment<'_>,
@@ -415,6 +433,7 @@ impl LayerTiles {
layer: LayerToRaster<'_>,
holder_count_by_content_hash: &HashMap<ContentHash, usize>,
replay_tiles: impl Fn(&Rc<PaintingSurface>, &[&TileShownInFrame]),
+ mut record_raster: Option<impl FnMut(TileCoord, RasterCause, IntRect)>,
) -> RasteredLayer {
let LayerToRaster {
identity,
@@ -425,6 +444,12 @@ impl LayerTiles {
rastered_within,
} = layer;
let raster = env.raster;
+ let records_rasters = record_raster.is_some();
+ let mut record = |coord: TileCoord, cause: RasterCause, rect: IntRect| {
+ if let Some(record_raster) = &mut record_raster {
+ record_raster(coord, cause, rect);
+ }
+ };
let mut rects_painted_straight = Vec::new();
let held = self.held_by_layer.entry(identity).or_default();
let tile_pool = &mut self.pool;
@@ -442,6 +467,15 @@ impl LayerTiles {
let mut tiles_to_raster: Vec<TileToRaster> = Vec::new();
for (shown_tile_index, tile) in shown.iter().enumerate() {
let held_content_hash = held.by_cell.get(&tile.coord).copied();
+ let raster_cause_for_overlay = records_rasters.then(|| {
+ let tile_held_at_cell = held_content_hash.and_then(|held_content_hash| {
+ Some((
+ tile_pool.get(&held_content_hash)?,
+ held_content_hash == tile.content_hash,
+ ))
+ });
+ raster_cause_of(tile_held_at_cell, tile.part_of_cell_needed, like)
+ });
if held_content_hash != Some(tile.content_hash) {
held.by_cell.insert(tile.coord, tile.content_hash);
held_tiles_changed = true;
@@ -512,6 +546,11 @@ impl LayerTiles {
held.by_cell.remove(&tile.coord);
held_tiles_changed = true;
rects_painted_straight.push(tile.part_of_cell_needed);
+ record(
+ tile.coord,
+ RasterCause::PaintedStraightIntoTheFrame,
+ tile.part_of_cell_needed,
+ );
continue;
};
tile_pool.insert(
@@ -531,6 +570,7 @@ impl LayerTiles {
}
tiles_to_raster.push(TileToRaster {
shown_tile_index,
+ raster_cause_for_overlay,
was_rastered: false,
});
}
@@ -539,7 +579,10 @@ impl LayerTiles {
self.changed_since_eviction = true;
}
if tiles_to_raster.is_empty() {
- return RasteredLayer { rects_painted_straight };
+ return RasteredLayer {
+ rects_painted_straight,
+ tile_count: 0,
+ };
}
let pooled_surface_and_held_part = |tile_pool: &TilePool, tile: &TileShownInFrame| {
@@ -631,9 +674,19 @@ impl LayerTiles {
pooled.holds_current_pixels = tile_to_raster.was_rastered;
if !tile_to_raster.was_rastered {
rects_painted_straight.push(pooled.held_part_of_cell);
+ record(
+ tile.coord,
+ RasterCause::PaintedStraightIntoTheFrame,
+ pooled.held_part_of_cell,
+ );
+ } else if let Some(cause) = tile_to_raster.raster_cause_for_overlay {
+ record(tile.coord, cause, pooled.held_part_of_cell);
}
}
- RasteredLayer { rects_painted_straight }
+ RasteredLayer {
+ rects_painted_straight,
+ tile_count: tiles_to_raster.len() as u64,
+ }
}
}
@@ -698,6 +751,30 @@ fn create_surface_on_backend_of(
.filter(|surface| surface.shares_backend_with(like))
}
+fn raster_cause_of(
+ tile_held_at_cell: Option<(&PooledTile, bool)>,
+ part_of_cell_needed: IntRect,
+ like: &Rc<PaintingSurface>,
+) -> RasterCause {
+ let Some((held_tile, held_content_hash_is_needed)) = tile_held_at_cell else {
+ return RasterCause::NewlyShown;
+ };
+ if !held_tile.held_part_of_cell.contains_rect(part_of_cell_needed) {
+ return RasterCause::HeldLessThanNeeded;
+ }
+ if held_tile
+ .surface()
+ .is_some_and(|surface| !surface.shares_backend_with(like))
+ {
+ return RasterCause::HeldOnAnotherBackend;
+ }
+ if held_content_hash_is_needed {
+ RasterCause::HeldPixelsInvalidated
+ } else {
+ RasterCause::ContentHashChanged
+ }
+}
+
pub(super) fn joined_rects_of_grid_given_row_by_row<T: Copy + PartialEq>(
rects: impl IntoIterator<Item = (IntRect, T)>,
) -> Vec<(IntRect, T)> {
@@ -755,6 +832,7 @@ fn held_tile_lies_in_shown_rect_at_unshown_cell(
struct TileToRaster {
shown_tile_index: usize,
+ raster_cause_for_overlay: Option<RasterCause>,
was_rastered: bool,
}
diff --git a/Services/Compositor/Rust/src/presenting/window_server.rs b/Services/Compositor/Rust/src/presenting/window_server.rs
index 5f51c4b6375..49faafdbfcf 100644
--- a/Services/Compositor/Rust/src/presenting/window_server.rs
+++ b/Services/Compositor/Rust/src/presenting/window_server.rs
@@ -8,7 +8,7 @@
//! painted layers and the overlays of the compositor from.
use super::layers::{LayerCompositingInFrame, PaintedLayers};
-use super::{ContextPresenting, FrameToPaint, PresentingEnvironment, paint_overlays, rect_of_size, size_of};
+use super::{ContextPresenting, FrameToPaint, PresentingEnvironment, rect_of_size, size_of};
use crate::raster_host::{FfiSublayer, FfiSublayerPlacement, LiveContent, MediaKind, SublayerContentKind};
use crate::surfaces::painting_surface::PaintingSurface;
use crate::surfaces::presentable_surface::{PresentableSurface, PresentableSurfacePool};
@@ -52,6 +52,36 @@ pub(super) enum WhyMediaIsReplayed {
VideoHasNoFrame,
HighDynamicRangeIsNotShownNow,
WindowServerCannotShowThePlacement,
+ TilesWerePaintedStraightIntoTheFrame,
+ InsideAnEffectTheCompositorComposites,
+ UnderALayerTheFrameHolds,
+}
+
+impl std::fmt::Display for WhyMediaIsReplayed {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter.write_str(match self {
+ WhyMediaIsReplayed::ContextIsNotShownInARemoteLayer => "the context is not shown in a remote layer",
+ WhyMediaIsReplayed::NoGpu => "the compositor has no GPU",
+ WhyMediaIsReplayed::ContextIsPresentedFromCpuMemory => "the context is presented from CPU memory",
+ WhyMediaIsReplayed::Placement(rejection) => return write!(formatter, "{rejection}"),
+ WhyMediaIsReplayed::NoPlacement(LiveMedia::ImageFrame(_)) => "the window server does not show images",
+ WhyMediaIsReplayed::NoPlacement(LiveMedia::CompositedContext(_)) => {
+ "the window server does not show nested contexts"
+ }
+ WhyMediaIsReplayed::NoPlacement(_) => "where the window server would show it is not worked out",
+ WhyMediaIsReplayed::CanvasHasNoPresentableSurface => "the canvas has no surface the window server can show",
+ WhyMediaIsReplayed::VideoHasNoFrame => "the video has no frame",
+ WhyMediaIsReplayed::HighDynamicRangeIsNotShownNow => {
+ "the window server does not show high dynamic range now"
+ }
+ WhyMediaIsReplayed::WindowServerCannotShowThePlacement => "the window server cannot show it where it is",
+ WhyMediaIsReplayed::TilesWerePaintedStraightIntoTheFrame => "tiles were painted straight into the frame",
+ WhyMediaIsReplayed::InsideAnEffectTheCompositorComposites => {
+ "it is inside an effect the compositor composites"
+ }
+ WhyMediaIsReplayed::UnderALayerTheFrameHolds => "it is under a layer the frame holds",
+ })
+ }
}
#[derive(Default)]
@@ -264,7 +294,10 @@ impl ContextPresenting {
like: &Rc<PaintingSurface>,
) -> bool {
let raster = env.raster;
- let overlays_rect = frame.frame_inputs.overlays.bounds;
+ let mut overlays_rect = frame.frame_inputs.overlays.bounds;
+ if self.layer_overlay.latest_frame().is_some() {
+ overlays_rect = overlays_rect.united(self.raster_rect());
+ }
if overlays_rect.is_empty() {
self.layers.window_server.latest_compositor_overlays_surface_and_rect = None;
return true;
@@ -284,7 +317,7 @@ impl ContextPresenting {
raster.clear(target, Color::TRANSPARENT);
let save_count = raster.save(target);
raster.translate(target, -overlays_rect.x as f32, -overlays_rect.y as f32);
- paint_overlays(env, target, frame.frame_inputs, true);
+ self.paint_overlays(env, target, frame.frame_inputs, true);
raster.restore_to_count(target, save_count);
self.layers.window_server.latest_compositor_overlays_surface_and_rect = Some((presentable, overlays_rect));
true
@@ -306,6 +339,7 @@ impl ContextPresenting {
.iter()
.skip(1)
.filter(|compositing| compositing.shown_by_window_server)
+ .filter(|compositing| !self.layer_overlay.hides_layer(&compositing.identity))
{
let layer_index = compositing.layer_index;
let layer = compositing.layer_in(&painted.stack);
diff --git a/Tests/LibCompositing/TestUIOverlays.cpp b/Tests/LibCompositing/TestUIOverlays.cpp
index 3df5225806f..665ee7cd445 100644
--- a/Tests/LibCompositing/TestUIOverlays.cpp
+++ b/Tests/LibCompositing/TestUIOverlays.cpp
@@ -41,6 +41,13 @@ TEST_CASE(overlays_survive_ipc)
.shown = true,
.hovered_control = PictureInPictureControl::BackToTab,
};
+ overlays.compositor_layers = CompositorLayersOverlayState {
+ .font_family = "Example Sans"_string,
+ .hidden_layer_ids = { 7, NumericLimits<u64>::max() },
+ .selected_layer_ids = { 7, 8 },
+ .hovered_layer_id = 9,
+ .raster_count_reset_generation = 3,
+ };
auto decoded = MUST(decode_overlays([&](IPC::Encoder& encoder) { return encoder.encode(overlays); }));
EXPECT(decoded == overlays);