Skip to content

Truly independent web browser

LibCompositing: Plan layers for canvases and videos

Aliaksandr Kalenik19ed9cd82b4e
diff --git a/Libraries/LibCompositing/Rust/src/display_list/damage.rs b/Libraries/LibCompositing/Rust/src/display_list/damage.rs
index 3e40492f66d..ca522f46de1 100644
--- a/Libraries/LibCompositing/Rust/src/display_list/damage.rs
+++ b/Libraries/LibCompositing/Rust/src/display_list/damage.rs
@@ -6,6 +6,7 @@
use super::effect_clip_plan::EffectClipPlan;
use super::effect_geometry::{Extent, changed_extent_through_filters, nearest_spreading_effects};
+use super::layers::{LayerKind, LayerPlan};
use super::replay::{OwnSpaceClipExtent, own_space_clip_extent};
use super::summary::{DisplayListSummary, LiveContent};
use crate::display_list::builder::{
@@ -33,6 +34,8 @@ struct CommandReference<'a> {
header: DisplayListCommandHeader,
payload: &'a [u8],
context: ContextRef,
+ // The offset on its tape of the record that holds the command: its own, or that of the command it is nested in.
+ record_offset: u32,
}
// A tape and its run table. The runs are the only place a command's visual context is read from.
@@ -49,11 +52,12 @@ impl<'a> Tape<'a> {
fn collect_commands_of_runs(&self, runs: &[DisplayListCommandRun], commands: &mut Vec<CommandReference<'a>>) {
for run in runs {
- for_each_command(self.run_bytes(run), |header, _, payload| {
+ for_each_command(self.run_bytes(run), |header, offset, payload| {
commands.push(CommandReference {
header: *header,
payload,
context: run.context,
+ record_offset: run.offset + offset as u32,
});
});
}
@@ -61,13 +65,18 @@ impl<'a> Tape<'a> {
}
// Records nested in a group inherit the visual context of the enclosing run.
-fn collect_nested_command_references(bytes: &[u8], context: ContextRef) -> Vec<CommandReference<'_>> {
+fn collect_nested_command_references(
+ bytes: &[u8],
+ context: ContextRef,
+ record_offset: u32,
+) -> Vec<CommandReference<'_>> {
let mut commands = Vec::new();
for_each_command(bytes, |header, _, payload| {
commands.push(CommandReference {
header: *header,
payload,
context,
+ record_offset,
});
});
commands
@@ -82,7 +91,7 @@ fn static_mask_contents(tape: Tape<'_>, effect_count: usize) -> Vec<Option<Stati
let mut masks: Vec<_> = (0..effect_count).map(|_| None).collect();
let mut seen = vec![false; effect_count];
for run in tape.runs {
- for_each_command(tape.run_bytes(run), |header, _, payload| {
+ for_each_command(tape.run_bytes(run), |header, offset, payload| {
if header.command_type != DisplayListCommandType::DeclareMaskContent {
return;
}
@@ -95,7 +104,7 @@ fn static_mask_contents(tape: Tape<'_>, effect_count: usize) -> Vec<Option<Stati
}
seen[index] = true;
let content = super::nested_records::span_bytes(payload, declaration.content);
- let nested = collect_nested_command_references(content, run.context);
+ let nested = collect_nested_command_references(content, run.context, run.offset + offset as u32);
// Mask groups use their declaration's visual context. Only compare drawing commands whose
// complete appearance is encoded in the payload, without canvas or video. The id of a nested
// display list, such as that of an SVG mask image, names one recording whose commands never
@@ -817,22 +826,87 @@ fn intersect_like_gfx_int_rect(rect: IntRect, other: IntRect) -> IntRect {
IntRect::new(left, top, right - left, bottom - top)
}
-struct DamageAccumulator {
+/// The layer plans of the old and the new frame, which have the same layers. A layer keeps its raster between the
+/// frames, so damage is attributed to the layers that draw the content it comes from.
+#[derive(Clone, Copy)]
+pub struct LayerPlans<'a> {
+ pub old: &'a LayerPlan,
+ pub new: &'a LayerPlan,
+}
+
+#[derive(Clone, Copy)]
+enum FrameSide {
+ Old,
+ New,
+}
+
+#[derive(Clone, Copy)]
+enum DamagedLayers {
+ OfRecord(FrameSide, u32),
+ All,
+}
+
+#[derive(Clone, Copy, Default)]
+struct LayerDamage {
+ rect: Option<IntRect>,
+ is_unbounded: bool,
+}
+
+struct DamageAccumulator<'a> {
damage_rect: Option<IntRect>,
changed_unbounded_command: bool,
viewport_rect: IntRect,
+ layer_plans: Option<LayerPlans<'a>>,
+ damage_of_layers: Vec<LayerDamage>,
}
-impl DamageAccumulator {
- // Once the damage covers the viewport, no further command can change the outcome.
+impl DamageAccumulator<'_> {
+ // Once the damage covers the viewport in every raster it reaches, no further command can change the outcome.
fn covers_viewport(&self) -> bool {
- self.changed_unbounded_command
- || self
- .damage_rect
- .is_some_and(|damage_rect| damage_rect.contains_rect(self.viewport_rect))
+ let covers = |is_unbounded: bool, rect: Option<IntRect>| {
+ is_unbounded || rect.is_some_and(|rect| rect.contains_rect(self.viewport_rect))
+ };
+ covers(self.changed_unbounded_command, self.damage_rect)
+ && self.layer_plans.is_none_or(|plans| {
+ plans
+ .new
+ .layers
+ .iter()
+ .zip(&self.damage_of_layers)
+ .all(|(layer, damage)| {
+ matches!(layer.kind, LayerKind::Media { .. }) || covers(damage.is_unbounded, damage.rect)
+ })
+ })
+ }
+
+ fn for_each_damaged_layer(&mut self, layers: DamagedLayers, mut f: impl FnMut(&mut LayerDamage)) {
+ let Some(plans) = self.layer_plans else {
+ return;
+ };
+ let layer = match layers {
+ DamagedLayers::OfRecord(FrameSide::Old, record_offset) => plans.old.layer_of_record(record_offset),
+ DamagedLayers::OfRecord(FrameSide::New, record_offset) => plans.new.layer_of_record(record_offset),
+ DamagedLayers::All => {
+ self.damage_of_layers.iter_mut().for_each(f);
+ return;
+ }
+ };
+ f(&mut self.damage_of_layers[layer]);
+ }
+
+ fn add_unbounded_damage(&mut self, layers: DamagedLayers) {
+ self.changed_unbounded_command = true;
+ self.for_each_damaged_layer(layers, |damage| damage.is_unbounded = true);
}
- fn add_command_damage(&mut self, command: &CommandReference<'_>, side: TreeSide<'_>) {
+ fn add_damage_rect(&mut self, rect: IntRect, layers: DamagedLayers) {
+ let united =
+ |damage_rect: Option<IntRect>| Some(damage_rect.map_or(rect, |damage_rect| damage_rect.united(rect)));
+ self.damage_rect = united(self.damage_rect);
+ self.for_each_damaged_layer(layers, |damage| damage.rect = united(damage.rect));
+ }
+
+ fn add_command_damage(&mut self, command: &CommandReference<'_>, side: TreeSide<'_>, frame: FrameSide) {
let context = command.context;
if side.culling.context_culls_everything(context) {
return;
@@ -849,12 +923,23 @@ impl DamageAccumulator {
if rect.is_empty() {
return;
}
- self.add_changed_content_damage(rect, context, side);
+ self.add_changed_content_damage(
+ rect,
+ context,
+ side,
+ DamagedLayers::OfRecord(frame, command.record_offset),
+ );
}
// Damage for content drawn within `rect` in `context` that changed, wherever the filters above
// it spread the change.
- fn add_changed_content_damage(&mut self, rect: FloatRect, context: ContextRef, side: TreeSide<'_>) {
+ fn add_changed_content_damage(
+ &mut self,
+ rect: FloatRect,
+ context: ContextRef,
+ side: TreeSide<'_>,
+ layers: DamagedLayers,
+ ) {
let nearest_spreading_effects = side
.lazy_geometry
.nearest_spreading_effects
@@ -880,7 +965,7 @@ impl DamageAccumulator {
(Extent::Within(rect), _) => side.world().map_rect_to_root(space, rect),
(_, Some(output_clip_bounds)) => output_clip_bounds,
_ => {
- self.changed_unbounded_command = true;
+ self.add_unbounded_damage(layers);
return;
}
};
@@ -892,7 +977,7 @@ impl DamageAccumulator {
|| !transformed_rect.width.is_finite()
|| !transformed_rect.height.is_finite()
{
- self.changed_unbounded_command = true;
+ self.add_unbounded_damage(layers);
return;
}
if let Some(output_clip_bounds) = output_clip_bounds {
@@ -910,19 +995,34 @@ impl DamageAccumulator {
if transformed_rect.is_empty() {
return;
}
- let command_damage = enclosing_int_rect(transformed_rect);
- self.damage_rect = Some(match self.damage_rect {
- Some(damage_rect) => damage_rect.united(command_damage),
- None => command_damage,
- });
+ self.add_damage_rect(enclosing_int_rect(transformed_rect), layers);
}
fn add_old_command_damage(&mut self, chains: &TreeChainComparison<'_>, command: &CommandReference<'_>) {
- self.add_command_damage(command, chains.old_side());
+ self.add_command_damage(command, chains.old_side(), FrameSide::Old);
}
fn add_new_command_damage(&mut self, chains: &TreeChainComparison<'_>, command: &CommandReference<'_>) {
- self.add_command_damage(command, chains.new_side());
+ self.add_command_damage(command, chains.new_side(), FrameSide::New);
+ }
+
+ // A command that the new plan draws into another layer than the old plan leaves the raster of one layer and
+ // enters that of the other, even where it draws the same pixels.
+ fn add_layer_change_damage(
+ &mut self,
+ chains: &TreeChainComparison<'_>,
+ old_command: &CommandReference<'_>,
+ new_command: &CommandReference<'_>,
+ ) {
+ let Some(plans) = self.layer_plans else {
+ return;
+ };
+ if plans.old.layer_of_record(old_command.record_offset) == plans.new.layer_of_record(new_command.record_offset)
+ {
+ return;
+ }
+ self.add_old_command_damage(chains, old_command);
+ self.add_new_command_damage(chains, new_command);
}
// A backdrop filter can read the pixels around its region, so damage beneath the region changes it
@@ -941,13 +1041,14 @@ impl DamageAccumulator {
return;
}
let mut seen_effects = vec![false; tree.effect_nodes.len()];
+ // Each effect with a backdrop filter, with the offset of its first record.
let mut backdrop_effects = Vec::new();
for run in command_runs {
let mut effect = run.context.effect;
while !effect.is_none() && !seen_effects[effect.0 as usize] {
seen_effects[effect.0 as usize] = true;
if backdrop_of(effect).is_some() {
- backdrop_effects.push(effect);
+ backdrop_effects.push((effect, run.offset));
}
effect = tree.effect_nodes[effect.0 as usize].parent;
}
@@ -963,7 +1064,7 @@ impl DamageAccumulator {
};
let damage = damage_rect.to_float();
let mut damage_grew = false;
- for (index, &effect) in backdrop_effects.iter().enumerate() {
+ for (index, &(effect, first_record_offset)) in backdrop_effects.iter().enumerate() {
if region_is_damaged[index] {
continue;
}
@@ -990,7 +1091,12 @@ impl DamageAccumulator {
clip: side.effect_clips.output_clip(effect),
effect,
};
- self.add_changed_content_damage(region, backdrop_context, side);
+ self.add_changed_content_damage(
+ region,
+ backdrop_context,
+ side,
+ DamagedLayers::OfRecord(FrameSide::New, first_record_offset),
+ );
}
if !damage_grew {
return;
@@ -1100,10 +1206,17 @@ impl DamageAccumulator {
inline_clip_spaces_may_have_moved: bool,
) {
let commands_moved = !verdict.equal;
- if !commands_moved && !scroll_offsets_differ && !inline_clip_spaces_may_have_moved {
+ let commands_may_change_layers = self
+ .layer_plans
+ .is_some_and(|plans| !plans.old.places_run_like(old_run, plans.new, new_run));
+ if !commands_moved
+ && !scroll_offsets_differ
+ && !inline_clip_spaces_may_have_moved
+ && !commands_may_change_layers
+ {
return;
}
- for_each_command(chains.old_tape.run_bytes(old_run), |header, _, payload| {
+ for_each_command(chains.old_tape.run_bytes(old_run), |header, offset, payload| {
if self.covers_viewport() {
return;
}
@@ -1111,12 +1224,17 @@ impl DamageAccumulator {
header: *header,
payload,
context: old_run.context,
+ record_offset: old_run.offset + offset as u32,
};
let new_command = CommandReference {
header: *header,
payload,
context: new_run.context,
+ record_offset: new_run.offset + offset as u32,
};
+ if commands_may_change_layers {
+ self.add_layer_change_damage(chains, &old_command, &new_command);
+ }
if commands_moved {
self.add_moved_command_damage(chains, &old_command, &new_command);
}
@@ -1158,6 +1276,7 @@ impl DamageAccumulator {
let add_matched_pair_damage =
|damage: &mut Self, old_command: &CommandReference<'_>, new_command: &CommandReference<'_>| {
+ damage.add_layer_change_damage(chains, old_command, new_command);
damage.add_visual_context_damage(chains, old_command, new_command);
if scroll_offsets_differ {
damage.add_scrollbar_scroll_damage(chains, old_command, new_command);
@@ -1438,6 +1557,22 @@ pub struct LiveContentChanges<'a> {
pub offsets_of_records_composited_as_media_layers: &'a [u32],
}
+#[derive(Clone, Debug, PartialEq)]
+pub struct DisplayListDamage {
+ pub rect: Option<IntRect>,
+ /// With the frames' layer plans, the damage of each layer, none where that has no bounds.
+ pub layer_rects: Vec<Option<IntRect>>,
+}
+
+impl DisplayListDamage {
+ pub fn unbounded(layer_count: usize) -> Self {
+ Self {
+ rect: None,
+ layer_rects: vec![None; layer_count],
+ }
+ }
+}
+
impl LiveContentChanges<'_> {
fn is_empty(&self) -> bool {
self.canvases.is_empty() && self.video_sinks.is_empty() && self.image_frames.is_empty()
@@ -1454,15 +1589,19 @@ impl LiveContentChanges<'_> {
// The viewport-space damage between two frames, or None when a change without bounds needs a
// full repaint. The diff pairs the run tables first: runs that are byte-identical under chains of
-// the same shape are never decoded unless their chains or scroll offsets changed. Only the runs
-// in between are diffed command by command, and the diff stops as soon as the damage covers the
-// viewport, so a later unbounded change may then be reported as the viewport rect instead of None.
+// the same shape are never decoded unless their chains, scroll offsets or layers changed. Only the
+// runs in between are diffed command by command, and the diff stops as soon as the damage covers
+// the viewport, so a later unbounded change may then be reported as the viewport rect instead of
+// None. Given the frames' layer plans, the damage of each layer is reported too.
pub fn compute_display_list_damage(
old_frame: DisplayListFrame<'_>,
new_frame: DisplayListFrame<'_>,
viewport_rect: IntRect,
live_content_changes: LiveContentChanges<'_>,
-) -> Option<IntRect> {
+ layer_plans: Option<LayerPlans<'_>>,
+) -> DisplayListDamage {
+ let layer_count = layer_plans.map_or(0, |plans| plans.new.layers.len());
+ let unbounded_damage = DisplayListDamage::unbounded(layer_count);
let old_tape = Tape {
bytes: old_frame.command_bytes,
runs: old_frame.command_runs,
@@ -1482,14 +1621,20 @@ pub fn compute_display_list_damage(
let chains = TreeChainComparison {
old_tape,
new_tape,
- old_effect_clips: EffectClipPlan::from_contexts(
+ old_effect_clips: match EffectClipPlan::from_contexts(
old_visual_context_tree,
old_command_runs.iter().map(|run| run.context),
- )?,
- new_effect_clips: EffectClipPlan::from_contexts(
+ ) {
+ Some(plan) => plan,
+ None => return unbounded_damage,
+ },
+ new_effect_clips: match EffectClipPlan::from_contexts(
new_visual_context_tree,
new_command_runs.iter().map(|run| run.context),
- )?,
+ ) {
+ Some(plan) => plan,
+ None => return unbounded_damage,
+ },
old_mask_contents: OnceCell::new(),
new_mask_contents: OnceCell::new(),
old_tree: old_visual_context_tree,
@@ -1548,6 +1693,8 @@ pub fn compute_display_list_damage(
damage_rect: None,
changed_unbounded_command: false,
viewport_rect,
+ layer_plans,
+ damage_of_layers: vec![LayerDamage::default(); layer_count],
};
let identical_run_pairs = old_command_runs[..identical_prefix_run_count]
.iter()
@@ -1615,6 +1762,7 @@ pub fn compute_display_list_damage(
header,
payload: &new_frame.command_bytes[payload_start..payload_start + header.payload_size as usize],
context: new_command_runs[live_content_record.record.run_index as usize].context,
+ record_offset: live_content_record.record.record_offset,
},
);
}
@@ -1623,23 +1771,26 @@ pub fn compute_display_list_damage(
// NB: A backdrop filter reads more than the part of its region that is repainted, so forced damage goes through it too.
let forced_damage_rect = live_content_changes.forced_damage_rect;
if !forced_damage_rect.is_empty() {
- damage.damage_rect = Some(match damage.damage_rect {
- Some(damage_rect) => damage_rect.united(forced_damage_rect),
- None => forced_damage_rect,
- });
+ damage.add_damage_rect(forced_damage_rect, DamagedLayers::All);
}
damage.add_backdrop_filter_damage(chains.new_side(), new_command_runs);
- if damage.changed_unbounded_command {
- return None;
- }
- let Some(damage_rect) = damage.damage_rect else {
- return Some(IntRect::default());
+ let bounded_damage_rect = |is_unbounded: bool, damage_rect: Option<IntRect>| {
+ if is_unbounded {
+ return None;
+ }
+ Some(damage_rect.map_or(IntRect::default(), |damage_rect| {
+ intersect_like_gfx_int_rect(damage_rect.inflated_edges(1, 1, 1, 1), viewport_rect)
+ }))
};
- Some(intersect_like_gfx_int_rect(
- damage_rect.inflated_edges(1, 1, 1, 1),
- viewport_rect,
- ))
+ DisplayListDamage {
+ rect: bounded_damage_rect(damage.changed_unbounded_command, damage.damage_rect),
+ layer_rects: damage
+ .damage_of_layers
+ .iter()
+ .map(|layer_damage| bounded_damage_rect(layer_damage.is_unbounded, layer_damage.rect))
+ .collect(),
+ }
}
#[cfg(test)]
@@ -2022,7 +2173,9 @@ mod tests {
},
viewport_rect,
LiveContentChanges::default(),
+ None,
)
+ .rect
}
fn context_in(spatial: SpatialNodeIndex, context: ContextRef) -> ContextRef {
@@ -2042,7 +2195,7 @@ mod tests {
visual_context_tree: tree,
scroll_offsets: &[],
};
- compute_display_list_damage(frame, frame, IntRect::new(0, 0, 100, 100), live_content_changes)
+ compute_display_list_damage(frame, frame, IntRect::new(0, 0, 100, 100), live_content_changes, None).rect
}
#[test]
diff --git a/Libraries/LibCompositing/Rust/src/display_list/layers.rs b/Libraries/LibCompositing/Rust/src/display_list/layers.rs
new file mode 100644
index 00000000000..1525e12321b
--- /dev/null
+++ b/Libraries/LibCompositing/Rust/src/display_list/layers.rs
@@ -0,0 +1,1330 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use crate::display_list::builder::{HEADER_SIZE, for_each_command, read_command, read_header};
+use crate::display_list::commands::{
+ ClipMode, ClipNodeIndex, DeclareMaskContent, DisplayListCommandRun, DisplayListCommandType, EffectNodeIndex,
+};
+use crate::display_list::effect_clip_plan::EffectClipPlan;
+use crate::display_list::effect_geometry::{Extent, compute_effect_geometry};
+use crate::display_list::summary::{DisplayListSummary, IndexedRecord, LiveContent};
+use crate::host::RecordSpan;
+use crate::visual_context::queries::TreeCullingScratch;
+use crate::visual_context::{ClipNodeData, EffectNodeData, SpatialData, VisualContextTree, WorldTransforms};
+use libgfx_rust::{FloatMatrix4x4, FloatPoint, FloatRect, IntRect, enclosing_int_rect};
+
+pub const MAXIMUM_MEDIA_LAYER_COUNT: usize = 8;
+const BOUNDS_MARGIN_IN_DEVICE_PIXELS: i32 = 3;
+const MAXIMUM_UPPER_PAINTED_LAYER_AREA_IN_VIEWPORTS: i64 = 2;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum LayerKind {
+ Base,
+ Painted,
+ Media { content: LiveContent },
+}
+
+impl std::fmt::Display for LayerKind {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ LayerKind::Base => formatter.write_str("base"),
+ LayerKind::Painted => formatter.write_str("painted"),
+ LayerKind::Media { content } => formatter.write_str(media_name(*content)),
+ }
+ }
+}
+
+fn media_name(content: LiveContent) -> &'static str {
+ match content {
+ LiveContent::Canvas(_) => "canvas",
+ LiveContent::VideoFrame(_) => "video",
+ LiveContent::ImageFrame(_) => "image",
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum MediaLayerRejection {
+ DrawnInsideAnotherCommand,
+ InsideGroupEffect,
+ UnderTransformThatIsNot2DAffine,
+ DrawsNothingVisible,
+ BetweenRunsOfOneGroupEffect,
+}
+
+impl std::fmt::Display for MediaLayerRejection {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter.write_str(match self {
+ MediaLayerRejection::DrawnInsideAnotherCommand => "drawn inside another command",
+ MediaLayerRejection::InsideGroupEffect => "inside a group effect",
+ MediaLayerRejection::UnderTransformThatIsNot2DAffine => "under a transform that is not 2D affine",
+ MediaLayerRejection::DrawsNothingVisible => "draws nothing visible",
+ MediaLayerRejection::BetweenRunsOfOneGroupEffect => "between the runs of one group effect",
+ })
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum UnlayeredReason {
+ NoActiveMedia,
+ EmptyViewport,
+ EmptyDisplayList,
+ SortingContext3D,
+ RootIsolationEffectIsNotPlainGroup,
+ BlendModeReadsRootGroup,
+ BackdropFilterReadsRootGroup,
+ CommandBlendsWithRootGroup,
+ MaskDeclaredOutsideItsMask,
+ ActiveMediaNotDrawn,
+ NoMediaCanBeLayer {
+ first_rejected_media: LiveContent,
+ rejection: MediaLayerRejection,
+ },
+ BackdropFilterInUpperPaintedLayer,
+ UpperPaintedLayersTooLarge,
+}
+
+impl std::fmt::Display for UnlayeredReason {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let text = match self {
+ UnlayeredReason::NoMediaCanBeLayer {
+ first_rejected_media,
+ rejection,
+ } => return write!(formatter, "{} {rejection}", media_name(*first_rejected_media)),
+ UnlayeredReason::UpperPaintedLayersTooLarge => {
+ return write!(
+ formatter,
+ "painted layers larger than {MAXIMUM_UPPER_PAINTED_LAYER_AREA_IN_VIEWPORTS} viewports"
+ );
+ }
+ UnlayeredReason::NoActiveMedia => "no canvas or video keeps updating",
+ UnlayeredReason::EmptyViewport => "empty viewport",
+ UnlayeredReason::EmptyDisplayList => "empty display list",
+ UnlayeredReason::SortingContext3D => "3D sorting context",
+ UnlayeredReason::RootIsolationEffectIsNotPlainGroup => "root isolation effect is not a plain group",
+ UnlayeredReason::BlendModeReadsRootGroup => "blend mode reads the root group",
+ UnlayeredReason::BackdropFilterReadsRootGroup => "backdrop filter reads the root group",
+ UnlayeredReason::CommandBlendsWithRootGroup => "command blends with the root group",
+ UnlayeredReason::MaskDeclaredOutsideItsMask => "mask content declared outside its mask",
+ UnlayeredReason::ActiveMediaNotDrawn => "no updating canvas or video is drawn",
+ UnlayeredReason::BackdropFilterInUpperPaintedLayer => "backdrop filter above a canvas or video",
+ };
+ formatter.write_str(text)
+ }
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Layer {
+ pub kind: LayerKind,
+ pub rect: IntRect,
+ pub record_spans: Vec<RecordSpan>,
+}
+
+// The records from `begin_offset` up to the next range's start are drawn into the layer at `layer`.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+struct LayerRecordRange {
+ begin_offset: u32,
+ layer: u8,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct LayerPlan {
+ pub layers: Vec<Layer>,
+ record_ranges_in_tape_order: Vec<LayerRecordRange>,
+}
+
+impl LayerPlan {
+ pub fn media_record_offsets(&self) -> impl Iterator<Item = u32> + '_ {
+ self.layers.iter().filter_map(|layer| match layer.kind {
+ LayerKind::Media { .. } => Some(layer.record_spans[0].begin_offset),
+ _ => None,
+ })
+ }
+
+ /// Whether the plan has the same layers as `other` in the same order, so that a raster kept for a layer of one
+ /// plan holds the content of the same layer of the other plan wherever no damage says otherwise.
+ pub fn has_same_layers_as(&self, other: &LayerPlan) -> bool {
+ self.layers.len() == other.layers.len()
+ && self
+ .layers
+ .iter()
+ .zip(&other.layers)
+ .all(|(layer, other_layer)| layer.kind == other_layer.kind)
+ }
+
+ /// One line per layer, bottom to top: `[L<index>] <kind> rect=[<x>,<y> <width>x<height>]` after `indent`.
+ pub fn write_layer_lines(&self, output: &mut impl std::fmt::Write, indent: &str) -> std::fmt::Result {
+ for (index, layer) in self.layers.iter().enumerate() {
+ let rect = layer.rect;
+ writeln!(
+ output,
+ "{indent}[L{index}] {} rect=[{},{} {}x{}]",
+ layer.kind, rect.x, rect.y, rect.width, rect.height
+ )?;
+ }
+ Ok(())
+ }
+
+ pub fn layer_of_record(&self, record_offset: u32) -> usize {
+ let range_index = self
+ .record_ranges_in_tape_order
+ .partition_point(|range| range.begin_offset <= record_offset)
+ .saturating_sub(1);
+ self.record_ranges_in_tape_order[range_index].layer as usize
+ }
+
+ /// Whether the records of `run` go into the same layers as those of `other_run`, an identical run of the list
+ /// that `other` plans, at the same offsets in the run.
+ pub fn places_run_like(
+ &self,
+ run: &DisplayListCommandRun,
+ other: &LayerPlan,
+ other_run: &DisplayListCommandRun,
+ ) -> bool {
+ self.layers_of_records_in(run).eq(other.layers_of_records_in(other_run))
+ }
+
+ // Where in the run the records of each layer start, as offsets in the run.
+ fn layers_of_records_in(&self, run: &DisplayListCommandRun) -> impl Iterator<Item = (u32, u8)> + '_ {
+ let first_range_index = self
+ .record_ranges_in_tape_order
+ .partition_point(|range| range.begin_offset <= run.offset)
+ .saturating_sub(1);
+ let (run_offset, run_end) = (run.offset, run.offset + run.size);
+ std::iter::once((0, self.record_ranges_in_tape_order[first_range_index].layer)).chain(
+ self.record_ranges_in_tape_order[first_range_index + 1..]
+ .iter()
+ .take_while(move |range| range.begin_offset < run_end)
+ .map(move |range| (range.begin_offset - run_offset, range.layer)),
+ )
+ }
+}
+
+pub struct LayerPlanInputs<'a> {
+ pub tape: &'a [u8],
+ pub command_runs: &'a [DisplayListCommandRun],
+ pub summary: &'a DisplayListSummary,
+ pub effect_clips: &'a EffectClipPlan,
+ pub tree: &'a VisualContextTree,
+ pub scroll_offsets: &'a [FloatPoint],
+ pub viewport_rect: IntRect,
+ pub active_media: &'a [LiveContent],
+}
+
+fn tree_has_sorting_contexts(tree: &VisualContextTree) -> bool {
+ tree.spatial_nodes.iter().any(|node| {
+ matches!(&node.data, SpatialData::Transform(transform) if transform.sorting_context_root_index.is_some())
+ })
+}
+
+fn root_isolation_effect_is_plain_group(tree: &VisualContextTree) -> bool {
+ let Some(root) = tree.root_isolation_effect else {
+ return true;
+ };
+ match &tree.effect_nodes[root.0 as usize].data {
+ EffectNodeData::Effects(effects) => {
+ effects.opacity == 1.0
+ && effects.blend_mode == libgfx_rust::CompositingAndBlendingOperator::Normal
+ && effects.filter.is_none()
+ && effects.backdrop_filter.is_none()
+ }
+ _ => false,
+ }
+}
+
+fn effect_chain_contains(tree: &VisualContextTree, mut effect: EffectNodeIndex, wanted: EffectNodeIndex) -> bool {
+ while !effect.is_none() {
+ if effect == wanted {
+ return true;
+ }
+ effect = tree.effect_nodes[effect.0 as usize].parent;
+ }
+ false
+}
+
+fn what_reads_root_group(inputs: &LayerPlanInputs<'_>) -> Option<UnlayeredReason> {
+ if let Some(effect) = inputs.tree.first_effect_reading_root_group() {
+ let reads_through_blend_mode = matches!(
+ &inputs.tree.effect_nodes[effect.0 as usize].data,
+ EffectNodeData::Effects(effects) if effects.blend_mode != libgfx_rust::CompositingAndBlendingOperator::Normal
+ );
+ return Some(if reads_through_blend_mode {
+ UnlayeredReason::BlendModeReadsRootGroup
+ } else {
+ UnlayeredReason::BackdropFilterReadsRootGroup
+ });
+ }
+ let command_blends_with_root_group = inputs.summary.destination_blending_records.iter().any(|record| {
+ let effect = inputs.command_runs[record.run_index as usize].context.effect;
+ inputs.tree.content_under_effect_composites_into_root_group(effect)
+ });
+ command_blends_with_root_group.then_some(UnlayeredReason::CommandBlendsWithRootGroup)
+}
+
+fn mask_declarations_sit_under_their_masks(inputs: &LayerPlanInputs<'_>) -> bool {
+ inputs.summary.mask_declarations.iter().all(|record| {
+ let offset = record.record_offset as usize;
+ let header = read_header(&inputs.tape[offset..]);
+ let payload = &inputs.tape[offset + HEADER_SIZE..offset + HEADER_SIZE + header.payload_size as usize];
+ let declaration = read_command::<DeclareMaskContent>(payload);
+ let run_effect = inputs.command_runs[record.run_index as usize].context.effect;
+ effect_chain_contains(inputs.tree, run_effect, declaration.effect)
+ })
+}
+
+// The structure decides the grouping effect rather than the effect values, so chunks stay put while an opacity animates.
+fn outermost_grouping_effects(tree: &VisualContextTree) -> Vec<EffectNodeIndex> {
+ let mut outermost = vec![EffectNodeIndex::NONE; tree.effect_nodes.len()];
+ tree.visit_effect_nodes_parents_first(|index| {
+ let node = &tree.effect_nodes[index];
+ let from_parent = if node.parent.is_none() {
+ EffectNodeIndex::NONE
+ } else {
+ outermost[node.parent.0 as usize]
+ };
+ let is_grouping = node.data.pushes_layer() && tree.root_isolation_effect != Some(EffectNodeIndex(index as u32));
+ outermost[index] = if !from_parent.is_none() {
+ from_parent
+ } else if is_grouping {
+ EffectNodeIndex(index as u32)
+ } else {
+ EffectNodeIndex::NONE
+ };
+ });
+ outermost
+}
+
+fn effects_with_backdrop_filter_on_chain(tree: &VisualContextTree) -> Vec<bool> {
+ let mut on_chain = vec![false; tree.effect_nodes.len()];
+ tree.visit_effect_nodes_parents_first(|index| {
+ let node = &tree.effect_nodes[index];
+ let own = matches!(&node.data, EffectNodeData::Effects(effects) if effects.backdrop_filter.is_some());
+ on_chain[index] = own || (!node.parent.is_none() && on_chain[node.parent.0 as usize]);
+ });
+ on_chain
+}
+
+fn clip_chain_bounds(tree: &VisualContextTree, world: &WorldTransforms) -> Vec<Option<FloatRect>> {
+ let mut bounds: Vec<Option<FloatRect>> = vec![None; tree.clip_nodes.len()];
+ tree.visit_clip_nodes_parents_first(|index| {
+ let node = &tree.clip_nodes[index];
+ let own = match &node.data {
+ ClipNodeData::Rect(data) if data.mode == ClipMode::Intersect => Some(data.rect),
+ ClipNodeData::Path(path) => Some(path.bounding_rect.to_float()),
+ _ => None,
+ }
+ .map(|rect| world.map_rect_to_root(node.spatial, rect))
+ .filter(|rect| rect.x.is_finite() && rect.y.is_finite() && rect.width.is_finite() && rect.height.is_finite());
+ let from_parent = if node.parent.is_none() {
+ None
+ } else {
+ bounds[node.parent.0 as usize]
+ };
+ bounds[index] = match (own, from_parent) {
+ (Some(own), Some(from_parent)) => Some(own.intersected(from_parent)),
+ (own, from_parent) => own.or(from_parent),
+ };
+ });
+ bounds
+}
+
+struct BoundsContext<'a> {
+ world: WorldTransforms,
+ culling: TreeCullingScratch,
+ clip_bounds: Vec<Option<FloatRect>>,
+ viewport_rect: IntRect,
+ tree: &'a VisualContextTree,
+}
+
+impl BoundsContext<'_> {
+ fn device_rect(&self, rect: Option<FloatRect>, clip: ClipNodeIndex) -> IntRect {
+ let clip_bounds = if clip.is_none() {
+ None
+ } else {
+ self.clip_bounds[clip.0 as usize]
+ };
+ let rect = match (rect, clip_bounds) {
+ (Some(rect), Some(clip_bounds)) => rect.intersected(clip_bounds),
+ (Some(rect), None) => rect,
+ (None, Some(clip_bounds)) => clip_bounds,
+ (None, None) => return self.viewport_rect,
+ };
+ if !(rect.x.is_finite() && rect.y.is_finite() && rect.width.is_finite() && rect.height.is_finite()) {
+ return self.viewport_rect;
+ }
+ if rect.is_empty() {
+ return IntRect::default();
+ }
+ let viewport = self.viewport_rect.to_float();
+ let rect = rect.intersected(viewport.inflated(
+ 2.0 * BOUNDS_MARGIN_IN_DEVICE_PIXELS as f32,
+ 2.0 * BOUNDS_MARGIN_IN_DEVICE_PIXELS as f32,
+ ));
+ if rect.is_empty() {
+ return IntRect::default();
+ }
+ enclosing_int_rect(rect)
+ .inflated_edges(
+ BOUNDS_MARGIN_IN_DEVICE_PIXELS,
+ BOUNDS_MARGIN_IN_DEVICE_PIXELS,
+ BOUNDS_MARGIN_IN_DEVICE_PIXELS,
+ BOUNDS_MARGIN_IN_DEVICE_PIXELS,
+ )
+ .intersected(self.viewport_rect)
+ }
+
+ fn ink_device_rect(&self, run: &DisplayListCommandRun, ink: IntRect) -> IntRect {
+ if ink.is_empty()
+ || self.world.backface_culled[run.context.spatial.0 as usize]
+ || self.culling.context_culls_everything(run.context)
+ {
+ return IntRect::default();
+ }
+ let rect = self.world.map_rect_to_root(run.context.spatial, ink.to_float());
+ self.device_rect(Some(rect), run.context.clip)
+ }
+
+ fn group_device_rect(&self, effect: EffectNodeIndex, output: Extent, effect_clips: &EffectClipPlan) -> IntRect {
+ let node = &self.tree.effect_nodes[effect.0 as usize];
+ let output_clip = effect_clips.output_clip(effect);
+ match output {
+ Extent::Nothing => IntRect::default(),
+ Extent::Within(rect) => {
+ self.device_rect(Some(self.world.map_rect_to_root(node.spatial, rect)), output_clip)
+ }
+ Extent::Anywhere => self.device_rect(None, output_clip),
+ }
+ }
+}
+
+struct LayersBeingPlanned {
+ layers: Vec<Layer>,
+ record_ranges_in_tape_order: Vec<LayerRecordRange>,
+}
+
+impl LayersBeingPlanned {
+ const BASE_LAYER_INDEX: usize = 0;
+
+ fn new(viewport_rect: IntRect) -> Self {
+ Self {
+ layers: vec![Layer {
+ kind: LayerKind::Base,
+ rect: viewport_rect,
+ record_spans: Vec::new(),
+ }],
+ record_ranges_in_tape_order: Vec::new(),
+ }
+ }
+
+ fn topmost_layer_above_base_touching(&self, bounds: IntRect) -> Option<usize> {
+ if bounds.is_empty() {
+ return None;
+ }
+ (Self::BASE_LAYER_INDEX + 1..self.layers.len())
+ .rev()
+ .find(|&index| !self.layers[index].rect.intersected(bounds).is_empty())
+ }
+
+ fn add_media_layer(&mut self, content: LiveContent, span: RecordSpan, bounds: IntRect) {
+ self.layers.push(Layer {
+ kind: LayerKind::Media { content },
+ rect: bounds,
+ record_spans: Vec::new(),
+ });
+ self.append_records_to_layer(self.layers.len() - 1, span);
+ }
+
+ // Records drawn within `bounds` go into the lowest painted layer that is above every layer they touch, or into
+ // the base layer when they touch none above it.
+ fn place_painted_records(
+ &mut self,
+ span: RecordSpan,
+ bounds: IntRect,
+ has_backdrop_filter: bool,
+ ) -> Result<usize, UnlayeredReason> {
+ let layer_index = match self.topmost_layer_above_base_touching(bounds) {
+ None => Self::BASE_LAYER_INDEX,
+ Some(touched) => {
+ if has_backdrop_filter {
+ return Err(UnlayeredReason::BackdropFilterInUpperPaintedLayer);
+ }
+ let layer_index = (touched..self.layers.len())
+ .find(|&index| self.layers[index].kind == LayerKind::Painted)
+ .unwrap_or_else(|| {
+ self.layers.push(Layer {
+ kind: LayerKind::Painted,
+ rect: IntRect::default(),
+ record_spans: Vec::new(),
+ });
+ self.layers.len() - 1
+ });
+ self.layers[layer_index].rect = self.layers[layer_index].rect.united(bounds);
+ layer_index
+ }
+ };
+ self.append_records_to_layer(layer_index, span);
+ Ok(layer_index)
+ }
+
+ fn append_records_to_layer(&mut self, layer_index: usize, span: RecordSpan) {
+ let spans = &mut self.layers[layer_index].record_spans;
+ match spans.last_mut() {
+ Some(last) if last.end_offset == span.begin_offset => last.end_offset = span.end_offset,
+ _ => spans.push(span),
+ }
+ if self
+ .record_ranges_in_tape_order
+ .last()
+ .is_none_or(|range| range.layer as usize != layer_index)
+ {
+ self.record_ranges_in_tape_order.push(LayerRecordRange {
+ begin_offset: span.begin_offset,
+ layer: layer_index as u8,
+ });
+ }
+ }
+}
+
+struct MediaCandidate {
+ content: LiveContent,
+ run_index: u32,
+ record_offset: u32,
+}
+
+fn media_layer_rejection(
+ inputs: &LayerPlanInputs<'_>,
+ grouping_effects: &[EffectNodeIndex],
+ bounds: &BoundsContext<'_>,
+ run_is_a_chunk_of_its_own: impl Fn(u32) -> bool,
+ run_index: u32,
+ record_offset: u32,
+) -> Option<MediaLayerRejection> {
+ let header = read_header(&inputs.tape[record_offset as usize..]);
+ if !matches!(
+ header.command_type,
+ DisplayListCommandType::DrawCanvas | DisplayListCommandType::DrawVideoFrame
+ ) {
+ return Some(MediaLayerRejection::DrawnInsideAnotherCommand);
+ }
+ let run = &inputs.command_runs[run_index as usize];
+ if !run.context.effect.is_none() && !grouping_effects[run.context.effect.0 as usize].is_none() {
+ return Some(MediaLayerRejection::InsideGroupEffect);
+ }
+ if !bounds.world.draw_matrix(run.context.spatial).is_2d_affine() {
+ return Some(MediaLayerRejection::UnderTransformThatIsNot2DAffine);
+ }
+ if bounds.ink_device_rect(run, header.bounding_rect).is_empty() {
+ return Some(MediaLayerRejection::DrawsNothingVisible);
+ }
+ if !run_is_a_chunk_of_its_own(run_index) {
+ return Some(MediaLayerRejection::BetweenRunsOfOneGroupEffect);
+ }
+ None
+}
+
+fn media_candidates(
+ inputs: &LayerPlanInputs<'_>,
+ grouping_effects: &[EffectNodeIndex],
+ bounds: &BoundsContext<'_>,
+ run_is_a_chunk_of_its_own: impl Fn(u32) -> bool,
+) -> Result<Vec<MediaCandidate>, UnlayeredReason> {
+ let mut candidates = Vec::new();
+ let mut first_rejection = None;
+ for live_content_record in &inputs.summary.live_content_records {
+ let content = live_content_record.content;
+ if matches!(content, LiveContent::ImageFrame(_)) || !inputs.active_media.contains(&content) {
+ continue;
+ }
+ let IndexedRecord {
+ run_index,
+ record_offset,
+ } = live_content_record.record;
+ match media_layer_rejection(
+ inputs,
+ grouping_effects,
+ bounds,
+ &run_is_a_chunk_of_its_own,
+ run_index,
+ record_offset,
+ ) {
+ None => candidates.push(MediaCandidate {
+ content,
+ run_index,
+ record_offset,
+ }),
+ Some(rejection) => {
+ first_rejection.get_or_insert(UnlayeredReason::NoMediaCanBeLayer {
+ first_rejected_media: content,
+ rejection,
+ });
+ }
+ }
+ }
+ if candidates.is_empty() {
+ return Err(first_rejection.unwrap_or(UnlayeredReason::ActiveMediaNotDrawn));
+ }
+ Ok(candidates)
+}
+
+fn run_ranges_holding_whole_grouping_effects(
+ command_runs: &[DisplayListCommandRun],
+ grouping_of_run: &[EffectNodeIndex],
+) -> Vec<(u32, u32)> {
+ let mut last_run_of_group = std::collections::HashMap::new();
+ for (run_index, group) in grouping_of_run.iter().enumerate() {
+ if !group.is_none() {
+ last_run_of_group.insert(group.0, run_index);
+ }
+ }
+ let mut ranges = Vec::new();
+ let mut run_index = 0;
+ while run_index < command_runs.len() {
+ let first = run_index;
+ let mut last = run_index;
+ let mut next = run_index;
+ while next <= last {
+ let group = grouping_of_run[next];
+ if !group.is_none() {
+ last = last.max(last_run_of_group[&group.0]);
+ }
+ next += 1;
+ }
+ ranges.push((first as u32, last as u32));
+ run_index = last + 1;
+ }
+ ranges
+}
+
+pub fn build_layer_plan(inputs: &LayerPlanInputs<'_>) -> Result<LayerPlan, UnlayeredReason> {
+ let tree = inputs.tree;
+ let command_runs = inputs.command_runs;
+ if inputs.active_media.is_empty() {
+ return Err(UnlayeredReason::NoActiveMedia);
+ }
+ if inputs.viewport_rect.is_empty() {
+ return Err(UnlayeredReason::EmptyViewport);
+ }
+ if command_runs.is_empty() {
+ return Err(UnlayeredReason::EmptyDisplayList);
+ }
+ if tree_has_sorting_contexts(tree) {
+ return Err(UnlayeredReason::SortingContext3D);
+ }
+ if !root_isolation_effect_is_plain_group(tree) {
+ return Err(UnlayeredReason::RootIsolationEffectIsNotPlainGroup);
+ }
+ if let Some(reason) = what_reads_root_group(inputs) {
+ return Err(reason);
+ }
+ if !mask_declarations_sit_under_their_masks(inputs) {
+ return Err(UnlayeredReason::MaskDeclaredOutsideItsMask);
+ }
+
+ let mut culling = TreeCullingScratch::default();
+ tree.fill_culling_scratch(&mut culling);
+ let world = WorldTransforms::new(tree, inputs.scroll_offsets, Some(FloatMatrix4x4::identity()));
+ let clip_bounds = clip_chain_bounds(tree, &world);
+ let bounds = BoundsContext {
+ world,
+ culling,
+ clip_bounds,
+ viewport_rect: inputs.viewport_rect,
+ tree,
+ };
+
+ let grouping_effects = outermost_grouping_effects(tree);
+ let grouping_of_run: Vec<EffectNodeIndex> = command_runs
+ .iter()
+ .map(|run| {
+ if run.context.effect.is_none() {
+ EffectNodeIndex::NONE
+ } else {
+ grouping_effects[run.context.effect.0 as usize]
+ }
+ })
+ .collect();
+ let chunk_ranges = run_ranges_holding_whole_grouping_effects(command_runs, &grouping_of_run);
+ let mut chunk_of_run = vec![0usize; command_runs.len()];
+ for (chunk_index, &(first, last)) in chunk_ranges.iter().enumerate() {
+ chunk_of_run[first as usize..=last as usize].fill(chunk_index);
+ }
+
+ let mut media = media_candidates(inputs, &grouping_effects, &bounds, |run_index| {
+ let (first, last) = chunk_ranges[chunk_of_run[run_index as usize]];
+ first == last
+ })?;
+ media.truncate(MAXIMUM_MEDIA_LAYER_COUNT);
+
+ let mut effect_geometry = Vec::new();
+ compute_effect_geometry(tree, command_runs, &bounds.world, &mut effect_geometry);
+ let backdrop_filter_on_chain = effects_with_backdrop_filter_on_chain(tree);
+ let mut group_rects: std::collections::HashMap<u32, IntRect> = std::collections::HashMap::new();
+ let mut run_device_rect = |run_index: usize| -> IntRect {
+ let run = &command_runs[run_index];
+ let group = grouping_of_run[run_index];
+ if group.is_none() {
+ return bounds.ink_device_rect(run, run.ink_bounds);
+ }
+ *group_rects.entry(group.0).or_insert_with(|| {
+ bounds.group_device_rect(group, effect_geometry[group.0 as usize].output, inputs.effect_clips)
+ })
+ };
+ let run_has_backdrop_filter = |run: &DisplayListCommandRun| {
+ !run.context.effect.is_none() && backdrop_filter_on_chain[run.context.effect.0 as usize]
+ };
+
+ let mut planned = LayersBeingPlanned::new(inputs.viewport_rect);
+ let mut media_iter = media.iter().peekable();
+ for &(first, last) in &chunk_ranges {
+ let first_run = &command_runs[first as usize];
+ let last_run = &command_runs[last as usize];
+ let mut chunk_bounds = IntRect::default();
+ let mut has_backdrop_filter = false;
+ for (run_index, run) in command_runs
+ .iter()
+ .enumerate()
+ .take(last as usize + 1)
+ .skip(first as usize)
+ {
+ chunk_bounds = chunk_bounds.united(run_device_rect(run_index));
+ has_backdrop_filter |= run_has_backdrop_filter(run);
+ }
+
+ let run_draws_media_layer = media_iter.peek().is_some_and(|candidate| candidate.run_index == first);
+ // The rect of a record under a perspective transform is an estimate, so such a run stays whole.
+ let run_can_be_split_between_layers = first == last
+ && grouping_of_run[first as usize].is_none()
+ && bounds.world.draw_matrix(first_run.context.spatial).is_2d_affine();
+ let places_each_record_of_run = run_draws_media_layer
+ || (run_can_be_split_between_layers && planned.topmost_layer_above_base_touching(chunk_bounds).is_some());
+ if !places_each_record_of_run {
+ let chunk_span = RecordSpan {
+ begin_offset: first_run.offset,
+ end_offset: last_run.offset + last_run.size,
+ };
+ planned.place_painted_records(chunk_span, chunk_bounds, has_backdrop_filter)?;
+ continue;
+ }
+
+ let run = first_run;
+ let records = &inputs.tape[run.offset as usize..(run.offset + run.size) as usize];
+ let mut layer_of_previous_painted_record = LayersBeingPlanned::BASE_LAYER_INDEX;
+ let mut why_unlayered = None;
+ for_each_command(records, |header, offset, payload| {
+ if why_unlayered.is_some() {
+ return;
+ }
+ let begin_offset = run.offset + offset as u32;
+ let span = RecordSpan {
+ begin_offset,
+ end_offset: begin_offset + (HEADER_SIZE + payload.len()) as u32,
+ };
+ if let Some(candidate) = media_iter.next_if(|candidate| candidate.record_offset == begin_offset) {
+ let media_bounds = bounds.ink_device_rect(run, header.bounding_rect);
+ planned.add_media_layer(candidate.content, span, media_bounds);
+ layer_of_previous_painted_record = LayersBeingPlanned::BASE_LAYER_INDEX;
+ } else if !header.has_bounding_rect {
+ planned.append_records_to_layer(layer_of_previous_painted_record, span);
+ } else {
+ let record_bounds = bounds.ink_device_rect(run, header.bounding_rect);
+ match planned.place_painted_records(span, record_bounds, has_backdrop_filter) {
+ Ok(layer_index) => layer_of_previous_painted_record = layer_index,
+ Err(reason) => why_unlayered = Some(reason),
+ }
+ }
+ });
+ if let Some(reason) = why_unlayered {
+ return Err(reason);
+ }
+ }
+ let LayersBeingPlanned {
+ layers,
+ record_ranges_in_tape_order,
+ } = planned;
+
+ let viewport_area = i64::from(inputs.viewport_rect.width) * i64::from(inputs.viewport_rect.height);
+ let upper_painted_area: i64 = layers
+ .iter()
+ .filter(|layer| layer.kind == LayerKind::Painted)
+ .map(|layer| i64::from(layer.rect.width) * i64::from(layer.rect.height))
+ .sum();
+ if upper_painted_area > MAXIMUM_UPPER_PAINTED_LAYER_AREA_IN_VIEWPORTS * viewport_area {
+ return Err(UnlayeredReason::UpperPaintedLayersTooLarge);
+ }
+
+ Ok(LayerPlan {
+ layers,
+ record_ranges_in_tape_order,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::display_list::builder::DisplayListBuilder;
+ use crate::display_list::commands::{
+ CanvasId, CompositorBlockingWheelEventRegion, ContextRef, DisplayListCommand, DrawCanvas, FillRect,
+ SpatialNodeIndex, VISUAL_VIEWPORT_NODE_INDEX,
+ };
+ use crate::display_list::damage::{
+ DisplayListDamage, DisplayListFrame, LayerPlans, LiveContentChanges, compute_display_list_damage,
+ };
+ use crate::display_list::summary::summarize;
+ use crate::node_slot_id::NodeSlotId;
+ use crate::visual_context::{EffectsData, ScrollData, TransformData, TransformDataRole};
+ use libgfx_rust::{Color, CompositingAndBlendingOperator, ScalingMode};
+
+ const VIEWPORT: IntRect = IntRect::new(0, 0, 800, 600);
+ const CANVAS: LiveContent = LiveContent::Canvas(CanvasId(1));
+
+ fn identity_tree() -> VisualContextTree {
+ VisualContextTree::create(TransformData {
+ matrix: FloatMatrix4x4::identity(),
+ origin: FloatPoint::default(),
+ sorting_context_root_index: None,
+ flattens_inherited_transform: false,
+ role: TransformDataRole::CssTransform,
+ synthetic_plane: false,
+ establishes_sorting_context: false,
+ bounds: FloatRect::default(),
+ })
+ }
+
+ fn tree_with_root_isolation_effect() -> VisualContextTree {
+ let mut tree = identity_tree();
+ let root = tree.append_effect(
+ effects(1.0, CompositingAndBlendingOperator::Normal),
+ EffectNodeIndex::NONE,
+ VISUAL_VIEWPORT_NODE_INDEX,
+ ClipNodeIndex::NONE,
+ );
+ tree.root_isolation_effect = Some(root);
+ tree
+ }
+
+ fn effects(opacity: f32, blend_mode: CompositingAndBlendingOperator) -> EffectNodeData {
+ EffectNodeData::Effects(EffectsData {
+ isolation: false,
+ opacity,
+ blend_mode,
+ filter: None,
+ backdrop_filter: None,
+ })
+ }
+
+ fn separate_clip(tree: &mut VisualContextTree, parent: ContextRef) -> ContextRef {
+ let clip = tree.append_clip(
+ ClipNodeData::rect_clip(VIEWPORT.to_float()),
+ parent.clip,
+ parent.spatial,
+ );
+ ContextRef { clip, ..parent }
+ }
+
+ fn fill(rect: IntRect) -> FillRect {
+ FillRect {
+ rect,
+ color: Color::from_rgb(0, 128, 0),
+ compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,
+ background_color_animation_effect: EffectNodeIndex::NONE,
+ }
+ }
+
+ fn canvas(rect: IntRect) -> DrawCanvas {
+ DrawCanvas {
+ dst_rect: rect,
+ canvas_id: CanvasId(1),
+ scaling_mode: ScalingMode::NearestNeighbor,
+ }
+ }
+
+ struct TestList {
+ builder: DisplayListBuilder,
+ }
+
+ impl TestList {
+ fn new() -> Self {
+ Self {
+ builder: DisplayListBuilder::new(),
+ }
+ }
+
+ fn with<C: DisplayListCommand>(mut self, command: C, context: ContextRef) -> Self {
+ self.builder.append(&command, &[], context);
+ self
+ }
+
+ fn plan(&self, tree: &VisualContextTree, scroll_offsets: &[FloatPoint]) -> Result<LayerPlan, UnlayeredReason> {
+ let (tape, runs) = (self.builder.bytes(), self.builder.command_runs());
+ let summary = summarize(tape, runs);
+ let effect_clips = EffectClipPlan::new(tree, runs).unwrap();
+ build_layer_plan(&LayerPlanInputs {
+ tape,
+ command_runs: runs,
+ summary: &summary,
+ effect_clips: &effect_clips,
+ tree,
+ scroll_offsets,
+ viewport_rect: VIEWPORT,
+ active_media: &[CANVAS],
+ })
+ }
+ }
+
+ fn damage_with_layer_plans(
+ tree: &VisualContextTree,
+ (old_list, old_plan, old_scroll_offsets): (&TestList, &LayerPlan, &[FloatPoint]),
+ (new_list, new_plan, new_scroll_offsets): (&TestList, &LayerPlan, &[FloatPoint]),
+ ) -> DisplayListDamage {
+ let old_summary = summarize(old_list.builder.bytes(), old_list.builder.command_runs());
+ let new_summary = summarize(new_list.builder.bytes(), new_list.builder.command_runs());
+ compute_display_list_damage(
+ DisplayListFrame {
+ command_bytes: old_list.builder.bytes(),
+ command_runs: old_list.builder.command_runs(),
+ summary: &old_summary,
+ visual_context_tree: tree,
+ scroll_offsets: old_scroll_offsets,
+ },
+ DisplayListFrame {
+ command_bytes: new_list.builder.bytes(),
+ command_runs: new_list.builder.command_runs(),
+ summary: &new_summary,
+ visual_context_tree: tree,
+ scroll_offsets: new_scroll_offsets,
+ },
+ VIEWPORT,
+ LiveContentChanges::default(),
+ Some(LayerPlans {
+ old: old_plan,
+ new: new_plan,
+ }),
+ )
+ }
+
+ fn kinds(plan: &LayerPlan) -> Vec<&'static str> {
+ plan.layers
+ .iter()
+ .map(|layer| match layer.kind {
+ LayerKind::Base => "base",
+ LayerKind::Painted => "painted",
+ LayerKind::Media { .. } => "media",
+ })
+ .collect()
+ }
+
+ #[test]
+ fn content_over_a_canvas_goes_above_it_and_other_content_stays_in_the_base_layer() {
+ let mut tree = tree_with_root_isolation_effect();
+ let root = ContextRef {
+ effect: tree.root_isolation_effect.unwrap(),
+ ..ContextRef::default()
+ };
+ let elsewhere = separate_clip(&mut tree, root);
+ let list = TestList::new()
+ .with(fill(IntRect::new(0, 0, 800, 600)), root)
+ .with(canvas(IntRect::new(100, 100, 200, 100)), root)
+ .with(fill(IntRect::new(150, 150, 20, 20)), root)
+ .with(fill(IntRect::new(500, 400, 20, 20)), elsewhere);
+ let plan = list.plan(&tree, &[]).unwrap();
+ assert_eq!(kinds(&plan), ["base", "media", "painted"]);
+ assert_eq!(plan.layers[1].rect, IntRect::new(97, 97, 206, 106));
+ assert_eq!(plan.layers[2].rect, IntRect::new(147, 147, 26, 26));
+ let run_end = |run: usize| list.builder.command_runs()[run].offset + list.builder.command_runs()[run].size;
+ let canvas_span = plan.layers[1].record_spans[0];
+ assert_eq!(
+ plan.layers[0].record_spans,
+ [
+ RecordSpan {
+ begin_offset: 0,
+ end_offset: canvas_span.begin_offset,
+ },
+ RecordSpan {
+ begin_offset: run_end(0),
+ end_offset: run_end(1),
+ },
+ ]
+ );
+ assert_eq!(
+ plan.layers[2].record_spans,
+ [RecordSpan {
+ begin_offset: canvas_span.end_offset,
+ end_offset: run_end(0),
+ }]
+ );
+ }
+
+ fn layers_of_records(list: &TestList, plan: &LayerPlan) -> Vec<usize> {
+ let mut layers = Vec::new();
+ for_each_command(list.builder.bytes(), |_, record_offset, _| {
+ layers.push(plan.layer_of_record(record_offset as u32));
+ });
+ layers
+ }
+
+ fn record_offsets(list: &TestList) -> Vec<u32> {
+ let mut offsets = Vec::new();
+ for_each_command(list.builder.bytes(), |_, record_offset, _| {
+ offsets.push(record_offset as u32);
+ });
+ offsets.push(list.builder.bytes().len() as u32);
+ offsets
+ }
+
+ #[test]
+ fn records_in_the_run_of_a_canvas_are_placed_one_by_one() {
+ let tree = identity_tree();
+ let root = ContextRef::default();
+ let list = TestList::new()
+ .with(fill(IntRect::new(0, 0, 800, 600)), root)
+ .with(canvas(IntRect::new(100, 100, 200, 100)), root)
+ .with(fill(IntRect::new(150, 150, 20, 20)), root)
+ .with(fill(IntRect::new(500, 400, 20, 20)), root)
+ .with(fill(IntRect::new(160, 160, 20, 20)), root);
+ assert_eq!(list.builder.command_runs().len(), 1);
+ let plan = list.plan(&tree, &[]).unwrap();
+ assert_eq!(kinds(&plan), ["base", "media", "painted"]);
+ assert_eq!(layers_of_records(&list, &plan), [0, 1, 2, 0, 2]);
+ assert_eq!(plan.layers[2].rect, IntRect::new(147, 147, 36, 36));
+ let offsets = record_offsets(&list);
+ let span = |first_record: usize, record_after_last: usize| RecordSpan {
+ begin_offset: offsets[first_record],
+ end_offset: offsets[record_after_last],
+ };
+ assert_eq!(plan.layers[0].record_spans, [span(0, 1), span(3, 4)]);
+ assert_eq!(plan.layers[1].record_spans, [span(1, 2)]);
+ assert_eq!(plan.layers[2].record_spans, [span(2, 3), span(4, 5)]);
+ }
+
+ #[test]
+ fn records_in_a_run_that_touches_a_canvas_are_placed_one_by_one() {
+ let mut tree = identity_tree();
+ let root = ContextRef::default();
+ let boxes = separate_clip(&mut tree, root);
+ let list = TestList::new()
+ .with(canvas(IntRect::new(100, 100, 200, 100)), root)
+ .with(fill(IntRect::new(500, 400, 20, 20)), boxes)
+ .with(fill(IntRect::new(150, 150, 20, 20)), boxes)
+ .with(fill(IntRect::new(600, 400, 20, 20)), boxes);
+ assert_eq!(list.builder.command_runs().len(), 2);
+ let plan = list.plan(&tree, &[]).unwrap();
+ assert_eq!(layers_of_records(&list, &plan), [1, 0, 2, 0]);
+ }
+
+ #[test]
+ fn a_run_under_a_perspective_transform_is_placed_whole() {
+ let mut tree = identity_tree();
+ let mut perspective_matrix = FloatMatrix4x4::identity();
+ perspective_matrix.elements[3][0] = 0.0001;
+ let under_perspective = tree.append_spatial_under(
+ ContextRef::default(),
+ SpatialData::Transform(TransformData {
+ matrix: perspective_matrix,
+ origin: FloatPoint::default(),
+ sorting_context_root_index: None,
+ flattens_inherited_transform: false,
+ role: TransformDataRole::CssTransform,
+ synthetic_plane: false,
+ establishes_sorting_context: false,
+ bounds: FloatRect::default(),
+ }),
+ );
+ let list = TestList::new()
+ .with(canvas(IntRect::new(100, 100, 200, 100)), ContextRef::default())
+ .with(fill(IntRect::new(150, 150, 20, 20)), under_perspective)
+ .with(fill(IntRect::new(500, 400, 20, 20)), under_perspective);
+ let plan = list.plan(&tree, &[]).unwrap();
+ assert_eq!(layers_of_records(&list, &plan), [1, 2, 2]);
+ }
+
+ #[test]
+ fn compositor_metadata_stays_in_the_layer_of_the_record_before_it() {
+ let tree = identity_tree();
+ let root = ContextRef::default();
+ let metadata = CompositorBlockingWheelEventRegion {
+ rect: FloatRect::new(0.0, 0.0, 900.0, 900.0),
+ };
+ let list = TestList::new()
+ .with(canvas(IntRect::new(100, 100, 200, 100)), root)
+ .with(fill(IntRect::new(150, 150, 20, 20)), root)
+ .with(metadata, root)
+ .with(fill(IntRect::new(160, 160, 20, 20)), root);
+ let plan = list.plan(&tree, &[]).unwrap();
+ assert_eq!(layers_of_records(&list, &plan), [1, 2, 2, 2]);
+ assert_eq!(plan.layers[2].record_spans.len(), 1);
+ }
+
+ #[test]
+ fn a_canvas_under_a_group_effect_is_not_a_layer() {
+ let mut tree = tree_with_root_isolation_effect();
+ let root = ContextRef {
+ effect: tree.root_isolation_effect.unwrap(),
+ ..ContextRef::default()
+ };
+ let group = tree.append_effect_node_under(root, effects(0.5, CompositingAndBlendingOperator::Normal));
+ let list = TestList::new().with(canvas(IntRect::new(100, 100, 200, 100)), group);
+ assert_eq!(
+ list.plan(&tree, &[]),
+ Err(UnlayeredReason::NoMediaCanBeLayer {
+ first_rejected_media: CANVAS,
+ rejection: MediaLayerRejection::InsideGroupEffect,
+ })
+ );
+ }
+
+ #[test]
+ fn a_canvas_between_the_runs_of_one_group_is_not_a_layer() {
+ let mut tree = tree_with_root_isolation_effect();
+ let root = ContextRef {
+ effect: tree.root_isolation_effect.unwrap(),
+ ..ContextRef::default()
+ };
+ let group = tree.append_effect_node_under(root, effects(1.0, CompositingAndBlendingOperator::Normal));
+ let list = TestList::new()
+ .with(fill(IntRect::new(0, 0, 10, 10)), group)
+ .with(canvas(IntRect::new(100, 100, 200, 100)), root)
+ .with(fill(IntRect::new(20, 0, 10, 10)), group);
+ assert_eq!(
+ list.plan(&tree, &[]),
+ Err(UnlayeredReason::NoMediaCanBeLayer {
+ first_rejected_media: CANVAS,
+ rejection: MediaLayerRejection::BetweenRunsOfOneGroupEffect,
+ })
+ );
+ }
+
+ #[test]
+ fn a_blend_mode_reading_the_root_group_leaves_the_list_unlayered() {
+ let mut tree = tree_with_root_isolation_effect();
+ let root = ContextRef {
+ effect: tree.root_isolation_effect.unwrap(),
+ ..ContextRef::default()
+ };
+ let multiply = tree.append_effect_node_under(root, effects(1.0, CompositingAndBlendingOperator::Multiply));
+ let list = TestList::new()
+ .with(canvas(IntRect::new(100, 100, 200, 100)), root)
+ .with(fill(IntRect::new(500, 400, 20, 20)), multiply);
+ assert_eq!(list.plan(&tree, &[]), Err(UnlayeredReason::BlendModeReadsRootGroup));
+ }
+
+ #[test]
+ fn a_canvas_that_does_not_update_is_not_a_layer() {
+ let tree = identity_tree();
+ let list = TestList::new().with(canvas(IntRect::new(100, 100, 200, 100)), ContextRef::default());
+ let (tape, runs) = (list.builder.bytes(), list.builder.command_runs());
+ let summary = summarize(tape, runs);
+ let effect_clips = EffectClipPlan::new(&tree, runs).unwrap();
+ let plan = build_layer_plan(&LayerPlanInputs {
+ tape,
+ command_runs: runs,
+ summary: &summary,
+ effect_clips: &effect_clips,
+ tree: &tree,
+ scroll_offsets: &[],
+ viewport_rect: VIEWPORT,
+ active_media: &[],
+ });
+ assert_eq!(plan, Err(UnlayeredReason::NoActiveMedia));
+ }
+
+ fn list_with_scrolled_box(tree: &mut VisualContextTree) -> (TestList, SpatialNodeIndex) {
+ let scroll_node = tree.append_spatial(
+ SpatialData::Scroll(ScrollData {
+ state_slot: crate::visual_context::scroll_state::NO_SCROLL_STATE_SLOT,
+ owner_paintable: NodeSlotId::INVALID,
+ }),
+ VISUAL_VIEWPORT_NODE_INDEX,
+ );
+ let scrolled = ContextRef {
+ spatial: scroll_node,
+ ..ContextRef::default()
+ };
+ let list = TestList::new()
+ .with(canvas(IntRect::new(100, 100, 200, 100)), ContextRef::default())
+ .with(fill(IntRect::new(500, 120, 20, 20)), scrolled);
+ (list, scroll_node)
+ }
+
+ #[test]
+ fn scrolling_content_over_a_canvas_moves_it_above_the_canvas() {
+ let mut tree = identity_tree();
+ let (list, scroll_node) = list_with_scrolled_box(&mut tree);
+ let mut scroll_offsets = vec![FloatPoint::default(); tree.spatial_nodes.len()];
+ let unscrolled = list.plan(&tree, &scroll_offsets).unwrap();
+ assert_eq!(kinds(&unscrolled), ["base", "media"]);
+ scroll_offsets[scroll_node.0 as usize] = FloatPoint { x: -300.0, y: 0.0 };
+ let scrolled = list.plan(&tree, &scroll_offsets).unwrap();
+ assert_eq!(kinds(&scrolled), ["base", "media", "painted"]);
+ assert!(!scrolled.has_same_layers_as(&unscrolled));
+ }
+
+ #[test]
+ fn content_scrolled_within_its_layer_damages_only_that_layer() {
+ let mut tree = identity_tree();
+ let (list, scroll_node) = list_with_scrolled_box(&mut tree);
+ let unscrolled_offsets = vec![FloatPoint::default(); tree.spatial_nodes.len()];
+ let mut scrolled_offsets = unscrolled_offsets.clone();
+ scrolled_offsets[scroll_node.0 as usize] = FloatPoint { x: 0.0, y: 50.0 };
+ let before = list.plan(&tree, &unscrolled_offsets).unwrap();
+ let after = list.plan(&tree, &scrolled_offsets).unwrap();
+ assert!(after.has_same_layers_as(&before));
+ let damage = damage_with_layer_plans(
+ &tree,
+ (&list, &before, &unscrolled_offsets),
+ (&list, &after, &scrolled_offsets),
+ );
+ assert_eq!(damage.layer_rects, [damage.rect, Some(IntRect::default())]);
+ }
+
+ struct ContextsAroundACanvas {
+ under_box: ContextRef,
+ canvas: ContextRef,
+ boxes_after_canvas: Vec<ContextRef>,
+ }
+
+ // Each box gets a clip of its own, so that it is a run of its own.
+ fn contexts_around_a_canvas(tree: &mut VisualContextTree, box_count_after_canvas: usize) -> ContextsAroundACanvas {
+ let root = ContextRef {
+ effect: tree.root_isolation_effect.unwrap(),
+ ..ContextRef::default()
+ };
+ ContextsAroundACanvas {
+ under_box: separate_clip(tree, root),
+ canvas: root,
+ boxes_after_canvas: (0..box_count_after_canvas).map(|_| separate_clip(tree, root)).collect(),
+ }
+ }
+
+ fn list_around_a_canvas(
+ contexts: &ContextsAroundACanvas,
+ (under, under_color): (IntRect, Color),
+ boxes_after_canvas: &[IntRect],
+ ) -> TestList {
+ let mut list = TestList::new()
+ .with(
+ FillRect {
+ color: under_color,
+ ..fill(under)
+ },
+ contexts.under_box,
+ )
+ .with(canvas(IntRect::new(100, 100, 200, 100)), contexts.canvas);
+ for (rect, context) in boxes_after_canvas.iter().zip(&contexts.boxes_after_canvas) {
+ list = list.with(fill(*rect), *context);
+ }
+ list
+ }
+
+ #[test]
+ fn content_that_changes_under_a_canvas_damages_only_the_base_layer() {
+ let mut tree = tree_with_root_isolation_effect();
+ let contexts = contexts_around_a_canvas(&mut tree, 2);
+ let list_with_under_color = |color| {
+ list_around_a_canvas(
+ &contexts,
+ (IntRect::new(50, 50, 400, 300), color),
+ &[IntRect::new(150, 150, 20, 20), IntRect::new(600, 500, 20, 20)],
+ )
+ };
+ let old_list = list_with_under_color(Color::from_rgb(255, 0, 0));
+ let new_list = list_with_under_color(Color::from_rgb(0, 0, 255));
+ let old_plan = old_list.plan(&tree, &[]).unwrap();
+ let new_plan = new_list.plan(&tree, &[]).unwrap();
+ assert_eq!(kinds(&new_plan), ["base", "media", "painted"]);
+ let damage = damage_with_layer_plans(&tree, (&old_list, &old_plan, &[]), (&new_list, &new_plan, &[]));
+ let under_rect = Some(IntRect::new(49, 49, 402, 302));
+ assert_eq!(damage.rect, under_rect);
+ assert_eq!(
+ damage.layer_rects,
+ [under_rect, Some(IntRect::default()), Some(IntRect::default())]
+ );
+ }
+
+ const SMALL_RED_BOX: (IntRect, Color) = (IntRect::new(0, 0, 10, 10), Color::from_rgb(255, 0, 0));
+
+ #[test]
+ fn a_box_that_moves_off_a_canvas_damages_the_layer_it_leaves_and_the_one_it_enters() {
+ let mut tree = tree_with_root_isolation_effect();
+ let contexts = contexts_around_a_canvas(&mut tree, 2);
+ let list_with_second_box_at =
+ |second| list_around_a_canvas(&contexts, SMALL_RED_BOX, &[IntRect::new(150, 150, 20, 20), second]);
+ let old_list = list_with_second_box_at(IntRect::new(160, 160, 20, 20));
+ let new_list = list_with_second_box_at(IntRect::new(600, 500, 20, 20));
+ let old_plan = old_list.plan(&tree, &[]).unwrap();
+ let new_plan = new_list.plan(&tree, &[]).unwrap();
+ assert_eq!(kinds(&old_plan), ["base", "media", "painted"]);
+ assert!(new_plan.has_same_layers_as(&old_plan));
+ let damage = damage_with_layer_plans(&tree, (&old_list, &old_plan, &[]), (&new_list, &new_plan, &[]));
+ assert_eq!(
+ damage.layer_rects,
+ [
+ Some(IntRect::new(599, 499, 22, 22)),
+ Some(IntRect::default()),
+ Some(IntRect::new(159, 159, 22, 22)),
+ ]
+ );
+ }
+
+ // The first box grows over an unchanged box, which the layer above the canvas then takes in. With `last_box`, a
+ // box after the unchanged one changes too, so that the diff compares the unchanged box command by command.
+ fn assert_unchanged_box_taken_in_by_a_growing_layer_damages_both_layers(last_box: Option<(IntRect, IntRect)>) {
+ let mut tree = tree_with_root_isolation_effect();
+ let contexts = contexts_around_a_canvas(&mut tree, 3);
+ let unchanged_box = IntRect::new(400, 150, 20, 20);
+ let list_with = |first_box, last_box: Option<IntRect>| {
+ let mut boxes = vec![first_box, unchanged_box];
+ boxes.extend(last_box);
+ list_around_a_canvas(&contexts, SMALL_RED_BOX, &boxes)
+ };
+ let old_list = list_with(IntRect::new(150, 150, 20, 20), last_box.map(|(old, _)| old));
+ let new_list = list_with(IntRect::new(150, 150, 300, 20), last_box.map(|(_, new)| new));
+ let old_plan = old_list.plan(&tree, &[]).unwrap();
+ let new_plan = new_list.plan(&tree, &[]).unwrap();
+ let unchanged_box_record = new_list.builder.command_runs()[3].offset;
+ assert_eq!(old_plan.layer_of_record(unchanged_box_record), 0);
+ assert_eq!(new_plan.layer_of_record(unchanged_box_record), 2);
+ let damage = damage_with_layer_plans(&tree, (&old_list, &old_plan, &[]), (&new_list, &new_plan, &[]));
+ assert!(damage.layer_rects[0].unwrap().contains_rect(unchanged_box));
+ assert!(damage.layer_rects[2].unwrap().contains_rect(unchanged_box));
+ }
+
+ #[test]
+ fn an_unchanged_box_that_a_growing_layer_takes_in_damages_the_layer_it_leaves() {
+ assert_unchanged_box_taken_in_by_a_growing_layer_damages_both_layers(None);
+ }
+
+ #[test]
+ fn an_unchanged_box_between_changed_boxes_that_a_growing_layer_takes_in_damages_the_layer_it_leaves() {
+ assert_unchanged_box_taken_in_by_a_growing_layer_damages_both_layers(Some((
+ IntRect::new(600, 500, 20, 20),
+ IntRect::new(620, 500, 20, 20),
+ )));
+ }
+
+ #[test]
+ fn an_unchanged_run_that_a_growing_layer_splits_differently_damages_the_layers_its_record_moves_between() {
+ let mut tree = identity_tree();
+ let root = ContextRef::default();
+ let growing_box = separate_clip(&mut tree, root);
+ let unchanged_box = IntRect::new(400, 150, 20, 20);
+ let list_with_growing_box = |growing_box_rect| {
+ TestList::new()
+ .with(canvas(IntRect::new(100, 100, 200, 100)), root)
+ .with(fill(growing_box_rect), growing_box)
+ .with(fill(unchanged_box), root)
+ .with(fill(IntRect::new(160, 160, 20, 20)), root)
+ };
+ let old_list = list_with_growing_box(IntRect::new(150, 150, 20, 20));
+ let new_list = list_with_growing_box(IntRect::new(150, 150, 300, 20));
+ let old_plan = old_list.plan(&tree, &[]).unwrap();
+ let new_plan = new_list.plan(&tree, &[]).unwrap();
+ assert_eq!(layers_of_records(&old_list, &old_plan), [1, 2, 0, 2]);
+ assert_eq!(layers_of_records(&new_list, &new_plan), [1, 2, 2, 2]);
+ assert!(new_plan.has_same_layers_as(&old_plan));
+ let damage = damage_with_layer_plans(&tree, (&old_list, &old_plan, &[]), (&new_list, &new_plan, &[]));
+ assert!(damage.layer_rects[0].unwrap().contains_rect(unchanged_box));
+ assert!(damage.layer_rects[2].unwrap().contains_rect(unchanged_box));
+ }
+}
diff --git a/Libraries/LibCompositing/Rust/src/display_list/mod.rs b/Libraries/LibCompositing/Rust/src/display_list/mod.rs
index fcce5a1f54d..6ba25d92b00 100644
--- a/Libraries/LibCompositing/Rust/src/display_list/mod.rs
+++ b/Libraries/LibCompositing/Rust/src/display_list/mod.rs
@@ -14,6 +14,7 @@ pub mod device_pixels;
pub mod effect_clip_plan;
pub mod effect_geometry;
pub mod ffi_bytes;
+pub mod layers;
pub mod nested_records;
pub mod replay;
pub mod storage;
diff --git a/Libraries/LibCompositing/Rust/src/display_list/summary.rs b/Libraries/LibCompositing/Rust/src/display_list/summary.rs
index a10cdf6b9fa..1120be270a7 100644
--- a/Libraries/LibCompositing/Rust/src/display_list/summary.rs
+++ b/Libraries/LibCompositing/Rust/src/display_list/summary.rs
@@ -46,6 +46,8 @@ pub struct DisplayListSummary {
pub canvas_ids: Vec<u64>,
pub carets: Vec<IndexedRecord>,
pub live_content_records: Vec<LiveContentRecord>,
+ pub destination_blending_records: Vec<IndexedRecord>,
+ pub mask_declarations: Vec<IndexedRecord>,
}
#[derive(Default)]
@@ -190,8 +192,16 @@ pub fn summarize(tape: &[u8], command_runs: &[DisplayListCommandRun]) -> Display
run_index: run_index as u32,
record_offset: (run_start + offset) as u32,
};
- if header.command_type == DisplayListCommandType::PaintCaret {
- summary.carets.push(indexed);
+ match header.command_type {
+ DisplayListCommandType::PaintCaret => summary.carets.push(indexed),
+ DisplayListCommandType::DeclareMaskContent => summary.mask_declarations.push(indexed),
+ _ => {}
+ }
+ if let Some((blend, blends_with_isolated_backdrop_color)) = command_blend(header.command_type, payload)
+ && blend != CompositingAndBlendingOperator::Normal
+ && !blends_with_isolated_backdrop_color
+ {
+ summary.destination_blending_records.push(indexed);
}
note_referenced_ids(header.command_type, payload, &mut ids);
let mut note_live_content = |command_type, payload: &[u8]| {
diff --git a/Libraries/LibCompositing/Rust/src/visual_context/queries.rs b/Libraries/LibCompositing/Rust/src/visual_context/queries.rs
index cbc12232846..8ae40b1d7bd 100644
--- a/Libraries/LibCompositing/Rust/src/visual_context/queries.rs
+++ b/Libraries/LibCompositing/Rust/src/visual_context/queries.rs
@@ -470,6 +470,45 @@ impl VisualContextTree {
false
}
+ pub fn nearest_layer_at_or_above(&self, mut effect: EffectNodeIndex) -> Option<EffectNodeIndex> {
+ while !effect.is_none() {
+ if self.effect_pushes_layer_at_replay(effect) {
+ return Some(effect);
+ }
+ effect = self.effect_nodes[effect.0 as usize].parent;
+ }
+ None
+ }
+
+ pub fn content_under_effect_composites_into_root_group(&self, effect: EffectNodeIndex) -> bool {
+ self.nearest_layer_at_or_above(effect)
+ .is_none_or(|layer| self.root_isolation_effect == Some(layer))
+ }
+
+ // The backdrop of an effect whose box's masks draw it is read where the outermost of those masks composites.
+ pub fn first_effect_reading_root_group(&self) -> Option<EffectNodeIndex> {
+ let reading_effect = self.effect_nodes.iter().enumerate().position(|(index, node)| {
+ let EffectNodeData::Effects(effects) = &node.data else {
+ return false;
+ };
+ if effects.blend_mode == CompositingAndBlendingOperator::Normal && effects.backdrop_filter.is_none() {
+ return false;
+ }
+ let mut reader = EffectNodeIndex(index as u32);
+ loop {
+ let parent = self.effect_nodes[reader.0 as usize].parent;
+ if parent.is_none()
+ || !matches!(&self.effect_nodes[parent.0 as usize].data, EffectNodeData::Mask(mask) if mask.masks_backdrop)
+ {
+ break;
+ }
+ reader = parent;
+ }
+ self.content_under_effect_composites_into_root_group(self.effect_nodes[reader.0 as usize].parent)
+ })?;
+ Some(EffectNodeIndex(reading_effect as u32))
+ }
+
// A blend mode or a backdrop filter reads what the canvas holds outside the effect's own layer.
pub fn has_unisolated_destination_reading_effect(&self) -> bool {
self.effect_nodes.iter().any(|node| {
diff --git a/Services/Compositor/Rust/src/frame_inputs.rs b/Services/Compositor/Rust/src/frame_inputs.rs
index 2efcbb20017..2638cabd3d1 100644
--- a/Services/Compositor/Rust/src/frame_inputs.rs
+++ b/Services/Compositor/Rust/src/frame_inputs.rs
@@ -126,7 +126,9 @@ impl FrameInputs {
self.frame_of(display_list),
viewport_rect,
live_content_changes,
+ None,
)
+ .rect
}
fn frame_of<'a>(&'a self, display_list: &'a DisplayListStorage) -> DisplayListFrame<'a> {