use crate::graphics::{FilterFunction, FilterPaint, POINTS_PER_PIXEL, Rect};
use crate::paint::{
ColorMatrix as ColorMatrixValues, IDENTITY_MATRIX, alpha_scale, compose, preserves_unit_range,
transform_color,
};
use crate::svg::usvg::filter::{
ColorInterpolation, ColorMatrix, ColorMatrixKind, DropShadow, Filter, GaussianBlur, Input,
Kind, Primitive,
};
use crate::writer::{
PdfError,
display::{Painter, Space},
painting, raster,
};
use krilla::surface::Surface;
use std::sync::Arc;
const RESULT: &str = "result";
const LIGHTING_KERNEL_RADIUS: f32 = 1.0;
pub(super) enum Step<'f> {
Function(&'f FilterFunction),
Reference(Arc<Filter>),
}
pub(super) fn draw(
painter: &mut Painter<'_, '_, '_>,
filter: &FilterPaint,
items: &[crate::graphics::DisplayItem],
space: Space,
surface: &mut Surface<'_>,
) -> Result<(), PdfError> {
if filter.bounds.is_none()
&& filter
.functions
.iter()
.any(|function| matches!(function, FilterFunction::Url(_)))
{
return Err(PdfError::UnplacedEffect);
}
let Some(steps) = steps(filter, painter.raster.definitions) else {
return painter.draw(items, space, surface);
};
if let Some((matrix, alpha)) = color_chain(&steps)
&& let Some((items, lines)) = recolor(painter, items, &matrix)?
{
return draw_recolored(painter, &items, &lines, alpha, space, surface);
}
let visible = painting::local_bounds(space.viewport, surface)?;
let density = painter.raster.pixels_per_point
* space.scale
* painting::transform_scale(surface.cur_transform());
let spread: f32 = steps.iter().map(|step| step.spread(density)).sum();
let area = expand(visible, spread);
let Some(raster) = raster::rasterize(painter, items, area, density)? else {
return Ok(());
};
let reach = raster.ink().map(|ink| expand(ink, spread));
let reach = steps
.iter()
.filter_map(|step| match step {
Step::Reference(filter) => Some(scaled(filter.rect(), POINTS_PER_PIXEL)),
Step::Function(_) => None,
})
.fold(reach, |reach, region| {
Some(reach.map_or(region, |reach| reach.union(region)))
});
let Some(mut raster) = reach.and_then(|reach| raster.cropped(reach)) else {
return Ok(());
};
apply(&steps, &mut raster)?;
match raster
.ink()
.and_then(|ink| raster.cropped(ink.intersection(visible)))
{
Some(raster) => raster::embed(&raster, surface),
None => Ok(()),
}
}
pub(super) fn apply(steps: &[Step<'_>], raster: &mut raster::Raster) -> Result<(), PdfError> {
let transform = raster.transform();
for step in steps {
match step {
Step::Function(function) => {
let filter = function_filter(function, raster.area)?;
crate::svg::resvg::filter::apply(&filter, transform, &mut raster.pixmap);
}
Step::Reference(filter) => crate::svg::resvg::filter::apply(
filter,
transform.pre_scale(POINTS_PER_PIXEL, POINTS_PER_PIXEL),
&mut raster.pixmap,
),
}
}
Ok(())
}
pub(super) fn expand(rect: Rect, by: f32) -> Rect {
Rect {
x: rect.x - by,
y: rect.y - by,
width: rect.width + 2.0 * by,
height: rect.height + 2.0 * by,
}
}
fn scaled(rect: crate::svg::usvg::NonZeroRect, factor: f32) -> Rect {
Rect {
x: rect.x() * factor,
y: rect.y() * factor,
width: rect.width() * factor,
height: rect.height() * factor,
}
}
pub(super) fn color_chain(steps: &[Step<'_>]) -> Option<(ColorMatrixValues, f32)> {
let matrix = steps
.iter()
.try_fold(IDENTITY_MATRIX, |chain, step| match step {
Step::Function(function) => function
.matrix()
.filter(preserves_unit_range)
.map(|matrix| compose(&chain, &matrix)),
Step::Reference(_) => None,
})?;
alpha_scale(&matrix).map(|alpha| (matrix, alpha))
}
fn draw_recolored(
painter: &mut Painter<'_, '_, '_>,
items: &[crate::graphics::DisplayItem],
lines: &[crate::layout::TextLine],
alpha: f32,
space: Space,
surface: &mut Surface<'_>,
) -> Result<(), PdfError> {
let opacity = krilla::num::NormalizedF32::new(alpha).ok_or(PdfError::InvalidAlpha(alpha))?;
let translucent = opacity != krilla::num::NormalizedF32::ONE;
if translucent {
surface.push_opacity(opacity);
}
let mut recolored = Painter {
lines,
page: painter.page,
page_area: painter.page_area,
text: painter.text,
fonts: painter.fonts,
images: painter.images,
raster: painter.raster,
prepared: crate::writer::backdrops::Prepared::default(),
};
let drawn = if translucent {
let nested = Space {
viewport: painting::local_bounds(space.viewport, surface)?,
scale: space.scale * painting::transform_scale(surface.cur_transform()),
};
recolored.draw(items, nested, surface)
} else {
recolored.draw(items, space, surface)
};
if translucent {
surface.pop();
}
drawn
}
type Recolored = (
Vec<crate::graphics::DisplayItem>,
Vec<crate::layout::TextLine>,
);
fn recolor(
painter: &Painter<'_, '_, '_>,
items: &[crate::graphics::DisplayItem],
matrix: &ColorMatrixValues,
) -> Result<Option<Recolored>, PdfError> {
use crate::graphics::DisplayItem;
let map = |color: crate::graphics::Color| map_color(matrix, color);
let mut lines = Vec::new();
let mut mapped = Vec::with_capacity(items.len());
for item in items {
mapped.push(match item {
DisplayItem::Box(paint) => match recolor_box(paint, &map) {
Some(paint) => DisplayItem::Box(paint),
None => return Ok(None),
},
DisplayItem::Text { line } => {
let source = painter
.lines
.get(*line)
.ok_or(PdfError::InvalidTextReference {
page: painter.page,
line: *line,
})?;
if !painter.text.paints_run_colors(&source.runs)? {
return Ok(None);
}
let mut line = source.clone();
line.color = map(line.color);
recolor_runs(&mut line.runs, &map);
lines.push(line);
DisplayItem::Text {
line: lines.len() - 1,
}
}
DisplayItem::Decoration(decoration) => {
let mut decoration = *decoration;
decoration.color = map(decoration.color);
DisplayItem::Decoration(decoration)
}
DisplayItem::TextShadow(shadow) => {
let mut shadow = shadow.clone();
shadow.color = map(shadow.color);
DisplayItem::TextShadow(shadow)
}
item @ (DisplayItem::PushClip(_)
| DisplayItem::PushTransform(_)
| DisplayItem::PushOpacity(_)
| DisplayItem::Pop) => item.clone(),
item @ DisplayItem::PushBackdropRoot => item.clone(),
DisplayItem::Frame(_)
| DisplayItem::Image(_)
| DisplayItem::Backdrop(_)
| DisplayItem::PushBlend(_)
| DisplayItem::PushFilter(_)
| DisplayItem::PushMask(_) => {
return Ok(None);
}
});
}
Ok(Some((mapped, lines)))
}
fn recolor_runs(
runs: &mut [crate::text::GlyphRun],
map: &impl Fn(crate::graphics::Color) -> crate::graphics::Color,
) {
for run in runs {
run.color = map(run.color);
if let Some(palette) = &mut run.palette {
*palette = palette.iter().copied().map(map).collect();
}
if let Some(stroke) = &mut run.stroke {
stroke.color = map(stroke.color);
}
for mark in &mut run.mark_shapes {
mark.color = map(mark.color);
}
recolor_runs(&mut run.marks, map);
}
}
fn recolor_box(
paint: &crate::graphics::BoxPaint,
map: &impl Fn(crate::graphics::Color) -> crate::graphics::Color,
) -> Option<crate::graphics::BoxPaint> {
use crate::graphics::{BorderStyle, OutlineStyle};
let shaded = |style: BorderStyle| {
matches!(
style,
BorderStyle::Groove | BorderStyle::Ridge | BorderStyle::Inset | BorderStyle::Outset
)
};
let decoration = &paint.decoration;
if decoration.backgrounds.has_images()
|| decoration.border_image.is_drawn()
|| decoration.borders.iter().any(|border| shaded(border.style))
|| matches!(decoration.outline.style, OutlineStyle::Line(style) if shaded(style))
{
return None;
}
let mut paint = paint.clone();
let decoration = &mut paint.decoration;
decoration.background = map(decoration.background);
for border in &mut decoration.borders {
border.color = map(border.color);
}
decoration.outline.color = map(decoration.outline.color);
decoration.shadows = Arc::new(
decoration
.shadows
.iter()
.map(|shadow| crate::paint::BoxShadow {
color: map(shadow.color),
..*shadow
})
.collect(),
);
Some(paint)
}
pub(super) fn map_color(
matrix: &ColorMatrixValues,
color: crate::graphics::Color,
) -> crate::graphics::Color {
const CHANNEL_MAX: f32 = 255.0;
let [red, green, blue] = color.rgb.map(|channel| f32::from(channel) / CHANNEL_MAX);
let mapped = transform_color(matrix, [red, green, blue, color.alpha]);
crate::graphics::Color {
rgb: [mapped[0], mapped[1], mapped[2]]
.map(|channel| (channel.clamp(0.0, 1.0) * CHANNEL_MAX).round() as u8),
alpha: color.alpha,
}
}
pub(super) fn steps<'f>(
filter: &'f FilterPaint,
definitions: &crate::document::svg::SvgDefinitions,
) -> Option<Vec<Step<'f>>> {
filter
.functions
.iter()
.map(|function| match function {
FilterFunction::Url(reference) => {
crate::svg::referenced_filter(reference, filter.bounds, definitions)
.map(Step::Reference)
}
function => Some(Step::Function(function)),
})
.collect()
}
impl Step<'_> {
pub(super) fn spread(&self, density: f32) -> f32 {
match self {
Self::Function(function) => function.spread(),
Self::Reference(filter) => filter
.primitives()
.iter()
.map(|primitive| primitive_spread(primitive, filter.rect(), density))
.sum::<f32>(),
}
}
}
fn primitive_spread(
primitive: &Primitive,
region: crate::svg::usvg::NonZeroRect,
density: f32,
) -> f32 {
let pixel = 1.0 / density;
let blur = |x: strict_num::PositiveF32, y: strict_num::PositiveF32| {
crate::paint::BLUR_EXTENT * x.get().max(y.get()) * POINTS_PER_PIXEL
};
match primitive.kind() {
Kind::GaussianBlur(blur_kind) => blur(blur_kind.std_dev_x, blur_kind.std_dev_y),
Kind::DropShadow(shadow) => {
shadow.dx.abs().max(shadow.dy.abs()) * POINTS_PER_PIXEL
+ blur(shadow.std_dev_x, shadow.std_dev_y)
}
Kind::Offset(offset) => offset.dx.abs().max(offset.dy.abs()) * POINTS_PER_PIXEL,
Kind::Morphology(morphology) => {
morphology.radius_x.get().max(morphology.radius_y.get()) * POINTS_PER_PIXEL
}
Kind::DisplacementMap(map) => map.scale.abs() / 2.0 * POINTS_PER_PIXEL,
Kind::ConvolveMatrix(convolve) => {
convolve.matrix.columns.max(convolve.matrix.rows) as f32 * pixel
}
Kind::DiffuseLighting(_) | Kind::SpecularLighting(_) => LIGHTING_KERNEL_RADIUS * pixel,
Kind::Tile(_) => region.width().max(region.height()) * POINTS_PER_PIXEL,
Kind::Blend(_)
| Kind::ColorMatrix(_)
| Kind::ComponentTransfer(_)
| Kind::Composite(_)
| Kind::Flood(_)
| Kind::Image(_)
| Kind::Merge(_)
| Kind::Turbulence(_) => 0.0,
}
}
pub(super) fn function_filter(function: &FilterFunction, area: Rect) -> Result<Filter, PdfError> {
let rect = crate::svg::usvg::NonZeroRect::from_xywh(area.x, area.y, area.width, area.height)
.ok_or(PdfError::InvalidGeometry)?;
let deviation =
|value: f32| strict_num::PositiveF32::new(value).ok_or(PdfError::InvalidGeometry);
let kind = match *function {
FilterFunction::Blur(value) => Kind::GaussianBlur(GaussianBlur {
input: Input::SourceGraphic,
std_dev_x: deviation(value)?,
std_dev_y: deviation(value)?,
}),
FilterFunction::DropShadow {
offset: [dx, dy],
deviation: value,
color,
} => Kind::DropShadow(DropShadow {
input: Input::SourceGraphic,
dx,
dy,
std_dev_x: deviation(value)?,
std_dev_y: deviation(value)?,
color: crate::svg::usvg::Color::new_rgb(color.rgb[0], color.rgb[1], color.rgb[2]),
opacity: crate::svg::usvg::Opacity::new_clamped(color.alpha),
}),
ref function => Kind::ColorMatrix(ColorMatrix {
input: Input::SourceGraphic,
kind: ColorMatrixKind::Matrix(
function.matrix().ok_or(PdfError::InvalidGeometry)?.to_vec(),
),
}),
};
Ok(Filter {
id: crate::svg::usvg::NonEmptyString::new(RESULT.into())
.ok_or(PdfError::InvalidGeometry)?,
rect,
primitives: vec![Primitive {
rect,
color_interpolation: ColorInterpolation::SRGB,
result: RESULT.into(),
kind,
}],
})
}