use std::{ops::Range, sync::Arc};
use cranpose_core::NodeId;
#[cfg(test)]
use cranpose_render_common::geometry::{expand_blurred_rect, union_rect};
#[cfg(test)]
use cranpose_render_common::primitive_emit::resolve_clip;
use cranpose_render_common::{
Brush,
graph::TextPrimitiveNode,
layer_shadow::{ShadowLight, layer_shadow_geometry},
layer_transform::{apply_layer_to_rect, layer_uniform_scale},
primitive_emit::{
DrawPrimitiveSink, ImageDrawParams, ShapeDrawParams, TextDrawParams, emit_draw_primitive,
},
};
#[cfg(test)]
use cranpose_ui::TextOverflow;
#[cfg(test)]
use cranpose_ui::measure_text;
#[cfg(test)]
use cranpose_ui::prepare_text_layout;
use cranpose_ui::text::{AnnotatedString, TextDrawStyle, TextStyle, shared_plain_render_string};
use cranpose_ui_graphics::{
BlendMode, Color, DrawPrimitive, GraphicsLayer, LayerShape, Point, Recorded, Rect,
RenderEffect, RoundedCornerShape, RuntimeShader, ShapeRecorder, TileMode,
};
use crate::scene::{
ClipRounding, CompositorScene, ContentContext, DrawnText, EffectLayer, ImageDraw, Placement,
RRectShadowDraw, RunDraw, ShadowDraw, SnapAnchor, TextDraw,
};
mod style;
mod text_effect;
use cranpose_render_common::{
style_shared::resolve_layer_brush,
text_decoration::{visit_text_backgrounds, visit_text_lines},
text_paint::{
resolve_text_color_without_gradient_fallback, spans_override_foreground,
spans_override_foreground_color,
},
};
use style::{apply_layer_to_brush, apply_layer_to_color, scale_corner_radii};
use text_effect::{mask_style, push_text_effect};
const GPU_TEXT_BRUSH_EFFECT_MAX_STOPS: usize = 16;
const GPU_TEXT_BRUSH_EFFECT_FIRST_STOP_SLOT: usize = 8;
pub(crate) const GPU_TEXT_BRUSH_EFFECT_SHADER: &str =
cranpose_ui_graphics::framework_shaders::GPU_TEXT_BRUSH_EFFECT_WGSL;
pub(crate) fn layer_casts_shadow(layer: &GraphicsLayer) -> bool {
layer.shadow_elevation > 0.0
}
pub(crate) fn push_layer_shadow(
scene: &mut CompositorScene,
layer: &GraphicsLayer,
layer_bounds: Rect,
transformed_bounds: Rect,
clip: Option<Rect>,
light: ShadowLight,
) {
if !layer_casts_shadow(layer) {
return;
}
let caster = match layer.shape {
LayerShape::Rectangle => None,
LayerShape::Rounded(shape) => {
let scale = layer_uniform_scale(layer).max(0.1);
let resolved = shape.resolve(layer_bounds.width, layer_bounds.height);
Some(RoundedCornerShape::with_radii(scale_corner_radii(
resolved, scale,
)))
}
};
for (shadow, color) in layer_shadow_geometry(layer, transformed_bounds, caster, light).passes()
{
scene.push_rrect_shadow(RRectShadowDraw {
shadow,
color,
clip,
snap_anchor: None,
});
}
}
fn tile_mode_to_shader_uniform(tile_mode: TileMode) -> f32 {
match tile_mode {
TileMode::Clamp => 0.0,
TileMode::Repeated => 1.0,
TileMode::Mirror => 2.0,
TileMode::Decal => 3.0,
}
}
fn normalized_gradient_stops(color_count: usize, stops: Option<&[f32]>) -> Vec<f32> {
if let Some(explicit) = stops.filter(|values| values.len() == color_count) {
return explicit.to_vec();
}
if color_count <= 1 {
return vec![0.0; color_count];
}
(0..color_count)
.map(|index| index as f32 / (color_count - 1) as f32)
.collect()
}
fn set_shader_vec4(shader: &mut RuntimeShader, slot: usize, values: [f32; 4]) {
shader.set_float4(slot * 4, values[0], values[1], values[2], values[3]);
}
fn resolve_gradient_component(extent: f32, value: f32) -> f32 {
if value.is_finite() {
value
} else if value.is_sign_positive() {
extent.max(0.0)
} else {
0.0
}
}
const GPU_TEXT_BRUSH_KIND_LINEAR: f32 = 0.0;
const GPU_TEXT_BRUSH_KIND_RADIAL: f32 = 1.0;
const GPU_TEXT_BRUSH_KIND_SWEEP: f32 = 2.0;
const GPU_TEXT_BRUSH_KIND_SOLID: f32 = 3.0;
const GPU_TEXT_BRUSH_EFFECT_MATERIAL_SLOT: usize = 5;
const GPU_TEXT_DRAW_MODE_FILL: f32 = 0.0;
const GPU_TEXT_DRAW_MODE_STROKE: f32 = 1.0;
const GPU_TEXT_STROKE_EFFECT_EDGE_PAD: f32 = 1.0;
#[derive(Clone, PartialEq)]
enum GpuTextDrawMode {
Fill,
Stroke { width: f32 },
}
#[derive(Clone, PartialEq)]
struct GpuTextMaterial {
brush: Brush,
alpha_multiplier: f32,
draw_mode: GpuTextDrawMode,
}
#[derive(Clone)]
struct GpuTextMaterialBatch {
material: GpuTextMaterial,
visible_ranges: Vec<Range<usize>>,
}
fn stroke_effect_padding_local(stroke_width_local: f32) -> f32 {
if !stroke_width_local.is_finite() || stroke_width_local <= 0.0 {
return 0.0;
}
stroke_width_local * 0.5 + GPU_TEXT_STROKE_EFFECT_EDGE_PAD
}
fn stroke_effect_padding_for_draw_mode(draw_mode: &GpuTextDrawMode) -> f32 {
match draw_mode {
GpuTextDrawMode::Fill => 0.0,
GpuTextDrawMode::Stroke { width } => stroke_effect_padding_local(*width),
}
}
fn expand_text_effect_rect(text_rect: Rect, stroke_padding: f32) -> Rect {
let padding = stroke_padding.max(0.0);
if padding <= 0.0 {
return text_rect;
}
Rect {
x: text_rect.x - padding,
y: text_rect.y - padding,
width: (text_rect.width + padding * 2.0).max(0.0),
height: (text_rect.height + padding * 2.0).max(0.0),
}
}
fn gpu_text_material_for_style(
text_style: &TextStyle,
fallback_color: Color,
text_scale: f32,
) -> GpuTextMaterial {
let scale = if text_scale.is_finite() && text_scale > 0.0 {
text_scale
} else {
1.0
};
let draw_mode = match text_style.span_style.draw_style {
Some(TextDrawStyle::Stroke { width }) if width.is_finite() && width > 0.0 => {
GpuTextDrawMode::Stroke {
width: width * scale,
}
}
_ => GpuTextDrawMode::Fill,
};
let brush = text_style
.span_style
.brush
.clone()
.or_else(|| text_style.span_style.color.map(Brush::solid))
.unwrap_or_else(|| Brush::solid(fallback_color));
let alpha_multiplier = text_style.span_style.alpha.unwrap_or(1.0);
GpuTextMaterial {
brush,
alpha_multiplier,
draw_mode,
}
}
fn build_gpu_text_effect(
material: &GpuTextMaterial,
text_rect: Rect,
) -> Option<(RenderEffect, Rect)> {
if !text_rect.width.is_finite()
|| !text_rect.height.is_finite()
|| text_rect.width <= 0.0
|| text_rect.height <= 0.0
{
return None;
}
let stroke_padding = stroke_effect_padding_for_draw_mode(&material.draw_mode);
let effect_rect = expand_text_effect_rect(text_rect, stroke_padding);
let mut shader = RuntimeShader::new(GPU_TEXT_BRUSH_EFFECT_SHADER);
shader.set_position_independent(true);
shader.set_input_padding(stroke_padding);
let logical_width = text_rect.width.max(f32::EPSILON);
let logical_height = text_rect.height.max(f32::EPSILON);
set_shader_vec4(&mut shader, 1, [logical_width, logical_height, 0.0, 0.0]);
let (draw_mode, stroke_width) = match material.draw_mode {
GpuTextDrawMode::Fill => (GPU_TEXT_DRAW_MODE_FILL, 0.0),
GpuTextDrawMode::Stroke { width } => (GPU_TEXT_DRAW_MODE_STROKE, width.max(0.0)),
};
set_shader_vec4(
&mut shader,
GPU_TEXT_BRUSH_EFFECT_MATERIAL_SLOT,
[draw_mode, stroke_width, stroke_padding, 0.0],
);
let alpha = if material.alpha_multiplier.is_finite() {
material.alpha_multiplier.clamp(0.0, 1.0)
} else {
1.0
};
let (brush_type, colors, stops, tile_mode) = match &material.brush {
Brush::LinearGradient {
colors,
stops,
start,
end,
tile_mode,
} => {
let resolved_start_x = resolve_gradient_component(logical_width, start.x);
let resolved_start_y = resolve_gradient_component(logical_height, start.y);
let resolved_end_x = resolve_gradient_component(logical_width, end.x);
let resolved_end_y = resolve_gradient_component(logical_height, end.y);
set_shader_vec4(
&mut shader,
2,
[
resolved_start_x,
resolved_start_y,
resolved_end_x,
resolved_end_y,
],
);
(
GPU_TEXT_BRUSH_KIND_LINEAR,
colors,
stops.as_deref(),
*tile_mode,
)
}
Brush::RadialGradient {
colors,
stops,
center,
radius,
tile_mode,
} => {
set_shader_vec4(&mut shader, 3, [center.x, center.y, *radius, 0.0]);
(
GPU_TEXT_BRUSH_KIND_RADIAL,
colors,
stops.as_deref(),
*tile_mode,
)
}
Brush::SweepGradient {
colors,
stops,
center,
} => {
set_shader_vec4(&mut shader, 4, [center.x, center.y, 0.0, 0.0]);
(
GPU_TEXT_BRUSH_KIND_SWEEP,
colors,
stops.as_deref(),
TileMode::Clamp,
)
}
Brush::Solid(color) => {
set_shader_vec4(
&mut shader,
GPU_TEXT_BRUSH_EFFECT_FIRST_STOP_SLOT,
[color.r(), color.g(), color.b(), color.a()],
);
shader.set_float((GPU_TEXT_BRUSH_EFFECT_FIRST_STOP_SLOT + 1) * 4, 0.0);
set_shader_vec4(
&mut shader,
0,
[
GPU_TEXT_BRUSH_KIND_SOLID,
1.0,
tile_mode_to_shader_uniform(TileMode::Clamp),
alpha,
],
);
return Some((RenderEffect::runtime_shader(shader), effect_rect));
}
};
let stop_count = colors.len();
if stop_count == 0 || stop_count > GPU_TEXT_BRUSH_EFFECT_MAX_STOPS {
return None;
}
set_shader_vec4(
&mut shader,
0,
[
brush_type,
stop_count as f32,
tile_mode_to_shader_uniform(tile_mode),
alpha,
],
);
let resolved_stops = normalized_gradient_stops(stop_count, stops);
for (index, color) in colors.iter().enumerate() {
let color_slot = GPU_TEXT_BRUSH_EFFECT_FIRST_STOP_SLOT + index * 2;
set_shader_vec4(
&mut shader,
color_slot,
[color.r(), color.g(), color.b(), color.a()],
);
shader.set_float((color_slot + 1) * 4, resolved_stops[index]);
}
Some((RenderEffect::runtime_shader(shader), effect_rect))
}
fn gpu_text_effect_for_style(
text_style: &TextStyle,
text_rect: Rect,
fallback_color: Color,
text_scale: f32,
) -> Option<(RenderEffect, Rect)> {
let uses_non_solid_brush = matches!(
text_style.span_style.brush,
Some(
Brush::LinearGradient { .. }
| Brush::RadialGradient { .. }
| Brush::SweepGradient { .. }
)
);
let uses_stroke = matches!(
text_style.span_style.draw_style,
Some(TextDrawStyle::Stroke { width }) if width.is_finite() && width > 0.0
);
if !uses_non_solid_brush && !uses_stroke {
return None;
}
let material = gpu_text_material_for_style(text_style, fallback_color, text_scale);
build_gpu_text_effect(&material, text_rect)
}
fn text_for_gpu_mask(text: impl Into<AnnotatedString>) -> AnnotatedString {
let text = text.into();
if text.span_styles().is_empty() {
return text;
}
text.map_span_styles(|span| {
span.color = None;
span.brush = None;
span.alpha = None;
span.draw_style = None;
span.shadow = None;
})
}
fn text_with_layer_transformed_span_paint(
text: &AnnotatedString,
content_layer: &GraphicsLayer,
) -> AnnotatedString {
if text.span_styles().is_empty() {
return text.clone();
}
text.map_span_styles(|span| {
span.color = span
.color
.map(|color| apply_layer_to_color(color, content_layer));
span.brush = span
.brush
.take()
.map(|brush| apply_layer_to_brush(brush, content_layer));
})
}
fn merged_span_style_for_range(
text: &AnnotatedString,
base_span_style: &cranpose_ui::text::SpanStyle,
start: usize,
end: usize,
) -> cranpose_ui::text::SpanStyle {
let mut merged_style = base_span_style.clone();
for span in text.span_styles() {
if span.range.start <= start && span.range.end >= end {
merged_style = merged_style.merge(&span.item);
}
}
merged_style
}
fn gpu_text_material_batches_for_text(
text: &AnnotatedString,
text_style: &TextStyle,
fallback_color: Color,
text_scale: f32,
) -> Vec<GpuTextMaterialBatch> {
let mut batches: Vec<GpuTextMaterialBatch> = Vec::new();
for window in text.span_boundaries().windows(2) {
let start = window[0];
let end = window[1];
if start == end {
continue;
}
let Some(range_text) = text.text().get(start..end) else {
continue;
};
if !range_text.chars().any(|ch| ch != '\n' && ch != '\r') {
continue;
}
let mut range_style = text_style.clone();
range_style.span_style =
merged_span_style_for_range(text, &text_style.span_style, start, end);
let material = gpu_text_material_for_style(&range_style, fallback_color, text_scale);
if let Some(last_batch) = batches.last_mut()
&& last_batch.material == material
{
if let Some(last_range) = last_batch.visible_ranges.last_mut() {
if last_range.end == start {
last_range.end = end;
} else {
last_batch.visible_ranges.push(start..end);
}
} else {
last_batch.visible_ranges.push(start..end);
}
continue;
}
batches.push(GpuTextMaterialBatch {
material,
visible_ranges: std::iter::once(start..end).collect(),
});
}
batches
}
fn text_for_gpu_mask_batch(
text: &AnnotatedString,
visible_ranges: &[Range<usize>],
) -> AnnotatedString {
let visible_style = cranpose_ui::text::SpanStyle {
color: Some(Color::WHITE),
..Default::default()
};
visible_ranges
.iter()
.filter(|range| range.start < range.end)
.fold(
AnnotatedString::builder().append_annotated(&text_for_gpu_mask(text.clone())),
|builder, range| builder.add_style(visible_style.clone(), range.clone()),
)
.to_annotated_string()
}
trait TextStyleDrawSink {
fn current_z(&mut self) -> usize;
fn push_shape(
&mut self,
primitive: DrawPrimitive,
clip: Option<Rect>,
anchor: Option<SnapAnchor>,
);
fn push_text(&mut self, draw: TextDraw);
fn push_shadow_text(&mut self, draw: TextDraw, blur_radius: f32);
fn push_effect_layer(&mut self, layer: EffectLayer);
}
impl TextStyleDrawSink for CompositorScene {
fn current_z(&mut self) -> usize {
self.next_z()
}
fn push_shape(
&mut self,
primitive: DrawPrimitive,
clip: Option<Rect>,
anchor: Option<SnapAnchor>,
) {
self.push_loose(primitive, Placement::at(Point::default(), anchor, clip));
}
fn push_text(&mut self, draw: TextDraw) {
Self::push_text(self, draw);
}
fn push_shadow_text(&mut self, draw: TextDraw, blur_radius: f32) {
let clip = draw.clip;
self.push_shadow_draw(ShadowDraw {
shapes: None,
post_blur_cutouts: None,
texts: vec![draw],
blur_radius,
clip,
rounded_clip: None,
z_index: 0,
});
}
fn push_effect_layer(&mut self, layer: EffectLayer) {
Self::push_effect_layer(self, layer);
}
}
#[cfg(test)]
#[derive(Default)]
struct TextBoundsCollector {
bounds: Option<Rect>,
next_z: usize,
}
#[cfg(test)]
impl TextStyleDrawSink for TextBoundsCollector {
fn current_z(&mut self) -> usize {
self.next_z
}
fn push_shape(
&mut self,
primitive: DrawPrimitive,
_clip: Option<Rect>,
_anchor: Option<SnapAnchor>,
) {
let (DrawPrimitive::Rect { rect, .. } | DrawPrimitive::RoundRect { rect, .. }) = primitive
else {
unreachable!("text decorations are rects");
};
self.bounds = union_rect(self.bounds, rect);
self.next_z += 1;
}
fn push_text(&mut self, draw: TextDraw) {
self.bounds = union_rect(self.bounds, draw.rect);
self.next_z += 1;
}
fn push_shadow_text(&mut self, draw: TextDraw, blur_radius: f32) {
let shadow_bounds = expand_blurred_rect(draw.rect, blur_radius, draw.scale, draw.clip);
if let Some(shadow_bounds) = shadow_bounds {
self.bounds = union_rect(self.bounds, shadow_bounds);
}
self.next_z += 1;
}
fn push_effect_layer(&mut self, layer: EffectLayer) {
self.bounds = union_rect(self.bounds, layer.rect);
}
}
fn push_span_gpu_text_material_draws<S: TextStyleDrawSink>(
sink: &mut S,
node: &TextPrimitiveNode,
placement: &TextPlacement<'_>,
text_rect: Rect,
transformed_text_style: &TextStyle,
fallback_color: Color,
) -> bool {
let text = &AnnotatedString::from(Arc::clone(&node.render_text));
let text_scale = layer_uniform_scale(placement.layer);
let transformed_span_text = text_with_layer_transformed_span_paint(text, placement.layer);
let material_batches = gpu_text_material_batches_for_text(
&transformed_span_text,
transformed_text_style,
fallback_color,
text_scale,
);
if material_batches.is_empty() {
return false;
}
let mut batch_effects = Vec::with_capacity(material_batches.len());
for batch in material_batches {
let Some((effect, effect_rect)) = build_gpu_text_effect(&batch.material, text_rect) else {
return false;
};
batch_effects.push((batch.visible_ranges, effect, effect_rect));
}
let mask = mask_style(transformed_text_style, Color(1.0, 1.0, 1.0, 0.0));
for (visible_ranges, effect, effect_rect) in batch_effects {
let mask_text = text_for_gpu_mask_batch(text, &visible_ranges);
push_text_effect(
sink,
node,
(text_rect, text_scale, placement.clip),
(&mask_text, Arc::clone(&mask.0), mask.1),
(effect, effect_rect),
);
}
true
}
fn emit_text_style_draws<S: TextStyleDrawSink>(
sink: &mut S,
node: &TextPrimitiveNode,
placement: TextPlacement<'_>,
) {
let TextPlacement {
bounds: rect,
text_rect,
layer: content_layer,
clip: text_clip,
snap_anchor,
} = placement;
let TextPrimitiveNode {
node_id,
render_text,
layout,
text_style,
font_size,
..
} = node;
let (node_id, font_size) = (*node_id, *font_size);
let text_scale = layer_uniform_scale(content_layer);
let transformed_text_rect = apply_layer_to_rect(text_rect, rect, content_layer);
let filled = |part: Rect, brush: &Brush| DrawPrimitive::Rect {
rect: apply_layer_to_rect(
part.translate(text_rect.x, text_rect.y),
rect,
content_layer,
),
brush: apply_layer_to_brush(brush.clone(), content_layer),
stroke: None,
};
let styled: cranpose_render_common::text_glyphs::StyledTextRef<'_> =
render_text.as_ref().into();
visit_text_backgrounds(layout, styled, text_style, |part, brush| {
sink.push_shape(filled(part, brush), text_clip, snap_anchor);
});
let text_color =
resolve_text_color_without_gradient_fallback(text_style, Color(1.0, 1.0, 1.0, 1.0));
let transformed_text_color = apply_layer_to_color(text_color, content_layer);
let transformed_text_style =
if text_style.span_style.shadow.is_none() && text_style.span_style.brush.is_none() {
Arc::clone(text_style)
} else {
let mut transformed = TextStyle::clone(text_style);
transformed.span_style.shadow = None;
transformed.span_style.brush = text_style
.span_style
.brush
.clone()
.map(|brush| apply_layer_to_brush(brush, content_layer));
Arc::new(transformed)
};
if let Some(shadow) = text_style.span_style.shadow {
let shadow_rect = text_rect.translate(shadow.offset.x, shadow.offset.y);
let shadow_color = apply_layer_to_color(shadow.color, content_layer);
let mut shadow_text_style = TextStyle::clone(&transformed_text_style);
shadow_text_style.span_style.brush = None;
shadow_text_style.span_style.alpha = None;
shadow_text_style.span_style.color = Some(shadow_color);
let blur_radius = shadow.blur_radius.max(0.0) * text_scale;
let shadow_style_hash = shadow_text_style.render_hash();
let shadow_text = Arc::clone(text_for_gpu_mask(Arc::clone(render_text)).render_string());
sink.push_shadow_text(
TextDraw {
node_id,
rect: apply_layer_to_rect(shadow_rect, rect, content_layer),
snap_anchor: None,
text: DrawnText::of(shadow_text, &shadow_text_style, node.paint().spread),
layout: layout.clone(),
color: shadow_color,
text_style: Arc::new(shadow_text_style),
style_hash: shadow_style_hash,
font_size,
scale: text_scale,
clip: text_clip,
},
blur_radius,
);
}
emit_text_glyph_draws(
sink,
node,
&placement,
(
transformed_text_rect,
&transformed_text_style,
transformed_text_color,
),
);
visit_text_lines(layout, styled, text_style, text_color, |part, brush| {
sink.push_shape(filled(part, brush), text_clip, snap_anchor);
});
}
fn emit_text_glyph_draws<S: TextStyleDrawSink>(
sink: &mut S,
node: &TextPrimitiveNode,
placement: &TextPlacement<'_>,
(text_rect, style, color): (Rect, &Arc<TextStyle>, Color),
) {
let text_clip = placement.clip;
let text_scale = layer_uniform_scale(placement.layer);
let spans = node.render_text.span_styles();
let has_span_foreground_overrides = spans_override_foreground(spans);
if has_span_foreground_overrides
&& push_span_gpu_text_material_draws(sink, node, placement, text_rect, style, color)
{
return;
}
if !has_span_foreground_overrides
&& let Some((effect, effect_rect)) =
gpu_text_effect_for_style(style, text_rect, color, text_scale)
{
if spans_override_foreground_color(spans)
&& push_span_gpu_text_material_draws(sink, node, placement, text_rect, style, color)
{
return;
}
let (mask, color) = mask_style(style, Color::WHITE);
let mask_text = text_for_gpu_mask(Arc::clone(&node.render_text));
push_text_effect(
sink,
node,
(text_rect, text_scale, text_clip),
(&mask_text, mask, color),
(effect, effect_rect),
);
return;
}
sink.push_text(TextDraw {
node_id: node.node_id,
rect: text_rect,
snap_anchor: None,
text: DrawnText::of(Arc::clone(&node.render_text), style, node.paint().spread),
layout: node.layout.clone(),
color,
text_style: Arc::clone(style),
style_hash: style.render_hash(),
font_size: node.font_size,
scale: text_scale,
clip: text_clip,
});
}
#[derive(Clone, Copy)]
pub(crate) struct TextPlacement<'a> {
pub(crate) bounds: Rect,
pub(crate) text_rect: Rect,
pub(crate) layer: &'a GraphicsLayer,
pub(crate) clip: Option<Rect>,
pub(crate) snap_anchor: Option<SnapAnchor>,
}
pub(crate) fn push_text_style_draws(
scene: &mut CompositorScene,
node: &TextPrimitiveNode,
placement: TextPlacement<'_>,
) {
let paint = node.paint();
if paint.plain {
scene.push_text(TextDraw {
node_id: node.node_id,
rect: apply_layer_to_rect(placement.text_rect, placement.bounds, placement.layer),
snap_anchor: placement.snap_anchor,
text: DrawnText::plain(Arc::clone(&node.render_text), paint),
layout: node.layout.clone(),
color: apply_layer_to_color(paint.color, placement.layer),
text_style: Arc::clone(&node.text_style),
style_hash: paint.style_hash,
font_size: node.font_size,
scale: layer_uniform_scale(placement.layer),
clip: placement.clip,
});
return;
}
let counts = crate::collect::scene_counts(scene);
emit_text_style_draws(scene, node, placement);
crate::collect::assign_snap_anchor_since(scene, counts, placement.snap_anchor);
}
#[cfg(test)]
pub(crate) fn estimate_text_style_draw_bounds(
node: &TextPrimitiveNode,
placement: TextPlacement<'_>,
) -> Option<Rect> {
let mut collector = TextBoundsCollector::default();
emit_text_style_draws(&mut collector, node, placement);
collector.bounds
}
const DRAW_PRIMITIVE_TEXT_NODE_ID: NodeId = NodeId(0);
fn loose_shape(primitive: &DrawPrimitive, layer: &GraphicsLayer) -> Option<DrawPrimitive> {
let painted = |brush: &Brush| resolve_layer_brush(brush, layer).into_brush();
Some(match primitive {
DrawPrimitive::Rect {
rect,
brush,
stroke,
} => DrawPrimitive::Rect {
rect: *rect,
brush: painted(brush),
stroke: *stroke,
},
DrawPrimitive::RoundRect {
rect,
brush,
radii,
stroke,
} => DrawPrimitive::RoundRect {
rect: *rect,
brush: painted(brush),
radii: *radii,
stroke: *stroke,
},
DrawPrimitive::Arc {
rect,
brush,
center,
radius,
start_angle,
sweep_angle,
stroke,
inner_radius,
} => DrawPrimitive::Arc {
rect: *rect,
brush: painted(brush),
center: *center,
radius: *radius,
start_angle: *start_angle,
sweep_angle: *sweep_angle,
stroke: *stroke,
inner_radius: *inner_radius,
},
DrawPrimitive::Line {
rect,
brush,
start,
end,
stroke,
} => DrawPrimitive::Line {
rect: *rect,
brush: painted(brush),
start: *start,
end: *end,
stroke: *stroke,
},
DrawPrimitive::Trapezoid {
rect,
brush,
trapezoid,
} => DrawPrimitive::Trapezoid {
rect: *rect,
brush: painted(brush),
trapezoid: *trapezoid,
},
DrawPrimitive::Blend {
primitive,
blend_mode,
} => DrawPrimitive::Blend {
primitive: Box::new(loose_shape(primitive, layer)?),
blend_mode: *blend_mode,
},
DrawPrimitive::Content
| DrawPrimitive::Group(_)
| DrawPrimitive::Image { .. }
| DrawPrimitive::Text(_)
| DrawPrimitive::Shadow(_) => return None,
})
}
fn blended(primitive: DrawPrimitive, blend_mode: Option<BlendMode>) -> DrawPrimitive {
match blend_mode {
Some(blend_mode) if blend_mode != BlendMode::SrcOver => DrawPrimitive::Blend {
primitive: Box::new(primitive),
blend_mode,
},
_ => primitive,
}
}
pub(crate) fn push_draw_primitive(
primitive: &DrawPrimitive,
content: &ContentContext<'_>,
scene: &mut CompositorScene,
blend_mode: Option<BlendMode>,
) {
let bounds = content.layer_bounds;
if let Some(shape) = loose_shape(primitive, content.local_layer) {
let placement = Placement::at(
Point::new(bounds.x, bounds.y),
content.anchor,
content.visual_clip,
)
.with_rounding(content.rounding);
scene.push_loose(blended(shape, blend_mode), placement);
return;
}
struct SceneEmitter<'a> {
scene: &'a mut CompositorScene,
snap_anchor: Option<SnapAnchor>,
rounding: Option<ClipRounding>,
}
impl DrawPrimitiveSink for SceneEmitter<'_> {
fn push_shape(&mut self, _params: ShapeDrawParams) {
unreachable!("shape primitives are recorded before emission");
}
fn push_image(&mut self, params: ImageDrawParams) {
self.scene.push_image(ImageDraw {
rect: params.rect,
quad: params.quad,
snap_anchor: None,
image: params.image,
alpha: params.alpha,
color_filter: params.color_filter,
sampling: params.sampling,
clip: params.clip,
rounding: self.rounding,
blend_mode: params.blend_mode,
src_rect: params.src_rect,
motion_context_animated: params.motion_context_animated,
});
}
fn push_shadow(
&mut self,
shadow_primitive: &cranpose_ui_graphics::ShadowPrimitive,
layer_bounds: Rect,
layer: &GraphicsLayer,
clip: Option<Rect>,
) {
push_shadow_primitive(
shadow_primitive,
layer_bounds,
layer,
clip,
self.snap_anchor,
self.scene,
);
}
fn push_text(&mut self, params: TextDrawParams) {
let render_text = shared_plain_render_string(params.text.text());
self.scene.push_text(TextDraw {
node_id: DRAW_PRIMITIVE_TEXT_NODE_ID,
rect: params.rect,
snap_anchor: None,
text: DrawnText::of_laid_out(render_text, ¶ms.text_style, ¶ms.layout),
layout: params.layout,
color: params.color,
text_style: params.text_style,
style_hash: params.style_hash,
font_size: params.font_size,
scale: params.scale,
clip: params.clip,
});
}
}
let mut emitter = SceneEmitter {
scene,
snap_anchor: content.anchor,
rounding: content.rounding,
};
emit_draw_primitive(
primitive,
bounds,
content.local_layer,
content.visual_clip,
&mut emitter,
blend_mode,
content.motion_context_animated,
);
}
fn record_shadow_caster(
recorder: &mut Arc<ShapeRecorder>,
primitive: &DrawPrimitive,
layer: &GraphicsLayer,
blend_mode: BlendMode,
) -> bool {
let Some(shape) = loose_shape(primitive, layer) else {
return false;
};
let recorder = Arc::make_mut(recorder);
let recorded = if blend_mode == BlendMode::SrcOver {
recorder.push_primitive(shape)
} else {
recorder.push_shape_primitive(shape, blend_mode)
};
matches!(recorded, Recorded::Shape(_))
}
fn push_shadow_primitive(
shadow_prim: &cranpose_ui_graphics::ShadowPrimitive,
layer_bounds: Rect,
layer: &GraphicsLayer,
clip: Option<Rect>,
snap_anchor: Option<SnapAnchor>,
scene: &mut CompositorScene,
) {
let placement = Placement::at(
Point::new(layer_bounds.x, layer_bounds.y),
snap_anchor,
None,
);
match shadow_prim {
cranpose_ui_graphics::ShadowPrimitive::Drop {
shape,
cutout,
blur_radius,
blend_mode,
} => {
let mut shapes = scene.take_shadow_recorder();
if !record_shadow_caster(&mut shapes, shape, layer, *blend_mode) {
return;
}
let cutouts = if let Some(cutout) = cutout {
let mut recorder = scene.take_shadow_recorder();
if !record_shadow_caster(&mut recorder, cutout, layer, BlendMode::DstOut) {
return;
}
RunDraw::whole(recorder, placement.clone())
} else {
None
};
scene.push_shadow_draw(ShadowDraw {
shapes: RunDraw::whole(shapes, placement),
post_blur_cutouts: cutouts,
texts: vec![],
blur_radius: *blur_radius,
clip,
rounded_clip: None,
z_index: 0,
});
}
cranpose_ui_graphics::ShadowPrimitive::Inner {
fill,
cutout,
blur_radius,
blend_mode,
clip_rect,
} => {
let abs_clip = Rect {
x: clip_rect.x + layer_bounds.x,
y: clip_rect.y + layer_bounds.y,
width: clip_rect.width,
height: clip_rect.height,
};
let transformed_clip = apply_layer_to_rect(abs_clip, layer_bounds, layer);
let Some(shadow_clip) = clip.map_or(Some(transformed_clip), |parent_clip| {
parent_clip.intersect(transformed_clip)
}) else {
return;
};
let mut shapes = scene.take_shadow_recorder();
if !record_shadow_caster(&mut shapes, fill, layer, *blend_mode)
|| !record_shadow_caster(&mut shapes, cutout, layer, BlendMode::DstOut)
{
return;
}
scene.push_shadow_draw(ShadowDraw {
shapes: RunDraw::whole(shapes, placement),
post_blur_cutouts: None,
texts: vec![],
blur_radius: *blur_radius,
clip: Some(shadow_clip),
rounded_clip: None,
z_index: 0,
});
}
}
}
#[cfg(test)]
#[path = "tests/pipeline_tests.rs"]
mod tests;