#![deny(missing_docs)]
#[cfg(test)]
use crate::theme::color_from_rgb;
use crate::Error;
use crate::{style::LinePattern, Color};
use super::primitives::{
CanonicalFillStyle, CanonicalGradientFill, CanonicalLineStyle, CanonicalPlannedBracket,
CanonicalPlannedText, CanonicalScatter,
};
use crate::layout::{
DeferredAnnotationTextPlan, PhysicalTextAlignment, PixelRect, ResolvedTextPlan,
};
use crate::render::coordinates::{
self, CanonicalBracket, CanonicalGradient, CanonicalPoint, CanonicalRect, CanonicalRoundedRect,
CanonicalText,
};
use crate::style::PointShape;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Point2D {
pub x: f64,
pub y: f64,
}
impl Point2D {
#[must_use]
pub fn new(x: f64, y: f64) -> Self {
Self { x, y }
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct PointStyle {
pub(crate) color: Color,
pub(crate) radius: u32,
pub(crate) outline: Option<PointOutline>,
pub(crate) shape: PointShape,
}
impl PointStyle {
#[cfg(test)]
#[must_use]
pub(crate) fn new(color: (u8, u8, u8), radius: u32) -> Self {
Self {
color: color_from_rgb(color).with_alpha(209.0 / 255.0),
radius,
outline: Some(PointOutline::publication().unwrap()),
shape: PointShape::Circle,
}
}
#[must_use]
pub const fn with_shape(mut self, shape: PointShape) -> Self {
self.shape = shape;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PointOutline {
pub(crate) color: Color,
pub(crate) width_ratio: crate::theme::RelativeSpacing,
}
impl PointOutline {
#[cfg(test)]
pub(crate) fn publication() -> Result<Self, Error> {
Ok(crate::theme::PointOutlineTheme::publication()?.backend_style())
}
pub(crate) fn width_for_radius(
&self,
radius: u32,
) -> Result<coordinates::CanonicalCoordinate, Error> {
let width = self
.width_ratio
.product(crate::theme::LocalMetric::css_pixels(f64::from(radius))?)
.round(crate::layout::kernel::SpatialRounding::NearestEven)?
.quanta();
if width > (1_i64 << 53) - 1 || (width == 0 && !self.width_ratio.is_zero()) {
return Err(Error::Render("point outline width exceeds canonical coordinates or its positive extent collapses".into()));
}
Ok(coordinates::CanonicalCoordinate::from_quanta(width))
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct LineStyle {
pub(crate) color: Color,
pub width: f32,
pub pattern: LinePattern,
}
impl LineStyle {
#[must_use]
#[cfg(test)]
pub(crate) fn solid(color: Color, width: f32) -> Self {
Self {
color,
width,
pattern: LinePattern::Solid,
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct FillStyle {
pub(crate) color: Color,
pub(crate) stroke: Color,
pub(crate) stroke_width: f32,
}
impl FillStyle {
pub(crate) const fn new(color: Color, stroke: Color, stroke_width: f32) -> Self {
if stroke_width == 0.0 {
return Self {
color,
stroke: Color::TRANSPARENT,
stroke_width: 0.0,
};
}
Self {
color,
stroke,
stroke_width,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GradientStop {
pub offset: f64,
pub color: (u8, u8, u8),
}
impl GradientStop {
#[must_use]
pub const fn new(offset: f64, color: (u8, u8, u8)) -> Self {
Self { offset, color }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TextAnchor {
#[default]
Start,
Middle,
End,
}
#[derive(Debug, Clone, PartialEq)]
pub struct TextStyle {
pub(crate) color: Color,
pub(crate) font_family: crate::font::canonical::FontStack,
pub font_size: f64,
pub weight: crate::text::TextWeight,
pub anchor: TextAnchor,
pub rotation: f64,
}
#[derive(Debug, Clone)]
pub struct SignificanceBracket {
pub x_left: f64,
pub x_right: f64,
pub y: f64,
pub label: String,
pub orientation: BracketOrientation,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LayerRole {
#[default]
Generic,
Grid,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SurfaceRole {
CanvasRoot,
PlotPanel,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BracketOrientation {
Vertical,
Horizontal,
}
pub(crate) const POLYGON_MITER_LIMIT: f64 = 4.0;
#[derive(Debug, Clone)]
pub struct BracketStyle {
pub(crate) color: Color,
pub(crate) label_color: Color,
pub width: f32,
pub(crate) font_family: crate::font::canonical::FontStack,
pub font_size: f64,
pub(crate) line_height: f64,
pub weight: crate::text::TextWeight,
pub label_gap: f64,
pub(crate) tick_height: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PlannedTextOrigin {
Middle,
Baseline,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct PlannedTextPlacement {
pub(crate) position: Point2D,
pub(crate) anchor: TextAnchor,
pub(crate) rotation: f64,
pub(crate) origin: PlannedTextOrigin,
pub(crate) reverse_lines: bool,
}
#[derive(Debug, Clone)]
pub(crate) struct PlacedText {
pub(crate) plan: ResolvedTextPlan,
pub(crate) placement: PlannedTextPlacement,
}
pub(crate) fn reserve_text_records<T>(
records: &mut Vec<T>,
additional: usize,
) -> Result<(), Error> {
if additional > records.capacity() - records.len() {
let capacity = records
.len()
.checked_add(additional)
.zip(records.capacity().checked_mul(2))
.map(|(required, doubled)| required.max(doubled).max(4))
.ok_or_else(|| Error::Render("producer text capacity overflow".into()))?;
crate::operation::check()?;
records
.try_reserve_exact(capacity - records.len())
.map_err(|_| Error::Render("producer text allocation failed".into()))?;
}
Ok(())
}
impl PlacedText {
pub(crate) fn middle(
plan: ResolvedTextPlan,
position: Point2D,
anchor: TextAnchor,
rotation: f64,
) -> Result<Self, Error> {
Ok(Self {
placement: crate::layout::text::placement::resolve(
PlannedTextPlacement::middle(position, anchor, rotation),
&plan,
None,
)?,
plan,
})
}
pub(crate) fn draw(&self, backend: &mut dyn Backend) -> Result<(), Error> {
backend.draw_planned_text(self.placement, &self.plan)
}
pub(crate) fn with_reversed_lines(mut self) -> Self {
self.placement.reverse_lines = true;
self
}
}
impl PlannedTextPlacement {
pub(crate) fn line_y(self, plan: &ResolvedTextPlan, y: i64) -> Result<i64, Error> {
if !self.reverse_lines {
return Ok(y);
}
plan.last_baseline_quanta
.unwrap_or(0)
.checked_sub(y)
.and_then(|offset| plan.first_baseline_quanta.unwrap_or(0).checked_add(offset))
.ok_or_else(|| Error::Render("reversed text line placement overflowed".into()))
}
pub(crate) const fn middle(position: Point2D, anchor: TextAnchor, rotation: f64) -> Self {
Self {
position,
anchor,
rotation,
origin: PlannedTextOrigin::Middle,
reverse_lines: false,
}
}
pub(crate) const fn baseline(position: Point2D, anchor: TextAnchor, rotation: f64) -> Self {
Self {
position,
anchor,
rotation,
origin: PlannedTextOrigin::Baseline,
reverse_lines: false,
}
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct PlannedSignificanceCall<'a> {
pub(crate) bracket: &'a SignificanceBracket,
pub(crate) style: &'a BracketStyle,
pub(crate) label: &'a DeferredAnnotationTextPlan,
}
pub trait Backend {
fn draw_fixed_content(
&mut self,
_content: &crate::composition::PlacedContent,
) -> Result<(), Error> {
Err(Error::Render(
"backend does not support fixed image content".into(),
))
}
#[doc(hidden)]
fn begin_paint_batch(
&mut self,
_reference: &crate::layout::PaintBatchRef,
) -> Result<(), Error> {
Ok(())
}
#[doc(hidden)]
fn end_paint_batch(&mut self) -> Result<(), Error> {
Ok(())
}
fn draw_canonical_text(&mut self, _text: &CanonicalPlannedText) -> Result<(), Error> {
Err(Error::Render(
"backend does not support canonical text".into(),
))
}
fn draw_canonical_bracket(&mut self, _bracket: &CanonicalPlannedBracket) -> Result<(), Error> {
Err(Error::Render(
"backend does not support canonical bracket".into(),
))
}
fn draw_canonical_scatter(&mut self, _scatter: &CanonicalScatter) -> Result<(), Error> {
Err(Error::Render(
"backend does not support canonical scatter".into(),
))
}
fn draw_canonical_line(
&mut self,
_points: &[CanonicalPoint],
_style: &CanonicalLineStyle,
) -> Result<(), Error> {
Err(Error::Render(
"backend does not support canonical lines".into(),
))
}
fn draw_canonical_polygon(
&mut self,
_points: &[CanonicalPoint],
_style: &CanonicalFillStyle,
) -> Result<(), Error> {
Err(Error::Render(
"backend does not support canonical polygons".into(),
))
}
fn draw_canonical_gradient(&mut self, _gradient: &CanonicalGradientFill) -> Result<(), Error> {
Err(Error::Render(
"backend does not support canonical gradients".into(),
))
}
fn begin_canonical_clip(&mut self, _region: coordinates::CanonicalBox) -> Result<(), Error> {
Err(Error::Render(
"backend does not support canonical clips".into(),
))
}
fn draw_canonical_surface(
&mut self,
_bounds: coordinates::CanonicalBox,
_paint: Color,
_role: SurfaceRole,
) -> Result<(), Error> {
Err(Error::Render(
"backend does not support canonical surfaces".into(),
))
}
fn draw_canonical_rounded_rect(
&mut self,
_rounded: coordinates::CanonicalRoundedBox,
) -> Result<(), Error> {
Err(Error::Render(
"backend does not support canonical rectangles".into(),
))
}
fn begin(&mut self, width: f64, height: f64) -> Result<(), Error>;
fn begin_layer(&mut self, _name: &str) -> Result<(), Error> {
Ok(())
}
fn begin_layer_with_role(&mut self, name: &str, _role: LayerRole) -> Result<(), Error> {
self.begin_layer(name)
}
fn end_layer(&mut self) -> Result<(), Error> {
Ok(())
}
fn begin_clip(&mut self, region: PixelRect) -> Result<(), Error>;
fn end_clip(&mut self) -> Result<(), Error>;
fn draw_surface(
&mut self,
bounds: PixelRect,
paint: Color,
role: SurfaceRole,
) -> Result<(), Error>;
fn draw_scatter(&mut self, points: &[Point2D], style: &PointStyle) -> Result<(), Error>;
fn draw_line(&mut self, points: &[Point2D], style: &LineStyle) -> Result<(), Error>;
fn draw_polygon(&mut self, points: &[Point2D], style: &FillStyle) -> Result<(), Error>;
fn draw_linear_gradient(
&mut self,
bounds: PixelRect,
start: Point2D,
end: Point2D,
stops: &[GradientStop],
) -> Result<(), Error>;
fn draw_text(&mut self, position: Point2D, text: &str, style: &TextStyle) -> Result<(), Error>;
#[doc(hidden)]
#[allow(
private_interfaces,
reason = "immutable text plans are a crate-private renderer transition"
)]
fn draw_planned_text(
&mut self,
placement: PlannedTextPlacement,
plan: &ResolvedTextPlan,
) -> Result<(), Error> {
self.draw_text(
placement.position,
&plan.source,
&planned_text_style(placement, plan)?,
)
}
fn draw_rounded_rect(
&mut self,
x: f64,
y: f64,
w: f64,
h: f64,
r: f64,
style: &FillStyle,
) -> Result<(), Error>;
fn draw_bracket(
&mut self,
bracket: &SignificanceBracket,
style: &BracketStyle,
) -> Result<(), Error>;
#[doc(hidden)]
#[allow(
private_interfaces,
reason = "immutable significance plans are a crate-private renderer transition"
)]
fn draw_planned_bracket(&mut self, call: PlannedSignificanceCall<'_>) -> Result<(), Error> {
self.draw_bracket(call.bracket, call.style)
}
fn end(&mut self) -> Result<(), Error>;
}
pub(crate) fn validate_clip_region(region: PixelRect) -> Result<CanonicalRect, Error> {
coordinates::canonical_clip(region)
}
pub(crate) fn validate_surface_bounds(bounds: PixelRect) -> Result<CanonicalRect, Error> {
coordinates::canonical_clip(bounds)
}
pub(crate) fn validate_points(
points: &[Point2D],
context: &str,
) -> Result<Vec<CanonicalPoint>, Error> {
coordinates::canonical_points(points, context)
}
pub(crate) fn points_share_canonical_position(
first: Point2D,
second: Point2D,
context: &str,
) -> Result<bool, Error> {
let points = coordinates::canonical_points(&[first, second], context)?;
Ok(points[0].same_position(points[1]))
}
pub(crate) fn validate_line_points(points: &[Point2D]) -> Result<Vec<CanonicalPoint>, Error> {
coordinates::canonical_line_points(points)
}
pub(crate) fn validate_polygon_points(points: &[Point2D]) -> Result<Vec<CanonicalPoint>, Error> {
coordinates::canonical_polygon_points(points)
}
pub(crate) fn validate_triangle_points(
points: &[Point2D],
radius: u32,
) -> Result<Vec<[CanonicalPoint; 3]>, Error> {
coordinates::canonical_triangles(points, radius)
}
pub(crate) fn validate_point_style(style: &PointStyle) -> Result<(), Error> {
if style.outline.is_some() && style.radius == 0 {
return Err(Error::Render(
"outlined point radius must be positive".into(),
));
}
Ok(())
}
pub(crate) fn validate_line_style(style: &LineStyle) -> Result<(), Error> {
if style.width.is_finite() && style.width >= 0.0 {
Ok(())
} else {
Err(Error::Render(
format!(
"line width must be finite and non-negative; got {}",
style.width
)
.into(),
))
}
}
pub(crate) fn validate_fill_style(style: &FillStyle) -> Result<(), Error> {
if !style.stroke_width.is_finite() || style.stroke_width < 0.0 {
return Err(Error::Render(
format!(
"fill stroke width must be finite and non-negative; got {}",
style.stroke_width
)
.into(),
));
}
Ok(())
}
pub(crate) fn validate_linear_gradient(
bounds: PixelRect,
start: Point2D,
end: Point2D,
stops: &[GradientStop],
) -> Result<CanonicalGradient, Error> {
coordinates::canonical_gradient(bounds, start, end, stops)
}
pub(crate) fn validate_text_style(style: &TextStyle) -> Result<(), Error> {
if style.rotation.is_finite() {
Ok(())
} else {
Err(Error::Render(
format!("text rotation must be finite; got {}", style.rotation).into(),
))
}
}
pub(crate) fn validate_text(position: Point2D, style: &TextStyle) -> Result<CanonicalText, Error> {
validate_text_style(style)?;
coordinates::canonical_text(
position,
style.rotation,
coordinates::CoordinatePrecision::CssQuantum,
)
}
pub(crate) fn planned_text_style(
placement: PlannedTextPlacement,
plan: &ResolvedTextPlan,
) -> Result<TextStyle, Error> {
Ok(TextStyle {
color: plan.style.paint,
font_family: plan
.copy_stack()
.map_err(|error| Error::Render(error.to_string().into()))?,
font_size: plan.style.font_size,
weight: plan.style.weight,
anchor: placement.anchor,
rotation: placement.rotation,
})
}
pub(crate) const fn nearest_even_text_half(value: i64) -> Option<i64> {
if value < 0 {
return None;
}
let quotient = value / 2;
if value % 2 == 0 || quotient % 2 == 0 {
Some(quotient)
} else {
quotient.checked_add(1)
}
}
pub(crate) fn validate_planned_text(
placement: PlannedTextPlacement,
plan: &ResolvedTextPlan,
) -> Result<CanonicalText, Error> {
let canonical = coordinates::canonical_text(
placement.position,
placement.rotation,
coordinates::CoordinatePrecision::CssQuantum,
)?;
validate_text_plan(placement, plan)?;
Ok(canonical)
}
#[expect(
clippy::too_many_lines,
reason = "one protocol validator checks linked immutable style, line, discretionary-break, and glyph spans"
)]
pub(crate) fn validate_text_plan(
placement: PlannedTextPlacement,
plan: &ResolvedTextPlan,
) -> Result<(), Error> {
let expected_alignment = match placement.anchor {
TextAnchor::Start => PhysicalTextAlignment::Start,
TextAnchor::Middle => PhysicalTextAlignment::Center,
TextAnchor::End => PhysicalTextAlignment::End,
};
if plan.style.alignment != expected_alignment {
return Err(Error::Render(
"planned text alignment does not match its backend placement".into(),
));
}
if !plan.style.font_size.is_finite()
|| plan.style.font_size <= 0.0
|| plan.style.stack_source.is_empty()
|| plan.style.stack.is_empty()
|| plan.style.line_height_quanta <= 0
|| plan.line_pitch_quanta <= 0
|| plan.width_quanta < 0
|| plan.height_quanta < 0
{
return Err(Error::Render(
"planned text has invalid resolved style or dimensions".into(),
));
}
let valid_span = |start: u32, end: u32| {
let start = start as usize;
let end = end as usize;
start <= end
&& end <= plan.source.len()
&& plan.source.is_char_boundary(start)
&& plan.source.is_char_boundary(end)
};
let valid_ink = |left: i64, bottom: i64, right: i64, top: i64| left <= right && bottom <= top;
match (plan.lines.first(), plan.lines.last()) {
(Some(first), Some(last)) => {
if plan.first_baseline_quanta != Some(first.translation_y_quanta)
|| plan.last_baseline_quanta != Some(last.translation_y_quanta)
|| plan.height_quanta == 0
{
return Err(Error::Render(
"planned text baselines do not match its stored lines".into(),
));
}
}
(None, None) => {
if plan.first_baseline_quanta.is_some()
|| plan.last_baseline_quanta.is_some()
|| plan.width_quanta != 0
|| plan.height_quanta != 0
{
return Err(Error::Render(
"empty planned text has nonempty metrics".into(),
));
}
}
_ => unreachable!("a slice cannot have only one of first/last"),
}
for (index, line) in plan.lines.iter().enumerate() {
placement.line_y(plan, line.translation_y_quanta)?;
if let Some(soft) = line.selected_soft_hyphen {
if !valid_span(soft.start_byte, soft.end_byte)
|| soft.start_byte < line.source_span.start_byte
|| soft.end_byte != line.source_span.end_byte
|| &plan.source[soft.start_byte as usize..soft.end_byte as usize] != "\u{ad}"
|| !line.runs.iter().any(|run| {
run.source_span.start_byte <= soft.start_byte
&& run.source_span.end_byte >= soft.end_byte
})
{
return Err(Error::Render(
"planned text has an invalid selected soft-hyphen span or run".into(),
));
}
}
let expected_y = plan
.first_baseline_quanta
.and_then(|first| {
i64::try_from(index)
.ok()
.and_then(|index| plan.line_pitch_quanta.checked_mul(index))
.and_then(|offset| first.checked_add(offset))
})
.ok_or_else(|| Error::Render("planned text line offset overflow".into()))?;
if line.translation_y_quanta != expected_y
|| !valid_span(line.source_span.start_byte, line.source_span.end_byte)
|| line
.ink_quanta
.is_some_and(|ink| !valid_ink(ink.left, ink.bottom, ink.right, ink.top))
{
return Err(Error::Render(
"planned text has an invalid line span, translation, or ink box".into(),
));
}
for run in &line.runs {
if !valid_span(run.source_span.start_byte, run.source_span.end_byte)
|| run.source_span.start_byte < line.source_span.start_byte
|| run.source_span.end_byte > line.source_span.end_byte
|| run.units_per_em == 0
|| run
.ink_quanta
.is_some_and(|ink| !valid_ink(ink.left, ink.bottom, ink.right, ink.top))
|| run.glyphs.iter().any(|glyph| {
glyph
.ink_quanta
.is_some_and(|ink| !valid_ink(ink.left, ink.bottom, ink.right, ink.top))
})
{
return Err(Error::Render(
"planned text has an invalid shaped run or glyph ink box".into(),
));
}
}
}
Ok(())
}
pub(crate) fn validate_rounded_rect(
x: f64,
y: f64,
width: f64,
height: f64,
radius: f64,
) -> Result<CanonicalRoundedRect, Error> {
coordinates::canonical_rounded_rect(x, y, width, height, radius)
}
pub(crate) fn validate_bracket(
bracket: &SignificanceBracket,
style: &BracketStyle,
) -> Result<CanonicalBracket, Error> {
if !style.width.is_finite() || style.width < 0.0 {
return Err(Error::Render(
format!(
"bracket width must be finite and non-negative; got {}",
style.width
)
.into(),
));
}
if !style.font_size.is_finite()
|| style.font_size <= 0.0
|| !style.line_height.is_finite()
|| style.line_height <= 0.0
|| !style.label_gap.is_finite()
|| style.label_gap < 0.0
|| !style.tick_height.is_finite()
|| style.tick_height < 0.0
{
return Err(Error::Render(
"bracket style requires positive font size and line height and finite nonnegative gap and tick height"
.into(),
));
}
coordinates::canonical_bracket(bracket, style.tick_height, style.label_gap)
}
pub(crate) fn planned_bracket_placement(
canonical: CanonicalBracket,
plan: &ResolvedTextPlan,
) -> Result<PlannedTextPlacement, Error> {
let position = canonical.label_position.value();
let default = match canonical.orientation {
BracketOrientation::Vertical => {
PlannedTextPlacement::baseline(position, TextAnchor::Middle, 0.0)
}
BracketOrientation::Horizontal => {
PlannedTextPlacement::middle(position, TextAnchor::Start, 0.0)
}
};
crate::layout::text::placement::resolve(default, plan, None)
}
pub(crate) fn validate_planned_bracket(
call: PlannedSignificanceCall<'_>,
) -> Result<CanonicalBracket, Error> {
let canonical = validate_bracket(call.bracket, call.style)?;
validate_bracket_label(canonical, call)?;
Ok(canonical)
}
pub(crate) fn validate_bracket_label(
canonical: CanonicalBracket,
call: PlannedSignificanceCall<'_>,
) -> Result<(), Error> {
let plan = &call.label.plan;
validate_text_plan(planned_bracket_placement(canonical, plan)?, plan)?;
if call.label.exact_override != plan.style.exact_override
|| call.bracket.label != plan.original_source()
|| call.style.label_color != plan.style.paint
|| !plan.same_stack(&call.style.font_family)
|| call.style.font_size.to_bits() != plan.style.font_size.to_bits()
|| call.style.weight != plan.style.weight
{
return Err(Error::Render(
"planned significance label does not match its frozen source and style".into(),
));
}
Ok(())
}
pub(crate) fn with_clip<T>(
backend: &mut dyn Backend,
region: PixelRect,
draw: impl FnOnce(&mut dyn Backend) -> Result<T, Error>,
) -> Result<T, Error> {
backend.begin_clip(region)?;
finish_scope(draw(backend), backend.end_clip(), "clip scope")
}
pub(crate) fn with_paint<T>(
backend: &mut dyn Backend,
owner: &crate::layout::PanelPath,
role: crate::layout::PaintRole,
layer: Option<crate::elements::LayerSlot>,
draw: impl FnOnce(&mut dyn Backend) -> Result<T, Error>,
) -> Result<T, Error> {
backend.begin_paint_batch(&crate::layout::PaintBatchRef::new(owner, role, layer))?;
finish_scope(
draw(backend),
backend.end_paint_batch(),
"semantic paint batch",
)
}
pub(crate) fn with_layer<T>(
backend: &mut dyn Backend,
name: &str,
draw: impl FnOnce(&mut dyn Backend) -> Result<T, Error>,
) -> Result<T, Error> {
backend.begin_layer(name)?;
finish_scope(
draw(backend),
backend.end_layer(),
&format!("layer {name:?}"),
)
}
pub(crate) fn with_layer_role<T>(
backend: &mut dyn Backend,
name: &str,
role: LayerRole,
draw: impl FnOnce(&mut dyn Backend) -> Result<T, Error>,
) -> Result<T, Error> {
backend.begin_layer_with_role(name, role)?;
finish_scope(
draw(backend),
backend.end_layer(),
&format!("layer {name:?}"),
)
}
pub(crate) fn finish_scope<T>(
primary: Result<T, Error>,
cleanup: Result<(), Error>,
scope: &str,
) -> Result<T, Error> {
match (primary, cleanup) {
(Ok(value), Ok(())) => Ok(value),
(Err(primary), Ok(())) => Err(primary),
(Ok(_), Err(cleanup)) => Err(Error::Render(
format!("failed to close {scope}: {cleanup}").into(),
)),
(Err(primary), Err(cleanup)) => match primary {
Error::Render(diagnostic) => Err(Error::Render(diagnostic.map_message(|message| {
format!("{message}; additionally failed to close {scope}: {cleanup}")
}))),
Error::Data(diagnostic) => Err(Error::Data(diagnostic.map_message(|message| {
format!("{message}; additionally failed to close {scope}: {cleanup}")
}))),
error => Err(error),
},
}
}