mirror of
https://github.com/storytold/deckcraft.git
synced 2026-12-02 02:36:14 -06:00
Merge branch 'main' into autocraft/fix-2029-line-chart-legend-key-is-a-fil
This commit is contained in:
@@ -125,10 +125,13 @@ pub fn draw(ctx: &mut RenderContext, bevel: &Bevel, fill: Option<Rgba>, path: &B
|
||||
let longest = bounds.width().max(bounds.height()) * k;
|
||||
let s = (MAX_SIDE / longest).min(1.0) * k;
|
||||
let (pw, ph) = (((bounds.width() * s).ceil() as u32).clamp(1, 2048), ((bounds.height() * s).ceil() as u32).clamp(1, 2048));
|
||||
let polys = crate::pathgrad::polygons(path);
|
||||
// Each pixel tests every edge, so a dense outline is simplified to the raster's edge budget.
|
||||
let pixel = (bounds.width() / f64::from(pw)).min(bounds.height() / f64::from(ph));
|
||||
let polys = crate::pathgrad::simplify(crate::pathgrad::polygons(path), pixel, crate::pathgrad::edge_budget(pw, ph));
|
||||
if polys.is_empty() {
|
||||
return;
|
||||
}
|
||||
let (pw, ph) = crate::pathgrad::fit_raster(polys.iter().map(|p| p.len().saturating_sub(1)).sum(), pw, ph);
|
||||
let areas: Vec<f64> = polys.iter().map(|p| p.windows(2).map(|w| w[0].x * w[1].y - w[1].x * w[0].y).sum::<f64>() / 2.0).collect();
|
||||
let face = lit.factor([0.0, 0.0, 1.0]);
|
||||
let ratio = if bevel.w > 0.0 { bevel.h / bevel.w } else { 0.0 };
|
||||
|
||||
+81
-18
@@ -113,6 +113,13 @@ fn bar_paint(ctx: &Ctx, c: &Chart, si: usize, pi: usize, s: &deckcraft_model::ch
|
||||
paint_of(ctx, s.fill.as_ref(), series_color(ctx, c, si))
|
||||
}
|
||||
|
||||
/// Colour of pie slice `i`: its `<c:dPt>` solid fill, else the palette's. Slices and legend keys share it.
|
||||
fn pie_slice_color(ctx: &Ctx, c: &Chart, s: Option<&deckcraft_model::chart::Series>, i: usize) -> Rgba {
|
||||
s.and_then(|s| s.point_fills.iter().find(|(k, _)| *k == i))
|
||||
.and_then(|(_, f)| if let Fill::Solid { color: cc } = f { Some(ctx.color(cc, None)) } else { None })
|
||||
.unwrap_or_else(|| series_color(ctx, c, i))
|
||||
}
|
||||
|
||||
fn polyline(pts: &[Point]) -> BezPath {
|
||||
let mut p = BezPath::new();
|
||||
for (k, q) in pts.iter().enumerate() {
|
||||
@@ -266,7 +273,24 @@ fn axis_ticks((lo, hi, st): (f64, f64, f64)) -> impl Iterator<Item = f64> {
|
||||
(0..=n).map(move |k| lo + k as f64 * st)
|
||||
}
|
||||
|
||||
/// Most category-by-series cells one chart draws: Excel's 255 series x 32,000 points per series
|
||||
/// (8,160,000); ordinary charts hold a few hundred.
|
||||
const MAX_CHART_CELLS: usize = 255 * 32_000;
|
||||
|
||||
/// Whether the independent category and series lists make the drawing loops multiply past the budget.
|
||||
fn over_cell_budget(c: &Chart) -> bool {
|
||||
let ncat = c.categories.len().max(c.series.iter().map(|s| s.values.len()).max().unwrap_or(0));
|
||||
cells_over_budget(ncat, c.series.len())
|
||||
}
|
||||
|
||||
fn cells_over_budget(categories: usize, series: usize) -> bool {
|
||||
categories.saturating_mul(series.max(1)) > MAX_CHART_CELLS
|
||||
}
|
||||
|
||||
pub fn draw(ctx: &mut RenderContext, rctx: &Ctx, c: &Chart, m: Affine, w: f64, h: f64) {
|
||||
if over_cell_budget(c) {
|
||||
return;
|
||||
}
|
||||
match c.kind {
|
||||
// Histograms and Pareto charts are drawn as the column (and line) chart of their bins.
|
||||
ChartType::Histogram | ChartType::Pareto => {
|
||||
@@ -493,6 +517,7 @@ fn draw_inner(ctx: &mut RenderContext, rctx: &Ctx, c: &Chart, frame: ChartFrame<
|
||||
to_axis: &to_axis,
|
||||
zero,
|
||||
base,
|
||||
text_color: text_col,
|
||||
error_marks: &mut err_marks,
|
||||
},
|
||||
);
|
||||
@@ -553,37 +578,49 @@ fn draw_legend(ctx: &mut RenderContext, draw: &LegendDraw<'_, '_>, mut area: Rec
|
||||
let width = draw.width;
|
||||
let Some(pos) = c.legend.as_ref().filter(|_| !legend_items.is_empty()) else { return area };
|
||||
let vertical = matches!(pos.as_str(), "l" | "r" | "tr");
|
||||
let item_ws: Vec<f64> = legend_items.iter().map(|(n, _, _)| n.chars().count() as f64 * base * 0.55 + base * 1.6).collect();
|
||||
// Each entry's text: its own size, weight and colour (`c:legendEntry`) over the legend's.
|
||||
let own = |i: usize| c.legend_entries.iter().find(|e| usize::try_from(e.idx).ok() == Some(i));
|
||||
let styles: Vec<(f64, bool, Rgba)> = (0..legend_items.len())
|
||||
.map(|i| {
|
||||
let e = own(i);
|
||||
let size = e.and_then(|e| e.size).filter(|v| v.is_finite() && *v > 0.0).map_or(base, |v| v.min(400.0));
|
||||
let col = e.and_then(|e| e.color.as_ref()).map_or(text_col, |cr| rctx.color(cr, None));
|
||||
(size, e.and_then(|e| e.bold).unwrap_or(false), col)
|
||||
})
|
||||
.collect();
|
||||
let item_ws: Vec<f64> = legend_items.iter().zip(&styles).map(|((n, _, _), (sz, _, _))| n.chars().count() as f64 * sz * 0.55 + sz * 1.6).collect();
|
||||
let tallest = styles.iter().map(|s| s.0).fold(base, f64::max);
|
||||
let size = if vertical {
|
||||
(item_ws.iter().copied().fold(0.0, f64::max).min(width * 0.4), legend_items.len() as f64 * base * 1.5)
|
||||
(item_ws.iter().copied().fold(0.0, f64::max).min(width * 0.4), styles.iter().map(|s| s.0 * 1.5).sum::<f64>())
|
||||
} else {
|
||||
(item_ws.iter().sum::<f64>().min(width * 0.9), base * 1.4)
|
||||
(item_ws.iter().sum::<f64>().min(width * 0.9), tallest * 1.4)
|
||||
};
|
||||
let (origin, plot_area) = legend_layout(pos, size, area, base, c.legend_overlay);
|
||||
area = plot_area;
|
||||
let (mut x, mut y) = (origin.x, origin.y);
|
||||
for (name, paint, outline) in legend_items {
|
||||
let key = Rect::new(x, y + base * 0.3, x + base * 0.7, y + base);
|
||||
for ((name, paint, outline), (sz, bold, col)) in legend_items.iter().zip(&styles) {
|
||||
let (sz, bold, col) = (*sz, *bold, *col);
|
||||
let key = Rect::new(x, y + sz * 0.3, x + sz * 0.7, y + sz);
|
||||
fill_with(ctx, paint, key, m);
|
||||
if let Some((oc, ow)) = outline.filter(|o| o.1 > 0.0) {
|
||||
ctx.set_transform(m);
|
||||
ctx.set_paint(color(oc, 1.0));
|
||||
ctx.set_stroke(kurbo::Stroke::new(ow.min(base * 0.2)));
|
||||
ctx.set_stroke(kurbo::Stroke::new(ow.min(sz * 0.2)));
|
||||
ctx.stroke_path(&key.to_path(0.1));
|
||||
}
|
||||
let tw = name.chars().count() as f64 * base * 0.55 + base;
|
||||
let tw = name.chars().count() as f64 * sz * 0.55 + sz;
|
||||
label(
|
||||
ctx,
|
||||
rctx,
|
||||
m,
|
||||
name,
|
||||
Rect::new(x + base, y, x + base + tw, y + base * 1.3),
|
||||
LabelStyle { size: base, align: Align::Left, anchor: Anchor::Middle, col: text_col, bold: false },
|
||||
Rect::new(x + sz, y, x + sz + tw, y + sz * 1.3),
|
||||
LabelStyle { size: sz, align: Align::Left, anchor: Anchor::Middle, col, bold },
|
||||
);
|
||||
if vertical {
|
||||
y += base * 1.5;
|
||||
y += sz * 1.5;
|
||||
} else {
|
||||
x += tw + base * 0.6;
|
||||
x += tw + sz * 0.6;
|
||||
}
|
||||
}
|
||||
area
|
||||
@@ -599,7 +636,7 @@ fn build_legend_items(rctx: &Ctx, c: &Chart, pie: bool, waterfall: bool) -> Vec<
|
||||
// A map draws its own colour scale.
|
||||
vec![]
|
||||
} else if pie {
|
||||
c.categories.iter().enumerate().map(|(i, n)| (n.clone(), Paint::Color(series_color(rctx, c, i)), None)).collect()
|
||||
c.categories.iter().enumerate().map(|(i, n)| (n.clone(), Paint::Color(pie_slice_color(rctx, c, c.series.first(), i)), None)).collect()
|
||||
} else {
|
||||
c.series
|
||||
.iter()
|
||||
@@ -880,6 +917,7 @@ struct LineDrawing<'a, 'ctx> {
|
||||
to_axis: &'a dyn Fn(bool, f64) -> f64,
|
||||
zero: f64,
|
||||
base: f64,
|
||||
text_color: Rgba,
|
||||
error_marks: &'a mut Vec<(f64, f64, f64, f64, bool)>,
|
||||
}
|
||||
|
||||
@@ -908,10 +946,13 @@ fn draw_lines(ctx: &mut RenderContext, draw: &mut LineDrawing<'_, '_>) {
|
||||
let col = if area_kind { series_fill(rctx, c, si, Some(s)) } else { series_line(rctx, c, si, s) };
|
||||
let series_stats = s.error_bars.as_ref().map(|_| deckcraft_model::chart::SeriesStats::of(&s.values));
|
||||
let mut pts = vec![];
|
||||
// Each point's own value (not the stacked total), for its data label.
|
||||
let mut values = vec![];
|
||||
// Whether the series has any x value, found once rather than per point.
|
||||
let any_x = s.x_values.iter().flatten().next().is_some();
|
||||
for i in 0..ncat {
|
||||
let Some(v) = s.values.get(i).copied().flatten() else { continue };
|
||||
let own = v;
|
||||
let v = if stacked {
|
||||
let base_v = acc.get(i).copied().unwrap_or(0.0);
|
||||
if let Some(a) = acc.get_mut(i) {
|
||||
@@ -936,6 +977,7 @@ fn draw_lines(ctx: &mut RenderContext, draw: &mut LineDrawing<'_, '_>) {
|
||||
err_marks.push((x, to_axis(sec, lo), to_axis(sec, hi), base * 0.4, s.error_bars.as_ref().is_some_and(|e| e.end_cap)));
|
||||
}
|
||||
pts.push(Point::new(x, to_axis(sec, v)));
|
||||
values.push(own);
|
||||
}
|
||||
if pts.is_empty() {
|
||||
continue;
|
||||
@@ -963,6 +1005,22 @@ fn draw_lines(ctx: &mut RenderContext, draw: &mut LineDrawing<'_, '_>) {
|
||||
ctx.fill_path(&kurbo::Circle::new(*q, 3.5).to_path(0.1));
|
||||
}
|
||||
}
|
||||
// A line series that asks for value labels (`c:dLbls/c:showVal`) shows each point's value
|
||||
// just above it, as bars do theirs (#2066). Area series keep none (theirs sit inside the
|
||||
// area), and scatter and bubble series, which also come here, are left as they were.
|
||||
if matches!(kind, ChartType::Line | ChartType::LineMarkers | ChartType::StackedLine) && c.series_data_labels(s) {
|
||||
let gap = base * 0.3 + 3.5;
|
||||
for (q, v) in pts.iter().zip(&values) {
|
||||
label(
|
||||
ctx,
|
||||
rctx,
|
||||
m,
|
||||
&c.data_label(s, *v),
|
||||
Rect::new(q.x - 40.0, q.y - gap - base * 1.4, q.x + 40.0, q.y - gap),
|
||||
LabelStyle { size: base * 0.9, align: Align::Center, anchor: Anchor::Bottom, col: draw.text_color, bold: false },
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1151,12 +1209,7 @@ fn draw_pie(ctx: &mut RenderContext, rctx: &Ctx, c: &Chart, m: Affine, area: Rec
|
||||
p.extend(arc.append_iter(0.1));
|
||||
p.close_path();
|
||||
ctx.set_transform(m);
|
||||
let col = s
|
||||
.point_fills
|
||||
.iter()
|
||||
.find(|(k, _)| *k == i)
|
||||
.and_then(|(_, f)| if let Fill::Solid { color: cc } = f { Some(rctx.color(cc, None)) } else { None })
|
||||
.unwrap_or_else(|| series_color(rctx, c, i));
|
||||
let col = pie_slice_color(rctx, c, Some(s), i);
|
||||
ctx.set_paint(color(col, 1.0));
|
||||
ctx.fill_path(&p);
|
||||
ctx.set_paint(color(Rgba::WHITE, 1.0));
|
||||
@@ -1448,6 +1501,16 @@ mod tests {
|
||||
|
||||
const AREA: Rect = Rect::new(0.0, 0.0, 400.0, 300.0);
|
||||
|
||||
#[test]
|
||||
fn category_by_series_cells_are_budgeted() {
|
||||
assert!(!over_cell_budget(&Chart::sample(ChartType::Column)));
|
||||
// Excel's maximum chart (255 series x 32,000 points) is within the budget; one more point is not.
|
||||
assert_eq!(MAX_CHART_CELLS, 8_160_000);
|
||||
assert!(!cells_over_budget(32_000, 255));
|
||||
assert!(cells_over_budget(32_001, 255));
|
||||
assert!(cells_over_budget(usize::MAX, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiny_data_gets_several_ticks() {
|
||||
let sc = deckcraft_model::chart::axis_scale(1e-13, 5e-13, None, None, None, 8, true);
|
||||
|
||||
@@ -11,6 +11,8 @@ use vello_cpu::{RenderContext, peniko};
|
||||
|
||||
/// Nesting depth of clips and layers past which a glyph opens no more (hostile fonts).
|
||||
const MAX_DEPTH: usize = 64;
|
||||
/// Fills and gradient stops one colour glyph may paint; the rest of a hostile glyph is skipped.
|
||||
const MAX_WORK: usize = 100_000;
|
||||
|
||||
/// Paint `gid` of `face` as a colour glyph, its origin mapped by `at` (y down, points) at `scale`
|
||||
/// points per font unit. `fg` is the text colour (palette index 0xFFFF) and `alpha` fades it all.
|
||||
@@ -26,7 +28,7 @@ pub fn paint(ctx: &mut RenderContext, face: &FontFace, gid: u32, at: Affine, sca
|
||||
.unwrap_or_default();
|
||||
// Font units are y up; the slide is y down.
|
||||
let base = at * Affine::scale(scale) * Affine::scale_non_uniform(1.0, -1.0);
|
||||
let mut p = Painter { ctx, face, base, stack: vec![Affine::IDENTITY], palette, fg, opened: Vec::new() };
|
||||
let mut p = Painter { ctx, face, base, stack: vec![Affine::IDENTITY], palette, fg, opened: Vec::new(), work: 0 };
|
||||
p.ctx.push_layer(None, None, Some(alpha.clamp(0.0, 1.0) as f32), None, None);
|
||||
let ok = glyph.paint(face.location(), &mut p).is_ok();
|
||||
// A malformed glyph may leave layers open: close them all.
|
||||
@@ -50,6 +52,8 @@ struct Painter<'a> {
|
||||
/// Clips and composite groups pushed by the glyph, innermost last: true when a layer was
|
||||
/// opened on the context for it (false past `MAX_DEPTH`, so its pop is skipped too).
|
||||
opened: Vec<bool>,
|
||||
/// Fills plus gradient stops painted so far, against [`MAX_WORK`].
|
||||
work: usize,
|
||||
}
|
||||
|
||||
fn affine(t: &Transform) -> Affine {
|
||||
@@ -174,6 +178,16 @@ impl ColorPainter for Painter<'_> {
|
||||
}
|
||||
|
||||
fn fill(&mut self, brush: Brush<'_>) {
|
||||
let stops = match &brush {
|
||||
Brush::Solid { .. } => 0,
|
||||
Brush::LinearGradient { color_stops, .. } | Brush::RadialGradient { color_stops, .. } | Brush::SweepGradient { color_stops, .. } => {
|
||||
color_stops.len()
|
||||
}
|
||||
};
|
||||
self.work = self.work.saturating_add(1 + stops);
|
||||
if self.work > MAX_WORK {
|
||||
return;
|
||||
}
|
||||
match brush {
|
||||
Brush::Solid { palette_index, alpha } => {
|
||||
let c = self.color(palette_index, alpha);
|
||||
|
||||
@@ -97,6 +97,9 @@ mod tests_wild;
|
||||
#[cfg(test)]
|
||||
mod tests_effect_holes;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_placed_group;
|
||||
|
||||
#[cfg(test)]
|
||||
mod mt_tests {
|
||||
use super::*;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Windows Metafile and Enhanced Metafile pictures (`image/x-wmf`, `image/x-emf`): parsed by
|
||||
//! `deckcraft-metafile` and drawn as vectors into a bitmap of the size the slide needs, so they go
|
||||
//! `craft-metafile` and drawn as vectors into a bitmap of the size the slide needs, so they go
|
||||
//! through the same crop, tile and recolour path as any other picture.
|
||||
//!
|
||||
//! Text items name the font the file asks for; they are drawn with the face slide text would use
|
||||
@@ -10,8 +10,8 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_metafile::{Cap, HAlign, Item, Join, LineStyle, PlacedClip, PlacedItem, Text, Tile, VAlign};
|
||||
use deckcraft_fonts::{FontDb, FontFace};
|
||||
use deckcraft_metafile::{HAlign, Item, PlacedItem, Text, Tile, VAlign};
|
||||
use kurbo::{Affine, BezPath, Rect, Shape as _};
|
||||
use skrifa::MetadataProvider as _;
|
||||
use vello_cpu::{Pixmap, RenderContext, Resources, peniko};
|
||||
@@ -28,13 +28,13 @@ const DEFAULT_EM: f64 = 12.0;
|
||||
|
||||
/// Is `bytes` a WMF or EMF file?
|
||||
pub fn is_metafile(bytes: &[u8]) -> bool {
|
||||
deckcraft_metafile::is_metafile(bytes)
|
||||
craft_metafile::is_metafile(bytes)
|
||||
}
|
||||
|
||||
/// Draw the metafile `bytes` into straight RGBA with its longer side `side` px (transparent where
|
||||
/// it draws nothing). `None` when it doesn't parse or has no size.
|
||||
pub fn rasterize(bytes: &[u8], side: u32) -> Option<image::RgbaImage> {
|
||||
let mut pic = deckcraft_metafile::parse(bytes).ok()?;
|
||||
let mut pic = craft_metafile::parse(bytes).ok()?;
|
||||
if !pic.has_size() {
|
||||
return None;
|
||||
}
|
||||
@@ -51,31 +51,39 @@ pub fn rasterize(bytes: &[u8], side: u32) -> Option<image::RgbaImage> {
|
||||
ctx.push_clip_layer(&r.to_path(0.1));
|
||||
for it in pic.place(r, [0.0; 4]) {
|
||||
match it {
|
||||
PlacedItem::Path { path, fill, stroke, even_odd, region } => clipped(&mut ctx, region.as_deref(), |ctx| {
|
||||
PlacedItem::Path { path, fill, stroke, line, even_odd, region, clips } => clipped(&mut ctx, region.as_deref(), &clips, |ctx| {
|
||||
if let Some(f) = fill {
|
||||
ctx.set_paint(rgba(f));
|
||||
ctx.set_fill_rule(if even_odd { peniko::Fill::EvenOdd } else { peniko::Fill::NonZero });
|
||||
ctx.fill_path(&path);
|
||||
}
|
||||
// GDI pens: round caps and joins; a cosmetic (zero-width) pen is one pixel.
|
||||
// The pen's caps, joins and dashes (GDI's default: round, solid); a cosmetic
|
||||
// (zero-width) pen is one pixel.
|
||||
if let Some((s, sw)) = stroke {
|
||||
ctx.set_paint(rgba(s));
|
||||
ctx.set_stroke(kurbo::Stroke::new(sw.max(1.0)).with_caps(kurbo::Cap::Round).with_join(kurbo::Join::Round));
|
||||
ctx.set_stroke(pen(sw.max(1.0), &line));
|
||||
ctx.stroke_path(&path);
|
||||
}
|
||||
}),
|
||||
PlacedItem::Bitmap { index, rect, region } => clipped(&mut ctx, region.as_deref(), |ctx| {
|
||||
PlacedItem::Bitmap { index, rect, transform, region, clips } => clipped(&mut ctx, region.as_deref(), &clips, |ctx| {
|
||||
let Some(Some(pm)) = pixmaps.get(index) else { return };
|
||||
let (bw, bh) = (pm.width().max(1) as f64, pm.height().max(1) as f64);
|
||||
ctx.set_paint(vello_cpu::Image {
|
||||
image: vello_cpu::ImageSource::Pixmap(pm.clone()),
|
||||
sampler: peniko::ImageSampler::default().with_quality(peniko::ImageQuality::Medium),
|
||||
});
|
||||
ctx.set_paint_transform(Affine::translate((rect.x0, rect.y0)) * Affine::scale_non_uniform(rect.width() / bw, rect.height() / bh));
|
||||
ctx.fill_rect(&rect);
|
||||
let c = transform.as_coeffs();
|
||||
if c[1] == 0.0 && c[2] == 0.0 {
|
||||
ctx.set_paint_transform(Affine::translate((rect.x0, rect.y0)) * Affine::scale_non_uniform(rect.width() / bw, rect.height() / bh));
|
||||
ctx.fill_rect(&rect);
|
||||
} else {
|
||||
// A turned or skewed bitmap: `transform` maps the unit square onto its place.
|
||||
ctx.set_paint_transform(transform * Affine::scale_non_uniform(1.0 / bw, 1.0 / bh));
|
||||
ctx.fill_path(&(transform * Rect::new(0.0, 0.0, 1.0, 1.0).to_path(0.1)));
|
||||
}
|
||||
ctx.reset_paint_transform();
|
||||
}),
|
||||
PlacedItem::Pattern { index, path, even_odd, tile, region } => clipped(&mut ctx, region.as_deref(), |ctx| {
|
||||
PlacedItem::Pattern { index, path, even_odd, tile, region, clips } => clipped(&mut ctx, region.as_deref(), &clips, |ctx| {
|
||||
let Some(Item::Pattern { tile: t, .. }) = pic.items.get(index) else { return };
|
||||
let key = Arc::as_ptr(t);
|
||||
let (pm, avg) = tiles.entry(key).or_insert_with(|| (premul(t.width, t.height, &t.rgba), average(&t.rgba))).clone();
|
||||
@@ -102,7 +110,7 @@ pub fn rasterize(bytes: &[u8], side: u32) -> Option<image::RgbaImage> {
|
||||
}
|
||||
}
|
||||
}),
|
||||
PlacedItem::Text { index, transform, clip, region } => clipped(&mut ctx, region.as_deref(), |ctx| {
|
||||
PlacedItem::Text { index, transform, clip, region, clips } => clipped(&mut ctx, region.as_deref(), &clips, |ctx| {
|
||||
let Some(Item::Text(t)) = pic.items.get(index) else { return };
|
||||
if let Some(c) = clip {
|
||||
ctx.push_clip_layer(&c.to_path(0.1));
|
||||
@@ -133,15 +141,40 @@ pub fn rasterize(bytes: &[u8], side: u32) -> Option<image::RgbaImage> {
|
||||
image::RgbaImage::from_raw(w as u32, h as u32, px)
|
||||
}
|
||||
|
||||
/// Draws `draw` inside the device-context clip. No region is the default clip.
|
||||
fn clipped(ctx: &mut RenderContext, region: Option<&BezPath>, draw: impl FnOnce(&mut RenderContext)) {
|
||||
/// Draws `draw` inside the device-context clip and every clip path. No region is the default clip.
|
||||
fn clipped(ctx: &mut RenderContext, region: Option<&BezPath>, clips: &[Arc<PlacedClip>], draw: impl FnOnce(&mut RenderContext)) {
|
||||
if let Some(region) = region {
|
||||
ctx.push_clip_layer(region);
|
||||
draw(ctx);
|
||||
ctx.pop_layer();
|
||||
} else {
|
||||
draw(ctx);
|
||||
}
|
||||
for c in clips {
|
||||
ctx.set_fill_rule(if c.even_odd { peniko::Fill::EvenOdd } else { peniko::Fill::NonZero });
|
||||
ctx.push_clip_layer(&c.path);
|
||||
}
|
||||
if !clips.is_empty() {
|
||||
ctx.set_fill_rule(peniko::Fill::NonZero);
|
||||
}
|
||||
draw(ctx);
|
||||
for _ in 0..clips.len() + usize::from(region.is_some()) {
|
||||
ctx.pop_layer();
|
||||
}
|
||||
}
|
||||
|
||||
/// A GDI pen as a stroke `width` wide (target units): its caps, joins, miter limit and dashes.
|
||||
fn pen(width: f64, line: &LineStyle) -> kurbo::Stroke {
|
||||
let cap = match line.cap {
|
||||
Cap::Round => kurbo::Cap::Round,
|
||||
Cap::Square => kurbo::Cap::Square,
|
||||
Cap::Flat => kurbo::Cap::Butt,
|
||||
};
|
||||
let join = match line.join {
|
||||
Join::Round => kurbo::Join::Round,
|
||||
Join::Bevel => kurbo::Join::Bevel,
|
||||
Join::Miter => kurbo::Join::Miter,
|
||||
};
|
||||
let stroke = kurbo::Stroke::new(width).with_caps(cap).with_join(join).with_miter_limit(f64::from(line.miter_limit));
|
||||
// A dash pattern with no length would never advance: such a pen draws solid.
|
||||
let dash: Vec<f64> = line.dash.iter().map(|d| f64::from(*d)).collect();
|
||||
if dash.iter().all(|d| d.is_finite() && *d >= 0.0) && dash.iter().sum::<f64>() > 0.0 { stroke.with_dashes(0.0, dash) } else { stroke }
|
||||
}
|
||||
|
||||
/// One glyph placed in text space (x along the baseline from the string's start, font units at
|
||||
|
||||
+139
-27
@@ -25,6 +25,39 @@ const MAX_EDGE_WORK: u64 = 64_000_000;
|
||||
/// Fewest edges a simplified polygon keeps, so a coarse outline still has a shape.
|
||||
const MIN_POLY_EDGES: usize = 8;
|
||||
|
||||
/// Most points `polygons` keeps from one path; a path flattening past this (a huge finite curve) is
|
||||
/// not drawn rather than held in memory first.
|
||||
const MAX_POINTS: usize = 2_000_000;
|
||||
|
||||
/// Quads beyond one per cubic that a path's cubics may subdivide into before [`polygons`] refuses it.
|
||||
const MAX_EXTRA_QUADS: f64 = 200_000.0;
|
||||
|
||||
/// Flattening tolerance of [`polygons`], in path units.
|
||||
const FLATTEN_TOLERANCE: f64 = 0.25;
|
||||
|
||||
/// The edge budget for a `pw` x `ph` raster where each pixel tests every edge.
|
||||
pub(crate) fn edge_budget(pw: u32, ph: u32) -> usize {
|
||||
let pixels = u64::from(pw).saturating_mul(u64::from(ph)).max(1);
|
||||
usize::try_from(MAX_EDGE_WORK / pixels).unwrap_or(usize::MAX).max(MIN_POLY_EDGES)
|
||||
}
|
||||
|
||||
/// `pw` x `ph` cut down (aspect kept) until every pixel testing all of `edges` stays within
|
||||
/// [`MAX_EDGE_WORK`]; the raster is stretched when painted, so a many-contour outline keeps every
|
||||
/// contour at a coarser sampling.
|
||||
pub(crate) fn fit_raster(edges: usize, pw: u32, ph: u32) -> (u32, u32) {
|
||||
let work = u64::from(pw).saturating_mul(u64::from(ph)).saturating_mul(edges.max(1) as u64);
|
||||
if work <= MAX_EDGE_WORK {
|
||||
return (pw, ph);
|
||||
}
|
||||
let k = (MAX_EDGE_WORK as f64 / work as f64).sqrt();
|
||||
let w = ((f64::from(pw) * k) as u32).max(1);
|
||||
let h = ((f64::from(ph) * k) as u32).max(1);
|
||||
// A side held at 1 pixel leaves the other to take the rest of the cut.
|
||||
let room = |side: u32| u32::try_from(MAX_EDGE_WORK / u64::from(side).saturating_mul(edges.max(1) as u64).max(1)).unwrap_or(u32::MAX).max(1);
|
||||
let w = w.min(room(h));
|
||||
(w, h.min(room(w)))
|
||||
}
|
||||
|
||||
/// Colour position (0 at the focus, 1 at the edge) of `p` for path `kind` in `bounds` with the
|
||||
/// focus rect `focus` (fractions inset from left, top, right, bottom), `outline` being the
|
||||
/// shape's flattened polygon(s) for `shape`.
|
||||
@@ -112,23 +145,59 @@ fn shape_position(outline: &[Vec<Point>], c: Point, p: Point) -> f64 {
|
||||
|
||||
/// The outline flattened into closed polygons.
|
||||
pub fn polygons(path: &BezPath) -> Vec<Vec<Point>> {
|
||||
// `kurbo::flatten` buffers all of a cubic's quads before calling back, and cannot be stopped
|
||||
// once running, so bound the quads the cubics will make first (kurbo's own count: it splits
|
||||
// cubics into quads at a tenth of the tolerance). An ordinary curve makes a few; only those
|
||||
// past the first of each count.
|
||||
let mut extra_quads = 0.0f64;
|
||||
let mut at = Point::ZERO;
|
||||
let mut start = Point::ZERO;
|
||||
for el in path.iter() {
|
||||
match el {
|
||||
PathEl::MoveTo(p) => {
|
||||
at = p;
|
||||
start = p;
|
||||
}
|
||||
PathEl::LineTo(p) | PathEl::QuadTo(_, p) => at = p,
|
||||
PathEl::CurveTo(a, b, p) => {
|
||||
let err = ((b.to_vec2() * 3.0 - p.to_vec2()) - (a.to_vec2() * 3.0 - at.to_vec2())).hypot2();
|
||||
extra_quads += (err / (432.0 * (FLATTEN_TOLERANCE * 0.1).powi(2))).powf(1.0 / 6.0).ceil().max(1.0) - 1.0;
|
||||
// A non-finite estimate is over the limit too.
|
||||
if extra_quads.is_nan() || extra_quads > MAX_EXTRA_QUADS {
|
||||
return Vec::new();
|
||||
}
|
||||
at = p;
|
||||
}
|
||||
PathEl::ClosePath => at = start,
|
||||
}
|
||||
}
|
||||
let mut out: Vec<Vec<Point>> = Vec::new();
|
||||
let mut cur: Vec<Point> = Vec::new();
|
||||
kurbo::flatten(path.iter(), 0.25, |el| match el {
|
||||
PathEl::MoveTo(p) => {
|
||||
if cur.len() > 1 {
|
||||
out.push(std::mem::take(&mut cur));
|
||||
}
|
||||
cur = vec![p];
|
||||
let mut total = 0usize;
|
||||
kurbo::flatten(path.iter(), FLATTEN_TOLERANCE, |el| {
|
||||
total += 1;
|
||||
if total > MAX_POINTS {
|
||||
return;
|
||||
}
|
||||
PathEl::LineTo(p) => cur.push(p),
|
||||
PathEl::ClosePath => {
|
||||
if let Some(f) = cur.first().copied() {
|
||||
cur.push(f);
|
||||
match el {
|
||||
PathEl::MoveTo(p) => {
|
||||
if cur.len() > 1 {
|
||||
out.push(std::mem::take(&mut cur));
|
||||
}
|
||||
cur = vec![p];
|
||||
}
|
||||
PathEl::LineTo(p) => cur.push(p),
|
||||
PathEl::ClosePath => {
|
||||
if let Some(f) = cur.first().copied() {
|
||||
cur.push(f);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
if total > MAX_POINTS {
|
||||
return Vec::new();
|
||||
}
|
||||
if cur.len() > 1 {
|
||||
out.push(cur);
|
||||
}
|
||||
@@ -145,8 +214,9 @@ pub fn polygons(path: &BezPath) -> Vec<Vec<Point>> {
|
||||
|
||||
/// `outline` cut down to at most about `max_edges` edges in total: first by dropping points
|
||||
/// closer than `tol` to the last kept one (detail finer than a raster pixel), then, if still too
|
||||
/// many, by keeping every k-th point. Each polygon stays closed. Returns it unchanged when it fits.
|
||||
fn simplify(outline: Vec<Vec<Point>>, tol: f64, max_edges: usize) -> Vec<Vec<Point>> {
|
||||
/// many, by keeping every k-th point (a polygon too small to thin stays whole, and none is
|
||||
/// dropped). Each polygon stays closed. Returns it unchanged when it fits.
|
||||
pub(crate) fn simplify(outline: Vec<Vec<Point>>, tol: f64, max_edges: usize) -> Vec<Vec<Point>> {
|
||||
let edges = |o: &[Vec<Point>]| o.iter().map(|p| p.len().saturating_sub(1)).sum::<usize>();
|
||||
if edges(&outline) <= max_edges {
|
||||
return outline;
|
||||
@@ -189,15 +259,8 @@ fn simplify(outline: Vec<Vec<Point>>, tol: f64, max_edges: usize) -> Vec<Vec<Poi
|
||||
}
|
||||
*poly = kept;
|
||||
}
|
||||
// Polygons too small to thin stay whole; drop the smallest ones if they alone overflow.
|
||||
if edges(&out) > max_edges {
|
||||
out.sort_by_key(|p| std::cmp::Reverse(p.len()));
|
||||
let mut sum = 0usize;
|
||||
out.retain(|p| {
|
||||
sum = sum.saturating_add(p.len().saturating_sub(1));
|
||||
sum <= max_edges
|
||||
});
|
||||
}
|
||||
// Polygons too small to thin stay whole, so the total can still exceed `max_edges`: the
|
||||
// caller shrinks its raster ([`fit_raster`]) rather than lose contours.
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -232,14 +295,20 @@ pub fn fill(ctx: &mut RenderContext, kind: &str, focus: [f64; 4], stops: &[(f64,
|
||||
let longest = bounds.width().max(bounds.height()) * k;
|
||||
let s = (MAX_SIDE / longest).min(1.0) * k;
|
||||
let (pw, ph) = (((bounds.width() * s).ceil() as u32).clamp(1, 4096), ((bounds.height() * s).ceil() as u32).clamp(1, 4096));
|
||||
let outline = if kind == "shape" {
|
||||
let pixels = u64::from(pw).saturating_mul(u64::from(ph)).max(1);
|
||||
let max_edges = usize::try_from(MAX_EDGE_WORK / pixels).unwrap_or(usize::MAX).max(MIN_POLY_EDGES);
|
||||
let (outline, pw, ph) = if kind == "shape" {
|
||||
let max_edges = edge_budget(pw, ph);
|
||||
let pixel = (bounds.width() / f64::from(pw)).min(bounds.height() / f64::from(ph));
|
||||
simplify(polygons(path), pixel, max_edges)
|
||||
let o = simplify(polygons(path), pixel, max_edges);
|
||||
let (pw, ph) = fit_raster(o.iter().map(|p| p.len().saturating_sub(1)).sum(), pw, ph);
|
||||
(o, pw, ph)
|
||||
} else {
|
||||
Vec::new()
|
||||
(Vec::new(), pw, ph)
|
||||
};
|
||||
// An outline `polygons` refused (too many points) has no contours: skip the shape rather than
|
||||
// paint it with the rectangle fallback's different gradient.
|
||||
if kind == "shape" && outline.is_empty() {
|
||||
return;
|
||||
}
|
||||
let lut = ramp(stops);
|
||||
let a = alpha.clamp(0.0, 1.0);
|
||||
let mut data = Vec::with_capacity((pw * ph) as usize);
|
||||
@@ -372,6 +441,20 @@ mod tests {
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(20), "{:?}", t.elapsed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_gradient_with_no_usable_outline_paints_nothing() {
|
||||
// One polygon over the per-polygon cap is dropped by `polygons`.
|
||||
let path = many_segment_square(26_000);
|
||||
assert!(polygons(&path).is_empty());
|
||||
let mut ctx = RenderContext::new(64, 64);
|
||||
let stops = [(0.0, Rgba::rgb(0, 0, 0)), (1.0, Rgba::rgb(255, 255, 255))];
|
||||
fill(&mut ctx, "shape", CENTRE, &stops, Rect::new(0.0, 0.0, 64.0, 64.0), &path, Affine::IDENTITY, 1.0);
|
||||
ctx.flush();
|
||||
let mut px = vec![0u8; 64 * 64 * 4];
|
||||
ctx.render(vello_cpu::PixmapMut::new(64, 64, &mut px).unwrap(), &mut vello_cpu::Resources::new());
|
||||
assert!(px.chunks(4).all(|p| p[3] == 0), "nothing was painted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ramp_runs_through_the_stops() {
|
||||
let stops = [(0.0, Rgba::rgb(0, 0, 0)), (0.5, Rgba::rgb(128, 128, 128)), (1.0, Rgba::rgb(255, 255, 255))];
|
||||
@@ -382,4 +465,33 @@ mod tests {
|
||||
assert!((r[64].r as i32 - 64).abs() <= 2);
|
||||
assert!(ramp(&[(0.3, Rgba::rgb(9, 9, 9))]).iter().all(|c| *c == Rgba::rgb(9, 9, 9)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn huge_cubics_are_refused_before_flattening() {
|
||||
let mut p = BezPath::new();
|
||||
p.move_to((0.0, 0.0));
|
||||
// About 250,000 quads each: over the limit.
|
||||
for _ in 0..3 {
|
||||
p.curve_to((1e15, -1e15), (-1e15, 1e15), (1.0, 1.0));
|
||||
}
|
||||
p.close_path();
|
||||
assert!(polygons(&p).is_empty());
|
||||
// A cubic of ordinary size still flattens.
|
||||
let mut q = BezPath::new();
|
||||
q.move_to((0.0, 0.0));
|
||||
q.curve_to((100.0, 0.0), (100.0, 100.0), (0.0, 100.0));
|
||||
q.close_path();
|
||||
assert_eq!(polygons(&q).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_contours_keep_every_contour_at_a_coarser_raster() {
|
||||
let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 1.0, 0.0), Point::new(x + 1.0, 1.0), Point::new(x, 1.0), Point::new(x, 0.0)];
|
||||
let polys: Vec<Vec<Point>> = (0..100).map(|i| square(f64::from(i) * 2.0)).collect();
|
||||
let simple = simplify(polys, 0.001, 244);
|
||||
assert_eq!(simple.len(), 100, "no contour is dropped");
|
||||
let (pw, ph) = fit_raster(400, 512, 512);
|
||||
assert!(u64::from(pw) * u64::from(ph) * 400 <= MAX_EDGE_WORK && pw > 100, "{pw}x{ph}");
|
||||
assert_eq!(fit_raster(200, 512, 512), (512, 512));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,10 @@ use crate::{SlideFields, shape_geometry, table};
|
||||
/// One shape's text as drawn on the slide.
|
||||
pub struct PlacedText {
|
||||
pub layout: TextLayout,
|
||||
/// Shape-local → slide points (text rotation included, flips not: see [`crate::text_transform`]).
|
||||
/// Text-local → slide points (text rotation included, flips not: see [`crate::text_transform`]).
|
||||
/// Text-local space is the shape's own space, except inside a group whose child coordinates
|
||||
/// scale the shape: there the text is set at the shape's size on the slide, as the renderer
|
||||
/// draws it, so font sizes and insets stay in points.
|
||||
pub transform: Affine,
|
||||
pub body: TextBody,
|
||||
}
|
||||
@@ -149,13 +152,15 @@ fn place(out: &mut Placed, rctx: &Ctx, fields: &SlideFields, s: &Shape, parent:
|
||||
ShapeKind::Chart(_) | ShapeKind::Ink { .. } => {}
|
||||
_ => {
|
||||
let Some(body) = s.text.as_ref().filter(|b| !b.is_empty()) else { return };
|
||||
let tr = shape_geometry(s, x.w, x.h).text_rect;
|
||||
place_text(out, rctx, fields, s.id, s, body, tr, m);
|
||||
// Placed space is slide points, so `m` is also the shape's transform relative to them.
|
||||
let (tw, th, tm) = text_space(m, m, depth, x.w, x.h);
|
||||
let tr = shape_geometry(s, tw, th).text_rect;
|
||||
place_text(out, rctx, fields, s.id, s, body, tr, tm);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Lay out `body` in text rect `tr` of shape `s` (shape-local → slide `m`) and record it and its hyperlinks.
|
||||
/// Lay out `body` in text rect `tr` of shape `s` (text-local → slide `m`) and record it and its hyperlinks.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn place_text(out: &mut Placed, rctx: &Ctx, fields: &SlideFields, owner: ShapeId, s: &Shape, body: &TextBody, tr: Rect, m: Affine) {
|
||||
let layout = deckcraft_text::layout(rctx, s, body, &Opts { rect: tr, fields, prompt_color: None, no_shrink: false });
|
||||
@@ -188,6 +193,25 @@ fn place_text(out: &mut Placed, rctx: &Ctx, fields: &SlideFields, owner: ShapeId
|
||||
out.texts.push(PlacedText { layout, transform: m, body: placed });
|
||||
}
|
||||
|
||||
/// The size and transform a shape's text is set in. `rel` is the shape's transform relative to
|
||||
/// slide points and `m` the one its text is drawn under; `depth` is its group nesting. Inside a
|
||||
/// group whose child coordinates scale the shape, the text is set at the shape's size in slide
|
||||
/// points under `m` with that scale taken out, so insets and font sizes stay in points; otherwise
|
||||
/// in `w` × `h` under `m` itself.
|
||||
pub(crate) fn text_space(rel: Affine, m: Affine, depth: usize, w: f64, h: f64) -> (f64, f64, Affine) {
|
||||
let c = rel.as_coeffs();
|
||||
let (sx, sy) = (c[0].hypot(c[1]), c[2].hypot(c[3]));
|
||||
let ok = |k: f64| k.is_finite() && k > 1e-9;
|
||||
if depth == 0 || !ok(sx) || !ok(sy) || ((sx - 1.0).abs() < 1e-9 && (sy - 1.0).abs() < 1e-9) {
|
||||
return (w, h, m);
|
||||
}
|
||||
let (tw, th) = (w * sx, h * sy);
|
||||
if !tw.is_finite() || !th.is_finite() {
|
||||
return (w, h, m);
|
||||
}
|
||||
(tw, th, m * Affine::scale_non_uniform(1.0 / sx, 1.0 / sy))
|
||||
}
|
||||
|
||||
/// The hyperlink of the model run containing character `at` of paragraph `para`.
|
||||
fn run_link(body: &TextBody, para: usize, at: usize) -> Option<Hyperlink> {
|
||||
let p = body.paragraphs.get(para)?;
|
||||
|
||||
@@ -368,17 +368,7 @@ impl Renderer {
|
||||
/// insets and font sizes stay in points; otherwise `w`, `h` and `m` themselves.
|
||||
fn text_space(&self, m: Affine, depth: usize, w: f64, h: f64) -> (f64, f64, Affine) {
|
||||
let (_, rel) = self.line_space(m, depth);
|
||||
let c = rel.as_coeffs();
|
||||
let (sx, sy) = (c[0].hypot(c[1]), c[2].hypot(c[3]));
|
||||
let ok = |k: f64| k.is_finite() && k > 1e-9;
|
||||
if depth == 0 || !ok(sx) || !ok(sy) || ((sx - 1.0).abs() < 1e-9 && (sy - 1.0).abs() < 1e-9) {
|
||||
return (w, h, m);
|
||||
}
|
||||
let (tw, th) = (w * sx, h * sy);
|
||||
if !tw.is_finite() || !th.is_finite() {
|
||||
return (w, h, m);
|
||||
}
|
||||
(tw, th, m * Affine::scale_non_uniform(1.0 / sx, 1.0 / sy))
|
||||
crate::placed::text_space(rel, m, depth, w, h)
|
||||
}
|
||||
|
||||
/// A shape's geometry in its own `w` × `h` space, built at its size on the slide: inside a
|
||||
@@ -784,8 +774,15 @@ impl Renderer {
|
||||
match &s.kind {
|
||||
ShapeKind::Picture { fill: pf } => {
|
||||
// The picture's own fill shows behind its transparent pixels, as in PowerPoint (an
|
||||
// emphasis tint recolours it, as it does any shape's fill).
|
||||
if s.fill.as_ref().is_some_and(|f| !f.is_none())
|
||||
// emphasis tint recolours it, as it does any shape's fill). A picture that sets
|
||||
// neither a fill nor a style shows the fill its layout or master placeholder sets
|
||||
// (#2068). A style fill alone, its own or inherited, stays undrawn.
|
||||
let explicit = |sh: &deckcraft_model::Shape| sh.fill.as_ref().is_some_and(|f| !f.is_none());
|
||||
let inherited = || {
|
||||
let (lp, mp) = resolve::parents(rctx, s);
|
||||
[lp, mp].into_iter().flatten().find(|p| p.fill.is_some() || p.style.is_some()).is_some_and(explicit)
|
||||
};
|
||||
if (explicit(s) || (s.fill.is_none() && s.style.is_none() && inherited()))
|
||||
&& let Some(fl) = &fill
|
||||
{
|
||||
self.fill_geometry(ctx, f, rctx, fl, fill_ph, geo, (w, h), m, pt_xy, &fade);
|
||||
|
||||
@@ -37,18 +37,20 @@ pub fn needs_filters(pres: &Presentation, slide: &Slide) -> bool {
|
||||
any
|
||||
}
|
||||
|
||||
/// Does the shape's text have a shadow or glow (on a run, in its list style, or in the master's
|
||||
/// text styles it inherits)? Such text is blurred, which needs filters.
|
||||
/// Does the shape's text have a shadow or glow (on a run, in its paragraph's `defRPr`, in its list
|
||||
/// style, or in the master's or presentation's text styles it inherits)? Such text is blurred,
|
||||
/// which needs filters.
|
||||
fn text_has_effects(rctx: &Ctx, s: &Shape) -> bool {
|
||||
use deckcraft_model::text::{ListStyle, RunProps};
|
||||
let fx = |r: &RunProps| r.shadow.as_ref().is_some_and(|s| !s.inner) || r.glow.as_ref().is_some_and(|g| g.radius > 0.0);
|
||||
let styled = |l: &ListStyle| l.levels.iter().flatten().any(|lv| fx(&lv.run));
|
||||
let Some(t) = &s.text else { return false };
|
||||
t.paragraphs.iter().any(|p| p.runs.iter().any(|r| fx(&r.props)) || fx(&p.end_props))
|
||||
t.paragraphs.iter().any(|p| p.runs.iter().any(|r| fx(&r.props)) || fx(&p.end_props) || fx(&p.def_props))
|
||||
|| styled(&t.list_style)
|
||||
|| styled(&rctx.master.title_style)
|
||||
|| styled(&rctx.master.body_style)
|
||||
|| styled(&rctx.master.other_style)
|
||||
|| styled(&rctx.pres.default_text_style)
|
||||
}
|
||||
|
||||
/// Render slide `index` at `opts.scale` pixels per point. A panic inside the renderer becomes a
|
||||
|
||||
@@ -1239,6 +1239,39 @@ fn effect_text(set: impl Fn(&mut deckcraft_model::text::RunProps)) -> Presentati
|
||||
deck_with(vec![sh])
|
||||
}
|
||||
|
||||
/// Text whose glow comes only from its paragraph's `defRPr` needs the filters too: drawn on the
|
||||
/// worker threads it panicked (vello_cpu has no filters there) and the slide came out blank.
|
||||
#[test]
|
||||
fn a_paragraph_default_text_glow_needs_filters() {
|
||||
let mut sh = Shape { id: ShapeId(741), xfrm: Some(Xfrm::new(100.0, 100.0, 600.0, 300.0)), text_box: true, ..Default::default() };
|
||||
let mut t = TextBody::from_text("IIII");
|
||||
let p = &mut t.paragraphs[0];
|
||||
p.runs[0].props.size = Some(100.0);
|
||||
p.runs[0].props.fill = Some(deckcraft_model::style::Fill::solid(ColorRef::rgb(deckcraft_color::Rgba::rgb(0, 0, 0))));
|
||||
p.def_props.glow = Some(deckcraft_model::style::Glow { color: ColorRef::rgb(deckcraft_color::Rgba::rgb(0, 255, 0)), radius: 8.0 });
|
||||
sh.text = Some(t);
|
||||
assert_green_glow_drawn_with_threads(&deck_with(vec![sh]));
|
||||
}
|
||||
|
||||
/// Text whose glow comes only from the presentation's default text style (`p:defaultTextStyle`)
|
||||
/// needs the filters too, or the threaded render panics and the slide comes out blank.
|
||||
#[test]
|
||||
fn a_presentation_default_text_style_glow_needs_filters() {
|
||||
let mut deck = effect_text(|_| {});
|
||||
let level = deck.default_text_style.levels[0].as_mut().expect("the default text style sets level 1");
|
||||
level.run.glow = Some(deckcraft_model::style::Glow { color: ColorRef::rgb(deckcraft_color::Rgba::rgb(0, 255, 0)), radius: 8.0 });
|
||||
assert_green_glow_drawn_with_threads(&deck);
|
||||
}
|
||||
|
||||
/// Asserts that `deck`'s first slide needs filters and that, rendered with worker threads
|
||||
/// requested, its text shows a green glow halo rather than a blank slide.
|
||||
fn assert_green_glow_drawn_with_threads(deck: &Presentation) {
|
||||
assert!(needs_filters(deck, &deck.slides[0]));
|
||||
let img = render_slide(deck, 0, &RenderOpts { scale: 1.0, threads: 4, ..Default::default() });
|
||||
let halo = img.pixels.as_chunks::<4>().0.iter().filter(|p| p[1] > 150 && p[0] < 120 && p[2] < 120).count();
|
||||
assert!(halo > 300, "green halo pixels {halo}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_glow_and_shadow_are_drawn() {
|
||||
let count = |img: &Image, f: &dyn Fn(&[u8; 4]) -> bool| img.pixels.as_chunks::<4>().0.iter().filter(|px| f(px)).count();
|
||||
@@ -1962,6 +1995,70 @@ fn mf_ink(img: &image::RgbaImage) -> Option<(u32, u32, u32, u32)> {
|
||||
b
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metafile_dashed_pen_leaves_gaps() {
|
||||
// CREATEPENINDIRECT PS_DASH | PS_ENDCAP_FLAT, 40 units (4 px) wide, black, then a line across
|
||||
// the picture at y = 72 px: 12 px dashes with 4 px gaps.
|
||||
let mut pen = i16s(&[0x0201, 40, 0]);
|
||||
pen.extend(0u32.to_le_bytes());
|
||||
let recs = vec![(0x02FA, pen), (0x012D, i16s(&[0])), (0x0214, i16s(&[720, 100])), (0x0213, i16s(&[720, 2780]))];
|
||||
let img = crate::metafile::rasterize(&wmf_with(2880, 1440, &recs), 288).expect("raster");
|
||||
let ink: Vec<bool> = (20..260).map(|x| img.get_pixel(x, 72)[3] > 128).collect();
|
||||
assert!(ink.iter().filter(|b| **b).count() > 120, "dashes are drawn");
|
||||
assert!(ink.iter().filter(|b| !**b).count() > 30, "with gaps between them");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metafile_skewed_bitmap_is_drawn_with_its_transform() {
|
||||
use craft_metafile::write::{Image as MetafileImage, Op, emf};
|
||||
use kurbo::{Affine, Rect};
|
||||
|
||||
let image = std::sync::Arc::new(MetafileImage { width: 2, height: 2, rgba: [255, 0, 0, 255].repeat(4) });
|
||||
let xf = Affine::translate((25.0, 25.0)) * Affine::new([1.0, 0.25, 0.2, 1.0, 0.0, 0.0]) * Affine::scale(24.0);
|
||||
let bytes = emf(&[Op::Image { image, xf, opacity: 1.0 }], Rect::new(0.0, 0.0, 100.0, 100.0), "DeckCraft", "skewed bitmap").expect("EMF");
|
||||
let img = crate::metafile::rasterize(&bytes, 160).expect("raster");
|
||||
let red: Vec<_> = img.enumerate_pixels().filter(|(_, _, p)| p[0] > 180 && p[1] < 80 && p[3] > 128).collect();
|
||||
assert!(red.len() > 100, "the transformed image is visible: {} red pixels", red.len());
|
||||
let (min_x, max_x) = red.iter().fold((u32::MAX, 0), |(lo, hi), (x, _, _)| (lo.min(*x), hi.max(*x)));
|
||||
let (min_y, max_y) = red.iter().fold((u32::MAX, 0), |(lo, hi), (_, y, _)| (lo.min(*y), hi.max(*y)));
|
||||
assert!(max_x - min_x > 25 && max_y - min_y > 25, "the image keeps both transformed axes: x={min_x}..{max_x}, y={min_y}..{max_y}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metafile_clip_path_and_nondefault_pen_geometry_are_applied() {
|
||||
use craft_metafile::write::{Op, Pen, emf};
|
||||
use craft_metafile::{Cap, Join};
|
||||
use kurbo::{BezPath, Rect, Shape as _};
|
||||
|
||||
let mut triangle = BezPath::new();
|
||||
triangle.move_to((10.0, 10.0));
|
||||
triangle.line_to((90.0, 10.0));
|
||||
triangle.line_to((50.0, 90.0));
|
||||
triangle.close_path();
|
||||
|
||||
let mut bevel = BezPath::new();
|
||||
bevel.move_to((15.0, 35.0));
|
||||
bevel.line_to((50.0, 60.0));
|
||||
bevel.line_to((85.0, 35.0));
|
||||
let mut miter = BezPath::new();
|
||||
miter.move_to((15.0, 45.0));
|
||||
miter.line_to((50.0, 70.0));
|
||||
miter.line_to((85.0, 45.0));
|
||||
let pen = |join| Pen { rgb: [0, 0, 0], width: 5.0, cap: Cap::Square, join, miter: 4.0, dash: None };
|
||||
let ops = [
|
||||
Op::Clip { path: triangle, even_odd: false },
|
||||
Op::Fill { path: Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.1), even_odd: false, rgb: [255, 0, 0] },
|
||||
Op::Stroke { path: bevel, pen: pen(Join::Bevel) },
|
||||
Op::Stroke { path: miter, pen: pen(Join::Miter) },
|
||||
Op::Unclip,
|
||||
];
|
||||
let bytes = emf(&ops, Rect::new(0.0, 0.0, 100.0, 100.0), "DeckCraft", "clipped strokes").expect("EMF");
|
||||
let img = crate::metafile::rasterize(&bytes, 160).expect("raster");
|
||||
assert!(img.get_pixel(80, 40)[0] > 180, "inside the clip path is filled");
|
||||
assert_eq!(img.get_pixel(8, 80)[3], 0, "outside the clip path remains transparent");
|
||||
assert!(img.pixels().any(|p| p[3] > 128 && p[0] < 80), "square capped bevel and miter strokes are rendered");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metafile_text_ink_lands_at_its_reference_point() {
|
||||
// 2 × 1 inch (144 × 72 pt) drawn 288 px wide: 2 px per point. A 36-point "HH", top-left
|
||||
@@ -2127,6 +2224,43 @@ fn group_child_scale_does_not_scale_line_widths() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #2067: a legend entry with its own text colour, size and weight (`c:legendEntry/c:txPr`) draws
|
||||
/// its name so; the other entries keep the legend's.
|
||||
#[test]
|
||||
fn a_legend_entry_draws_its_own_text_colour_and_size() {
|
||||
let draw = |entry: Option<deckcraft_model::chart::LegendEntry>| {
|
||||
let mut c = Chart::sample(ChartType::Line);
|
||||
c.title = None;
|
||||
c.legend = Some("r".into());
|
||||
c.text_size = Some(10.0);
|
||||
c.text_color = Some(ColorRef::rgb(deckcraft_color::Rgba::rgb(128, 128, 128)));
|
||||
c.legend_entries = entry.into_iter().collect();
|
||||
let sh = Shape { id: ShapeId(634), xfrm: Some(Xfrm::new(0.0, 0.0, 480.0, 300.0)), kind: ShapeKind::Chart(Box::new(c)), ..Default::default() };
|
||||
render_slide(&deck_with(vec![sh]), 0, &RenderOpts { scale: 1.0, ..Default::default() })
|
||||
};
|
||||
let green = |img: &Image| {
|
||||
(0..480u32)
|
||||
.flat_map(|x| (0..300u32).map(move |y| (x, y)))
|
||||
.filter(|(x, y)| {
|
||||
let p = img.pixel(*x, *y);
|
||||
p[1] > 150 && p[0] < 80 && p[2] < 80
|
||||
})
|
||||
.count()
|
||||
};
|
||||
let entry = |size: Option<f64>| deckcraft_model::chart::LegendEntry {
|
||||
idx: 0,
|
||||
size,
|
||||
bold: Some(true),
|
||||
color: Some(ColorRef::rgb(deckcraft_color::Rgba::rgb(0, 200, 0))),
|
||||
};
|
||||
let none = green(&draw(None));
|
||||
let own = green(&draw(Some(entry(None))));
|
||||
let big = green(&draw(Some(entry(Some(20.0)))));
|
||||
assert_eq!(none, 0, "no green in a chart without the entry");
|
||||
assert!(own > 40, "the first entry's name is drawn in its own colour ({own})");
|
||||
assert!(big > own * 2, "and at its own size ({own} at 10 pt, {big} at 20 pt)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_picture_and_an_embedded_objects_preview_draw_their_fill_behind_transparent_pixels() {
|
||||
// PowerPoint draws a picture's own fill behind its transparent pixels (and an old equation
|
||||
@@ -2163,6 +2297,60 @@ fn a_picture_and_an_embedded_objects_preview_draw_their_fill_behind_transparent_
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_picture_in_a_placeholder_shows_the_layout_placeholders_fill_behind_transparent_pixels() {
|
||||
// #2068: a slide picture with an empty `p:spPr` in a layout picture placeholder that sets a
|
||||
// fill shows that fill behind its clear pixels. Its own fill (none included) and its own
|
||||
// style still decide when it has them. The left half of the image is clear.
|
||||
let png = {
|
||||
let img = image::RgbaImage::from_fn(8, 4, |x, _| if x < 4 { image::Rgba([0, 0, 0, 0]) } else { image::Rgba([20, 20, 160, 255]) });
|
||||
let mut out = std::io::Cursor::new(vec![]);
|
||||
image::DynamicImage::ImageRgba8(img).write_to(&mut out, image::ImageFormat::Png).unwrap();
|
||||
out.into_inner()
|
||||
};
|
||||
let orange = Fill::solid(ColorRef::rgb(deckcraft_color::Rgba::rgb(255, 153, 0)));
|
||||
let ph = || Some(Placeholder { kind: PhType::Picture, idx: 11, ..Default::default() });
|
||||
let style = ShapeStyle::accent(deckcraft_color::SchemeSlot::Accent1);
|
||||
// (layout fill, picture's own fill, picture's own style, the clear half shows orange)
|
||||
let cases = [
|
||||
(Some(orange.clone()), None, None, true),
|
||||
(None, None, None, false),
|
||||
(Some(orange.clone()), Some(Fill::None), None, false),
|
||||
(Some(orange.clone()), None, Some(style), false),
|
||||
];
|
||||
for (i, (layout_fill, own_fill, own_style, shows)) in cases.into_iter().enumerate() {
|
||||
let mut p = Presentation::default();
|
||||
let media = p.add_media("half.png", "image/png", png.clone()).expect("media");
|
||||
let lid = p.slides[0].layout;
|
||||
let m = std::sync::Arc::make_mut(&mut p.masters[0]);
|
||||
let layout = m.layouts.iter_mut().find(|l| l.id == lid).expect("layout");
|
||||
layout.shapes.push(Shape {
|
||||
id: ShapeId(2),
|
||||
ph: ph(),
|
||||
xfrm: Some(Xfrm::new(100.0, 100.0, 400.0, 200.0)),
|
||||
fill: layout_fill,
|
||||
..Default::default()
|
||||
});
|
||||
let pic = Shape {
|
||||
id: ShapeId(3),
|
||||
ph: ph(),
|
||||
kind: ShapeKind::Picture { fill: deckcraft_model::style::PictureFill { media, ..Default::default() } },
|
||||
fill: own_fill,
|
||||
style: own_style,
|
||||
..Default::default()
|
||||
};
|
||||
std::sync::Arc::make_mut(&mut p.slides[0]).shapes = vec![pic];
|
||||
let img = render_slide(&p, 0, &RenderOpts { scale: 1.0, ..Default::default() });
|
||||
let (clear, opaque) = (img.pixel(200, 200), img.pixel(400, 200));
|
||||
assert!(opaque[2] > 140 && opaque[0] < 40, "case {i}: the picture's own pixels: {opaque:?}");
|
||||
if shows {
|
||||
assert_eq!(clear[..3], [255, 153, 0], "case {i}: the layout's fill behind the clear half");
|
||||
} else {
|
||||
assert!(clear[..3].iter().all(|v| *v > 240), "case {i}: the slide shows through: {clear:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_picture_casts_its_shadow_from_its_pixels() {
|
||||
// PowerPoint shades only where a picture paints: a logo on a transparent background casts the
|
||||
@@ -3050,6 +3238,117 @@ fn pie_data_labels_take_the_chart_text_colour_when_it_has_one() {
|
||||
assert!(count(&plain, &white) > count(&coloured, &white), "the labels were white before");
|
||||
}
|
||||
|
||||
/// #2066: a line series that asks for value labels (`c:dLbls/c:showVal`, chart-wide or its own)
|
||||
/// shows each point's value above it; with the chart's text red, the labels add red ink there.
|
||||
/// Area series still draw none (their labels belong inside the area, not on a point).
|
||||
#[test]
|
||||
fn line_chart_value_labels_are_drawn_above_their_points() {
|
||||
let draw = |kind: ChartType, labels: bool, own: bool| {
|
||||
let mut c = Chart::sample(kind);
|
||||
c.title = None;
|
||||
c.legend = None;
|
||||
c.text_color = Some(ColorRef::rgb(deckcraft_color::Rgba::rgb(255, 0, 0)));
|
||||
if own {
|
||||
c.series[0].data_labels = Some(labels);
|
||||
} else {
|
||||
c.data_labels = labels;
|
||||
}
|
||||
let sh = Shape { id: ShapeId(633), xfrm: Some(Xfrm::new(0.0, 0.0, 400.0, 300.0)), kind: ShapeKind::Chart(Box::new(c)), ..Default::default() };
|
||||
render_slide(&deck_with(vec![sh]), 0, &RenderOpts { scale: 1.0, ..Default::default() })
|
||||
};
|
||||
let red = |img: &Image| {
|
||||
(0..400u32)
|
||||
.flat_map(|x| (0..300u32).map(move |y| (x, y)))
|
||||
.filter(|(x, y)| {
|
||||
let p = img.pixel(*x, *y);
|
||||
p[0] > 200 && p[1] < 60 && p[2] < 60
|
||||
})
|
||||
.count()
|
||||
};
|
||||
for kind in [ChartType::Line, ChartType::LineMarkers] {
|
||||
let (off, on) = (red(&draw(kind, false, false)), red(&draw(kind, true, false)));
|
||||
assert!(on > off + 100, "{kind:?}: labels add red ink ({off} → {on})");
|
||||
let own = red(&draw(kind, true, true));
|
||||
assert!(own > off + 30, "{kind:?}: a series' own showVal shows its labels ({off} → {own})");
|
||||
}
|
||||
// Area series keep none, and scatter and bubble series (drawn by the same code) are unchanged.
|
||||
for kind in [ChartType::Area, ChartType::Scatter, ChartType::Bubble] {
|
||||
let (off, on) = (red(&draw(kind, false, false)), red(&draw(kind, true, false)));
|
||||
assert_eq!(on, off, "{kind:?}: no point labels");
|
||||
}
|
||||
}
|
||||
|
||||
/// The magenta pixels the labels add to a line chart of two series, only the second labelled,
|
||||
/// with the chart's text magenta (no series, gridline or axis line is): its axis labels are
|
||||
/// magenta too, so they are what the unlabelled chart has.
|
||||
fn line_label_ink(kind: ChartType, first: f64, second: f64) -> (Image, Vec<(u32, u32)>) {
|
||||
let off: std::collections::HashSet<_> = magenta_pixels(&line_label_render(kind, first, second, false)).into_iter().collect();
|
||||
let img = line_label_render(kind, first, second, true);
|
||||
let added = magenta_pixels(&img).into_iter().filter(|p| !off.contains(p)).collect();
|
||||
(img, added)
|
||||
}
|
||||
|
||||
fn line_label_render(kind: ChartType, first: f64, second: f64, labels: bool) -> Image {
|
||||
let mut c = Chart::sample(ChartType::Line);
|
||||
c.kind = kind;
|
||||
c.title = None;
|
||||
c.legend = None;
|
||||
c.series.truncate(2);
|
||||
c.series[0].values = vec![Some(first); 4];
|
||||
c.series[1].values = vec![Some(second); 4];
|
||||
c.series[1].data_labels = Some(labels);
|
||||
c.text_color = Some(ColorRef::rgb(deckcraft_color::Rgba::rgb(255, 0, 255)));
|
||||
let sh = Shape { id: ShapeId(634), xfrm: Some(Xfrm::new(0.0, 0.0, 400.0, 300.0)), kind: ShapeKind::Chart(Box::new(c)), ..Default::default() };
|
||||
render_slide(&deck_with(vec![sh]), 0, &RenderOpts { scale: 1.0, ..Default::default() })
|
||||
}
|
||||
|
||||
/// Magenta ink on white, its anti-aliased edges included.
|
||||
fn is_magenta(p: [u8; 4]) -> bool {
|
||||
p[0] > 200 && p[2] > 200 && p[1] < 200
|
||||
}
|
||||
|
||||
fn magenta_pixels(img: &Image) -> Vec<(u32, u32)> {
|
||||
(0..img.width).flat_map(|x| (0..img.height).map(move |y| (x, y))).filter(|(x, y)| is_magenta(img.pixel(*x, *y))).collect()
|
||||
}
|
||||
|
||||
/// #2066: in a stacked line chart a point's label is its own value, not the running total it is
|
||||
/// drawn at. The second series' 5s, stacked on 100s, are labels as wide as an unstacked series of
|
||||
/// 5s, and far narrower than one of 105s (the width: the pixel columns the label ink covers).
|
||||
#[test]
|
||||
fn a_stacked_line_labels_each_point_with_its_own_value() {
|
||||
let width = |kind, second| line_label_ink(kind, 100.0, second).1.iter().map(|(x, _)| *x).collect::<std::collections::HashSet<_>>().len();
|
||||
let (stacked, fives, totals) = (width(ChartType::StackedLine, 5.0), width(ChartType::Line, 5.0), width(ChartType::Line, 105.0));
|
||||
assert!(stacked > 0 && fives > 0, "labels are drawn ({stacked}, {fives})");
|
||||
assert!(stacked.abs_diff(fives) <= 4, "stacked 5s are labelled \"5\" ({stacked} columns vs {fives} for 5s)");
|
||||
assert!(stacked * 2 < totals, "not with the total \"105\" ({stacked} columns vs {totals} for 105s)");
|
||||
}
|
||||
|
||||
/// #2066: a line label sits just above its point: all its ink is above the series' line, and
|
||||
/// its lowest row is close to it.
|
||||
#[test]
|
||||
fn a_line_label_sits_just_above_its_point() {
|
||||
let (img, ink) = line_label_ink(ChartType::Line, 20.0, 50.0);
|
||||
assert!(!ink.is_empty(), "labels are drawn");
|
||||
let cols: std::collections::HashSet<u32> = ink.iter().map(|(x, _)| *x).collect();
|
||||
let (first, last) = (cols.iter().min().copied().unwrap(), cols.iter().max().copied().unwrap());
|
||||
// The labelled series' flat line at 50: the topmost coloured pixel in the plot's columns
|
||||
// between the labels (the other line is lower, at 20; the axis labels lie outside them).
|
||||
let line_top = (first..last)
|
||||
.filter(|x| !cols.iter().any(|c| c.abs_diff(*x) < 4))
|
||||
.filter_map(|x| {
|
||||
(0..img.height).find(|y| {
|
||||
let p = img.pixel(x, *y);
|
||||
let (hi, lo) = (p[0].max(p[1]).max(p[2]), p[0].min(p[1]).min(p[2]));
|
||||
hi - lo > 80 && !is_magenta(p)
|
||||
})
|
||||
})
|
||||
.min()
|
||||
.unwrap();
|
||||
let lowest = ink.iter().map(|(_, y)| *y).max().unwrap();
|
||||
assert!(lowest < line_top, "the labels are above the line (lowest ink row {lowest}, line at {line_top})");
|
||||
assert!(line_top - lowest < 20, "and just above it (lowest ink row {lowest}, line at {line_top})");
|
||||
}
|
||||
|
||||
/// #1165: an ellipse sized at the EMU limit, crossing the slide, made vello's flattener allocate a
|
||||
/// buffer from its on-screen length and abort. It is skipped; the rest of the slide still draws.
|
||||
#[test]
|
||||
@@ -3105,3 +3404,65 @@ fn a_shape_whose_outline_is_not_finite_is_not_drawable() {
|
||||
quad.paths[0].path = path;
|
||||
assert!(!crate::geometry::drawable(&quad, m, 100.0, 50.0));
|
||||
}
|
||||
|
||||
/// A WMF without a placeable header (the frame comes from its window records) holding `records`
|
||||
/// (function, parameter bytes).
|
||||
fn wmf_bare(records: &[(u16, Vec<u8>)]) -> Vec<u8> {
|
||||
let mut body = Vec::new();
|
||||
let mut max_words = 3u32;
|
||||
for (func, params) in records {
|
||||
let words = (6 + params.len() as u32).div_ceil(2);
|
||||
max_words = max_words.max(words);
|
||||
body.extend(words.to_le_bytes());
|
||||
body.extend(func.to_le_bytes());
|
||||
body.extend(params);
|
||||
if params.len() % 2 == 1 {
|
||||
body.push(0);
|
||||
}
|
||||
}
|
||||
body.extend([3, 0, 0, 0, 0, 0]);
|
||||
let mut f = Vec::new();
|
||||
for v in [1u16, 9, 0x300] {
|
||||
f.extend(v.to_le_bytes());
|
||||
}
|
||||
f.extend((((18 + body.len()) / 2) as u32).to_le_bytes());
|
||||
f.extend(1u16.to_le_bytes());
|
||||
f.extend(max_words.to_le_bytes());
|
||||
f.extend(0u16.to_le_bytes());
|
||||
f.extend(body);
|
||||
f
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metafile_scaled_viewport_places_each_sub_picture_in_its_half() {
|
||||
// #2069: an 800 × 400 frame drawn as two sub-pictures. Each saves the DC, halves the viewport
|
||||
// width with SCALEVIEWPORTEXT, sets its own 400 × 400 window (the second shifted right by its
|
||||
// window origin), draws a circle and restores the DC: red on the left, blue on the right.
|
||||
let sub = |origin_x: i32, colorref: u32| {
|
||||
let mut brush = 0u16.to_le_bytes().to_vec();
|
||||
brush.extend(colorref.to_le_bytes());
|
||||
brush.extend(0u16.to_le_bytes());
|
||||
vec![
|
||||
(0x001E, vec![]), // SAVEDC
|
||||
(0x0103, i16s(&[8])), // SETMAPMODE MM_ANISOTROPIC
|
||||
(0x0412, i16s(&[1, 1, 2, 1])), // SCALEVIEWPORTEXT y 1/1, x 1/2
|
||||
(0x020B, i16s(&[0, origin_x])), // SETWINDOWORG
|
||||
(0x020C, i16s(&[400, 400])), // SETWINDOWEXT
|
||||
(0x02FC, brush), // CREATEBRUSHINDIRECT
|
||||
(0x012D, i16s(&[0])), // SELECTOBJECT
|
||||
(0x0418, i16s(&[380, 380, 20, 20])), // ELLIPSE
|
||||
(0x0127, i16s(&[-1])), // RESTOREDC
|
||||
(0x01F0, i16s(&[0])), // DELETEOBJECT
|
||||
]
|
||||
};
|
||||
let mut recs = vec![(0x020B, i16s(&[0, 0])), (0x020C, i16s(&[400, 800]))];
|
||||
recs.extend(sub(0, 0x0000_00FF));
|
||||
recs.extend(sub(-400, 0x00FF_0000));
|
||||
let img = crate::metafile::rasterize(&wmf_bare(&recs), 200).expect("raster");
|
||||
assert_eq!(img.dimensions(), (200, 100));
|
||||
let red = |p: &image::Rgba<u8>| p[0] > 200 && p[1] < 60 && p[2] < 60 && p[3] > 200;
|
||||
let blue = |p: &image::Rgba<u8>| p[2] > 200 && p[0] < 60 && p[1] < 60 && p[3] > 200;
|
||||
assert!(red(img.get_pixel(50, 50)), "red circle in the left half: {:?}", img.get_pixel(50, 50));
|
||||
assert!(blue(img.get_pixel(150, 50)), "blue circle in the right half: {:?}", img.get_pixel(150, 50));
|
||||
assert!(img.get_pixel(100, 50)[3] < 128, "the circles don't meet in the middle: {:?}", img.get_pixel(100, 50));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
//! `place_slide` sets the text of a shape inside a group whose child coordinates scale it the way
|
||||
//! the slide draws it: at the shape's size on the slide, with font sizes and insets in points.
|
||||
|
||||
use super::{Fill, Point, place_slide};
|
||||
use deckcraft_model::style::ColorRef;
|
||||
use deckcraft_model::text::TextBody;
|
||||
use deckcraft_model::{Presentation, Shape, ShapeId, ShapeKind, Xfrm};
|
||||
|
||||
/// A deck whose slide shows a shape at (100, 100), 400 × 200 points, with 24 pt black text: on its
|
||||
/// own, or inside a group whose child space is `scale` times smaller than the group.
|
||||
fn deck(scale: Option<f64>) -> Presentation {
|
||||
let mut body = TextBody::from_text("Placed where it is drawn");
|
||||
body.paragraphs[0].runs[0].props.size = Some(24.0);
|
||||
body.paragraphs[0].runs[0].props.fill = Some(Fill::solid(ColorRef::rgb(deckcraft_color::Rgba::BLACK)));
|
||||
let shape = match scale {
|
||||
None => Shape { id: ShapeId(701), xfrm: Some(Xfrm::new(100.0, 100.0, 400.0, 200.0)), text: Some(body), ..Default::default() },
|
||||
Some(k) => {
|
||||
let child = Shape { id: ShapeId(701), xfrm: Some(Xfrm::new(0.0, 0.0, 400.0 / k, 200.0 / k)), text: Some(body), ..Default::default() };
|
||||
Shape {
|
||||
id: ShapeId(700),
|
||||
xfrm: Some(Xfrm::new(100.0, 100.0, 400.0, 200.0)),
|
||||
kind: ShapeKind::Group { children: vec![child], child: Xfrm::new(0.0, 0.0, 400.0 / k, 200.0 / k) },
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut p = Presentation::default();
|
||||
std::sync::Arc::make_mut(&mut p.slides[0]).shapes = vec![shape];
|
||||
p
|
||||
}
|
||||
|
||||
/// Each placed glyph: its id, its origin on the slide and its run's drawn size (the font size
|
||||
/// times the scale of the text's transform).
|
||||
fn glyphs_on_slide(p: &Presentation) -> Vec<(u32, Point, f64)> {
|
||||
let placed = place_slide(p, 0);
|
||||
let mut out = vec![];
|
||||
for t in &placed.texts {
|
||||
let k = t.transform.determinant().abs().sqrt();
|
||||
for g in &t.layout.runs {
|
||||
for &(gid, x, y) in &g.glyphs {
|
||||
out.push((gid, t.transform * Point::new(x, y), g.size * k));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_in_a_scaled_group_is_placed_as_drawn() {
|
||||
let plain = glyphs_on_slide(&deck(None));
|
||||
assert!(!plain.is_empty());
|
||||
assert!(plain.iter().all(|g| (g.2 - 24.0).abs() < 1e-6), "{plain:?}");
|
||||
for scale in [1.0, 1600.0, 4.0, 0.25] {
|
||||
let grouped = glyphs_on_slide(&deck(Some(scale)));
|
||||
assert_eq!(grouped.len(), plain.len(), "scale {scale}");
|
||||
for (a, b) in grouped.iter().zip(&plain) {
|
||||
assert_eq!(a.0, b.0, "scale {scale}");
|
||||
assert!((a.1 - b.1).hypot() < 0.01, "scale {scale}: glyph at {:?}, on its own at {:?}", a.1, b.1);
|
||||
assert!((a.2 - b.2).abs() < 0.01, "scale {scale}: drawn at {} pt, on its own at {} pt", a.2, b.2);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -155,7 +155,7 @@ pub fn draw_layout_with(ctx: &mut RenderContext, l: &deckcraft_text::TextLayout,
|
||||
};
|
||||
let li = lines_of.line_at(run.para, *y);
|
||||
if !grads.iter().any(|(i, _)| *i == li) {
|
||||
let scheme = deckcraft_color::ColorScheme { name: String::new(), colors: [Rgba::BLACK; 12] };
|
||||
let scheme = deckcraft_color::ColorScheme::new(String::new(), [Rgba::BLACK; 12]);
|
||||
let stops = g.stops.iter().map(|s| (s.pos, s.color.resolve(&scheme, None))).collect();
|
||||
let bounds = l.lines.get(li).and_then(line_bounds).unwrap_or(tr);
|
||||
grads.push((li, paint::gradient(&g.shape, stops, bounds, run.alpha * ps.opacity)));
|
||||
|
||||
Reference in New Issue
Block a user