Files

468 lines
16 KiB
Rust

//! The display list: what a page looks like, as fill, stroke, image and glyph commands in page coordinates. The core's
//! tiny-skia painter (`render`), the face's canvas painter and the PDF and SVG exports all walk this one list, so the
//! screen and the export agree. Text is laid out here and enters as glyph outlines (each glyph defined once).
use crate::model::*;
use crate::path::{self, Seg};
use crate::text::{self, FontBook, FontKey};
use serde::Serialize;
use std::collections::HashMap;
use std::sync::Arc;
pub type Tf = [f32; 6];
#[derive(Clone, Debug, Serialize)]
pub struct DisplayList {
pub width: f32,
pub height: f32,
pub background: Option<[u8; 4]>,
/// Glyph outlines in font units (y up), referred to by index from `Text` items.
pub glyphs: Vec<GlyphDef>,
pub items: Vec<Item>,
/// Every top-level object of every visible vector layer, for selection and snapping in the face.
pub objects: Vec<ObjectInfo>,
/// Pixel sizes of the assets the list uses.
pub assets: Vec<AssetInfo>,
}
#[derive(Clone, Debug, Serialize)]
pub struct GlyphDef {
pub d: Arc<str>,
pub upem: f32,
}
#[derive(Clone, Debug, Serialize)]
pub struct AssetInfo {
pub id: String,
pub width: u32,
pub height: u32,
}
#[derive(Clone, Debug, Serialize)]
pub struct ObjectInfo {
pub id: Id,
pub layer: Id,
pub kind: &'static str,
/// The object's own box (x, y, w, h) before its transform.
pub local: [f32; 4],
pub transform: Tf,
/// The four corners of the box on the page (clockwise from the box's top left).
pub corners: [[f32; 2]; 4],
/// The axis-aligned bounds on the page: x0, y0, x1, y1.
pub bounds: [f32; 4],
pub locked: bool,
}
#[derive(Clone, Debug, Serialize)]
#[serde(tag = "k", rename_all = "snake_case")]
pub enum Item {
Fill {
d: String,
t: Tf,
paint: DPaint,
even_odd: bool,
layer: Id,
obj: Option<Id>,
},
Stroke {
d: String,
t: Tf,
paint: DPaint,
width: f32,
cap: Cap,
join: Join,
dash: Vec<f32>,
layer: Id,
obj: Option<Id>,
},
/// The asset's pixels (0..width, 0..height) through `t`, clipped to `clip` (path data through `clip_t`).
Image {
asset: String,
t: Tf,
clip: Option<String>,
clip_t: Tf,
smooth: bool,
layer: Id,
obj: Option<Id>,
},
Text {
t: Tf,
color: [u8; 4],
size: f32,
glyphs: Vec<DGlyph>,
#[serde(skip)]
family: String,
#[serde(skip)]
weight: u16,
#[serde(skip)]
italic: bool,
layer: Id,
obj: Option<Id>,
},
/// Everything up to the matching `Pop` is drawn into its own layer, then composited at `opacity`.
Push {
opacity: f32,
},
Pop,
}
#[derive(Clone, Debug, Serialize)]
pub struct DGlyph {
/// Index into `DisplayList::glyphs` (none for an empty glyph such as a space).
pub g: Option<u32>,
pub x: f32,
pub y: f32,
#[serde(skip)]
pub font: FontKey,
#[serde(skip)]
pub gid: u16,
#[serde(skip)]
pub advance: f32,
#[serde(skip)]
pub text: String,
}
#[derive(Clone, Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum DPaint {
Solid { c: [u8; 4] },
Linear { x1: f32, y1: f32, x2: f32, y2: f32, stops: Vec<(f32, [u8; 4])> },
Radial { cx: f32, cy: f32, r: f32, stops: Vec<(f32, [u8; 4])> },
}
pub fn mul(a: Tf, b: Tf) -> Tf {
// a after b: (a ∘ b)(p) = a(b(p)).
[
a[0] * b[0] + a[2] * b[1],
a[1] * b[0] + a[3] * b[1],
a[0] * b[2] + a[2] * b[3],
a[1] * b[2] + a[3] * b[3],
a[0] * b[4] + a[2] * b[5] + a[4],
a[1] * b[4] + a[3] * b[5] + a[5],
]
}
pub fn apply_tf(t: Tf, x: f32, y: f32) -> [f32; 2] {
[t[0] * x + t[2] * y + t[4], t[1] * x + t[3] * y + t[5]]
}
pub fn translate(x: f32, y: f32) -> Tf {
[1.0, 0.0, 0.0, 1.0, x, y]
}
pub fn scale(sx: f32, sy: f32) -> Tf {
[sx, 0.0, 0.0, sy, 0.0, 0.0]
}
/// Inverse of an affine transform (identity when it is singular).
pub fn invert(t: Tf) -> Tf {
let det = t[0] * t[3] - t[1] * t[2];
if det.abs() < 1e-12 {
return identity();
}
let (a, b, c, d) = (t[3] / det, -t[1] / det, -t[2] / det, t[0] / det);
[a, b, c, d, -(a * t[4] + c * t[5]), -(b * t[4] + d * t[5])]
}
fn dpaint(p: &Paint, bx: [f32; 4]) -> DPaint {
let [x, y, w, h] = bx;
let stops = |s: &[Stop]| s.iter().map(|s| (s.offset.clamp(0.0, 1.0), s.color.0)).collect();
match p {
Paint::Solid { color } => DPaint::Solid { c: color.0 },
Paint::Linear { x1, y1, x2, y2, stops: s } => {
DPaint::Linear { x1: x + x1 * w, y1: y + y1 * h, x2: x + x2 * w, y2: y + y2 * h, stops: stops(s) }
}
Paint::Radial { cx, cy, r, stops: s } => {
DPaint::Radial { cx: x + cx * w, cy: y + cy * h, r: (r * w.abs().max(h.abs())).max(0.01), stops: stops(s) }
}
}
}
/// The object's own box: x, y, w, h before its transform. Text needs the layout, so it is passed in.
pub fn local_box(o: &Object, book: &FontBook) -> [f32; 4] {
match &o.shape {
Shape::Rect { w, h, .. } | Shape::Ellipse { w, h } | Shape::Image { w, h, .. } => [0.0, 0.0, *w, *h],
Shape::Line { x1, y1, x2, y2, .. } => [x1.min(*x2), y1.min(*y2), (x2 - x1).abs(), (y2 - y1).abs()],
Shape::Path { d } => {
let b = path::parse(d).ok().and_then(|s| path::bounds(&s)).unwrap_or([0.0; 4]);
[b[0], b[1], b[2] - b[0], b[3] - b[1]]
}
Shape::Text { w, text, style } => {
let l = text::layout(book, text, style, *w);
[0.0, 0.0, l.width.max(if *w > 0.0 { *w } else { 1.0 }), l.height]
}
Shape::Group { objects } => {
let mut b: Option<[f32; 4]> = None;
for c in objects {
let lb = local_box(c, book);
for (px, py) in
[(lb[0], lb[1]), (lb[0] + lb[2], lb[1]), (lb[0] + lb[2], lb[1] + lb[3]), (lb[0], lb[1] + lb[3])]
{
let [x, y] = apply_tf(c.transform, px, py);
b = Some(match b {
None => [x, y, x, y],
Some([a, c2, d, e]) => [a.min(x), c2.min(y), d.max(x), e.max(y)],
});
}
}
let b = b.unwrap_or([0.0; 4]);
[b[0], b[1], b[2] - b[0], b[3] - b[1]]
}
}
}
struct Builder<'a> {
book: &'a FontBook,
doc: &'a Document,
glyph_index: HashMap<(FontKey, u16), Option<u32>>,
glyphs: Vec<GlyphDef>,
items: Vec<Item>,
assets: Vec<AssetInfo>,
}
impl Builder<'_> {
fn asset(&mut self, id: &str) -> Option<(u32, u32)> {
let r = self.doc.assets.get(id)?;
if !self.assets.iter().any(|a| a.id == id) {
self.assets.push(AssetInfo { id: id.to_string(), width: r.width, height: r.height });
}
Some((r.width, r.height))
}
fn glyph(&mut self, font: FontKey, gid: u16) -> Option<u32> {
if let Some(g) = self.glyph_index.get(&(font, gid)) {
return *g;
}
let g = self.book.outline(font, gid).filter(|d| !d.is_empty()).map(|d| {
self.glyphs.push(GlyphDef { d, upem: self.book.font(font).units_per_em });
(self.glyphs.len() - 1) as u32
});
self.glyph_index.insert((font, gid), g);
g
}
fn object(&mut self, o: &Object, parent: Tf, layer: Id, top: Option<Id>) {
if !o.visible {
return;
}
let t = mul(parent, o.transform);
let obj = top.or(Some(o.id));
let group = o.opacity < 0.999;
if group {
self.items.push(Item::Push { opacity: o.opacity.max(0.0) });
}
let bx = local_box(o, self.book);
let fill = |b: &mut Self, segs: &[Seg]| {
if let Some(p) = &o.fill {
b.items.push(Item::Fill { d: path::write(segs), t, paint: dpaint(p, bx), even_odd: false, layer, obj });
}
};
let stroke = |b: &mut Self, segs: &[Seg]| {
if let Some(s) = &o.stroke
&& s.width > 0.0
{
b.items.push(Item::Stroke {
d: path::write(segs),
t,
paint: dpaint(&s.paint, bx),
width: s.width,
cap: s.cap,
join: s.join,
dash: s.dash.clone(),
layer,
obj,
});
}
};
match &o.shape {
Shape::Rect { w, h, radius } => {
let segs = path::rect(*w, *h, *radius);
fill(self, &segs);
stroke(self, &segs);
}
Shape::Ellipse { w, h } => {
let segs = path::ellipse(*w, *h);
fill(self, &segs);
stroke(self, &segs);
}
Shape::Path { d } => {
if let Ok(segs) = path::parse(d) {
fill(self, &segs);
stroke(self, &segs);
}
}
Shape::Line { x1, y1, x2, y2, arrow_start, arrow_end } => {
let w = o.stroke.as_ref().map(|s| s.width).unwrap_or(1.0);
let (mut a, mut b) = ((*x1, *y1), (*x2, *y2));
if *arrow_end {
b = path::shorten(*x1, *y1, *x2, *y2, w);
}
if *arrow_start {
a = path::shorten(*x2, *y2, *x1, *y1, w);
}
stroke(self, &[Seg::Move(a.0, a.1), Seg::Line(b.0, b.1)]);
if let Some(s) = &o.stroke {
for (on, (fx, fy, tx, ty)) in
[(*arrow_end, (*x1, *y1, *x2, *y2)), (*arrow_start, (*x2, *y2, *x1, *y1))]
{
if on {
let head = path::arrow_head(fx, fy, tx, ty, w);
self.items.push(Item::Fill {
d: path::write(&head),
t,
paint: dpaint(&s.paint, bx),
even_odd: false,
layer,
obj,
});
}
}
}
}
Shape::Image { asset, w, h, crop } => {
let frame = path::rect(*w, *h, 0.0);
fill(self, &frame);
if let Some((pw, ph)) = self.asset(asset) {
let it = mul(t, mul(translate(crop.x, crop.y), scale(crop.w / pw as f32, crop.h / ph as f32)));
self.items.push(Item::Image {
asset: asset.clone(),
t: it,
clip: Some(path::write(&frame)),
clip_t: t,
smooth: true,
layer,
obj,
});
}
stroke(self, &frame);
}
Shape::Text { w, text, style } => {
let l = text::layout(self.book, text, style, *w);
let mut glyphs = Vec::new();
for line in &l.lines {
for g in &line.glyphs {
let def = self.glyph(g.font, g.gid);
glyphs.push(DGlyph {
g: def,
x: g.x,
y: line.baseline,
font: g.font,
gid: g.gid,
advance: g.advance,
text: g.text.clone(),
});
}
}
let frame = path::rect(bx[2], bx[3], 0.0);
fill(self, &frame);
self.items.push(Item::Text {
t,
color: style.color.0,
size: style.size,
glyphs,
family: style.family.clone(),
weight: style.weight,
italic: style.italic,
layer,
obj,
});
stroke(self, &frame);
}
Shape::Group { objects } => {
for c in objects {
self.object(c, t, layer, obj);
}
}
}
if group {
self.items.push(Item::Pop);
}
}
fn layers(&mut self, ls: &[Layer], objects: &mut Vec<ObjectInfo>) {
for l in ls {
if !l.visible {
continue;
}
let group = l.opacity < 0.999;
if group {
self.items.push(Item::Push { opacity: l.opacity.max(0.0) });
}
match &l.kind {
LayerKind::Vector { objects: os } => {
for o in os {
self.object(o, identity(), l.id, None);
if o.visible {
objects.push(info(o, l.id, l.locked, self.book));
}
}
}
LayerKind::Bitmap { asset, x, y, w, h } => {
if let Some((pw, ph)) = self.asset(asset) {
let t = mul(translate(*x, *y), scale(w / pw as f32, h / ph as f32));
let exact = (w - pw as f32).abs() < 1e-3 && (h - ph as f32).abs() < 1e-3;
self.items.push(Item::Image {
asset: asset.clone(),
t,
clip: None,
clip_t: identity(),
smooth: !exact,
layer: l.id,
obj: None,
});
}
}
LayerKind::Group { layers } => self.layers(layers, objects),
}
if group {
self.items.push(Item::Pop);
}
}
}
}
pub fn info(o: &Object, layer: Id, layer_locked: bool, book: &FontBook) -> ObjectInfo {
let b = local_box(o, book);
let pts = [[b[0], b[1]], [b[0] + b[2], b[1]], [b[0] + b[2], b[1] + b[3]], [b[0], b[1] + b[3]]];
let corners = pts.map(|[x, y]| apply_tf(o.transform, x, y));
let mut bounds = [f32::MAX, f32::MAX, f32::MIN, f32::MIN];
for [x, y] in corners {
bounds = [bounds[0].min(x), bounds[1].min(y), bounds[2].max(x), bounds[3].max(y)];
}
let kind = match o.shape {
Shape::Rect { .. } => "rect",
Shape::Ellipse { .. } => "ellipse",
Shape::Line { .. } => "line",
Shape::Path { .. } => "path",
Shape::Text { .. } => "text",
Shape::Image { .. } => "image",
Shape::Group { .. } => "group",
};
ObjectInfo {
id: o.id,
layer,
kind,
local: b,
transform: o.transform,
corners,
bounds,
locked: o.locked || layer_locked,
}
}
/// The display list of one page.
pub fn build(doc: &Document, page: &Page, book: &FontBook) -> DisplayList {
let mut b =
Builder { book, doc, glyph_index: HashMap::new(), glyphs: Vec::new(), items: Vec::new(), assets: Vec::new() };
let mut objects = Vec::new();
b.layers(&page.layers, &mut objects);
DisplayList {
width: page.width,
height: page.height,
background: page.background.map(|c| c.0),
glyphs: b.glyphs,
items: b.items,
objects,
assets: b.assets,
}
}