[doc] Editor core: document model, exact undo, .pictor format, text layout, display list, tiny-skia render, bitmap tools, SVG import, PNG/JPG/SVG/PDF export; worker doc.open and doc.import_svg
This commit is contained in:
@@ -0,0 +1,693 @@
|
||||
//! Pixel tools on a bitmap layer's raster: brush, pencil, eraser, fill bucket, magic wand, rectangle and lasso
|
||||
//! selections, delete and copy, adjustments, blur, sharpen, invert, clone stamp, and applying a matte (background
|
||||
//! removal). Each returns the rectangle it changed, so the caller can record one exact undo patch.
|
||||
use crate::model::{Document, PixelRect, Raster};
|
||||
use crate::ops::Op;
|
||||
|
||||
/// A selection: one coverage byte per pixel of the raster it belongs to.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Mask {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Mask {
|
||||
pub fn empty(width: u32, height: u32) -> Mask {
|
||||
Mask { width, height, data: vec![0; width as usize * height as usize] }
|
||||
}
|
||||
|
||||
pub fn rect(width: u32, height: u32, r: PixelRect) -> Mask {
|
||||
let mut m = Mask::empty(width, height);
|
||||
let r = r.clamp(width, height);
|
||||
for y in r.y..r.y + r.h {
|
||||
let row = y as usize * width as usize;
|
||||
m.data[row + r.x as usize..row + (r.x + r.w) as usize].fill(255);
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// A polygon (lasso), anti-aliased at its edge.
|
||||
pub fn polygon(width: u32, height: u32, points: &[(f32, f32)]) -> Mask {
|
||||
let mut m = Mask::empty(width, height);
|
||||
if points.len() < 3 {
|
||||
return m;
|
||||
}
|
||||
let mut pb = tiny_skia::PathBuilder::new();
|
||||
pb.move_to(points[0].0, points[0].1);
|
||||
for p in &points[1..] {
|
||||
pb.line_to(p.0, p.1);
|
||||
}
|
||||
pb.close();
|
||||
let (Some(path), Some(mut sm)) = (pb.finish(), tiny_skia::Mask::new(width, height)) else { return m };
|
||||
sm.fill_path(&path, tiny_skia::FillRule::EvenOdd, true, tiny_skia::Transform::identity());
|
||||
m.data.copy_from_slice(sm.data());
|
||||
m
|
||||
}
|
||||
|
||||
pub fn get(&self, x: u32, y: u32) -> u8 {
|
||||
self.data[y as usize * self.width as usize + x as usize]
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.data.iter().all(|v| *v == 0)
|
||||
}
|
||||
|
||||
pub fn bbox(&self) -> PixelRect {
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (u32::MAX, u32::MAX, 0, 0);
|
||||
for y in 0..self.height {
|
||||
for x in 0..self.width {
|
||||
if self.get(x, y) > 0 {
|
||||
x0 = x0.min(x);
|
||||
y0 = y0.min(y);
|
||||
x1 = x1.max(x + 1);
|
||||
y1 = y1.max(y + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
if x0 == u32::MAX {
|
||||
PixelRect { x: 0, y: 0, w: 0, h: 0 }
|
||||
} else {
|
||||
PixelRect { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }
|
||||
}
|
||||
}
|
||||
|
||||
pub fn invert(&mut self) {
|
||||
for v in &mut self.data {
|
||||
*v = 255 - *v;
|
||||
}
|
||||
}
|
||||
|
||||
/// The selection's edge as path data (pixel edges between inside and outside), for the marching ants.
|
||||
pub fn outline(&self) -> String {
|
||||
use std::fmt::Write;
|
||||
let inside = |x: i64, y: i64| {
|
||||
x >= 0 && y >= 0 && x < self.width as i64 && y < self.height as i64 && self.get(x as u32, y as u32) >= 128
|
||||
};
|
||||
let mut d = String::new();
|
||||
// Horizontal edges, merged along each row.
|
||||
for y in 0..=self.height as i64 {
|
||||
let mut start: Option<i64> = None;
|
||||
for x in 0..=self.width as i64 {
|
||||
let edge = x < self.width as i64 && inside(x, y) != inside(x, y - 1);
|
||||
match (edge, start) {
|
||||
(true, None) => start = Some(x),
|
||||
(false, Some(s)) => {
|
||||
let _ = write!(d, "M{s} {y}H{x}");
|
||||
start = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
for x in 0..=self.width as i64 {
|
||||
let mut start: Option<i64> = None;
|
||||
for y in 0..=self.height as i64 {
|
||||
let edge = y < self.height as i64 && inside(x, y) != inside(x - 1, y);
|
||||
match (edge, start) {
|
||||
(true, None) => start = Some(y),
|
||||
(false, Some(s)) => {
|
||||
let _ = write!(d, "M{x} {s}V{y}");
|
||||
start = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
d
|
||||
}
|
||||
}
|
||||
|
||||
fn sel(mask: Option<&Mask>, x: u32, y: u32) -> f32 {
|
||||
mask.map(|m| m.get(x, y) as f32 / 255.0).unwrap_or(1.0)
|
||||
}
|
||||
|
||||
/// Source-over in straight alpha: `src` (straight RGBA) with extra coverage `cov` onto `dst`.
|
||||
fn blend(dst: &mut [u8], src: [u8; 4], cov: f32) {
|
||||
let sa = src[3] as f32 / 255.0 * cov;
|
||||
if sa <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let da = dst[3] as f32 / 255.0;
|
||||
let oa = sa + da * (1.0 - sa);
|
||||
if oa <= 0.0 {
|
||||
dst.copy_from_slice(&[0, 0, 0, 0]);
|
||||
return;
|
||||
}
|
||||
for i in 0..3 {
|
||||
let v = (src[i] as f32 * sa + dst[i] as f32 * da * (1.0 - sa)) / oa;
|
||||
dst[i] = v.round().clamp(0.0, 255.0) as u8;
|
||||
}
|
||||
dst[3] = (oa * 255.0).round().clamp(0.0, 255.0) as u8;
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Brush {
|
||||
/// Radius in pixels at full pressure.
|
||||
pub radius: f32,
|
||||
/// 0 = soft to the centre, 1 = a hard edge.
|
||||
pub hardness: f32,
|
||||
pub color: [u8; 4],
|
||||
/// 0..1 for the whole stroke (a stroke never builds up over itself).
|
||||
pub opacity: f32,
|
||||
pub erase: bool,
|
||||
}
|
||||
|
||||
/// Stroke coverage (0..1) over a rectangle: dabs along the points, the maximum where they overlap.
|
||||
struct Coverage {
|
||||
rect: PixelRect,
|
||||
cov: Vec<f32>,
|
||||
}
|
||||
|
||||
fn coverage(width: u32, height: u32, points: &[(f32, f32, f32)], radius: f32, hardness: f32) -> Coverage {
|
||||
let r = radius.max(0.5);
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);
|
||||
for (x, y, _) in points {
|
||||
x0 = x0.min(x - r - 1.0);
|
||||
y0 = y0.min(y - r - 1.0);
|
||||
x1 = x1.max(x + r + 1.0);
|
||||
y1 = y1.max(y + r + 1.0);
|
||||
}
|
||||
let rect = PixelRect {
|
||||
x: x0.max(0.0) as u32,
|
||||
y: y0.max(0.0) as u32,
|
||||
w: (x1.min(width as f32).max(0.0) - x0.max(0.0)).max(0.0).ceil() as u32,
|
||||
h: (y1.min(height as f32).max(0.0) - y0.max(0.0)).max(0.0).ceil() as u32,
|
||||
}
|
||||
.clamp(width, height);
|
||||
let mut cov = vec![0f32; rect.w as usize * rect.h as usize];
|
||||
let hard = hardness.clamp(0.0, 0.99);
|
||||
let mut dab = |cx: f32, cy: f32, pr: f32| {
|
||||
let rr = (r * pr.clamp(0.05, 1.0)).max(0.5);
|
||||
let bx0 = ((cx - rr - 1.0).floor().max(rect.x as f32)) as u32;
|
||||
let by0 = ((cy - rr - 1.0).floor().max(rect.y as f32)) as u32;
|
||||
let bx1 = ((cx + rr + 1.0).ceil().min((rect.x + rect.w) as f32)) as u32;
|
||||
let by1 = ((cy + rr + 1.0).ceil().min((rect.y + rect.h) as f32)) as u32;
|
||||
for y in by0..by1 {
|
||||
for x in bx0..bx1 {
|
||||
let d = (((x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2)).sqrt()) / rr;
|
||||
// A hard core, then a smooth fall to the edge; half a pixel of anti-aliasing at any size.
|
||||
let edge = 1.0 - (d * rr - rr + 0.5).clamp(0.0, 1.0);
|
||||
let a = if d <= hard {
|
||||
edge
|
||||
} else {
|
||||
let t = ((d - hard) / (1.0 - hard)).clamp(0.0, 1.0);
|
||||
(1.0 - t * t * (3.0 - 2.0 * t)).min(edge)
|
||||
};
|
||||
let i = (y - rect.y) as usize * rect.w as usize + (x - rect.x) as usize;
|
||||
if a > cov[i] {
|
||||
cov[i] = a;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Some(&(x, y, p)) = points.first() {
|
||||
dab(x, y, p);
|
||||
}
|
||||
for w in points.windows(2) {
|
||||
let (ax, ay, ap) = w[0];
|
||||
let (bx, by, bp) = w[1];
|
||||
let len = ((bx - ax).powi(2) + (by - ay).powi(2)).sqrt();
|
||||
let step = (r * ap.min(bp).clamp(0.05, 1.0) * 0.25).max(0.5);
|
||||
let n = (len / step).ceil().max(1.0) as usize;
|
||||
for i in 1..=n {
|
||||
let t = i as f32 / n as f32;
|
||||
dab(ax + (bx - ax) * t, ay + (by - ay) * t, ap + (bp - ap) * t);
|
||||
}
|
||||
}
|
||||
Coverage { rect, cov }
|
||||
}
|
||||
|
||||
/// Brush or eraser along `points` (x, y, pressure 0..1).
|
||||
pub fn brush(r: &mut Raster, points: &[(f32, f32, f32)], b: &Brush, mask: Option<&Mask>) -> PixelRect {
|
||||
if points.is_empty() {
|
||||
return PixelRect { x: 0, y: 0, w: 0, h: 0 };
|
||||
}
|
||||
let c = coverage(r.width, r.height, points, b.radius, b.hardness);
|
||||
for y in 0..c.rect.h {
|
||||
for x in 0..c.rect.w {
|
||||
let (px, py) = (c.rect.x + x, c.rect.y + y);
|
||||
let k = c.cov[(y * c.rect.w + x) as usize] * b.opacity.clamp(0.0, 1.0) * sel(mask, px, py);
|
||||
if k <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let i = (py as usize * r.width as usize + px as usize) * 4;
|
||||
let dst = &mut r.rgba[i..i + 4];
|
||||
if b.erase {
|
||||
let a = dst[3] as f32 * (1.0 - k * b.color[3] as f32 / 255.0);
|
||||
dst[3] = a.round() as u8;
|
||||
} else {
|
||||
blend(dst, b.color, k);
|
||||
}
|
||||
}
|
||||
}
|
||||
c.rect
|
||||
}
|
||||
|
||||
/// Pencil: hard square pixels of `size` along the points, no anti-aliasing.
|
||||
pub fn pencil(
|
||||
r: &mut Raster,
|
||||
points: &[(f32, f32)],
|
||||
size: u32,
|
||||
color: [u8; 4],
|
||||
erase: bool,
|
||||
mask: Option<&Mask>,
|
||||
) -> PixelRect {
|
||||
let mut dirty = PixelRect { x: 0, y: 0, w: 0, h: 0 };
|
||||
let s = size.max(1) as i64;
|
||||
let mut put = |x: i64, y: i64, r: &mut Raster| {
|
||||
let x0 = x - (s - 1) / 2;
|
||||
let y0 = y - (s - 1) / 2;
|
||||
for yy in y0..y0 + s {
|
||||
for xx in x0..x0 + s {
|
||||
if xx < 0 || yy < 0 || xx >= r.width as i64 || yy >= r.height as i64 {
|
||||
continue;
|
||||
}
|
||||
let k = sel(mask, xx as u32, yy as u32);
|
||||
if k <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let i = (yy as usize * r.width as usize + xx as usize) * 4;
|
||||
if erase {
|
||||
r.rgba[i + 3] = (r.rgba[i + 3] as f32 * (1.0 - k)).round() as u8;
|
||||
} else if k >= 1.0 {
|
||||
r.rgba[i..i + 4].copy_from_slice(&color);
|
||||
} else {
|
||||
blend(&mut r.rgba[i..i + 4], color, k);
|
||||
}
|
||||
dirty = dirty.union(PixelRect { x: xx as u32, y: yy as u32, w: 1, h: 1 });
|
||||
}
|
||||
}
|
||||
};
|
||||
let pts: Vec<(i64, i64)> = points.iter().map(|(x, y)| (x.floor() as i64, y.floor() as i64)).collect();
|
||||
if let Some(&(x, y)) = pts.first() {
|
||||
put(x, y, r);
|
||||
}
|
||||
for w in pts.windows(2) {
|
||||
// Bresenham.
|
||||
let (mut x0, mut y0) = w[0];
|
||||
let (x1, y1) = w[1];
|
||||
let (dx, dy) = ((x1 - x0).abs(), -(y1 - y0).abs());
|
||||
let (sx, sy) = (if x0 < x1 { 1 } else { -1 }, if y0 < y1 { 1 } else { -1 });
|
||||
let mut err = dx + dy;
|
||||
loop {
|
||||
put(x0, y0, r);
|
||||
if x0 == x1 && y0 == y1 {
|
||||
break;
|
||||
}
|
||||
let e2 = 2 * err;
|
||||
if e2 >= dy {
|
||||
err += dy;
|
||||
x0 += sx;
|
||||
}
|
||||
if e2 <= dx {
|
||||
err += dx;
|
||||
y0 += sy;
|
||||
}
|
||||
}
|
||||
}
|
||||
dirty
|
||||
}
|
||||
|
||||
fn close(a: &[u8], b: [u8; 4], tol: u8) -> bool {
|
||||
// Fully transparent pixels match each other whatever their colour channels say.
|
||||
if a[3] == 0 && b[3] == 0 {
|
||||
return true;
|
||||
}
|
||||
(0..4).all(|i| (a[i] as i16 - b[i] as i16).unsigned_abs() <= tol as u16)
|
||||
}
|
||||
|
||||
/// The region around (x, y) whose pixels are within `tol` of its colour (4-connected).
|
||||
pub fn region(r: &Raster, x: u32, y: u32, tol: u8) -> Mask {
|
||||
let mut m = Mask::empty(r.width, r.height);
|
||||
if x >= r.width || y >= r.height {
|
||||
return m;
|
||||
}
|
||||
let seed = r.pixel(x, y);
|
||||
let w = r.width as usize;
|
||||
let mut stack = vec![(x, y)];
|
||||
while let Some((sx, sy)) = stack.pop() {
|
||||
// Scanline fill: walk left and right, then queue the rows above and below.
|
||||
let row = sy as usize * w;
|
||||
if m.data[row + sx as usize] != 0 {
|
||||
continue;
|
||||
}
|
||||
let px = |xx: u32| &r.rgba[(row + xx as usize) * 4..(row + xx as usize) * 4 + 4];
|
||||
let mut l = sx;
|
||||
while l > 0 && m.data[row + l as usize - 1] == 0 && close(px(l - 1), seed, tol) {
|
||||
l -= 1;
|
||||
}
|
||||
let mut rr = sx;
|
||||
while rr + 1 < r.width && m.data[row + rr as usize + 1] == 0 && close(px(rr + 1), seed, tol) {
|
||||
rr += 1;
|
||||
}
|
||||
for xx in l..=rr {
|
||||
m.data[row + xx as usize] = 255;
|
||||
}
|
||||
for ny in [sy.wrapping_sub(1), sy + 1] {
|
||||
if ny >= r.height {
|
||||
continue;
|
||||
}
|
||||
let nrow = ny as usize * w;
|
||||
let mut xx = l;
|
||||
while xx <= rr {
|
||||
let i = nrow + xx as usize;
|
||||
if m.data[i] == 0 && close(&r.rgba[i * 4..i * 4 + 4], seed, tol) {
|
||||
stack.push((xx, ny));
|
||||
// Skip the rest of this run; it is filled from the pushed seed.
|
||||
while xx <= rr && close(&r.rgba[(nrow + xx as usize) * 4..(nrow + xx as usize) * 4 + 4], seed, tol)
|
||||
{
|
||||
xx += 1;
|
||||
}
|
||||
} else {
|
||||
xx += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// Fill bucket: the region around (x, y) becomes `color` (inside the selection, if any).
|
||||
pub fn fill(r: &mut Raster, x: u32, y: u32, tol: u8, color: [u8; 4], mask: Option<&Mask>) -> PixelRect {
|
||||
let reg = region(r, x, y, tol);
|
||||
let b = reg.bbox();
|
||||
for yy in b.y..b.y + b.h {
|
||||
for xx in b.x..b.x + b.w {
|
||||
if reg.get(xx, yy) == 0 {
|
||||
continue;
|
||||
}
|
||||
let k = sel(mask, xx, yy);
|
||||
let i = (yy as usize * r.width as usize + xx as usize) * 4;
|
||||
if k >= 1.0 {
|
||||
r.rgba[i..i + 4].copy_from_slice(&color);
|
||||
} else if k > 0.0 {
|
||||
let old: [u8; 4] = r.rgba[i..i + 4].try_into().unwrap();
|
||||
for c in 0..4 {
|
||||
r.rgba[i + c] = (old[c] as f32 + (color[c] as f32 - old[c] as f32) * k).round() as u8;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Delete: the selected pixels (or all) become transparent.
|
||||
pub fn clear(r: &mut Raster, mask: Option<&Mask>) -> PixelRect {
|
||||
let b = mask.map(|m| m.bbox()).unwrap_or(PixelRect { x: 0, y: 0, w: r.width, h: r.height });
|
||||
for y in b.y..b.y + b.h {
|
||||
for x in b.x..b.x + b.w {
|
||||
let k = sel(mask, x, y);
|
||||
let i = (y as usize * r.width as usize + x as usize) * 4 + 3;
|
||||
r.rgba[i] = (r.rgba[i] as f32 * (1.0 - k)).round() as u8;
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Copy: the selected pixels (alpha × selection) in their bounding box, and where that box is.
|
||||
pub fn copy(r: &Raster, mask: Option<&Mask>) -> (Raster, PixelRect) {
|
||||
let b = mask.map(|m| m.bbox()).unwrap_or(PixelRect { x: 0, y: 0, w: r.width, h: r.height });
|
||||
let mut out = r.crop(b);
|
||||
if let Some(m) = mask {
|
||||
for y in 0..b.h {
|
||||
for x in 0..b.w {
|
||||
let i = (y as usize * b.w as usize + x as usize) * 4 + 3;
|
||||
out.rgba[i] = (out.rgba[i] as u32 * m.get(b.x + x, b.y + y) as u32 / 255) as u8;
|
||||
}
|
||||
}
|
||||
}
|
||||
(out, b)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum Adjust {
|
||||
/// −100..100.
|
||||
Brightness {
|
||||
amount: f32,
|
||||
},
|
||||
/// −100..100.
|
||||
Contrast {
|
||||
amount: f32,
|
||||
},
|
||||
/// Input black and white points (0..255), gamma (0.1..10), output black and white.
|
||||
Levels {
|
||||
in_black: f32,
|
||||
in_white: f32,
|
||||
gamma: f32,
|
||||
out_black: f32,
|
||||
out_white: f32,
|
||||
},
|
||||
/// Hue in degrees, saturation and lightness −100..100.
|
||||
HueSaturation {
|
||||
hue: f32,
|
||||
saturation: f32,
|
||||
lightness: f32,
|
||||
},
|
||||
Invert,
|
||||
/// Radius in pixels.
|
||||
Blur {
|
||||
radius: f32,
|
||||
},
|
||||
/// Amount 0..5, radius in pixels.
|
||||
Sharpen {
|
||||
amount: f32,
|
||||
radius: f32,
|
||||
},
|
||||
}
|
||||
|
||||
fn rgb_to_hsl(r: f32, g: f32, b: f32) -> (f32, f32, f32) {
|
||||
let max = r.max(g).max(b);
|
||||
let min = r.min(g).min(b);
|
||||
let l = (max + min) / 2.0;
|
||||
if max == min {
|
||||
return (0.0, 0.0, l);
|
||||
}
|
||||
let d = max - min;
|
||||
let s = if l > 0.5 { d / (2.0 - max - min) } else { d / (max + min) };
|
||||
let h = if max == r {
|
||||
(g - b) / d + if g < b { 6.0 } else { 0.0 }
|
||||
} else if max == g {
|
||||
(b - r) / d + 2.0
|
||||
} else {
|
||||
(r - g) / d + 4.0
|
||||
};
|
||||
(h * 60.0, s, l)
|
||||
}
|
||||
|
||||
fn hsl_to_rgb(h: f32, s: f32, l: f32) -> (f32, f32, f32) {
|
||||
if s == 0.0 {
|
||||
return (l, l, l);
|
||||
}
|
||||
let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s };
|
||||
let p = 2.0 * l - q;
|
||||
let hue = |mut t: f32| {
|
||||
t = t.rem_euclid(1.0);
|
||||
if t < 1.0 / 6.0 {
|
||||
p + (q - p) * 6.0 * t
|
||||
} else if t < 0.5 {
|
||||
q
|
||||
} else if t < 2.0 / 3.0 {
|
||||
p + (q - p) * (2.0 / 3.0 - t) * 6.0
|
||||
} else {
|
||||
p
|
||||
}
|
||||
};
|
||||
let h = h / 360.0;
|
||||
(hue(h + 1.0 / 3.0), hue(h), hue(h - 1.0 / 3.0))
|
||||
}
|
||||
|
||||
/// A box blur of premultiplied RGBA, three passes (close to a Gaussian).
|
||||
fn blurred(src: &Raster, radius: f32) -> Vec<f32> {
|
||||
let (w, h) = (src.width as usize, src.height as usize);
|
||||
let mut buf: Vec<f32> = Vec::with_capacity(w * h * 4);
|
||||
for p in src.rgba.as_chunks::<4>().0 {
|
||||
let a = p[3] as f32 / 255.0;
|
||||
buf.extend_from_slice(&[p[0] as f32 * a, p[1] as f32 * a, p[2] as f32 * a, p[3] as f32]);
|
||||
}
|
||||
let r = ((radius / 3.0f32.sqrt()).round() as usize).max(1);
|
||||
let mut tmp = vec![0f32; buf.len()];
|
||||
for _ in 0..3 {
|
||||
for horizontal in [true, false] {
|
||||
let (n, m) = if horizontal { (h, w) } else { (w, h) };
|
||||
for line in 0..n {
|
||||
let idx = |k: usize| if horizontal { (line * w + k) * 4 } else { (k * w + line) * 4 };
|
||||
let mut acc = [0f32; 4];
|
||||
let count = (2 * r + 1) as f32;
|
||||
// Edge pixels repeat beyond the border.
|
||||
for k in 0..(2 * r + 1) {
|
||||
let kk = (k as isize - r as isize).clamp(0, m as isize - 1) as usize;
|
||||
for c in 0..4 {
|
||||
acc[c] += buf[idx(kk) + c];
|
||||
}
|
||||
}
|
||||
for k in 0..m {
|
||||
for c in 0..4 {
|
||||
tmp[idx(k) + c] = acc[c] / count;
|
||||
}
|
||||
let out = (k as isize - r as isize).clamp(0, m as isize - 1) as usize;
|
||||
let inn = (k as isize + r as isize + 1).clamp(0, m as isize - 1) as usize;
|
||||
for c in 0..4 {
|
||||
acc[c] += buf[idx(inn) + c] - buf[idx(out) + c];
|
||||
}
|
||||
}
|
||||
}
|
||||
std::mem::swap(&mut buf, &mut tmp);
|
||||
}
|
||||
}
|
||||
buf
|
||||
}
|
||||
|
||||
/// Writes the adjustment of `src` into `dst` (the same size), inside the selection; `dst` may start as a copy of
|
||||
/// `src` (a live preview re-runs this from the untouched original).
|
||||
pub fn adjust(src: &Raster, dst: &mut Raster, a: &Adjust, mask: Option<&Mask>) -> PixelRect {
|
||||
let b = mask.map(|m| m.bbox()).unwrap_or(PixelRect { x: 0, y: 0, w: src.width, h: src.height });
|
||||
let blur = match a {
|
||||
Adjust::Blur { radius } | Adjust::Sharpen { radius, .. } => Some(blurred(src, radius.max(0.5))),
|
||||
_ => None,
|
||||
};
|
||||
let lut = |f: &dyn Fn(f32) -> f32| -> [u8; 256] {
|
||||
let mut t = [0u8; 256];
|
||||
for (i, v) in t.iter_mut().enumerate() {
|
||||
*v = f(i as f32).round().clamp(0.0, 255.0) as u8;
|
||||
}
|
||||
t
|
||||
};
|
||||
let table: Option<[u8; 256]> = match *a {
|
||||
Adjust::Brightness { amount } => Some(lut(&|v| v + amount * 2.55)),
|
||||
Adjust::Contrast { amount } => {
|
||||
let c = amount.clamp(-100.0, 100.0) * 2.55;
|
||||
let f = (259.0 * (c + 255.0)) / (255.0 * (259.0 - c));
|
||||
Some(lut(&|v| f * (v - 128.0) + 128.0))
|
||||
}
|
||||
Adjust::Levels { in_black, in_white, gamma, out_black, out_white } => {
|
||||
let span = (in_white - in_black).max(1.0);
|
||||
let g = gamma.clamp(0.1, 10.0);
|
||||
Some(lut(&|v| {
|
||||
let t = ((v - in_black) / span).clamp(0.0, 1.0).powf(1.0 / g);
|
||||
out_black + t * (out_white - out_black)
|
||||
}))
|
||||
}
|
||||
Adjust::Invert => Some(lut(&|v| 255.0 - v)),
|
||||
_ => None,
|
||||
};
|
||||
for y in b.y..b.y + b.h {
|
||||
for x in b.x..b.x + b.w {
|
||||
let k = sel(mask, x, y);
|
||||
let i = (y as usize * src.width as usize + x as usize) * 4;
|
||||
let s: [u8; 4] = src.rgba[i..i + 4].try_into().unwrap();
|
||||
let out: [u8; 4] = match (a, &table, &blur) {
|
||||
(_, Some(t), _) => [t[s[0] as usize], t[s[1] as usize], t[s[2] as usize], s[3]],
|
||||
(Adjust::HueSaturation { hue, saturation, lightness }, _, _) => {
|
||||
let (h, sat, l) = rgb_to_hsl(s[0] as f32 / 255.0, s[1] as f32 / 255.0, s[2] as f32 / 255.0);
|
||||
let sat = (sat * (1.0 + saturation / 100.0)).clamp(0.0, 1.0);
|
||||
let l = if *lightness >= 0.0 {
|
||||
l + (1.0 - l) * lightness / 100.0
|
||||
} else {
|
||||
l * (1.0 + lightness / 100.0)
|
||||
};
|
||||
let (r, g, bb) = hsl_to_rgb(h + hue, sat, l.clamp(0.0, 1.0));
|
||||
[(r * 255.0).round() as u8, (g * 255.0).round() as u8, (bb * 255.0).round() as u8, s[3]]
|
||||
}
|
||||
(Adjust::Blur { .. }, _, Some(bl)) => {
|
||||
let a = bl[i + 3];
|
||||
if a <= 0.0 {
|
||||
[0, 0, 0, 0]
|
||||
} else {
|
||||
let f = 255.0 / a;
|
||||
[
|
||||
(bl[i] * f).round().min(255.0) as u8,
|
||||
(bl[i + 1] * f).round().min(255.0) as u8,
|
||||
(bl[i + 2] * f).round().min(255.0) as u8,
|
||||
a.round() as u8,
|
||||
]
|
||||
}
|
||||
}
|
||||
(Adjust::Sharpen { amount, .. }, _, Some(bl)) => {
|
||||
let a = (bl[i + 3] / 255.0).max(1e-3);
|
||||
let mut o = [0u8; 4];
|
||||
for c in 0..3 {
|
||||
let blur_c = bl[i + c] / a;
|
||||
o[c] = (s[c] as f32 + amount * (s[c] as f32 - blur_c)).round().clamp(0.0, 255.0) as u8;
|
||||
}
|
||||
o[3] = s[3];
|
||||
o
|
||||
}
|
||||
_ => s,
|
||||
};
|
||||
let d = &mut dst.rgba[i..i + 4];
|
||||
if k >= 1.0 {
|
||||
d.copy_from_slice(&out);
|
||||
} else if k > 0.0 {
|
||||
for c in 0..4 {
|
||||
d[c] = (s[c] as f32 + (out[c] as f32 - s[c] as f32) * k).round() as u8;
|
||||
}
|
||||
} else {
|
||||
d.copy_from_slice(&s);
|
||||
}
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Clone stamp: dabs that copy from `source` (the layer as it was when the stroke began) at an offset.
|
||||
pub fn clone_stamp(
|
||||
r: &mut Raster,
|
||||
source: &Raster,
|
||||
offset: (f32, f32),
|
||||
points: &[(f32, f32, f32)],
|
||||
b: &Brush,
|
||||
mask: Option<&Mask>,
|
||||
) -> PixelRect {
|
||||
if points.is_empty() {
|
||||
return PixelRect { x: 0, y: 0, w: 0, h: 0 };
|
||||
}
|
||||
let c = coverage(r.width, r.height, points, b.radius, b.hardness);
|
||||
for y in 0..c.rect.h {
|
||||
for x in 0..c.rect.w {
|
||||
let (px, py) = (c.rect.x + x, c.rect.y + y);
|
||||
let k = c.cov[(y * c.rect.w + x) as usize] * b.opacity.clamp(0.0, 1.0) * sel(mask, px, py);
|
||||
if k <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let sx = px as f32 + offset.0;
|
||||
let sy = py as f32 + offset.1;
|
||||
if sx < 0.0 || sy < 0.0 || sx >= source.width as f32 || sy >= source.height as f32 {
|
||||
continue;
|
||||
}
|
||||
let s = source.pixel(sx as u32, sy as u32);
|
||||
let i = (py as usize * r.width as usize + px as usize) * 4;
|
||||
blend(&mut r.rgba[i..i + 4], s, k);
|
||||
}
|
||||
}
|
||||
c.rect
|
||||
}
|
||||
|
||||
/// Multiplies the alpha by a matte (0..255 per pixel, the raster's size): background removal as a layer action.
|
||||
pub fn apply_matte(r: &mut Raster, matte: &[u8]) -> PixelRect {
|
||||
for (p, m) in r.rgba.as_chunks_mut::<4>().0.iter_mut().zip(matte) {
|
||||
p[3] = (p[3] as u32 * *m as u32 / 255) as u8;
|
||||
}
|
||||
PixelRect { x: 0, y: 0, w: r.width, h: r.height }
|
||||
}
|
||||
|
||||
/// Runs a pixel edit on an asset and returns the operation and its inverse (already applied), for
|
||||
/// `History::record`; none when nothing changed or the asset is missing.
|
||||
pub fn edit(doc: &mut Document, asset: &str, f: impl FnOnce(&mut Raster) -> PixelRect) -> Option<(Op, Op)> {
|
||||
let r = doc.assets.get_mut(asset)?;
|
||||
let before = r.clone();
|
||||
let rect = f(r).clamp(r.width, r.height);
|
||||
if rect.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let after = r.crop(rect);
|
||||
let old = before.crop(rect);
|
||||
if after == old {
|
||||
return None;
|
||||
}
|
||||
Some((
|
||||
Op::Patch { asset: asset.to_string(), rect, pixels: after.rgba },
|
||||
Op::Patch { asset: asset.to_string(), rect, pixels: old.rgba },
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,467 @@
|
||||
//! 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,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,934 @@
|
||||
//! Exports: PNG at a scale, JPG on white, SVG (vector layers as SVG, pixels embedded as PNG) and PDF with pdf-writer
|
||||
//! (vectors stay vectors, text is real text in subset fonts with a ToUnicode map, each page at its exact size).
|
||||
//! All of them walk the display list (`display::build`), the same one the screen is painted from.
|
||||
use crate::display::{self, DGlyph, DPaint, DisplayList, Item, Tf};
|
||||
use crate::model::*;
|
||||
use crate::path;
|
||||
use crate::text::{Embedding, FontBook, FontKey};
|
||||
use pdf_writer::{Content, Filter, Finish, Name, Pdf, Rect as PRect, Ref, Str};
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::fmt::Write as _;
|
||||
use std::io::Write as _;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ExportError {
|
||||
#[error("The font \u{201c}{family}\u{201d} cannot be put in a PDF: {reason}. Choose another font for that text.")]
|
||||
FontNotEmbeddable { family: String, reason: &'static str },
|
||||
#[error("The font \u{201c}{0}\u{201d} could not be prepared for the PDF.")]
|
||||
FontBroken(String),
|
||||
#[error("The picture is too large to export at this scale.")]
|
||||
TooLarge,
|
||||
#[error("Could not encode the picture: {0}")]
|
||||
Encode(String),
|
||||
}
|
||||
|
||||
/// A page as PNG at `scale` pixels per point.
|
||||
pub fn png(doc: &Document, page: &Page, book: &FontBook, scale: f32) -> Result<Vec<u8>, ExportError> {
|
||||
let r = raster(doc, page, book, scale)?;
|
||||
crate::format::encode_png(&r).map_err(|e| ExportError::Encode(e.to_string()))
|
||||
}
|
||||
|
||||
/// A page as JPG (quality 0–100) at `scale`, on white where the page is transparent.
|
||||
pub fn jpg(doc: &Document, page: &Page, book: &FontBook, scale: f32, quality: u8) -> Result<Vec<u8>, ExportError> {
|
||||
use image::ImageEncoder;
|
||||
let r = raster(doc, page, book, scale)?;
|
||||
let mut rgb = Vec::with_capacity(r.rgba.len() / 4 * 3);
|
||||
for p in r.rgba.as_chunks::<4>().0 {
|
||||
let a = p[3] as u32;
|
||||
for c in &p[..3] {
|
||||
rgb.push(((*c as u32 * a + 255 * (255 - a) + 127) / 255) as u8);
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, quality.clamp(1, 100))
|
||||
.write_image(&rgb, r.width, r.height, image::ExtendedColorType::Rgb8)
|
||||
.map_err(|e| ExportError::Encode(e.to_string()))?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn raster(doc: &Document, page: &Page, book: &FontBook, scale: f32) -> Result<Raster, ExportError> {
|
||||
let px = (page.width * scale) as u64 * (page.height * scale) as u64;
|
||||
if scale.is_nan() || scale <= 0.0 || px > 200_000_000 {
|
||||
return Err(ExportError::TooLarge);
|
||||
}
|
||||
crate::render::page(doc, page, book, scale).ok_or(ExportError::TooLarge)
|
||||
}
|
||||
|
||||
// ---- SVG ----------------------------------------------------------------------------------------------------------
|
||||
|
||||
fn hex(c: [u8; 4]) -> String {
|
||||
format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2])
|
||||
}
|
||||
|
||||
fn esc(s: &str) -> String {
|
||||
s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """)
|
||||
}
|
||||
|
||||
fn mat(t: Tf) -> String {
|
||||
format!("matrix({} {} {} {} {} {})", t[0], t[1], t[2], t[3], t[4], t[5])
|
||||
}
|
||||
|
||||
/// A page as SVG. Text is written as `<text>` with each character's x, so it stays text.
|
||||
pub fn svg(doc: &Document, page: &Page, book: &FontBook) -> String {
|
||||
use base64::Engine as _;
|
||||
let list = display::build(doc, page, book);
|
||||
let mut defs = String::new();
|
||||
let mut body = String::new();
|
||||
let mut n = 0;
|
||||
let mut paint = |p: &DPaint, defs: &mut String| -> (String, Option<f32>) {
|
||||
match p {
|
||||
DPaint::Solid { c } => (hex(*c), (c[3] < 255).then_some(c[3] as f32 / 255.0)),
|
||||
DPaint::Linear { x1, y1, x2, y2, stops } => {
|
||||
n += 1;
|
||||
let _ = write!(
|
||||
defs,
|
||||
r#"<linearGradient id="g{n}" gradientUnits="userSpaceOnUse" x1="{x1}" y1="{y1}" x2="{x2}" y2="{y2}">"#
|
||||
);
|
||||
for (o, c) in stops {
|
||||
let _ = write!(
|
||||
defs,
|
||||
r#"<stop offset="{o}" stop-color="{}" stop-opacity="{}"/>"#,
|
||||
hex(*c),
|
||||
c[3] as f32 / 255.0
|
||||
);
|
||||
}
|
||||
defs.push_str("</linearGradient>");
|
||||
(format!("url(#g{n})"), None)
|
||||
}
|
||||
DPaint::Radial { cx, cy, r, stops } => {
|
||||
n += 1;
|
||||
let _ = write!(
|
||||
defs,
|
||||
r#"<radialGradient id="g{n}" gradientUnits="userSpaceOnUse" cx="{cx}" cy="{cy}" r="{r}">"#
|
||||
);
|
||||
for (o, c) in stops {
|
||||
let _ = write!(
|
||||
defs,
|
||||
r#"<stop offset="{o}" stop-color="{}" stop-opacity="{}"/>"#,
|
||||
hex(*c),
|
||||
c[3] as f32 / 255.0
|
||||
);
|
||||
}
|
||||
defs.push_str("</radialGradient>");
|
||||
(format!("url(#g{n})"), None)
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut clips = 0;
|
||||
let mut pngs: HashMap<&str, String> = HashMap::new();
|
||||
for item in &list.items {
|
||||
match item {
|
||||
Item::Push { opacity } => {
|
||||
let _ = write!(body, r#"<g opacity="{opacity}">"#);
|
||||
}
|
||||
Item::Pop => body.push_str("</g>"),
|
||||
Item::Fill { d, t, paint: p, even_odd, .. } => {
|
||||
let (f, a) = paint(p, &mut defs);
|
||||
let _ = write!(body, r#"<path d="{d}" transform="{}" fill="{f}""#, mat(*t));
|
||||
if let Some(a) = a {
|
||||
let _ = write!(body, r#" fill-opacity="{a}""#);
|
||||
}
|
||||
if *even_odd {
|
||||
body.push_str(r#" fill-rule="evenodd""#);
|
||||
}
|
||||
body.push_str("/>");
|
||||
}
|
||||
Item::Stroke { d, t, paint: p, width, cap, join, dash, .. } => {
|
||||
let (s, a) = paint(p, &mut defs);
|
||||
let _ = write!(
|
||||
body,
|
||||
r#"<path d="{d}" transform="{}" fill="none" stroke="{s}" stroke-width="{width}""#,
|
||||
mat(*t)
|
||||
);
|
||||
if let Some(a) = a {
|
||||
let _ = write!(body, r#" stroke-opacity="{a}""#);
|
||||
}
|
||||
let cap = match cap {
|
||||
Cap::Butt => "butt",
|
||||
Cap::Round => "round",
|
||||
Cap::Square => "square",
|
||||
};
|
||||
let join = match join {
|
||||
Join::Miter => "miter",
|
||||
Join::Round => "round",
|
||||
Join::Bevel => "bevel",
|
||||
};
|
||||
let _ = write!(body, r#" stroke-linecap="{cap}" stroke-linejoin="{join}""#);
|
||||
if !dash.is_empty() {
|
||||
let d: Vec<String> = dash.iter().map(|v| v.to_string()).collect();
|
||||
let _ = write!(body, r#" stroke-dasharray="{}""#, d.join(" "));
|
||||
}
|
||||
body.push_str("/>");
|
||||
}
|
||||
Item::Image { asset, t, clip, clip_t, .. } => {
|
||||
let Some(r) = doc.assets.get(asset) else { continue };
|
||||
let href = pngs.entry(asset.as_str()).or_insert_with(|| {
|
||||
let png = crate::format::encode_png(r).unwrap_or_default();
|
||||
format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(png))
|
||||
});
|
||||
if let Some(cd) = clip {
|
||||
clips += 1;
|
||||
let _ = write!(
|
||||
defs,
|
||||
r#"<clipPath id="c{clips}"><path d="{cd}" transform="{}"/></clipPath>"#,
|
||||
mat(*clip_t)
|
||||
);
|
||||
let _ = write!(body, r#"<g clip-path="url(#c{clips})">"#);
|
||||
}
|
||||
let _ = write!(
|
||||
body,
|
||||
r#"<image href="{href}" width="{}" height="{}" transform="{}" preserveAspectRatio="none"/>"#,
|
||||
r.width,
|
||||
r.height,
|
||||
mat(*t)
|
||||
);
|
||||
if clip.is_some() {
|
||||
body.push_str("</g>");
|
||||
}
|
||||
}
|
||||
Item::Text { t, color, size, glyphs, family, weight, italic, .. } => {
|
||||
// One <text> per line (glyphs that share a baseline), every character placed at its glyph's x.
|
||||
let mut lines: BTreeMap<i64, Vec<&DGlyph>> = BTreeMap::new();
|
||||
for g in glyphs {
|
||||
lines.entry((g.y * 100.0) as i64).or_default().push(g);
|
||||
}
|
||||
let _ = write!(
|
||||
body,
|
||||
r#"<g transform="{}" font-family="{}" font-size="{size}" font-weight="{weight}"{} fill="{}"{}>"#,
|
||||
mat(*t),
|
||||
esc(family),
|
||||
if *italic { r#" font-style="italic""# } else { "" },
|
||||
hex(*color),
|
||||
if color[3] < 255 {
|
||||
format!(r#" fill-opacity="{}""#, color[3] as f32 / 255.0)
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
);
|
||||
for gs in lines.values() {
|
||||
let mut xs = Vec::new();
|
||||
let mut s = String::new();
|
||||
for g in gs {
|
||||
for (i, ch) in g.text.chars().enumerate() {
|
||||
xs.push(format!(
|
||||
"{}",
|
||||
g.x + if i == 0 { 0.0 } else { g.advance * i as f32 / g.text.chars().count() as f32 }
|
||||
));
|
||||
s.push(ch);
|
||||
}
|
||||
}
|
||||
if s.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let _ = write!(
|
||||
body,
|
||||
r#"<text xml:space="preserve" x="{}" y="{}">{}</text>"#,
|
||||
xs.join(" "),
|
||||
gs[0].y,
|
||||
esc(&s)
|
||||
);
|
||||
}
|
||||
body.push_str("</g>");
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = format!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="{w}pt" height="{h}pt" viewBox="0 0 {w} {h}">"#,
|
||||
w = list.width,
|
||||
h = list.height
|
||||
);
|
||||
if !defs.is_empty() {
|
||||
let _ = write!(out, "<defs>{defs}</defs>");
|
||||
}
|
||||
if let Some(bg) = list.background {
|
||||
let _ = write!(out, r#"<rect width="{}" height="{}" fill="{}"/>"#, list.width, list.height, hex(bg));
|
||||
}
|
||||
out.push_str(&body);
|
||||
out.push_str("</svg>");
|
||||
out
|
||||
}
|
||||
|
||||
// ---- PDF ----------------------------------------------------------------------------------------------------------
|
||||
|
||||
fn deflate(data: &[u8]) -> Vec<u8> {
|
||||
let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::new(6));
|
||||
let _ = e.write_all(data);
|
||||
e.finish().unwrap_or_default()
|
||||
}
|
||||
|
||||
struct FontUse {
|
||||
name: String,
|
||||
/// Subset fonts are addressed by the subset's glyph ids (CID = new gid); others by their own ids.
|
||||
subset: bool,
|
||||
remapper: subsetter::GlyphRemapper,
|
||||
/// CID → (original glyph id, the text it stands for).
|
||||
glyphs: BTreeMap<u16, (u16, String)>,
|
||||
}
|
||||
|
||||
/// The fonts a set of display lists uses, and whether each may be embedded.
|
||||
pub fn check_fonts(lists: &[DisplayList], book: &FontBook) -> Result<(), ExportError> {
|
||||
for l in lists {
|
||||
for it in &l.items {
|
||||
if let Item::Text { glyphs, .. } = it {
|
||||
for g in glyphs {
|
||||
let f = book.font(g.font);
|
||||
if let Embedding::Forbidden(reason) = f.embedding {
|
||||
return Err(ExportError::FontNotEmbeddable { family: f.family.clone(), reason });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Writer<'a> {
|
||||
pdf: Pdf,
|
||||
next: i32,
|
||||
book: &'a FontBook,
|
||||
fonts: BTreeMap<FontKey, (Ref, FontUse)>,
|
||||
images: BTreeMap<String, (Ref, String)>,
|
||||
alphas: BTreeMap<(u8, u8), (Ref, String)>,
|
||||
patterns: Vec<(Ref, String, DPaint, Tf)>,
|
||||
forms: Vec<(Ref, String, Vec<u8>)>,
|
||||
}
|
||||
|
||||
impl Writer<'_> {
|
||||
fn alloc(&mut self) -> Ref {
|
||||
self.next += 1;
|
||||
Ref::new(self.next)
|
||||
}
|
||||
|
||||
fn alpha(&mut self, fill: u8, stroke: u8) -> String {
|
||||
if let Some((_, n)) = self.alphas.get(&(fill, stroke)) {
|
||||
return n.clone();
|
||||
}
|
||||
let r = self.alloc();
|
||||
let n = format!("A{}", self.alphas.len());
|
||||
self.alphas.insert((fill, stroke), (r, n.clone()));
|
||||
n
|
||||
}
|
||||
|
||||
fn pattern(&mut self, p: &DPaint, full: Tf) -> String {
|
||||
let r = self.alloc();
|
||||
let n = format!("P{}", self.patterns.len());
|
||||
self.patterns.push((r, n.clone(), p.clone(), full));
|
||||
n
|
||||
}
|
||||
|
||||
fn image(&mut self, asset: &str) -> String {
|
||||
if let Some((_, n)) = self.images.get(asset) {
|
||||
return n.clone();
|
||||
}
|
||||
let r = self.alloc();
|
||||
let n = format!("Im{}", self.images.len());
|
||||
self.images.insert(asset.to_string(), (r, n.clone()));
|
||||
n
|
||||
}
|
||||
|
||||
fn font(&mut self, key: FontKey) -> String {
|
||||
if let Some((_, u)) = self.fonts.get(&key) {
|
||||
return u.name.clone();
|
||||
}
|
||||
let r = self.alloc();
|
||||
let n = format!("F{}", self.fonts.len());
|
||||
let f = self.book.font(key);
|
||||
let subset = ttf_parser::Face::parse(&f.data, f.index).map(|fc| fc.is_subsetting_allowed()).unwrap_or(false);
|
||||
let u = FontUse { name: n.clone(), subset, remapper: subsetter::GlyphRemapper::new(), glyphs: BTreeMap::new() };
|
||||
self.fonts.insert(key, (r, u));
|
||||
n
|
||||
}
|
||||
}
|
||||
|
||||
/// The names a page or form refers to, copied out of the writer so the PDF can be written while they are used.
|
||||
#[derive(Default)]
|
||||
struct ResTable {
|
||||
fonts: Vec<(String, Ref)>,
|
||||
xobjects: Vec<(String, Ref)>,
|
||||
states: Vec<(String, Ref)>,
|
||||
patterns: Vec<(String, Ref)>,
|
||||
}
|
||||
|
||||
impl Writer<'_> {
|
||||
fn table(&self) -> ResTable {
|
||||
ResTable {
|
||||
fonts: self.fonts.values().map(|(r, u)| (u.name.clone(), *r)).collect(),
|
||||
xobjects: self
|
||||
.images
|
||||
.values()
|
||||
.map(|(r, n)| (n.clone(), *r))
|
||||
.chain(self.forms.iter().map(|(r, n, _)| (n.clone(), *r)))
|
||||
.collect(),
|
||||
states: self.alphas.values().map(|(r, n)| (n.clone(), *r)).collect(),
|
||||
patterns: self.patterns.iter().map(|(r, n, _, _)| (n.clone(), *r)).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write_resources(t: &ResTable, res: &mut pdf_writer::writers::Resources) {
|
||||
let mut f = res.fonts();
|
||||
for (n, r) in &t.fonts {
|
||||
f.pair(Name(n.as_bytes()), *r);
|
||||
}
|
||||
f.finish();
|
||||
let mut x = res.x_objects();
|
||||
for (n, r) in &t.xobjects {
|
||||
x.pair(Name(n.as_bytes()), *r);
|
||||
}
|
||||
x.finish();
|
||||
let mut g = res.ext_g_states();
|
||||
for (n, r) in &t.states {
|
||||
g.pair(Name(n.as_bytes()), *r);
|
||||
}
|
||||
g.finish();
|
||||
let mut p = res.patterns();
|
||||
for (n, r) in &t.patterns {
|
||||
p.pair(Name(n.as_bytes()), *r);
|
||||
}
|
||||
p.finish();
|
||||
}
|
||||
|
||||
fn path_ops(c: &mut Content, d: &str) {
|
||||
let Ok(segs) = path::parse(d) else { return };
|
||||
let (mut cx, mut cy) = (0.0f32, 0.0f32);
|
||||
for s in segs {
|
||||
match s {
|
||||
path::Seg::Move(x, y) => {
|
||||
c.move_to(x, y);
|
||||
(cx, cy) = (x, y);
|
||||
}
|
||||
path::Seg::Line(x, y) => {
|
||||
c.line_to(x, y);
|
||||
(cx, cy) = (x, y);
|
||||
}
|
||||
path::Seg::Quad(a, b, x, y) => {
|
||||
// Quadratic → cubic.
|
||||
let (c1x, c1y) = (cx + 2.0 / 3.0 * (a - cx), cy + 2.0 / 3.0 * (b - cy));
|
||||
let (c2x, c2y) = (x + 2.0 / 3.0 * (a - x), y + 2.0 / 3.0 * (b - y));
|
||||
c.cubic_to(c1x, c1y, c2x, c2y, x, y);
|
||||
(cx, cy) = (x, y);
|
||||
}
|
||||
path::Seg::Cubic(a, b, e, f, x, y) => {
|
||||
c.cubic_to(a, b, e, f, x, y);
|
||||
(cx, cy) = (x, y);
|
||||
}
|
||||
path::Seg::Close => {
|
||||
c.close_path();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn rgb(c: [u8; 4]) -> (f32, f32, f32) {
|
||||
(c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0)
|
||||
}
|
||||
|
||||
/// The alpha a paint is drawn with (a gradient's stops share one: the average of theirs).
|
||||
fn paint_alpha(p: &DPaint) -> u8 {
|
||||
match p {
|
||||
DPaint::Solid { c } => c[3],
|
||||
DPaint::Linear { stops, .. } | DPaint::Radial { stops, .. } => {
|
||||
if stops.is_empty() {
|
||||
255
|
||||
} else {
|
||||
(stops.iter().map(|(_, c)| c[3] as u32).sum::<u32>() / stops.len() as u32) as u8
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_paint(w: &mut Writer, c: &mut Content, p: &DPaint, full: Tf, stroke: bool) {
|
||||
match p {
|
||||
DPaint::Solid { c: col } => {
|
||||
let (r, g, b) = rgb(*col);
|
||||
if stroke {
|
||||
c.set_stroke_rgb(r, g, b);
|
||||
} else {
|
||||
c.set_fill_rgb(r, g, b);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let n = w.pattern(p, full);
|
||||
if stroke {
|
||||
c.set_stroke_color_space(pdf_writer::types::ColorSpaceOperand::Pattern);
|
||||
c.set_stroke_pattern(None, Name(n.as_bytes()));
|
||||
} else {
|
||||
c.set_fill_color_space(pdf_writer::types::ColorSpaceOperand::Pattern);
|
||||
c.set_fill_pattern(None, Name(n.as_bytes()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The document as PDF: every page at its size, vectors as vectors, real text, pictures with their alpha.
|
||||
pub fn pdf(doc: &Document, book: &FontBook) -> Result<Vec<u8>, ExportError> {
|
||||
let lists: Vec<DisplayList> = doc.pages.iter().map(|p| display::build(doc, p, book)).collect();
|
||||
check_fonts(&lists, book)?;
|
||||
let mut w = Writer {
|
||||
pdf: Pdf::new(),
|
||||
next: 0,
|
||||
book,
|
||||
fonts: BTreeMap::new(),
|
||||
images: BTreeMap::new(),
|
||||
alphas: BTreeMap::new(),
|
||||
patterns: Vec::new(),
|
||||
forms: Vec::new(),
|
||||
};
|
||||
let catalog = w.alloc();
|
||||
let pages_id = w.alloc();
|
||||
let mut page_refs = Vec::new();
|
||||
let mut contents = Vec::new();
|
||||
for list in &lists {
|
||||
let flip: Tf = [1.0, 0.0, 0.0, -1.0, 0.0, list.height];
|
||||
let mut stack: Vec<(Content, f32)> = vec![(Content::new(), 1.0)];
|
||||
{
|
||||
let c = &mut stack[0].0;
|
||||
c.transform(flip);
|
||||
if let Some(bg) = list.background {
|
||||
let (r, g, b) = rgb(bg);
|
||||
c.set_fill_rgb(r, g, b);
|
||||
c.rect(0.0, 0.0, list.width, list.height);
|
||||
c.fill_nonzero();
|
||||
}
|
||||
}
|
||||
for item in &list.items {
|
||||
match item {
|
||||
Item::Push { opacity } => stack.push((Content::new(), *opacity)),
|
||||
Item::Pop => {
|
||||
if stack.len() > 1 {
|
||||
let (inner, opacity) = stack.pop().unwrap();
|
||||
let r = w.alloc();
|
||||
let n = format!("X{}", w.forms.len());
|
||||
w.forms.push((r, n.clone(), inner.finish().to_vec()));
|
||||
let a = w.alpha((opacity * 255.0).round() as u8, (opacity * 255.0).round() as u8);
|
||||
let c = &mut stack.last_mut().unwrap().0;
|
||||
c.save_state();
|
||||
c.set_parameters(Name(a.as_bytes()));
|
||||
c.x_object(Name(n.as_bytes()));
|
||||
c.restore_state();
|
||||
}
|
||||
}
|
||||
Item::Fill { d, t, paint, even_odd, .. } => {
|
||||
let full = display::mul(flip, *t);
|
||||
let alpha = paint_alpha(paint);
|
||||
let a = (alpha < 255).then(|| w.alpha(alpha, 255));
|
||||
let mut c = std::mem::replace(&mut stack.last_mut().unwrap().0, Content::new());
|
||||
c.save_state();
|
||||
if let Some(a) = &a {
|
||||
c.set_parameters(Name(a.as_bytes()));
|
||||
}
|
||||
c.transform(*t);
|
||||
set_paint(&mut w, &mut c, paint, full, false);
|
||||
path_ops(&mut c, d);
|
||||
if *even_odd {
|
||||
c.fill_even_odd();
|
||||
} else {
|
||||
c.fill_nonzero();
|
||||
}
|
||||
c.restore_state();
|
||||
stack.last_mut().unwrap().0 = c;
|
||||
}
|
||||
Item::Stroke { d, t, paint, width, cap, join, dash, .. } => {
|
||||
let full = display::mul(flip, *t);
|
||||
let alpha = paint_alpha(paint);
|
||||
let a = (alpha < 255).then(|| w.alpha(255, alpha));
|
||||
let mut c = std::mem::replace(&mut stack.last_mut().unwrap().0, Content::new());
|
||||
c.save_state();
|
||||
if let Some(a) = &a {
|
||||
c.set_parameters(Name(a.as_bytes()));
|
||||
}
|
||||
c.transform(*t);
|
||||
set_paint(&mut w, &mut c, paint, full, true);
|
||||
c.set_line_width(*width);
|
||||
c.set_line_cap(match cap {
|
||||
Cap::Butt => pdf_writer::types::LineCapStyle::ButtCap,
|
||||
Cap::Round => pdf_writer::types::LineCapStyle::RoundCap,
|
||||
Cap::Square => pdf_writer::types::LineCapStyle::ProjectingSquareCap,
|
||||
});
|
||||
c.set_line_join(match join {
|
||||
Join::Miter => pdf_writer::types::LineJoinStyle::MiterJoin,
|
||||
Join::Round => pdf_writer::types::LineJoinStyle::RoundJoin,
|
||||
Join::Bevel => pdf_writer::types::LineJoinStyle::BevelJoin,
|
||||
});
|
||||
c.set_miter_limit(10.0);
|
||||
if dash.len() >= 2 && dash.iter().any(|v| *v > 0.0) {
|
||||
c.set_dash_pattern(dash.iter().copied(), 0.0);
|
||||
}
|
||||
path_ops(&mut c, d);
|
||||
c.stroke();
|
||||
c.restore_state();
|
||||
stack.last_mut().unwrap().0 = c;
|
||||
}
|
||||
Item::Image { asset, t, clip, clip_t, .. } => {
|
||||
let Some(r) = doc.assets.get(asset) else { continue };
|
||||
let (pw, ph) = (r.width as f32, r.height as f32);
|
||||
let n = w.image(asset);
|
||||
let c = &mut stack.last_mut().unwrap().0;
|
||||
c.save_state();
|
||||
let rel = match clip {
|
||||
Some(cd) => {
|
||||
c.transform(*clip_t);
|
||||
path_ops(c, cd);
|
||||
c.clip_nonzero();
|
||||
c.end_path();
|
||||
display::mul(display::invert(*clip_t), *t)
|
||||
}
|
||||
None => *t,
|
||||
};
|
||||
c.transform(rel);
|
||||
// The image's unit square, its first row at the top (the page runs y down here).
|
||||
c.transform([pw, 0.0, 0.0, -ph, 0.0, ph]);
|
||||
c.x_object(Name(n.as_bytes()));
|
||||
c.restore_state();
|
||||
}
|
||||
Item::Text { t, color, size, glyphs, .. } => {
|
||||
let mut c = std::mem::replace(&mut stack.last_mut().unwrap().0, Content::new());
|
||||
c.save_state();
|
||||
if color[3] < 255 {
|
||||
let a = w.alpha(color[3], 255);
|
||||
c.set_parameters(Name(a.as_bytes()));
|
||||
}
|
||||
c.transform(*t);
|
||||
let (r, g, b) = rgb(*color);
|
||||
c.set_fill_rgb(r, g, b);
|
||||
c.begin_text();
|
||||
// Runs of glyphs that share a line and a font.
|
||||
let mut i = 0;
|
||||
while i < glyphs.len() {
|
||||
let font = glyphs[i].font;
|
||||
let y = glyphs[i].y;
|
||||
let mut j = i + 1;
|
||||
while j < glyphs.len() && glyphs[j].font == font && glyphs[j].y == y {
|
||||
j += 1;
|
||||
}
|
||||
let run = &glyphs[i..j];
|
||||
let fname = w.font(font);
|
||||
let f = book.font(font);
|
||||
let face = ttf_parser::Face::parse(&f.data, f.index).ok();
|
||||
let width_of = |gid: u16| -> f32 {
|
||||
face.as_ref()
|
||||
.and_then(|fc| fc.glyph_hor_advance(ttf_parser::GlyphId(gid)))
|
||||
.map(|a| a as f32 * 1000.0 / f.units_per_em)
|
||||
.unwrap_or(0.0)
|
||||
};
|
||||
let cids: Vec<u16> = {
|
||||
let u = &mut w.fonts.get_mut(&font).unwrap().1;
|
||||
run.iter()
|
||||
.map(|g| {
|
||||
let cid = if u.subset { u.remapper.remap(g.gid) } else { g.gid };
|
||||
let e = u.glyphs.entry(cid).or_insert_with(|| (g.gid, String::new()));
|
||||
if e.1.is_empty() {
|
||||
e.1.push_str(&g.text);
|
||||
}
|
||||
cid
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
c.set_font(Name(fname.as_bytes()), *size);
|
||||
c.set_text_matrix([1.0, 0.0, 0.0, -1.0, run[0].x, y]);
|
||||
let mut items_buf: Vec<(Vec<u8>, f32)> = Vec::new();
|
||||
let mut x = run[0].x;
|
||||
for (k, g) in run.iter().enumerate() {
|
||||
// Where the PDF would put the next glyph vs where the layout put it.
|
||||
let adv = width_of(g.gid) * size / 1000.0;
|
||||
let next_x = run.get(k + 1).map(|n| n.x).unwrap_or(x + adv);
|
||||
let adjust = (next_x - (x + adv)) * 1000.0 / size;
|
||||
items_buf.push((cids[k].to_be_bytes().to_vec(), adjust));
|
||||
x = next_x;
|
||||
}
|
||||
{
|
||||
let mut sp = c.show_positioned();
|
||||
let mut its = sp.items();
|
||||
for (bytes, adjust) in &items_buf {
|
||||
its.show(Str(bytes));
|
||||
if adjust.abs() > 0.01 {
|
||||
its.adjust(-adjust);
|
||||
}
|
||||
}
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
c.end_text();
|
||||
c.restore_state();
|
||||
stack.last_mut().unwrap().0 = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
while stack.len() > 1 {
|
||||
let (inner, opacity) = stack.pop().unwrap();
|
||||
let r = w.alloc();
|
||||
let n = format!("X{}", w.forms.len());
|
||||
w.forms.push((r, n.clone(), inner.finish().to_vec()));
|
||||
let a = w.alpha((opacity * 255.0).round() as u8, (opacity * 255.0).round() as u8);
|
||||
let c = &mut stack.last_mut().unwrap().0;
|
||||
c.save_state();
|
||||
c.set_parameters(Name(a.as_bytes()));
|
||||
c.x_object(Name(n.as_bytes()));
|
||||
c.restore_state();
|
||||
}
|
||||
let page_ref = w.alloc();
|
||||
let content_ref = w.alloc();
|
||||
page_refs.push(page_ref);
|
||||
contents.push((page_ref, content_ref, stack.pop().unwrap().0.finish().to_vec(), list.width, list.height));
|
||||
}
|
||||
|
||||
type FontJob = (FontKey, Ref, bool, subsetter::GlyphRemapper, BTreeMap<u16, (u16, String)>);
|
||||
let font_list: Vec<FontJob> =
|
||||
w.fonts.iter().map(|(k, (r, u))| (*k, *r, u.subset, u.remapper.clone(), u.glyphs.clone())).collect();
|
||||
for (key, type0, subset, remapper, glyphs) in font_list {
|
||||
write_font(&mut w, key, type0, subset, &remapper, &glyphs)?;
|
||||
}
|
||||
|
||||
let images: Vec<(String, Ref)> = w.images.iter().map(|(a, (r, _))| (a.clone(), *r)).collect();
|
||||
for (asset, r) in images {
|
||||
let raster = &doc.assets[&asset];
|
||||
let mut rgb_data = Vec::with_capacity(raster.rgba.len() / 4 * 3);
|
||||
let mut alpha = Vec::with_capacity(raster.rgba.len() / 4);
|
||||
for p in raster.rgba.as_chunks::<4>().0 {
|
||||
rgb_data.extend_from_slice(&p[..3]);
|
||||
alpha.push(p[3]);
|
||||
}
|
||||
let has_alpha = alpha.iter().any(|a| *a < 255);
|
||||
let mask_ref = has_alpha.then(|| w.alloc());
|
||||
let data = deflate(&rgb_data);
|
||||
let mut im = w.pdf.image_xobject(r, &data);
|
||||
im.filter(Filter::FlateDecode);
|
||||
im.width(raster.width as i32);
|
||||
im.height(raster.height as i32);
|
||||
im.color_space().device_rgb();
|
||||
im.bits_per_component(8);
|
||||
if let Some(m) = mask_ref {
|
||||
im.s_mask(m);
|
||||
}
|
||||
im.finish();
|
||||
if let Some(m) = mask_ref {
|
||||
let data = deflate(&alpha);
|
||||
let mut sm = w.pdf.image_xobject(m, &data);
|
||||
sm.filter(Filter::FlateDecode);
|
||||
sm.width(raster.width as i32);
|
||||
sm.height(raster.height as i32);
|
||||
sm.color_space().device_gray();
|
||||
sm.bits_per_component(8);
|
||||
sm.finish();
|
||||
}
|
||||
}
|
||||
|
||||
let alphas: Vec<((u8, u8), Ref)> = w.alphas.iter().map(|(k, (r, _))| (*k, *r)).collect();
|
||||
for ((fa, sa), r) in alphas {
|
||||
w.pdf.ext_graphics(r).non_stroking_alpha(fa as f32 / 255.0).stroking_alpha(sa as f32 / 255.0);
|
||||
}
|
||||
|
||||
let patterns = std::mem::take(&mut w.patterns);
|
||||
for (r, _, p, full) in &patterns {
|
||||
let shading = w.alloc();
|
||||
let func = w.alloc();
|
||||
let (stops, kind, coords): (&Vec<(f32, [u8; 4])>, _, Vec<f32>) = match p {
|
||||
DPaint::Linear { x1, y1, x2, y2, stops } => {
|
||||
(stops, pdf_writer::types::FunctionShadingType::Axial, vec![*x1, *y1, *x2, *y2])
|
||||
}
|
||||
DPaint::Radial { cx, cy, r, stops } => {
|
||||
(stops, pdf_writer::types::FunctionShadingType::Radial, vec![*cx, *cy, 0.0, *cx, *cy, *r])
|
||||
}
|
||||
DPaint::Solid { .. } => continue,
|
||||
};
|
||||
write_stops(&mut w, func, stops);
|
||||
{
|
||||
let mut sh = w.pdf.function_shading(shading);
|
||||
sh.shading_type(kind);
|
||||
sh.color_space().device_rgb();
|
||||
sh.coords(coords);
|
||||
sh.function(func);
|
||||
sh.extend([true, true]);
|
||||
}
|
||||
let mut pat = w.pdf.shading_pattern(*r);
|
||||
pat.pair(Name(b"Shading"), shading);
|
||||
pat.matrix(*full);
|
||||
}
|
||||
w.patterns = patterns;
|
||||
|
||||
let table = w.table();
|
||||
let forms = std::mem::take(&mut w.forms);
|
||||
let (pw, ph) = lists.first().map(|l| (l.width, l.height)).unwrap_or((1.0, 1.0));
|
||||
for (r, _, content) in &forms {
|
||||
let data = deflate(content);
|
||||
let mut f = w.pdf.form_xobject(*r, &data);
|
||||
f.filter(Filter::FlateDecode);
|
||||
let maxw = lists.iter().map(|l| l.width).fold(pw, f32::max);
|
||||
let maxh = lists.iter().map(|l| l.height).fold(ph, f32::max);
|
||||
f.bbox(PRect::new(-1.0, -1.0, maxw + 1.0, maxh + 1.0));
|
||||
f.group().transparency().isolated(true);
|
||||
let mut res = f.resources();
|
||||
write_resources(&table, &mut res);
|
||||
res.finish();
|
||||
f.finish();
|
||||
}
|
||||
w.forms = forms;
|
||||
|
||||
for (page_ref, content_ref, content, width, height) in &contents {
|
||||
let data = deflate(content);
|
||||
w.pdf.stream(*content_ref, &data).filter(Filter::FlateDecode);
|
||||
let mut page = w.pdf.page(*page_ref);
|
||||
page.media_box(PRect::new(0.0, 0.0, *width, *height));
|
||||
page.parent(pages_id);
|
||||
page.contents(*content_ref);
|
||||
let mut res = page.resources();
|
||||
write_resources(&table, &mut res);
|
||||
res.finish();
|
||||
page.finish();
|
||||
}
|
||||
w.pdf.pages(pages_id).kids(page_refs.iter().copied()).count(page_refs.len() as i32);
|
||||
w.pdf.catalog(catalog).pages(pages_id);
|
||||
let info = w.alloc();
|
||||
w.pdf.document_info(info).producer(pdf_writer::TextStr("Pictor"));
|
||||
Ok(w.pdf.finish())
|
||||
}
|
||||
|
||||
fn write_stops(w: &mut Writer, func: Ref, stops: &[(f32, [u8; 4])]) {
|
||||
let col = |c: [u8; 4]| {
|
||||
let (r, g, b) = rgb(c);
|
||||
[r, g, b]
|
||||
};
|
||||
let mut stops: Vec<(f32, [u8; 4])> = stops.to_vec();
|
||||
if stops.is_empty() {
|
||||
stops.push((0.0, [0, 0, 0, 255]));
|
||||
}
|
||||
if stops.len() == 1 {
|
||||
stops.push(stops[0]);
|
||||
}
|
||||
if stops.len() == 2 {
|
||||
w.pdf.exponential_function(func).domain([0.0, 1.0]).c0(col(stops[0].1)).c1(col(stops[1].1)).n(1.0);
|
||||
return;
|
||||
}
|
||||
// Stitch one exponential function per pair of stops.
|
||||
let mut parts = Vec::new();
|
||||
for pair in stops.windows(2) {
|
||||
let r = w.alloc();
|
||||
w.pdf.exponential_function(r).domain([0.0, 1.0]).c0(col(pair[0].1)).c1(col(pair[1].1)).n(1.0);
|
||||
parts.push(r);
|
||||
}
|
||||
let bounds: Vec<f32> = stops[1..stops.len() - 1].iter().map(|s| s.0).collect();
|
||||
let encode: Vec<f32> = parts.iter().flat_map(|_| [0.0, 1.0]).collect();
|
||||
let mut s = w.pdf.stitching_function(func);
|
||||
s.domain([0.0, 1.0]);
|
||||
s.functions(parts);
|
||||
s.bounds(bounds);
|
||||
s.encode(encode);
|
||||
}
|
||||
|
||||
/// Writes a Type 0 font: the font program (a subset when its licence allows), its descriptor, widths and the
|
||||
/// ToUnicode map. CIDs are the subset's glyph ids (or the font's own when it is embedded whole), so CIDToGIDMap is
|
||||
/// the identity.
|
||||
fn write_font(
|
||||
w: &mut Writer,
|
||||
key: FontKey,
|
||||
type0: Ref,
|
||||
subset: bool,
|
||||
remapper: &subsetter::GlyphRemapper,
|
||||
glyphs: &BTreeMap<u16, (u16, String)>,
|
||||
) -> Result<(), ExportError> {
|
||||
let f = w.book.font(key);
|
||||
let face = ttf_parser::Face::parse(&f.data, f.index).map_err(|_| ExportError::FontBroken(f.family.clone()))?;
|
||||
let program: Vec<u8> = if subset {
|
||||
subsetter::subset(&f.data, f.index, remapper).map_err(|_| ExportError::FontBroken(f.family.clone()))?
|
||||
} else {
|
||||
f.data.to_vec()
|
||||
};
|
||||
let cid_ref = w.alloc();
|
||||
let desc_ref = w.alloc();
|
||||
let file_ref = w.alloc();
|
||||
let cmap_ref = w.alloc();
|
||||
// A subset tag from the glyph set, so two subsets of one font get different names.
|
||||
let tag: String = {
|
||||
use sha2::Digest;
|
||||
let mut h = sha2::Sha256::new();
|
||||
for (cid, (gid, _)) in glyphs {
|
||||
h.update(cid.to_be_bytes());
|
||||
h.update(gid.to_be_bytes());
|
||||
}
|
||||
h.update(f.post_script_name.as_bytes());
|
||||
h.finalize().iter().take(6).map(|b| (b'A' + b % 26) as char).collect()
|
||||
};
|
||||
let ps: String = f.post_script_name.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').collect();
|
||||
let ps = if ps.is_empty() { "Font".to_string() } else { ps };
|
||||
let base = if subset { format!("{tag}+{ps}") } else { ps };
|
||||
let s = 1000.0 / f.units_per_em;
|
||||
|
||||
w.pdf
|
||||
.type0_font(type0)
|
||||
.base_font(Name(base.as_bytes()))
|
||||
.encoding_predefined(Name(b"Identity-H"))
|
||||
.descendant_font(cid_ref)
|
||||
.to_unicode(cmap_ref);
|
||||
|
||||
{
|
||||
let mut cid = w.pdf.cid_font(cid_ref);
|
||||
cid.subtype(if f.cff { pdf_writer::types::CidFontType::Type0 } else { pdf_writer::types::CidFontType::Type2 });
|
||||
cid.base_font(Name(base.as_bytes()));
|
||||
cid.system_info(pdf_writer::types::SystemInfo {
|
||||
registry: Str(b"Adobe"),
|
||||
ordering: Str(b"Identity"),
|
||||
supplement: 0,
|
||||
});
|
||||
cid.font_descriptor(desc_ref);
|
||||
cid.default_width(0.0);
|
||||
if !f.cff {
|
||||
cid.cid_to_gid_map_predefined(Name(b"Identity"));
|
||||
}
|
||||
{
|
||||
let mut ws = cid.widths();
|
||||
for (cid_v, (gid, _)) in glyphs {
|
||||
let adv = face.glyph_hor_advance(ttf_parser::GlyphId(*gid)).unwrap_or(0) as f32 * s;
|
||||
ws.consecutive(*cid_v, [adv]);
|
||||
}
|
||||
}
|
||||
cid.finish();
|
||||
}
|
||||
|
||||
let bbox = face.global_bounding_box();
|
||||
{
|
||||
let mut fd = w.pdf.font_descriptor(desc_ref);
|
||||
fd.name(Name(base.as_bytes()));
|
||||
let mut flags = pdf_writer::types::FontFlags::SYMBOLIC;
|
||||
if f.italic {
|
||||
flags |= pdf_writer::types::FontFlags::ITALIC;
|
||||
}
|
||||
fd.flags(flags);
|
||||
fd.bbox(PRect::new(bbox.x_min as f32 * s, bbox.y_min as f32 * s, bbox.x_max as f32 * s, bbox.y_max as f32 * s));
|
||||
fd.italic_angle(face.italic_angle());
|
||||
fd.ascent(f.ascender * s);
|
||||
fd.descent(f.descender * s);
|
||||
fd.cap_height(f.cap_height * s);
|
||||
fd.stem_v(80.0 + (f.weight as f32 - 400.0).max(0.0) / 5.0);
|
||||
if f.cff {
|
||||
fd.font_file3(file_ref);
|
||||
} else {
|
||||
fd.font_file2(file_ref);
|
||||
}
|
||||
fd.finish();
|
||||
}
|
||||
{
|
||||
let data = deflate(&program);
|
||||
let mut st = w.pdf.stream(file_ref, &data);
|
||||
st.filter(Filter::FlateDecode);
|
||||
if f.cff {
|
||||
st.pair(Name(b"Subtype"), Name(b"OpenType"));
|
||||
} else {
|
||||
st.pair(Name(b"Length1"), program.len() as i32);
|
||||
}
|
||||
st.finish();
|
||||
}
|
||||
{
|
||||
let mut cmap = pdf_writer::types::UnicodeCmap::new(
|
||||
Name(b"Custom"),
|
||||
pdf_writer::types::SystemInfo { registry: Str(b"Adobe"), ordering: Str(b"UCS"), supplement: 0 },
|
||||
);
|
||||
for (cid, (_, text)) in glyphs {
|
||||
if !text.is_empty() {
|
||||
cmap.pair_with_multiple(*cid, text.chars());
|
||||
}
|
||||
}
|
||||
let data = cmap.finish();
|
||||
w.pdf.cmap(cmap_ref, &data);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
//! Fixture documents: the format round trip, the undo property test, the core's renders and the app's fidelity test
|
||||
//! (the face's canvas painter against the core's PNG) all use these.
|
||||
use crate::model::*;
|
||||
|
||||
fn obj(doc: &mut Document, shape: Shape) -> Object {
|
||||
Object {
|
||||
id: doc.new_id(),
|
||||
name: String::new(),
|
||||
transform: identity(),
|
||||
opacity: 1.0,
|
||||
visible: true,
|
||||
locked: false,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
shape,
|
||||
}
|
||||
}
|
||||
|
||||
fn at(mut o: Object, x: f32, y: f32) -> Object {
|
||||
o.transform[4] = x;
|
||||
o.transform[5] = y;
|
||||
o
|
||||
}
|
||||
|
||||
fn rgb(hex: &str) -> Rgba {
|
||||
Rgba::hex(hex).expect("a hex colour")
|
||||
}
|
||||
|
||||
/// A generated picture (no files): a gradient with a disc, `w` × `h`.
|
||||
pub fn picture(w: u32, h: u32) -> Raster {
|
||||
let mut r = Raster::new(w, h);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let i = ((y * w + x) * 4) as usize;
|
||||
let (fx, fy) = (x as f32 / w as f32, y as f32 / h as f32);
|
||||
let d = ((fx - 0.6).powi(2) + (fy - 0.4).powi(2)).sqrt();
|
||||
let disc = d < 0.22;
|
||||
r.rgba[i] = if disc { 242 } else { (40.0 + 180.0 * fx) as u8 };
|
||||
r.rgba[i + 1] = if disc { 122 } else { (60.0 + 120.0 * fy) as u8 };
|
||||
r.rgba[i + 2] = if disc { 185 } else { 150 };
|
||||
r.rgba[i + 3] = 255;
|
||||
}
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
fn vector_layer(doc: &mut Document, name: &str, objects: Vec<Object>) -> Layer {
|
||||
let mut l = Layer::vector(doc.new_id(), name);
|
||||
l.kind = LayerKind::Vector { objects };
|
||||
l
|
||||
}
|
||||
|
||||
/// Shapes: rounded rectangle with a stroke, an ellipse with a linear gradient, a dashed path with curves, an arrow,
|
||||
/// a half-transparent group, a rotated rectangle.
|
||||
pub fn shapes() -> Document {
|
||||
let mut d = Document::with_page(400.0, 300.0, Some(Rgba::WHITE));
|
||||
let mut r = at(obj(&mut d, Shape::Rect { w: 140.0, h: 90.0, radius: 14.0 }), 20.0, 20.0);
|
||||
r.fill = Some(Paint::solid(rgb("1f2a44")));
|
||||
r.stroke = Some(Stroke {
|
||||
paint: Paint::solid(rgb("b08d57")),
|
||||
width: 4.0,
|
||||
dash: vec![],
|
||||
cap: Cap::Butt,
|
||||
join: Join::Round,
|
||||
});
|
||||
let mut e = at(obj(&mut d, Shape::Ellipse { w: 150.0, h: 100.0 }), 200.0, 20.0);
|
||||
e.fill = Some(Paint::Linear {
|
||||
x1: 0.0,
|
||||
y1: 0.0,
|
||||
x2: 1.0,
|
||||
y2: 1.0,
|
||||
stops: vec![Stop { offset: 0.0, color: rgb("f27ab9") }, Stop { offset: 1.0, color: rgb("d3d98f") }],
|
||||
});
|
||||
let mut p = at(
|
||||
obj(&mut d, Shape::Path { d: "M0 60 C40 0 80 120 120 60 Q150 20 180 60 L180 90 L0 90 Z".into() }),
|
||||
20.0,
|
||||
150.0,
|
||||
);
|
||||
p.fill = Some(Paint::solid(Rgba([74, 163, 255, 160])));
|
||||
p.stroke = Some(Stroke {
|
||||
paint: Paint::solid(rgb("111111")),
|
||||
width: 2.0,
|
||||
dash: vec![8.0, 4.0],
|
||||
cap: Cap::Round,
|
||||
join: Join::Miter,
|
||||
});
|
||||
let mut a =
|
||||
obj(&mut d, Shape::Line { x1: 230.0, y1: 280.0, x2: 370.0, y2: 160.0, arrow_start: false, arrow_end: true });
|
||||
a.stroke = Some(Stroke {
|
||||
paint: Paint::solid(rgb("ff3b3b")),
|
||||
width: 5.0,
|
||||
dash: vec![],
|
||||
cap: Cap::Round,
|
||||
join: Join::Round,
|
||||
});
|
||||
let mut g1 = at(obj(&mut d, Shape::Rect { w: 60.0, h: 60.0, radius: 0.0 }), 0.0, 0.0);
|
||||
g1.fill = Some(Paint::solid(rgb("3ad07a")));
|
||||
let mut g2 = at(obj(&mut d, Shape::Ellipse { w: 60.0, h: 60.0 }), 30.0, 20.0);
|
||||
g2.fill = Some(Paint::solid(rgb("ffd23f")));
|
||||
let mut g = at(obj(&mut d, Shape::Group { objects: vec![g1, g2] }), 220.0, 150.0);
|
||||
g.opacity = 0.5;
|
||||
let mut rot = obj(&mut d, Shape::Rect { w: 50.0, h: 30.0, radius: 4.0 });
|
||||
let (s, c) = 0.5f32.sin_cos();
|
||||
rot.transform = [c, s, -s, c, 330.0, 240.0];
|
||||
rot.fill = Some(Paint::Radial {
|
||||
cx: 0.5,
|
||||
cy: 0.5,
|
||||
r: 0.6,
|
||||
stops: vec![Stop { offset: 0.0, color: rgb("ffffff") }, Stop { offset: 1.0, color: rgb("1f2a44") }],
|
||||
});
|
||||
let layer = vector_layer(&mut d, "Shapes", vec![r, e, p, a, g, rot]);
|
||||
d.pages[0].layers = vec![layer];
|
||||
d
|
||||
}
|
||||
|
||||
/// Text: wrapped, centred, right-aligned and justified boxes, bold and italic, letter spacing, Czech letters.
|
||||
pub fn text() -> Document {
|
||||
let mut d = Document::with_page(420.0, 300.0, Some(Rgba::WHITE));
|
||||
let style = |family: &str, weight: u16, italic: bool, size: f32, color: &str, align: Align| TextStyle {
|
||||
family: family.into(),
|
||||
weight,
|
||||
italic,
|
||||
size,
|
||||
color: rgb(color),
|
||||
align,
|
||||
line_height: 1.25,
|
||||
letter_spacing: 0.0,
|
||||
};
|
||||
let t1 = at(
|
||||
obj(
|
||||
&mut d,
|
||||
Shape::Text {
|
||||
w: 0.0,
|
||||
text: "Monika Nováková".into(),
|
||||
style: style("Georgia", 700, false, 26.0, "1f2a44", Align::Left),
|
||||
},
|
||||
),
|
||||
20.0,
|
||||
16.0,
|
||||
);
|
||||
let mut s2 = style("Arial", 400, false, 9.0, "b08d57", Align::Left);
|
||||
s2.letter_spacing = 2.0;
|
||||
let t2 = at(obj(&mut d, Shape::Text { w: 0.0, text: "PROJEKTOVÁ MANAŽERKA".into(), style: s2 }), 22.0, 52.0);
|
||||
let body = "Pictor lays text out in the core: shaping, line breaks and alignment, so the screen and the PDF agree. Příliš žluťoučký kůň úpěl ďábelské ódy.";
|
||||
let t3 = at(
|
||||
obj(
|
||||
&mut d,
|
||||
Shape::Text {
|
||||
w: 180.0,
|
||||
text: body.into(),
|
||||
style: style("Segoe UI", 400, false, 10.0, "222222", Align::Justify),
|
||||
},
|
||||
),
|
||||
20.0,
|
||||
80.0,
|
||||
);
|
||||
let t4 = at(
|
||||
obj(
|
||||
&mut d,
|
||||
Shape::Text {
|
||||
w: 180.0,
|
||||
text: "Centred\nin two lines".into(),
|
||||
style: style("Segoe UI", 600, false, 12.0, "1f2a44", Align::Center),
|
||||
},
|
||||
),
|
||||
220.0,
|
||||
80.0,
|
||||
);
|
||||
let t5 = at(
|
||||
obj(
|
||||
&mut d,
|
||||
Shape::Text {
|
||||
w: 180.0,
|
||||
text: "Right, italic".into(),
|
||||
style: style("Georgia", 400, true, 12.0, "7a2e4d", Align::Right),
|
||||
},
|
||||
),
|
||||
220.0,
|
||||
140.0,
|
||||
);
|
||||
let layer = vector_layer(&mut d, "Text", vec![t1, t2, t3, t4, t5]);
|
||||
d.pages[0].layers = vec![layer];
|
||||
d
|
||||
}
|
||||
|
||||
/// A photo-like bitmap layer at 70 % with a vector layer above (a half-transparent rectangle and an outline).
|
||||
pub fn bitmap() -> Document {
|
||||
let mut d = Document::from_image(picture(240, 160), "Photo");
|
||||
let mut r = at(obj(&mut d, Shape::Rect { w: 100.0, h: 60.0, radius: 6.0 }), 20.0, 80.0);
|
||||
r.fill = Some(Paint::solid(Rgba([255, 255, 255, 120])));
|
||||
r.stroke = Some(Stroke {
|
||||
paint: Paint::solid(rgb("1f2a44")),
|
||||
width: 3.0,
|
||||
dash: vec![],
|
||||
cap: Cap::Butt,
|
||||
join: Join::Miter,
|
||||
});
|
||||
if let LayerKind::Vector { objects } = &mut d.pages[0].layers[1].kind {
|
||||
objects.push(r);
|
||||
}
|
||||
d.pages[0].layers[0].opacity = 0.7;
|
||||
d
|
||||
}
|
||||
|
||||
/// A placed picture cropped inside its frame, with a border, over a radial gradient background shape.
|
||||
pub fn image() -> Document {
|
||||
let mut d = Document::with_page(300.0, 220.0, Some(Rgba::WHITE));
|
||||
let asset = "i1".to_string();
|
||||
d.assets.insert(asset.clone(), picture(200, 140));
|
||||
let mut bg = obj(&mut d, Shape::Rect { w: 300.0, h: 220.0, radius: 0.0 });
|
||||
bg.fill = Some(Paint::Radial {
|
||||
cx: 0.3,
|
||||
cy: 0.3,
|
||||
r: 0.9,
|
||||
stops: vec![
|
||||
Stop { offset: 0.0, color: rgb("d3d98f") },
|
||||
Stop { offset: 0.5, color: rgb("f27ab9") },
|
||||
Stop { offset: 1.0, color: rgb("1f2a44") },
|
||||
],
|
||||
});
|
||||
let mut im = at(
|
||||
obj(&mut d, Shape::Image { asset, w: 120.0, h: 120.0, crop: Rect { x: -60.0, y: -10.0, w: 200.0, h: 140.0 } }),
|
||||
90.0,
|
||||
50.0,
|
||||
);
|
||||
im.stroke = Some(Stroke {
|
||||
paint: Paint::solid(rgb("ffffff")),
|
||||
width: 4.0,
|
||||
dash: vec![],
|
||||
cap: Cap::Butt,
|
||||
join: Join::Miter,
|
||||
});
|
||||
let layer = vector_layer(&mut d, "Picture", vec![bg, im]);
|
||||
d.pages[0].layers = vec![layer];
|
||||
d
|
||||
}
|
||||
|
||||
pub fn all() -> Vec<(&'static str, Document)> {
|
||||
vec![("shapes", shapes()), ("text", text()), ("bitmap", bitmap()), ("image", image())]
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
//! The .pictor file: a zip with `document.json`, `assets/<id>.png` and `fonts/<sha256>.<ttf|otf>`
|
||||
//! (docs/FORMATS.md, "The .pictor document"). Reading is strict: entries are read by known name with a size cap and
|
||||
//! never extracted to disk, every name is checked, every referenced asset must be there and match its size, and a
|
||||
//! newer format is refused before anything else is read.
|
||||
use crate::model::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::io::{Cursor, Read, Write};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum FormatError {
|
||||
#[error("This is not a Pictor document (it is not a zip with document.json).")]
|
||||
NotPictor,
|
||||
#[error(
|
||||
"This file was made by a newer Pictor (format {0}); this one reads format {FORMAT}. Update Pictor to open it."
|
||||
)]
|
||||
Newer(u32),
|
||||
#[error("The document is damaged: {0}")]
|
||||
Damaged(String),
|
||||
#[error("The document is too large to open safely: {0}")]
|
||||
TooLarge(String),
|
||||
#[error("The document has an unsafe entry name: {0}")]
|
||||
UnsafeName(String),
|
||||
#[error("The document refers to a missing picture: {0}")]
|
||||
MissingAsset(String),
|
||||
#[error("Could not write the document: {0}")]
|
||||
Write(String),
|
||||
}
|
||||
|
||||
/// Caps for reading a .pictor from outside.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Limits {
|
||||
pub max_entries: usize,
|
||||
pub max_json_bytes: u64,
|
||||
pub max_entry_bytes: u64,
|
||||
pub max_total_bytes: u64,
|
||||
/// Uncompressed size ÷ compressed size, per entry.
|
||||
pub max_ratio: u64,
|
||||
pub max_pixels: u64,
|
||||
pub max_total_pixels: u64,
|
||||
pub max_page_side_pt: f32,
|
||||
pub max_depth: usize,
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
Limits {
|
||||
max_entries: 4096,
|
||||
max_json_bytes: 64 << 20,
|
||||
max_entry_bytes: 256 << 20,
|
||||
max_total_bytes: 1 << 30,
|
||||
max_ratio: 1000,
|
||||
max_pixels: 100_000_000,
|
||||
max_total_pixels: 400_000_000,
|
||||
max_page_side_pt: 14_400.0,
|
||||
max_depth: 32,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A font stored in a document.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct FontFile {
|
||||
pub family: String,
|
||||
pub weight: u16,
|
||||
pub italic: bool,
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct AssetEntry {
|
||||
id: String,
|
||||
width: u32,
|
||||
height: u32,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct FontEntry {
|
||||
family: String,
|
||||
weight: u16,
|
||||
italic: bool,
|
||||
file: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct OnDisk {
|
||||
#[serde(flatten)]
|
||||
doc: Document,
|
||||
#[serde(default)]
|
||||
assets: Vec<AssetEntry>,
|
||||
#[serde(default)]
|
||||
fonts: Vec<FontEntry>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct VersionOnly {
|
||||
format: u32,
|
||||
}
|
||||
|
||||
/// Asset ids are short letters, digits, `-` and `_` (they become file names).
|
||||
pub fn valid_asset_id(id: &str) -> bool {
|
||||
!id.is_empty() && id.len() <= 80 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||
}
|
||||
|
||||
pub fn write(doc: &Document, fonts: &[FontFile]) -> Result<Vec<u8>, FormatError> {
|
||||
use sha2::Digest;
|
||||
let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
let deflate = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||
let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
|
||||
let used = used_assets(doc);
|
||||
let mut assets = Vec::new();
|
||||
for (id, r) in &doc.assets {
|
||||
if !used.contains(id) {
|
||||
continue;
|
||||
}
|
||||
if !valid_asset_id(id) {
|
||||
return Err(FormatError::Write(format!("asset id {id:?}")));
|
||||
}
|
||||
assets.push(AssetEntry { id: id.clone(), width: r.width, height: r.height });
|
||||
let png = encode_png(r)?;
|
||||
zip.start_file(format!("assets/{id}.png"), stored).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||
zip.write_all(&png).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||
}
|
||||
let mut font_entries = Vec::new();
|
||||
for f in fonts {
|
||||
let ext = if f.data.get(0..4) == Some(b"OTTO") { "otf" } else { "ttf" };
|
||||
let hex: String = sha2::Sha256::digest(&f.data).iter().map(|b| format!("{b:02x}")).collect();
|
||||
let name = format!("fonts/{hex}.{ext}");
|
||||
if !font_entries.iter().any(|e: &FontEntry| e.file == name) {
|
||||
zip.start_file(name.clone(), deflate).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||
zip.write_all(&f.data).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||
}
|
||||
font_entries.push(FontEntry { family: f.family.clone(), weight: f.weight, italic: f.italic, file: name });
|
||||
}
|
||||
let on_disk = OnDisk { doc: doc.clone(), assets, fonts: font_entries };
|
||||
let json = serde_json::to_vec(&on_disk).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||
zip.start_file("document.json", deflate).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||
zip.write_all(&json).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||
let out = zip.finish().map_err(|e| FormatError::Write(e.to_string()))?;
|
||||
Ok(out.into_inner())
|
||||
}
|
||||
|
||||
pub fn encode_png(r: &Raster) -> Result<Vec<u8>, FormatError> {
|
||||
use image::ImageEncoder;
|
||||
let mut png = Vec::new();
|
||||
image::codecs::png::PngEncoder::new_with_quality(
|
||||
&mut png,
|
||||
image::codecs::png::CompressionType::Fast,
|
||||
image::codecs::png::FilterType::Adaptive,
|
||||
)
|
||||
.write_image(&r.rgba, r.width, r.height, image::ExtendedColorType::Rgba8)
|
||||
.map_err(|e| FormatError::Write(e.to_string()))?;
|
||||
Ok(png)
|
||||
}
|
||||
|
||||
/// The asset ids the pages refer to.
|
||||
pub fn used_assets(doc: &Document) -> std::collections::BTreeSet<String> {
|
||||
let mut out = std::collections::BTreeSet::new();
|
||||
fn objects(os: &[Object], out: &mut std::collections::BTreeSet<String>) {
|
||||
for o in os {
|
||||
match &o.shape {
|
||||
Shape::Image { asset, .. } => {
|
||||
out.insert(asset.clone());
|
||||
}
|
||||
Shape::Group { objects: g } => objects(g, out),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn layers(ls: &[Layer], out: &mut std::collections::BTreeSet<String>) {
|
||||
for l in ls {
|
||||
match &l.kind {
|
||||
LayerKind::Vector { objects: os } => objects(os, out),
|
||||
LayerKind::Bitmap { asset, .. } => {
|
||||
out.insert(asset.clone());
|
||||
}
|
||||
LayerKind::Group { layers: g } => layers(g, out),
|
||||
}
|
||||
}
|
||||
}
|
||||
for p in &doc.pages {
|
||||
layers(&p.layers, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn safe_name(name: &str) -> bool {
|
||||
!name.is_empty()
|
||||
&& name.len() <= 200
|
||||
&& !name.starts_with('/')
|
||||
&& !name.contains('\\')
|
||||
&& !name.contains(':')
|
||||
&& !name.split('/').any(|part| part.is_empty() || part == ".." || part == ".")
|
||||
}
|
||||
|
||||
fn read_entry<R: Read + std::io::Seek>(
|
||||
zip: &mut zip::ZipArchive<R>,
|
||||
name: &str,
|
||||
cap: u64,
|
||||
limits: &Limits,
|
||||
total: &mut u64,
|
||||
) -> Result<Vec<u8>, FormatError> {
|
||||
let mut f = zip.by_name(name).map_err(|_| FormatError::MissingAsset(name.to_string()))?;
|
||||
let declared = f.size();
|
||||
let compressed = f.compressed_size().max(1);
|
||||
if declared > cap {
|
||||
return Err(FormatError::TooLarge(format!("{name} is {declared} bytes")));
|
||||
}
|
||||
if declared / compressed > limits.max_ratio && declared > 1 << 20 {
|
||||
return Err(FormatError::TooLarge(format!("{name} expands {}×", declared / compressed)));
|
||||
}
|
||||
let mut out = Vec::with_capacity(declared.min(cap) as usize);
|
||||
(&mut f).take(cap + 1).read_to_end(&mut out).map_err(|e| FormatError::Damaged(format!("{name}: {e}")))?;
|
||||
if out.len() as u64 > cap || out.len() as u64 != declared {
|
||||
return Err(FormatError::TooLarge(format!("{name} is larger than it says")));
|
||||
}
|
||||
*total += out.len() as u64;
|
||||
if *total > limits.max_total_bytes {
|
||||
return Err(FormatError::TooLarge("the entries together".into()));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Reads a .pictor. Fonts come back as data for the font book; the document's assets are decoded.
|
||||
pub fn read(bytes: &[u8], limits: &Limits) -> Result<(Document, Vec<FontFile>), FormatError> {
|
||||
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|_| FormatError::NotPictor)?;
|
||||
if zip.len() > limits.max_entries {
|
||||
return Err(FormatError::TooLarge(format!("{} entries", zip.len())));
|
||||
}
|
||||
for i in 0..zip.len() {
|
||||
let f = zip.by_index_raw(i).map_err(|e| FormatError::Damaged(e.to_string()))?;
|
||||
let name = f.name().to_string();
|
||||
if !safe_name(&name) {
|
||||
return Err(FormatError::UnsafeName(name));
|
||||
}
|
||||
if f.is_dir() || f.is_symlink() {
|
||||
return Err(FormatError::UnsafeName(name));
|
||||
}
|
||||
}
|
||||
if zip.index_for_name("document.json").is_none() {
|
||||
return Err(FormatError::NotPictor);
|
||||
}
|
||||
let mut total = 0u64;
|
||||
let json = read_entry(&mut zip, "document.json", limits.max_json_bytes, limits, &mut total)?;
|
||||
// The version first: a newer document is refused before its schema is trusted.
|
||||
let v: VersionOnly =
|
||||
serde_json::from_slice(&json).map_err(|e| FormatError::Damaged(format!("document.json: {e}")))?;
|
||||
if v.format > FORMAT {
|
||||
return Err(FormatError::Newer(v.format));
|
||||
}
|
||||
if v.format == 0 {
|
||||
return Err(FormatError::Damaged("format 0".into()));
|
||||
}
|
||||
let on_disk: OnDisk =
|
||||
serde_json::from_slice(&json).map_err(|e| FormatError::Damaged(format!("document.json: {e}")))?;
|
||||
let mut doc = on_disk.doc;
|
||||
validate(&doc, limits)?;
|
||||
let used = used_assets(&doc);
|
||||
let mut pixels = 0u64;
|
||||
for a in &on_disk.assets {
|
||||
if !valid_asset_id(&a.id) {
|
||||
return Err(FormatError::UnsafeName(a.id.clone()));
|
||||
}
|
||||
let px = a.width as u64 * a.height as u64;
|
||||
if px == 0 || px > limits.max_pixels {
|
||||
return Err(FormatError::TooLarge(format!("picture {} is {}×{}", a.id, a.width, a.height)));
|
||||
}
|
||||
pixels += px;
|
||||
if pixels > limits.max_total_pixels {
|
||||
return Err(FormatError::TooLarge("the pictures together".into()));
|
||||
}
|
||||
let name = format!("assets/{}.png", a.id);
|
||||
let png = read_entry(&mut zip, &name, limits.max_entry_bytes, limits, &mut total)?;
|
||||
let raster =
|
||||
decode_png(&png, a.width, a.height, limits).map_err(|e| FormatError::Damaged(format!("{name}: {e}")))?;
|
||||
doc.assets.insert(a.id.clone(), raster);
|
||||
}
|
||||
for id in &used {
|
||||
if !doc.assets.contains_key(id) {
|
||||
return Err(FormatError::MissingAsset(id.clone()));
|
||||
}
|
||||
}
|
||||
let mut fonts = Vec::new();
|
||||
for f in &on_disk.fonts {
|
||||
if !safe_name(&f.file) || !f.file.starts_with("fonts/") {
|
||||
return Err(FormatError::UnsafeName(f.file.clone()));
|
||||
}
|
||||
let data = read_entry(&mut zip, &f.file, limits.max_entry_bytes, limits, &mut total)?;
|
||||
if ttf_parser::Face::parse(&data, 0).is_err() {
|
||||
return Err(FormatError::Damaged(format!("{} is not a font", f.file)));
|
||||
}
|
||||
fonts.push(FontFile { family: f.family.clone(), weight: f.weight, italic: f.italic, data });
|
||||
}
|
||||
Ok((doc, fonts))
|
||||
}
|
||||
|
||||
pub fn decode_png(png: &[u8], width: u32, height: u32, limits: &Limits) -> Result<Raster, String> {
|
||||
let mut reader = image::ImageReader::with_format(Cursor::new(png), image::ImageFormat::Png);
|
||||
let mut l = image::Limits::default();
|
||||
l.max_image_width = Some(width);
|
||||
l.max_image_height = Some(height);
|
||||
l.max_alloc = Some((limits.max_pixels * 8).min(u64::MAX / 2));
|
||||
reader.limits(l);
|
||||
let img = reader.decode().map_err(|e| e.to_string())?;
|
||||
if img.width() != width || img.height() != height {
|
||||
return Err(format!("is {}×{}, not {width}×{height}", img.width(), img.height()));
|
||||
}
|
||||
Ok(Raster { width, height, rgba: img.into_rgba8().into_raw() })
|
||||
}
|
||||
|
||||
/// Structural checks of a parsed document: sizes, numbers, ids, paths, depth.
|
||||
pub fn validate(doc: &Document, limits: &Limits) -> Result<(), FormatError> {
|
||||
let bad = |s: String| Err(FormatError::Damaged(s));
|
||||
if doc.pages.is_empty() {
|
||||
return bad("no pages".into());
|
||||
}
|
||||
let mut ids = std::collections::HashSet::new();
|
||||
let mut check_id = |id: Id| -> Result<(), FormatError> {
|
||||
if id == 0 || id >= doc.next_id || !ids.insert(id) {
|
||||
return Err(FormatError::Damaged(format!("id {id} is repeated or out of range")));
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
let fin = |v: f32, what: &str| -> Result<(), FormatError> {
|
||||
if v.is_finite() && v.abs() <= 1e6 { Ok(()) } else { Err(FormatError::Damaged(format!("{what} is {v}"))) }
|
||||
};
|
||||
fn obj(
|
||||
o: &Object,
|
||||
depth: usize,
|
||||
limits: &Limits,
|
||||
check_id: &mut dyn FnMut(Id) -> Result<(), FormatError>,
|
||||
fin: &dyn Fn(f32, &str) -> Result<(), FormatError>,
|
||||
) -> Result<(), FormatError> {
|
||||
if depth > limits.max_depth {
|
||||
return Err(FormatError::TooLarge("groups nested too deep".into()));
|
||||
}
|
||||
check_id(o.id)?;
|
||||
for v in o.transform {
|
||||
fin(v, "a transform")?;
|
||||
}
|
||||
if !(0.0..=1.0).contains(&o.opacity) {
|
||||
return Err(FormatError::Damaged(format!("opacity {}", o.opacity)));
|
||||
}
|
||||
if let Some(s) = &o.stroke {
|
||||
fin(s.width, "a stroke width")?;
|
||||
if s.dash.len() > 64 {
|
||||
return Err(FormatError::Damaged("a dash pattern is too long".into()));
|
||||
}
|
||||
}
|
||||
match &o.shape {
|
||||
Shape::Rect { w, h, radius } => {
|
||||
fin(*w, "a width")?;
|
||||
fin(*h, "a height")?;
|
||||
fin(*radius, "a radius")?
|
||||
}
|
||||
Shape::Ellipse { w, h } => {
|
||||
fin(*w, "a width")?;
|
||||
fin(*h, "a height")?
|
||||
}
|
||||
Shape::Line { x1, y1, x2, y2, .. } => {
|
||||
for v in [x1, y1, x2, y2] {
|
||||
fin(*v, "a line end")?;
|
||||
}
|
||||
}
|
||||
Shape::Path { d } => {
|
||||
let segs = crate::path::parse(d).map_err(|e| FormatError::Damaged(e.to_string()))?;
|
||||
if !matches!(segs.first(), None | Some(crate::path::Seg::Move(..))) {
|
||||
return Err(FormatError::Damaged("a path starts with M".into()));
|
||||
}
|
||||
}
|
||||
Shape::Text { w, text, style } => {
|
||||
fin(*w, "a text width")?;
|
||||
if text.len() > 1 << 20 {
|
||||
return Err(FormatError::TooLarge("a text box".into()));
|
||||
}
|
||||
if !(0.5..=2000.0).contains(&style.size) || !(0.5..=10.0).contains(&style.line_height) {
|
||||
return Err(FormatError::Damaged("a text size".into()));
|
||||
}
|
||||
fin(style.letter_spacing, "letter spacing")?;
|
||||
}
|
||||
Shape::Image { asset, w, h, crop } => {
|
||||
if !valid_asset_id(asset) {
|
||||
return Err(FormatError::UnsafeName(asset.clone()));
|
||||
}
|
||||
for v in [w, h, &crop.x, &crop.y, &crop.w, &crop.h] {
|
||||
fin(*v, "an image frame")?;
|
||||
}
|
||||
}
|
||||
Shape::Group { objects } => {
|
||||
for c in objects {
|
||||
obj(c, depth + 1, limits, check_id, fin)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn layers(
|
||||
ls: &[Layer],
|
||||
depth: usize,
|
||||
limits: &Limits,
|
||||
check_id: &mut dyn FnMut(Id) -> Result<(), FormatError>,
|
||||
fin: &dyn Fn(f32, &str) -> Result<(), FormatError>,
|
||||
) -> Result<(), FormatError> {
|
||||
if depth > limits.max_depth {
|
||||
return Err(FormatError::TooLarge("layers nested too deep".into()));
|
||||
}
|
||||
for l in ls {
|
||||
check_id(l.id)?;
|
||||
if !(0.0..=1.0).contains(&l.opacity) {
|
||||
return Err(FormatError::Damaged(format!("opacity {}", l.opacity)));
|
||||
}
|
||||
match &l.kind {
|
||||
LayerKind::Vector { objects } => {
|
||||
for o in objects {
|
||||
obj(o, depth + 1, limits, check_id, fin)?;
|
||||
}
|
||||
}
|
||||
LayerKind::Bitmap { asset, x, y, w, h } => {
|
||||
if !valid_asset_id(asset) {
|
||||
return Err(FormatError::UnsafeName(asset.clone()));
|
||||
}
|
||||
for v in [x, y, w, h] {
|
||||
fin(*v, "a layer's place")?;
|
||||
}
|
||||
}
|
||||
LayerKind::Group { layers: g } => layers(g, depth + 1, limits, check_id, fin)?,
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
for p in &doc.pages {
|
||||
check_id(p.id)?;
|
||||
if !(p.width >= 1.0
|
||||
&& p.width <= limits.max_page_side_pt
|
||||
&& p.height >= 1.0
|
||||
&& p.height <= limits.max_page_side_pt)
|
||||
{
|
||||
return bad(format!("a page is {} × {} pt", p.width, p.height));
|
||||
}
|
||||
for m in p.margins {
|
||||
fin(m, "a margin")?;
|
||||
}
|
||||
if p.guides.len() > 1000 {
|
||||
return bad("too many guides".into());
|
||||
}
|
||||
layers(&p.layers, 0, limits, &mut check_id, &fin)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
//! Pictor's document: pages of layers (vector objects, bitmaps, groups), operations with exact undo, the .pictor
|
||||
//! file, text layout, the display list both painters draw, the tiny-skia render, bitmap tools, SVG import and the
|
||||
//! PNG / JPG / SVG / PDF exports. Pure: no network, no processes, no registry; fonts come from the caller's font book.
|
||||
pub mod bitmap;
|
||||
pub mod display;
|
||||
pub mod export;
|
||||
pub mod fixtures;
|
||||
pub mod format;
|
||||
pub mod model;
|
||||
pub mod ops;
|
||||
pub mod path;
|
||||
pub mod render;
|
||||
pub mod svg;
|
||||
pub mod text;
|
||||
|
||||
pub use format::{FontFile, FormatError, Limits};
|
||||
pub use model::*;
|
||||
pub use ops::{History, Op, OpError, apply};
|
||||
pub use text::FontBook;
|
||||
@@ -0,0 +1,580 @@
|
||||
//! The document: pages, layers, objects. Everything here is plain data that serialises to `document.json`
|
||||
//! (docs/FORMATS.md, "The .pictor document"). Pixels live in [`Raster`] assets, outside the JSON.
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// The format version this code writes and the newest it reads.
|
||||
pub const FORMAT: u32 = 1;
|
||||
|
||||
pub type Id = u64;
|
||||
|
||||
/// Points per millimetre (1 pt = 1/72 in).
|
||||
pub const PT_PER_MM: f32 = 72.0 / 25.4;
|
||||
/// A4 in points.
|
||||
pub const A4: (f32, f32) = (595.276, 841.89);
|
||||
/// US Letter in points.
|
||||
pub const LETTER: (f32, f32) = (612.0, 792.0);
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Document {
|
||||
pub format: u32,
|
||||
/// The next free id for pages, layers and objects.
|
||||
pub next_id: Id,
|
||||
pub pages: Vec<Page>,
|
||||
/// Pixels of bitmap layers and placed images, by asset id. Written as PNG files beside `document.json`.
|
||||
#[serde(skip)]
|
||||
pub assets: BTreeMap<String, Raster>,
|
||||
}
|
||||
|
||||
/// Straight (not premultiplied) RGBA, 8 bits per channel, rows top to bottom.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct Raster {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub rgba: Vec<u8>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Raster {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "Raster({}×{})", self.width, self.height)
|
||||
}
|
||||
}
|
||||
|
||||
impl Raster {
|
||||
pub fn new(width: u32, height: u32) -> Raster {
|
||||
Raster { width, height, rgba: vec![0; width as usize * height as usize * 4] }
|
||||
}
|
||||
pub fn filled(width: u32, height: u32, rgba: [u8; 4]) -> Raster {
|
||||
let mut r = Raster::new(width, height);
|
||||
for px in r.rgba.as_chunks_mut::<4>().0 {
|
||||
px.copy_from_slice(&rgba);
|
||||
}
|
||||
r
|
||||
}
|
||||
pub fn pixel(&self, x: u32, y: u32) -> [u8; 4] {
|
||||
let i = (y as usize * self.width as usize + x as usize) * 4;
|
||||
[self.rgba[i], self.rgba[i + 1], self.rgba[i + 2], self.rgba[i + 3]]
|
||||
}
|
||||
/// A copy of a rectangle (clamped to the raster).
|
||||
pub fn crop(&self, r: PixelRect) -> Raster {
|
||||
let r = r.clamp(self.width, self.height);
|
||||
let mut out = Raster::new(r.w, r.h);
|
||||
for y in 0..r.h {
|
||||
let src = ((r.y + y) as usize * self.width as usize + r.x as usize) * 4;
|
||||
let dst = y as usize * r.w as usize * 4;
|
||||
out.rgba[dst..dst + r.w as usize * 4].copy_from_slice(&self.rgba[src..src + r.w as usize * 4]);
|
||||
}
|
||||
out
|
||||
}
|
||||
/// Writes `src` at (x, y) (clamped).
|
||||
pub fn put(&mut self, x: u32, y: u32, src: &Raster) {
|
||||
let w = src.width.min(self.width.saturating_sub(x));
|
||||
let h = src.height.min(self.height.saturating_sub(y));
|
||||
for row in 0..h {
|
||||
let s = row as usize * src.width as usize * 4;
|
||||
let d = ((y + row) as usize * self.width as usize + x as usize) * 4;
|
||||
self.rgba[d..d + w as usize * 4].copy_from_slice(&src.rgba[s..s + w as usize * 4]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A rectangle of whole pixels.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PixelRect {
|
||||
pub x: u32,
|
||||
pub y: u32,
|
||||
pub w: u32,
|
||||
pub h: u32,
|
||||
}
|
||||
|
||||
impl PixelRect {
|
||||
pub fn clamp(self, width: u32, height: u32) -> PixelRect {
|
||||
let x = self.x.min(width);
|
||||
let y = self.y.min(height);
|
||||
PixelRect { x, y, w: self.w.min(width - x), h: self.h.min(height - y) }
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.w == 0 || self.h == 0
|
||||
}
|
||||
pub fn union(self, o: PixelRect) -> PixelRect {
|
||||
if self.is_empty() {
|
||||
return o;
|
||||
}
|
||||
if o.is_empty() {
|
||||
return self;
|
||||
}
|
||||
let x0 = self.x.min(o.x);
|
||||
let y0 = self.y.min(o.y);
|
||||
let x1 = (self.x + self.w).max(o.x + o.w);
|
||||
let y1 = (self.y + self.h).max(o.y + o.h);
|
||||
PixelRect { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Page {
|
||||
pub id: Id,
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
/// Top, right, bottom, left, in points.
|
||||
#[serde(default)]
|
||||
pub margins: [f32; 4],
|
||||
#[serde(default)]
|
||||
pub guides: Vec<Guide>,
|
||||
/// The paper colour; none = transparent (an image document).
|
||||
#[serde(default)]
|
||||
pub background: Option<Rgba>,
|
||||
pub layers: Vec<Layer>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Guide {
|
||||
pub vertical: bool,
|
||||
pub at: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Layer {
|
||||
pub id: Id,
|
||||
pub name: String,
|
||||
#[serde(default = "yes")]
|
||||
pub visible: bool,
|
||||
#[serde(default)]
|
||||
pub locked: bool,
|
||||
#[serde(default = "one")]
|
||||
pub opacity: f32,
|
||||
#[serde(flatten)]
|
||||
pub kind: LayerKind,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum LayerKind {
|
||||
Vector {
|
||||
objects: Vec<Object>,
|
||||
},
|
||||
/// Pixels (the asset, at its own size) placed on the page in the rectangle x, y, w, h (points).
|
||||
Bitmap {
|
||||
asset: String,
|
||||
x: f32,
|
||||
y: f32,
|
||||
w: f32,
|
||||
h: f32,
|
||||
},
|
||||
Group {
|
||||
layers: Vec<Layer>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Object {
|
||||
pub id: Id,
|
||||
#[serde(default)]
|
||||
pub name: String,
|
||||
/// a b c d e f: x' = a·x + c·y + e, y' = b·x + d·y + f (the canvas and SVG order).
|
||||
#[serde(default = "identity")]
|
||||
pub transform: [f32; 6],
|
||||
#[serde(default = "one")]
|
||||
pub opacity: f32,
|
||||
#[serde(default = "yes")]
|
||||
pub visible: bool,
|
||||
#[serde(default)]
|
||||
pub locked: bool,
|
||||
#[serde(default)]
|
||||
pub fill: Option<Paint>,
|
||||
#[serde(default)]
|
||||
pub stroke: Option<Stroke>,
|
||||
pub shape: Shape,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum Shape {
|
||||
Rect {
|
||||
w: f32,
|
||||
h: f32,
|
||||
#[serde(default)]
|
||||
radius: f32,
|
||||
},
|
||||
Ellipse {
|
||||
w: f32,
|
||||
h: f32,
|
||||
},
|
||||
Line {
|
||||
x1: f32,
|
||||
y1: f32,
|
||||
x2: f32,
|
||||
y2: f32,
|
||||
#[serde(default)]
|
||||
arrow_start: bool,
|
||||
#[serde(default)]
|
||||
arrow_end: bool,
|
||||
},
|
||||
/// SVG path data, absolute M L C Q Z only (`crate::path`).
|
||||
Path {
|
||||
d: String,
|
||||
},
|
||||
/// A text box `w` points wide (0 = no wrapping); its height follows from the text.
|
||||
Text {
|
||||
w: f32,
|
||||
text: String,
|
||||
style: TextStyle,
|
||||
},
|
||||
/// A picture in a frame `w` × `h`; `crop` is where the whole picture lies, in the frame's coordinates.
|
||||
Image {
|
||||
asset: String,
|
||||
w: f32,
|
||||
h: f32,
|
||||
crop: Rect,
|
||||
},
|
||||
Group {
|
||||
objects: Vec<Object>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Rect {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub w: f32,
|
||||
pub h: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct TextStyle {
|
||||
pub family: String,
|
||||
#[serde(default = "regular")]
|
||||
pub weight: u16,
|
||||
#[serde(default)]
|
||||
pub italic: bool,
|
||||
pub size: f32,
|
||||
pub color: Rgba,
|
||||
#[serde(default)]
|
||||
pub align: Align,
|
||||
/// A multiple of the size.
|
||||
#[serde(default = "line_height")]
|
||||
pub line_height: f32,
|
||||
/// Extra space after each character, in points.
|
||||
#[serde(default)]
|
||||
pub letter_spacing: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Align {
|
||||
#[default]
|
||||
Left,
|
||||
Center,
|
||||
Right,
|
||||
Justify,
|
||||
}
|
||||
|
||||
/// sRGB, straight alpha.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Rgba(pub [u8; 4]);
|
||||
|
||||
impl Rgba {
|
||||
pub const BLACK: Rgba = Rgba([0, 0, 0, 255]);
|
||||
pub const WHITE: Rgba = Rgba([255, 255, 255, 255]);
|
||||
pub fn hex(s: &str) -> Option<Rgba> {
|
||||
let s = s.trim_start_matches('#');
|
||||
let v = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok();
|
||||
match s.len() {
|
||||
6 => Some(Rgba([v(0)?, v(2)?, v(4)?, 255])),
|
||||
8 => Some(Rgba([v(0)?, v(2)?, v(4)?, v(6)?])),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum Paint {
|
||||
Solid {
|
||||
color: Rgba,
|
||||
},
|
||||
/// From (x1, y1) to (x2, y2), as fractions of the shape's box (0..1).
|
||||
Linear {
|
||||
x1: f32,
|
||||
y1: f32,
|
||||
x2: f32,
|
||||
y2: f32,
|
||||
stops: Vec<Stop>,
|
||||
},
|
||||
/// Centre and radius as fractions of the shape's box (the radius of its width).
|
||||
Radial {
|
||||
cx: f32,
|
||||
cy: f32,
|
||||
r: f32,
|
||||
stops: Vec<Stop>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Paint {
|
||||
pub fn solid(c: Rgba) -> Paint {
|
||||
Paint::Solid { color: c }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Stop {
|
||||
pub offset: f32,
|
||||
pub color: Rgba,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Stroke {
|
||||
pub paint: Paint,
|
||||
pub width: f32,
|
||||
#[serde(default)]
|
||||
pub dash: Vec<f32>,
|
||||
#[serde(default)]
|
||||
pub cap: Cap,
|
||||
#[serde(default)]
|
||||
pub join: Join,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Cap {
|
||||
#[default]
|
||||
Butt,
|
||||
Round,
|
||||
Square,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Join {
|
||||
#[default]
|
||||
Miter,
|
||||
Round,
|
||||
Bevel,
|
||||
}
|
||||
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
fn one() -> f32 {
|
||||
1.0
|
||||
}
|
||||
fn regular() -> u16 {
|
||||
400
|
||||
}
|
||||
fn line_height() -> f32 {
|
||||
1.2
|
||||
}
|
||||
pub fn identity() -> [f32; 6] {
|
||||
[1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
|
||||
}
|
||||
|
||||
impl Default for Document {
|
||||
fn default() -> Self {
|
||||
Document { format: FORMAT, next_id: 1, pages: Vec::new(), assets: BTreeMap::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Document {
|
||||
pub fn new_id(&mut self) -> Id {
|
||||
let id = self.next_id;
|
||||
self.next_id += 1;
|
||||
id
|
||||
}
|
||||
|
||||
/// A blank page of the given size with one empty vector layer.
|
||||
pub fn with_page(width: f32, height: f32, background: Option<Rgba>) -> Document {
|
||||
let mut d = Document::default();
|
||||
let pid = d.new_id();
|
||||
let lid = d.new_id();
|
||||
d.pages.push(Page {
|
||||
id: pid,
|
||||
width,
|
||||
height,
|
||||
margins: [0.0; 4],
|
||||
guides: Vec::new(),
|
||||
background,
|
||||
layers: vec![Layer::vector(lid, "Layer 1")],
|
||||
});
|
||||
d
|
||||
}
|
||||
|
||||
/// An A4 page, white, with 15 mm margins.
|
||||
pub fn a4() -> Document {
|
||||
let mut d = Document::with_page(A4.0, A4.1, Some(Rgba::WHITE));
|
||||
d.pages[0].margins = [15.0 * PT_PER_MM; 4];
|
||||
d
|
||||
}
|
||||
|
||||
/// An image document: the page is the image's size (1 pt = 1 px), the image a bitmap layer, an empty vector
|
||||
/// layer above it.
|
||||
pub fn from_image(raster: Raster, name: &str) -> Document {
|
||||
let (w, h) = (raster.width as f32, raster.height as f32);
|
||||
let mut d = Document::default();
|
||||
let pid = d.new_id();
|
||||
let bid = d.new_id();
|
||||
let vid = d.new_id();
|
||||
let asset = format!("b{bid}");
|
||||
d.assets.insert(asset.clone(), raster);
|
||||
d.pages.push(Page {
|
||||
id: pid,
|
||||
width: w,
|
||||
height: h,
|
||||
margins: [0.0; 4],
|
||||
guides: Vec::new(),
|
||||
background: None,
|
||||
layers: vec![
|
||||
Layer {
|
||||
id: bid,
|
||||
name: name.to_string(),
|
||||
visible: true,
|
||||
locked: false,
|
||||
opacity: 1.0,
|
||||
kind: LayerKind::Bitmap { asset, x: 0.0, y: 0.0, w, h },
|
||||
},
|
||||
Layer::vector(vid, "Layer 2"),
|
||||
],
|
||||
});
|
||||
d
|
||||
}
|
||||
|
||||
pub fn page(&self, id: Id) -> Option<&Page> {
|
||||
self.pages.iter().find(|p| p.id == id)
|
||||
}
|
||||
pub fn page_mut(&mut self, id: Id) -> Option<&mut Page> {
|
||||
self.pages.iter_mut().find(|p| p.id == id)
|
||||
}
|
||||
}
|
||||
|
||||
impl Layer {
|
||||
pub fn vector(id: Id, name: &str) -> Layer {
|
||||
Layer {
|
||||
id,
|
||||
name: name.to_string(),
|
||||
visible: true,
|
||||
locked: false,
|
||||
opacity: 1.0,
|
||||
kind: LayerKind::Vector { objects: Vec::new() },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Page {
|
||||
/// The layer with this id, at any depth.
|
||||
pub fn layer(&self, id: Id) -> Option<&Layer> {
|
||||
fn find(ls: &[Layer], id: Id) -> Option<&Layer> {
|
||||
for l in ls {
|
||||
if l.id == id {
|
||||
return Some(l);
|
||||
}
|
||||
if let LayerKind::Group { layers } = &l.kind
|
||||
&& let Some(f) = find(layers, id)
|
||||
{
|
||||
return Some(f);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
find(&self.layers, id)
|
||||
}
|
||||
|
||||
/// The list that holds layers: the page's own (`parent` none) or a group layer's.
|
||||
pub fn layer_list_mut(&mut self, parent: Option<Id>) -> Option<&mut Vec<Layer>> {
|
||||
match parent {
|
||||
None => Some(&mut self.layers),
|
||||
Some(pid) => {
|
||||
fn find(ls: &mut [Layer], id: Id) -> Option<&mut Vec<Layer>> {
|
||||
for l in ls {
|
||||
if let LayerKind::Group { layers } = &mut l.kind {
|
||||
if l.id == id {
|
||||
return Some(layers);
|
||||
}
|
||||
if let Some(f) = find(layers, id) {
|
||||
return Some(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
find(&mut self.layers, pid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn layer_mut(&mut self, id: Id) -> Option<&mut Layer> {
|
||||
fn find(ls: &mut [Layer], id: Id) -> Option<&mut Layer> {
|
||||
for l in ls {
|
||||
if l.id == id {
|
||||
return Some(l);
|
||||
}
|
||||
if let LayerKind::Group { layers } = &mut l.kind
|
||||
&& let Some(f) = find(layers, id)
|
||||
{
|
||||
return Some(f);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
find(&mut self.layers, id)
|
||||
}
|
||||
}
|
||||
|
||||
/// The list that holds objects: a vector layer's own (`parent` none) or a group object's.
|
||||
pub fn object_list_mut(layer: &mut Layer, parent: Option<Id>) -> Option<&mut Vec<Object>> {
|
||||
let LayerKind::Vector { objects } = &mut layer.kind else { return None };
|
||||
match parent {
|
||||
None => Some(objects),
|
||||
Some(pid) => {
|
||||
fn find(os: &mut [Object], id: Id) -> Option<&mut Vec<Object>> {
|
||||
for o in os {
|
||||
if let Shape::Group { objects } = &mut o.shape {
|
||||
if o.id == id {
|
||||
return Some(objects);
|
||||
}
|
||||
if let Some(f) = find(objects, id) {
|
||||
return Some(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
find(objects, pid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The object with this id, at any depth of a vector layer.
|
||||
pub fn find_object_mut(layer: &mut Layer, id: Id) -> Option<&mut Object> {
|
||||
let LayerKind::Vector { objects } = &mut layer.kind else { return None };
|
||||
fn find(os: &mut [Object], id: Id) -> Option<&mut Object> {
|
||||
for o in os {
|
||||
if o.id == id {
|
||||
return Some(o);
|
||||
}
|
||||
if let Shape::Group { objects } = &mut o.shape
|
||||
&& let Some(f) = find(objects, id)
|
||||
{
|
||||
return Some(f);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
find(objects, id)
|
||||
}
|
||||
|
||||
pub fn find_object(layer: &Layer, id: Id) -> Option<&Object> {
|
||||
let LayerKind::Vector { objects } = &layer.kind else { return None };
|
||||
fn find(os: &[Object], id: Id) -> Option<&Object> {
|
||||
for o in os {
|
||||
if o.id == id {
|
||||
return Some(o);
|
||||
}
|
||||
if let Shape::Group { objects } = &o.shape
|
||||
&& let Some(f) = find(objects, id)
|
||||
{
|
||||
return Some(f);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
find(objects, id)
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
//! Every edit is an [`Op`]. Applying one returns its exact inverse, so undo is applying inverses back; the
|
||||
//! [`History`] keeps both without a limit within a session.
|
||||
use crate::model::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "op", rename_all = "snake_case")]
|
||||
pub enum Op {
|
||||
InsertPage {
|
||||
index: usize,
|
||||
page: Page,
|
||||
},
|
||||
RemovePage {
|
||||
index: usize,
|
||||
},
|
||||
/// Size, margins, guides and paper colour (the layers are untouched).
|
||||
SetPage {
|
||||
page: Id,
|
||||
width: f32,
|
||||
height: f32,
|
||||
margins: [f32; 4],
|
||||
guides: Vec<Guide>,
|
||||
background: Option<Rgba>,
|
||||
},
|
||||
/// Into the page's layers (`parent` none) or a group layer's, at `index`.
|
||||
InsertLayer {
|
||||
page: Id,
|
||||
parent: Option<Id>,
|
||||
index: usize,
|
||||
layer: Layer,
|
||||
},
|
||||
RemoveLayer {
|
||||
page: Id,
|
||||
parent: Option<Id>,
|
||||
index: usize,
|
||||
},
|
||||
/// Name, visibility, lock, opacity and, for a bitmap layer, its placement (not its children).
|
||||
SetLayer {
|
||||
page: Id,
|
||||
layer: Id,
|
||||
name: String,
|
||||
visible: bool,
|
||||
locked: bool,
|
||||
opacity: f32,
|
||||
place: Option<Rect>,
|
||||
},
|
||||
InsertObject {
|
||||
page: Id,
|
||||
layer: Id,
|
||||
parent: Option<Id>,
|
||||
index: usize,
|
||||
object: Object,
|
||||
},
|
||||
RemoveObject {
|
||||
page: Id,
|
||||
layer: Id,
|
||||
parent: Option<Id>,
|
||||
index: usize,
|
||||
},
|
||||
/// The whole object with this id, replaced (a move, scale, colour or text change).
|
||||
ReplaceObject {
|
||||
page: Id,
|
||||
layer: Id,
|
||||
object: Object,
|
||||
},
|
||||
/// Pixels of an asset: `rect` gets `pixels` (w × h RGBA).
|
||||
Patch {
|
||||
asset: String,
|
||||
rect: PixelRect,
|
||||
#[serde(skip)]
|
||||
pixels: Vec<u8>,
|
||||
},
|
||||
/// Adds (`raster` some), replaces or removes (none) an asset.
|
||||
PutAsset {
|
||||
asset: String,
|
||||
#[serde(skip)]
|
||||
raster: Option<Raster>,
|
||||
},
|
||||
Batch {
|
||||
ops: Vec<Op>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq)]
|
||||
pub enum OpError {
|
||||
#[error("there is no page {0}")]
|
||||
NoPage(Id),
|
||||
#[error("there is no layer {0}")]
|
||||
NoLayer(Id),
|
||||
#[error("there is no object {0}")]
|
||||
NoObject(Id),
|
||||
#[error("there is no asset {0}")]
|
||||
NoAsset(String),
|
||||
#[error("index {0} is out of range")]
|
||||
Index(usize),
|
||||
#[error("layer {0} does not hold objects")]
|
||||
NotVector(Id),
|
||||
#[error("the pixels do not fit the rectangle")]
|
||||
PatchSize,
|
||||
}
|
||||
|
||||
/// Applies `op` and returns its inverse. On an error the document is unchanged.
|
||||
pub fn apply(doc: &mut Document, op: Op) -> Result<Op, OpError> {
|
||||
match op {
|
||||
Op::InsertPage { index, page } => {
|
||||
if index > doc.pages.len() {
|
||||
return Err(OpError::Index(index));
|
||||
}
|
||||
doc.pages.insert(index, page);
|
||||
Ok(Op::RemovePage { index })
|
||||
}
|
||||
Op::RemovePage { index } => {
|
||||
if index >= doc.pages.len() {
|
||||
return Err(OpError::Index(index));
|
||||
}
|
||||
let page = doc.pages.remove(index);
|
||||
Ok(Op::InsertPage { index, page })
|
||||
}
|
||||
Op::SetPage { page, width, height, margins, guides, background } => {
|
||||
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||
let inv = Op::SetPage {
|
||||
page,
|
||||
width: p.width,
|
||||
height: p.height,
|
||||
margins: p.margins,
|
||||
guides: std::mem::take(&mut p.guides),
|
||||
background: p.background,
|
||||
};
|
||||
p.width = width;
|
||||
p.height = height;
|
||||
p.margins = margins;
|
||||
p.guides = guides;
|
||||
p.background = background;
|
||||
Ok(inv)
|
||||
}
|
||||
Op::InsertLayer { page, parent, index, layer } => {
|
||||
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||
let list = p.layer_list_mut(parent).ok_or(OpError::NoLayer(parent.unwrap_or(0)))?;
|
||||
if index > list.len() {
|
||||
return Err(OpError::Index(index));
|
||||
}
|
||||
list.insert(index, layer);
|
||||
Ok(Op::RemoveLayer { page, parent, index })
|
||||
}
|
||||
Op::RemoveLayer { page, parent, index } => {
|
||||
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||
let list = p.layer_list_mut(parent).ok_or(OpError::NoLayer(parent.unwrap_or(0)))?;
|
||||
if index >= list.len() {
|
||||
return Err(OpError::Index(index));
|
||||
}
|
||||
let layer = list.remove(index);
|
||||
Ok(Op::InsertLayer { page, parent, index, layer })
|
||||
}
|
||||
Op::SetLayer { page, layer, name, visible, locked, opacity, place } => {
|
||||
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||
let l = p.layer_mut(layer).ok_or(OpError::NoLayer(layer))?;
|
||||
let old_place = match &mut l.kind {
|
||||
LayerKind::Bitmap { x, y, w, h, .. } => {
|
||||
let old = Rect { x: *x, y: *y, w: *w, h: *h };
|
||||
if let Some(r) = place {
|
||||
(*x, *y, *w, *h) = (r.x, r.y, r.w, r.h);
|
||||
}
|
||||
Some(old)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let inv = Op::SetLayer {
|
||||
page,
|
||||
layer,
|
||||
name: std::mem::replace(&mut l.name, name),
|
||||
visible: std::mem::replace(&mut l.visible, visible),
|
||||
locked: std::mem::replace(&mut l.locked, locked),
|
||||
opacity: std::mem::replace(&mut l.opacity, opacity),
|
||||
place: if place.is_some() { old_place } else { None },
|
||||
};
|
||||
Ok(inv)
|
||||
}
|
||||
Op::InsertObject { page, layer, parent, index, object } => {
|
||||
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||
let l = p.layer_mut(layer).ok_or(OpError::NoLayer(layer))?;
|
||||
let list = object_list_mut(l, parent).ok_or(match parent {
|
||||
Some(o) => OpError::NoObject(o),
|
||||
None => OpError::NotVector(layer),
|
||||
})?;
|
||||
if index > list.len() {
|
||||
return Err(OpError::Index(index));
|
||||
}
|
||||
list.insert(index, object);
|
||||
Ok(Op::RemoveObject { page, layer, parent, index })
|
||||
}
|
||||
Op::RemoveObject { page, layer, parent, index } => {
|
||||
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||
let l = p.layer_mut(layer).ok_or(OpError::NoLayer(layer))?;
|
||||
let list = object_list_mut(l, parent).ok_or(match parent {
|
||||
Some(o) => OpError::NoObject(o),
|
||||
None => OpError::NotVector(layer),
|
||||
})?;
|
||||
if index >= list.len() {
|
||||
return Err(OpError::Index(index));
|
||||
}
|
||||
let object = list.remove(index);
|
||||
Ok(Op::InsertObject { page, layer, parent, index, object })
|
||||
}
|
||||
Op::ReplaceObject { page, layer, object } => {
|
||||
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||
let l = p.layer_mut(layer).ok_or(OpError::NoLayer(layer))?;
|
||||
let o = find_object_mut(l, object.id).ok_or(OpError::NoObject(object.id))?;
|
||||
let old = std::mem::replace(o, object);
|
||||
Ok(Op::ReplaceObject { page, layer, object: old })
|
||||
}
|
||||
Op::Patch { asset, rect, pixels } => {
|
||||
let r = doc.assets.get_mut(&asset).ok_or_else(|| OpError::NoAsset(asset.clone()))?;
|
||||
if rect.clamp(r.width, r.height) != rect || pixels.len() != rect.w as usize * rect.h as usize * 4 {
|
||||
return Err(OpError::PatchSize);
|
||||
}
|
||||
let before = r.crop(rect);
|
||||
r.put(rect.x, rect.y, &Raster { width: rect.w, height: rect.h, rgba: pixels });
|
||||
Ok(Op::Patch { asset, rect, pixels: before.rgba })
|
||||
}
|
||||
Op::PutAsset { asset, raster } => {
|
||||
let old = match raster {
|
||||
Some(r) => doc.assets.insert(asset.clone(), r),
|
||||
None => doc.assets.remove(&asset),
|
||||
};
|
||||
Ok(Op::PutAsset { asset, raster: old })
|
||||
}
|
||||
Op::Batch { ops } => {
|
||||
let mut done: Vec<Op> = Vec::with_capacity(ops.len());
|
||||
for op in ops {
|
||||
match apply(doc, op) {
|
||||
Ok(inv) => done.push(inv),
|
||||
Err(e) => {
|
||||
// Roll back what was done, so a failed batch leaves no trace.
|
||||
for inv in done.into_iter().rev() {
|
||||
let _ = apply(doc, inv);
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
done.reverse();
|
||||
Ok(Op::Batch { ops: done })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A patch op for the rectangle `rect` that turns `before` into `after` (both the whole asset).
|
||||
pub fn patch_between(asset: &str, after: &Raster, rect: PixelRect) -> Op {
|
||||
Op::Patch { asset: asset.to_string(), rect, pixels: after.crop(rect).rgba }
|
||||
}
|
||||
|
||||
/// Done and undone operations, each with its inverse.
|
||||
#[derive(Default)]
|
||||
pub struct History {
|
||||
done: Vec<(Op, Op)>,
|
||||
undone: Vec<(Op, Op)>,
|
||||
/// Bumped on every change, so the face and "unsaved changes" can tell.
|
||||
pub revision: u64,
|
||||
saved_revision: u64,
|
||||
}
|
||||
|
||||
impl History {
|
||||
/// Applies an operation and records it.
|
||||
pub fn apply(&mut self, doc: &mut Document, op: Op) -> Result<(), OpError> {
|
||||
let inv = apply(doc, op.clone())?;
|
||||
self.done.push((op, inv));
|
||||
self.undone.clear();
|
||||
self.revision += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Records an operation that was applied outside (`op` was applied, `inverse` undoes it).
|
||||
pub fn record(&mut self, op: Op, inverse: Op) {
|
||||
self.done.push((op, inverse));
|
||||
self.undone.clear();
|
||||
self.revision += 1;
|
||||
}
|
||||
|
||||
pub fn undo(&mut self, doc: &mut Document) -> Result<bool, OpError> {
|
||||
let Some((op, inv)) = self.done.pop() else { return Ok(false) };
|
||||
match apply(doc, inv.clone()) {
|
||||
Ok(_) => {
|
||||
self.undone.push((op, inv));
|
||||
self.revision += 1;
|
||||
Ok(true)
|
||||
}
|
||||
Err(e) => {
|
||||
self.done.push((op, inv));
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn redo(&mut self, doc: &mut Document) -> Result<bool, OpError> {
|
||||
let Some((op, inv)) = self.undone.pop() else { return Ok(false) };
|
||||
match apply(doc, op.clone()) {
|
||||
Ok(_) => {
|
||||
self.done.push((op, inv));
|
||||
self.revision += 1;
|
||||
Ok(true)
|
||||
}
|
||||
Err(e) => {
|
||||
self.undone.push((op, inv));
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn can_undo(&self) -> bool {
|
||||
!self.done.is_empty()
|
||||
}
|
||||
pub fn can_redo(&self) -> bool {
|
||||
!self.undone.is_empty()
|
||||
}
|
||||
pub fn mark_saved(&mut self) {
|
||||
self.saved_revision = self.revision;
|
||||
}
|
||||
pub fn is_dirty(&self) -> bool {
|
||||
self.revision != self.saved_revision
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
//! Path data: the subset of SVG path syntax Pictor writes and reads (M L H V C Q Z, absolute or relative; numbers in
|
||||
//! plain or exponent form). Parsed into absolute segments; arcs are not accepted (SVG import turns them into curves).
|
||||
use std::fmt::Write;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Seg {
|
||||
Move(f32, f32),
|
||||
Line(f32, f32),
|
||||
Quad(f32, f32, f32, f32),
|
||||
Cubic(f32, f32, f32, f32, f32, f32),
|
||||
Close,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq)]
|
||||
#[error("path data is not understood at {at}: {why}")]
|
||||
pub struct PathError {
|
||||
pub at: usize,
|
||||
pub why: &'static str,
|
||||
}
|
||||
|
||||
/// The most segments one path may have (a hostile document could otherwise ask for any amount of work).
|
||||
pub const MAX_SEGMENTS: usize = 200_000;
|
||||
|
||||
pub fn parse(d: &str) -> Result<Vec<Seg>, PathError> {
|
||||
let b = d.as_bytes();
|
||||
let mut i = 0;
|
||||
let mut out = Vec::new();
|
||||
let (mut cx, mut cy, mut sx, mut sy) = (0f32, 0f32, 0f32, 0f32);
|
||||
let mut cmd = 0u8;
|
||||
let skip = |i: &mut usize| {
|
||||
while *i < b.len() && (b[*i].is_ascii_whitespace() || b[*i] == b',') {
|
||||
*i += 1;
|
||||
}
|
||||
};
|
||||
let num = |i: &mut usize| -> Result<f32, PathError> {
|
||||
skip(i);
|
||||
let start = *i;
|
||||
if *i < b.len() && (b[*i] == b'-' || b[*i] == b'+') {
|
||||
*i += 1;
|
||||
}
|
||||
let mut dot = false;
|
||||
let mut digits = false;
|
||||
while *i < b.len() && (b[*i].is_ascii_digit() || (b[*i] == b'.' && !dot)) {
|
||||
if b[*i] == b'.' {
|
||||
dot = true;
|
||||
} else {
|
||||
digits = true;
|
||||
}
|
||||
*i += 1;
|
||||
}
|
||||
if *i < b.len() && (b[*i] == b'e' || b[*i] == b'E') && digits {
|
||||
*i += 1;
|
||||
if *i < b.len() && (b[*i] == b'-' || b[*i] == b'+') {
|
||||
*i += 1;
|
||||
}
|
||||
while *i < b.len() && b[*i].is_ascii_digit() {
|
||||
*i += 1;
|
||||
}
|
||||
}
|
||||
if !digits {
|
||||
return Err(PathError { at: start, why: "a number was expected" });
|
||||
}
|
||||
let v: f32 = d[start..*i].parse().map_err(|_| PathError { at: start, why: "a number was expected" })?;
|
||||
if !v.is_finite() {
|
||||
return Err(PathError { at: start, why: "the number is too large" });
|
||||
}
|
||||
Ok(v)
|
||||
};
|
||||
loop {
|
||||
skip(&mut i);
|
||||
if i >= b.len() {
|
||||
break;
|
||||
}
|
||||
if b[i].is_ascii_alphabetic() {
|
||||
cmd = b[i];
|
||||
i += 1;
|
||||
if cmd == b'Z' || cmd == b'z' {
|
||||
out.push(Seg::Close);
|
||||
cx = sx;
|
||||
cy = sy;
|
||||
cmd = 0;
|
||||
continue;
|
||||
}
|
||||
} else if cmd == 0 {
|
||||
return Err(PathError { at: i, why: "a command was expected" });
|
||||
}
|
||||
let rel = cmd.is_ascii_lowercase();
|
||||
let (ox, oy) = if rel { (cx, cy) } else { (0.0, 0.0) };
|
||||
match cmd.to_ascii_uppercase() {
|
||||
b'M' => {
|
||||
let (x, y) = (num(&mut i)? + ox, num(&mut i)? + oy);
|
||||
out.push(Seg::Move(x, y));
|
||||
(cx, cy, sx, sy) = (x, y, x, y);
|
||||
cmd = if rel { b'l' } else { b'L' };
|
||||
}
|
||||
b'L' => {
|
||||
let (x, y) = (num(&mut i)? + ox, num(&mut i)? + oy);
|
||||
out.push(Seg::Line(x, y));
|
||||
(cx, cy) = (x, y);
|
||||
}
|
||||
b'H' => {
|
||||
let x = num(&mut i)? + ox;
|
||||
out.push(Seg::Line(x, cy));
|
||||
cx = x;
|
||||
}
|
||||
b'V' => {
|
||||
let y = num(&mut i)? + oy;
|
||||
out.push(Seg::Line(cx, y));
|
||||
cy = y;
|
||||
}
|
||||
b'C' => {
|
||||
let v = [num(&mut i)?, num(&mut i)?, num(&mut i)?, num(&mut i)?, num(&mut i)?, num(&mut i)?];
|
||||
let s = Seg::Cubic(v[0] + ox, v[1] + oy, v[2] + ox, v[3] + oy, v[4] + ox, v[5] + oy);
|
||||
out.push(s);
|
||||
(cx, cy) = (v[4] + ox, v[5] + oy);
|
||||
}
|
||||
b'Q' => {
|
||||
let v = [num(&mut i)?, num(&mut i)?, num(&mut i)?, num(&mut i)?];
|
||||
out.push(Seg::Quad(v[0] + ox, v[1] + oy, v[2] + ox, v[3] + oy));
|
||||
(cx, cy) = (v[2] + ox, v[3] + oy);
|
||||
}
|
||||
_ => return Err(PathError { at: i.saturating_sub(1), why: "only M L H V C Q Z are allowed" }),
|
||||
}
|
||||
if out.len() > MAX_SEGMENTS {
|
||||
return Err(PathError { at: i, why: "the path has too many segments" });
|
||||
}
|
||||
if !matches!(out.first(), Some(Seg::Move(..))) {
|
||||
return Err(PathError { at: 0, why: "a path starts with M" });
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Writes segments as compact absolute path data.
|
||||
pub fn write(segs: &[Seg]) -> String {
|
||||
let mut s = String::new();
|
||||
let n = |v: f32| -> String {
|
||||
let r = (v * 1000.0).round() / 1000.0;
|
||||
if r == r.trunc() { format!("{}", r as i64) } else { format!("{r}") }
|
||||
};
|
||||
for seg in segs {
|
||||
if !s.is_empty() {
|
||||
s.push(' ');
|
||||
}
|
||||
let _ = match *seg {
|
||||
Seg::Move(x, y) => write!(s, "M{} {}", n(x), n(y)),
|
||||
Seg::Line(x, y) => write!(s, "L{} {}", n(x), n(y)),
|
||||
Seg::Quad(a, b, x, y) => write!(s, "Q{} {} {} {}", n(a), n(b), n(x), n(y)),
|
||||
Seg::Cubic(a, b, c, d, x, y) => write!(s, "C{} {} {} {} {} {}", n(a), n(b), n(c), n(d), n(x), n(y)),
|
||||
Seg::Close => write!(s, "Z"),
|
||||
};
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// The control-point box (contains the curve).
|
||||
pub fn bounds(segs: &[Seg]) -> Option<[f32; 4]> {
|
||||
let mut b: Option<[f32; 4]> = None;
|
||||
let mut add = |x: f32, y: f32| {
|
||||
b = Some(match b {
|
||||
None => [x, y, x, y],
|
||||
Some([a, c, d, e]) => [a.min(x), c.min(y), d.max(x), e.max(y)],
|
||||
})
|
||||
};
|
||||
for s in segs {
|
||||
match *s {
|
||||
Seg::Move(x, y) | Seg::Line(x, y) => add(x, y),
|
||||
Seg::Quad(a, c, x, y) => {
|
||||
add(a, c);
|
||||
add(x, y)
|
||||
}
|
||||
Seg::Cubic(a, c, d, e, x, y) => {
|
||||
add(a, c);
|
||||
add(d, e);
|
||||
add(x, y)
|
||||
}
|
||||
Seg::Close => {}
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
pub fn to_skia(segs: &[Seg]) -> Option<tiny_skia::Path> {
|
||||
let mut pb = tiny_skia::PathBuilder::new();
|
||||
for s in segs {
|
||||
match *s {
|
||||
Seg::Move(x, y) => pb.move_to(x, y),
|
||||
Seg::Line(x, y) => pb.line_to(x, y),
|
||||
Seg::Quad(a, b, x, y) => pb.quad_to(a, b, x, y),
|
||||
Seg::Cubic(a, b, c, d, x, y) => pb.cubic_to(a, b, c, d, x, y),
|
||||
Seg::Close => pb.close(),
|
||||
}
|
||||
}
|
||||
pb.finish()
|
||||
}
|
||||
|
||||
/// Bézier constant for a quarter circle.
|
||||
const K: f32 = 0.552_284_8;
|
||||
|
||||
pub fn rect(w: f32, h: f32, radius: f32) -> Vec<Seg> {
|
||||
let r = radius.max(0.0).min(w.abs() / 2.0).min(h.abs() / 2.0);
|
||||
if r <= 0.0 {
|
||||
return vec![Seg::Move(0.0, 0.0), Seg::Line(w, 0.0), Seg::Line(w, h), Seg::Line(0.0, h), Seg::Close];
|
||||
}
|
||||
let k = r * (1.0 - K);
|
||||
vec![
|
||||
Seg::Move(r, 0.0),
|
||||
Seg::Line(w - r, 0.0),
|
||||
Seg::Cubic(w - k, 0.0, w, k, w, r),
|
||||
Seg::Line(w, h - r),
|
||||
Seg::Cubic(w, h - k, w - k, h, w - r, h),
|
||||
Seg::Line(r, h),
|
||||
Seg::Cubic(k, h, 0.0, h - k, 0.0, h - r),
|
||||
Seg::Line(0.0, r),
|
||||
Seg::Cubic(0.0, k, k, 0.0, r, 0.0),
|
||||
Seg::Close,
|
||||
]
|
||||
}
|
||||
|
||||
pub fn ellipse(w: f32, h: f32) -> Vec<Seg> {
|
||||
let (rx, ry) = (w / 2.0, h / 2.0);
|
||||
let (cx, cy) = (rx, ry);
|
||||
let (kx, ky) = (rx * K, ry * K);
|
||||
vec![
|
||||
Seg::Move(cx + rx, cy),
|
||||
Seg::Cubic(cx + rx, cy + ky, cx + kx, cy + ry, cx, cy + ry),
|
||||
Seg::Cubic(cx - kx, cy + ry, cx - rx, cy + ky, cx - rx, cy),
|
||||
Seg::Cubic(cx - rx, cy - ky, cx - kx, cy - ry, cx, cy - ry),
|
||||
Seg::Cubic(cx + kx, cy - ry, cx + rx, cy - ky, cx + rx, cy),
|
||||
Seg::Close,
|
||||
]
|
||||
}
|
||||
|
||||
/// An arrow head at (x2, y2) pointing away from (x1, y1), for a line of width `w`.
|
||||
pub fn arrow_head(x1: f32, y1: f32, x2: f32, y2: f32, w: f32) -> Vec<Seg> {
|
||||
let (dx, dy) = (x2 - x1, y2 - y1);
|
||||
let len = (dx * dx + dy * dy).sqrt().max(1e-3);
|
||||
let (ux, uy) = (dx / len, dy / len);
|
||||
let size = (w * 4.0).max(8.0);
|
||||
let (bx, by) = (x2 - ux * size, y2 - uy * size);
|
||||
let (px, py) = (-uy * size * 0.5, ux * size * 0.5);
|
||||
vec![Seg::Move(x2, y2), Seg::Line(bx + px, by + py), Seg::Line(bx - px, by - py), Seg::Close]
|
||||
}
|
||||
|
||||
/// Where a line meets its arrow head (so the stroke stops under the head instead of poking through its tip).
|
||||
pub fn shorten(x1: f32, y1: f32, x2: f32, y2: f32, w: f32) -> (f32, f32) {
|
||||
let (dx, dy) = (x2 - x1, y2 - y1);
|
||||
let len = (dx * dx + dy * dy).sqrt().max(1e-3);
|
||||
let size = (w * 4.0).max(8.0) * 0.8;
|
||||
let t = (size / len).min(1.0);
|
||||
(x2 - dx * t, y2 - dy * t)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_relative_and_writes_absolute() {
|
||||
let s = parse("m10 10 l5 0 h5 v-5 c1 1 2 2 3 3 q1 1 2 2 z").unwrap();
|
||||
assert_eq!(s[0], Seg::Move(10.0, 10.0));
|
||||
assert_eq!(s[1], Seg::Line(15.0, 10.0));
|
||||
assert_eq!(s[2], Seg::Line(20.0, 10.0));
|
||||
assert_eq!(s[3], Seg::Line(20.0, 5.0));
|
||||
assert_eq!(s[4], Seg::Cubic(21.0, 6.0, 22.0, 7.0, 23.0, 8.0));
|
||||
assert_eq!(write(&parse(&write(&s)).unwrap()), write(&s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_arcs_garbage_and_huge_numbers() {
|
||||
assert!(parse("M0 0 A 5 5 0 0 1 10 10").is_err());
|
||||
assert!(parse("M0 0 L x 1").is_err());
|
||||
assert!(parse("L 1 1").is_err());
|
||||
assert!(parse("M 1e39 0").is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
//! The core's painter: a display list to pixels with tiny-skia (PNG and JPG export, thumbnails, the fidelity
|
||||
//! reference). The face's canvas painter (`apps/desktop/src/editor/paint.ts`) follows the same rules.
|
||||
use crate::display::*;
|
||||
use crate::model::*;
|
||||
use crate::path;
|
||||
use std::collections::HashMap;
|
||||
use tiny_skia as sk;
|
||||
|
||||
fn tf(t: Tf) -> sk::Transform {
|
||||
sk::Transform::from_row(t[0], t[1], t[2], t[3], t[4], t[5])
|
||||
}
|
||||
|
||||
fn color(c: [u8; 4]) -> sk::Color {
|
||||
sk::Color::from_rgba8(c[0], c[1], c[2], c[3])
|
||||
}
|
||||
|
||||
fn shader(p: &DPaint) -> Option<sk::Shader<'static>> {
|
||||
let stops = |s: &[(f32, [u8; 4])]| s.iter().map(|(o, c)| sk::GradientStop::new(*o, color(*c))).collect::<Vec<_>>();
|
||||
match p {
|
||||
DPaint::Solid { c } => Some(sk::Shader::SolidColor(color(*c))),
|
||||
DPaint::Linear { x1, y1, x2, y2, stops: s } => sk::LinearGradient::new(
|
||||
sk::Point::from_xy(*x1, *y1),
|
||||
sk::Point::from_xy(*x2, *y2),
|
||||
stops(s),
|
||||
sk::SpreadMode::Pad,
|
||||
sk::Transform::identity(),
|
||||
)
|
||||
.or_else(|| s.last().map(|(_, c)| sk::Shader::SolidColor(color(*c)))),
|
||||
DPaint::Radial { cx, cy, r, stops: s } => sk::RadialGradient::new(
|
||||
sk::Point::from_xy(*cx, *cy),
|
||||
0.0,
|
||||
sk::Point::from_xy(*cx, *cy),
|
||||
*r,
|
||||
stops(s),
|
||||
sk::SpreadMode::Pad,
|
||||
sk::Transform::identity(),
|
||||
)
|
||||
.or_else(|| s.last().map(|(_, c)| sk::Shader::SolidColor(color(*c)))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Straight RGBA → a premultiplied pixmap.
|
||||
pub fn pixmap_of(r: &Raster) -> Option<sk::Pixmap> {
|
||||
let mut pm = sk::Pixmap::new(r.width, r.height)?;
|
||||
for (dst, src) in pm.pixels_mut().iter_mut().zip(r.rgba.as_chunks::<4>().0) {
|
||||
*dst = sk::ColorU8::from_rgba(src[0], src[1], src[2], src[3]).premultiply();
|
||||
}
|
||||
Some(pm)
|
||||
}
|
||||
|
||||
/// A premultiplied pixmap → straight RGBA.
|
||||
pub fn raster_of(pm: &sk::Pixmap) -> Raster {
|
||||
let mut rgba = Vec::with_capacity(pm.data().len());
|
||||
for p in pm.pixels() {
|
||||
let c = p.demultiply();
|
||||
rgba.extend_from_slice(&[c.red(), c.green(), c.blue(), c.alpha()]);
|
||||
}
|
||||
Raster { width: pm.width(), height: pm.height(), rgba }
|
||||
}
|
||||
|
||||
/// Paints a display list at `scale` pixels per point. `assets` are the document's pixels.
|
||||
pub fn paint(
|
||||
list: &DisplayList,
|
||||
assets: &std::collections::BTreeMap<String, Raster>,
|
||||
scale: f32,
|
||||
) -> Option<sk::Pixmap> {
|
||||
let w = (list.width * scale).round().max(1.0) as u32;
|
||||
let h = (list.height * scale).round().max(1.0) as u32;
|
||||
let mut stack: Vec<(sk::Pixmap, f32)> = vec![(sk::Pixmap::new(w, h)?, 1.0)];
|
||||
if let Some(bg) = list.background {
|
||||
stack[0].0.fill(color(bg));
|
||||
}
|
||||
let base: Tf = [scale, 0.0, 0.0, scale, 0.0, 0.0];
|
||||
let mut images: HashMap<&str, sk::Pixmap> = HashMap::new();
|
||||
let glyph_paths: Vec<Option<sk::Path>> =
|
||||
list.glyphs.iter().map(|g| path::parse(&g.d).ok().and_then(|s| path::to_skia(&s))).collect();
|
||||
for item in &list.items {
|
||||
match item {
|
||||
Item::Push { opacity } => stack.push((sk::Pixmap::new(w, h)?, *opacity)),
|
||||
Item::Pop => {
|
||||
if stack.len() > 1 {
|
||||
let (top, opacity) = stack.pop()?;
|
||||
let pp = sk::PixmapPaint { opacity, ..Default::default() };
|
||||
stack.last_mut()?.0.draw_pixmap(0, 0, top.as_ref(), &pp, sk::Transform::identity(), None);
|
||||
}
|
||||
}
|
||||
Item::Fill { d, t, paint, even_odd, .. } => {
|
||||
let Some(p) = path::parse(d).ok().and_then(|s| path::to_skia(&s)) else { continue };
|
||||
let Some(sh) = shader(paint) else { continue };
|
||||
let pt = sk::Paint { shader: sh, anti_alias: true, ..Default::default() };
|
||||
let rule = if *even_odd { sk::FillRule::EvenOdd } else { sk::FillRule::Winding };
|
||||
stack.last_mut()?.0.fill_path(&p, &pt, rule, tf(mul(base, *t)), None);
|
||||
}
|
||||
Item::Stroke { d, t, paint, width, cap, join, dash, .. } => {
|
||||
let Some(p) = path::parse(d).ok().and_then(|s| path::to_skia(&s)) else { continue };
|
||||
let Some(sh) = shader(paint) else { continue };
|
||||
let pt = sk::Paint { shader: sh, anti_alias: true, ..Default::default() };
|
||||
let stroke = sk::Stroke {
|
||||
width: *width,
|
||||
line_cap: match cap {
|
||||
Cap::Butt => sk::LineCap::Butt,
|
||||
Cap::Round => sk::LineCap::Round,
|
||||
Cap::Square => sk::LineCap::Square,
|
||||
},
|
||||
line_join: match join {
|
||||
Join::Miter => sk::LineJoin::Miter,
|
||||
Join::Round => sk::LineJoin::Round,
|
||||
Join::Bevel => sk::LineJoin::Bevel,
|
||||
},
|
||||
miter_limit: 10.0,
|
||||
dash: if dash.len() >= 2 && dash.iter().all(|v| *v >= 0.0) && dash.iter().any(|v| *v > 0.0) {
|
||||
let mut d = dash.clone();
|
||||
if d.len() % 2 == 1 {
|
||||
d.extend_from_within(..);
|
||||
}
|
||||
sk::StrokeDash::new(d, 0.0)
|
||||
} else {
|
||||
None
|
||||
},
|
||||
};
|
||||
stack.last_mut()?.0.stroke_path(&p, &pt, &stroke, tf(mul(base, *t)), None);
|
||||
}
|
||||
Item::Image { asset, t, clip, clip_t, smooth, .. } => {
|
||||
let Some(r) = assets.get(asset) else { continue };
|
||||
if !images.contains_key(asset.as_str()) {
|
||||
images.insert(asset.as_str(), pixmap_of(r)?);
|
||||
}
|
||||
let img = &images[asset.as_str()];
|
||||
let full = mul(base, *t);
|
||||
let exact = !*smooth
|
||||
&& full[1] == 0.0
|
||||
&& full[2] == 0.0
|
||||
&& (full[0] - 1.0).abs() < 1e-4
|
||||
&& (full[3] - 1.0).abs() < 1e-4;
|
||||
let quality = if exact { sk::FilterQuality::Nearest } else { sk::FilterQuality::Bilinear };
|
||||
let mask = match clip {
|
||||
Some(cd) => {
|
||||
let Some(cp) = path::parse(cd).ok().and_then(|s| path::to_skia(&s)) else { continue };
|
||||
let mut m = sk::Mask::new(w, h)?;
|
||||
m.fill_path(&cp, sk::FillRule::Winding, true, tf(mul(base, *clip_t)));
|
||||
Some(m)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let pt = sk::Paint {
|
||||
shader: sk::Pattern::new(
|
||||
img.as_ref(),
|
||||
sk::SpreadMode::Pad,
|
||||
quality,
|
||||
1.0,
|
||||
sk::Transform::identity(),
|
||||
),
|
||||
anti_alias: true,
|
||||
..Default::default()
|
||||
};
|
||||
let rect = sk::Rect::from_xywh(0.0, 0.0, img.width() as f32, img.height() as f32)?;
|
||||
stack.last_mut()?.0.fill_rect(rect, &pt, tf(full), mask.as_ref());
|
||||
}
|
||||
Item::Text { t, color: c, size, glyphs, .. } => {
|
||||
let pt =
|
||||
sk::Paint { shader: sk::Shader::SolidColor(color(*c)), anti_alias: true, ..Default::default() };
|
||||
for g in glyphs {
|
||||
let Some(gi) = g.g else { continue };
|
||||
let Some(Some(p)) = glyph_paths.get(gi as usize) else { continue };
|
||||
let upem = list.glyphs[gi as usize].upem;
|
||||
let s = size / upem;
|
||||
let gt = mul(base, mul(*t, [s, 0.0, 0.0, -s, g.x, g.y]));
|
||||
stack.last_mut()?.0.fill_path(p, &pt, sk::FillRule::Winding, tf(gt), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
while stack.len() > 1 {
|
||||
let (top, opacity) = stack.pop()?;
|
||||
let pp = sk::PixmapPaint { opacity, ..Default::default() };
|
||||
stack.last_mut()?.0.draw_pixmap(0, 0, top.as_ref(), &pp, sk::Transform::identity(), None);
|
||||
}
|
||||
stack.pop().map(|(p, _)| p)
|
||||
}
|
||||
|
||||
/// A page rendered to straight RGBA at `scale` pixels per point.
|
||||
pub fn page(doc: &Document, page: &Page, book: &crate::text::FontBook, scale: f32) -> Option<Raster> {
|
||||
let list = build(doc, page, book);
|
||||
paint(&list, &doc.assets, scale).map(|p| raster_of(&p))
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
//! SVG import with usvg: paths (with their fills, strokes and gradients), images and text (as outlines) become vector
|
||||
//! objects in one group, scaled from CSS pixels to points. Runs in the worker: an SVG is an outside file.
|
||||
use crate::model::*;
|
||||
use crate::path::{self, Seg};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum SvgError {
|
||||
#[error("This SVG could not be read: {0}")]
|
||||
Parse(String),
|
||||
#[error("This SVG is too large to import.")]
|
||||
TooLarge,
|
||||
}
|
||||
|
||||
/// The most objects one import makes.
|
||||
const MAX_OBJECTS: usize = 50_000;
|
||||
|
||||
struct Ctx {
|
||||
doc: Document,
|
||||
count: usize,
|
||||
images: u32,
|
||||
}
|
||||
|
||||
fn rgba(c: usvg::Color, opacity: f32) -> Rgba {
|
||||
Rgba([c.red, c.green, c.blue, (opacity.clamp(0.0, 1.0) * 255.0).round() as u8])
|
||||
}
|
||||
|
||||
fn paint(p: &usvg::Paint, opacity: f32, ts: tiny_skia::Transform, bbox: [f32; 4]) -> Option<Paint> {
|
||||
let [bx, by, bw, bh] = bbox;
|
||||
let frac = |x: f32, y: f32| -> (f32, f32) {
|
||||
let mut pt = tiny_skia::Point::from_xy(x, y);
|
||||
ts.map_point(&mut pt);
|
||||
((pt.x - bx) / bw.max(1e-3), (pt.y - by) / bh.max(1e-3))
|
||||
};
|
||||
let stops = |s: &[usvg::Stop]| {
|
||||
s.iter()
|
||||
.map(|s| Stop { offset: s.offset().get(), color: rgba(s.color(), s.opacity().get() * opacity) })
|
||||
.collect()
|
||||
};
|
||||
match p {
|
||||
usvg::Paint::Color(c) => Some(Paint::Solid { color: rgba(*c, opacity) }),
|
||||
usvg::Paint::LinearGradient(g) => {
|
||||
let t = ts.pre_concat(g.transform());
|
||||
let frac = |x: f32, y: f32| {
|
||||
let mut pt = tiny_skia::Point::from_xy(x, y);
|
||||
t.map_point(&mut pt);
|
||||
((pt.x - bx) / bw.max(1e-3), (pt.y - by) / bh.max(1e-3))
|
||||
};
|
||||
let (x1, y1) = frac(g.x1(), g.y1());
|
||||
let (x2, y2) = frac(g.x2(), g.y2());
|
||||
Some(Paint::Linear { x1, y1, x2, y2, stops: stops(g.stops()) })
|
||||
}
|
||||
usvg::Paint::RadialGradient(g) => {
|
||||
let t = ts.pre_concat(g.transform());
|
||||
let mut c = tiny_skia::Point::from_xy(g.cx(), g.cy());
|
||||
t.map_point(&mut c);
|
||||
let (sx, sy) = t.get_scale();
|
||||
let r = g.r().get() * sx.max(sy);
|
||||
let _ = frac;
|
||||
Some(Paint::Radial {
|
||||
cx: (c.x - bx) / bw.max(1e-3),
|
||||
cy: (c.y - by) / bh.max(1e-3),
|
||||
r: r / bw.abs().max(bh.abs()).max(1e-3),
|
||||
stops: stops(g.stops()),
|
||||
})
|
||||
}
|
||||
// Patterns are not kept: their first colour stands in.
|
||||
usvg::Paint::Pattern(_) => Some(Paint::Solid { color: Rgba([128, 128, 128, (opacity * 255.0) as u8]) }),
|
||||
}
|
||||
}
|
||||
|
||||
fn object(ctx: &mut Ctx, shape: Shape) -> Object {
|
||||
Object {
|
||||
id: ctx.doc.new_id(),
|
||||
name: String::new(),
|
||||
transform: identity(),
|
||||
opacity: 1.0,
|
||||
visible: true,
|
||||
locked: false,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
shape,
|
||||
}
|
||||
}
|
||||
|
||||
fn group(ctx: &mut Ctx, g: &usvg::Group, out: &mut Vec<Object>) -> Result<(), SvgError> {
|
||||
for node in g.children() {
|
||||
ctx.count += 1;
|
||||
if ctx.count > MAX_OBJECTS {
|
||||
return Err(SvgError::TooLarge);
|
||||
}
|
||||
match node {
|
||||
usvg::Node::Group(child) => {
|
||||
if child.opacity().get() < 0.999 {
|
||||
let mut inner = Vec::new();
|
||||
group(ctx, child, &mut inner)?;
|
||||
let mut o = object(ctx, Shape::Group { objects: inner });
|
||||
o.opacity = child.opacity().get();
|
||||
out.push(o);
|
||||
} else {
|
||||
group(ctx, child, out)?;
|
||||
}
|
||||
}
|
||||
usvg::Node::Path(p) => {
|
||||
if !p.is_visible() {
|
||||
continue;
|
||||
}
|
||||
let ts = p.abs_transform();
|
||||
let mut segs = Vec::new();
|
||||
for s in p.data().segments() {
|
||||
let map = |pt: tiny_skia::Point| {
|
||||
let mut q = pt;
|
||||
ts.map_point(&mut q);
|
||||
(q.x, q.y)
|
||||
};
|
||||
segs.push(match s {
|
||||
tiny_skia::PathSegment::MoveTo(a) => {
|
||||
let (x, y) = map(a);
|
||||
Seg::Move(x, y)
|
||||
}
|
||||
tiny_skia::PathSegment::LineTo(a) => {
|
||||
let (x, y) = map(a);
|
||||
Seg::Line(x, y)
|
||||
}
|
||||
tiny_skia::PathSegment::QuadTo(a, b) => {
|
||||
let ((ax, ay), (x, y)) = (map(a), map(b));
|
||||
Seg::Quad(ax, ay, x, y)
|
||||
}
|
||||
tiny_skia::PathSegment::CubicTo(a, b, c) => {
|
||||
let ((ax, ay), (bx, by), (x, y)) = (map(a), map(b), map(c));
|
||||
Seg::Cubic(ax, ay, bx, by, x, y)
|
||||
}
|
||||
tiny_skia::PathSegment::Close => Seg::Close,
|
||||
});
|
||||
}
|
||||
let Some(b) = path::bounds(&segs) else { continue };
|
||||
let bbox = [b[0], b[1], b[2] - b[0], b[3] - b[1]];
|
||||
let mut o = object(ctx, Shape::Path { d: path::write(&segs) });
|
||||
if let Some(f) = p.fill() {
|
||||
o.fill = paint(f.paint(), f.opacity().get(), ts, bbox);
|
||||
}
|
||||
if let Some(s) = p.stroke() {
|
||||
let (sx, sy) = ts.get_scale();
|
||||
let k = (sx * sy).abs().sqrt();
|
||||
o.stroke = paint(s.paint(), s.opacity().get(), ts, bbox).map(|pt| Stroke {
|
||||
paint: pt,
|
||||
width: s.width().get() * k,
|
||||
dash: s.dasharray().map(|d| d.iter().map(|v| v * k).collect()).unwrap_or_default(),
|
||||
cap: match s.linecap() {
|
||||
usvg::LineCap::Butt => Cap::Butt,
|
||||
usvg::LineCap::Round => Cap::Round,
|
||||
usvg::LineCap::Square => Cap::Square,
|
||||
},
|
||||
join: match s.linejoin() {
|
||||
usvg::LineJoin::Round => Join::Round,
|
||||
usvg::LineJoin::Bevel => Join::Bevel,
|
||||
_ => Join::Miter,
|
||||
},
|
||||
});
|
||||
}
|
||||
if o.fill.is_some() || o.stroke.is_some() {
|
||||
out.push(o);
|
||||
}
|
||||
}
|
||||
usvg::Node::Image(im) => {
|
||||
if !im.is_visible() {
|
||||
continue;
|
||||
}
|
||||
let data: Option<&Arc<Vec<u8>>> = match im.kind() {
|
||||
usvg::ImageKind::PNG(d)
|
||||
| usvg::ImageKind::JPEG(d)
|
||||
| usvg::ImageKind::GIF(d)
|
||||
| usvg::ImageKind::WEBP(d) => Some(d),
|
||||
_ => None,
|
||||
};
|
||||
let Some(data) = data else { continue };
|
||||
let mut reader = image::ImageReader::new(std::io::Cursor::new(data.as_slice()));
|
||||
reader = match reader.with_guessed_format() {
|
||||
Ok(r) => r,
|
||||
Err(_) => continue,
|
||||
};
|
||||
let mut l = image::Limits::default();
|
||||
l.max_image_width = Some(12_000);
|
||||
l.max_image_height = Some(12_000);
|
||||
l.max_alloc = Some(600 << 20);
|
||||
reader.limits(l);
|
||||
let Ok(img) = reader.decode() else { continue };
|
||||
let rgba_img = img.into_rgba8();
|
||||
ctx.images += 1;
|
||||
let asset = format!("s{}", ctx.images);
|
||||
let (pw, ph) = (rgba_img.width(), rgba_img.height());
|
||||
ctx.doc.assets.insert(asset.clone(), Raster { width: pw, height: ph, rgba: rgba_img.into_raw() });
|
||||
let size = im.size();
|
||||
let t = im.abs_transform();
|
||||
let mut o = object(
|
||||
ctx,
|
||||
Shape::Image {
|
||||
asset,
|
||||
w: size.width(),
|
||||
h: size.height(),
|
||||
crop: Rect { x: 0.0, y: 0.0, w: size.width(), h: size.height() },
|
||||
},
|
||||
);
|
||||
o.transform = [t.sx, t.ky, t.kx, t.sy, t.tx, t.ty];
|
||||
out.push(o);
|
||||
}
|
||||
usvg::Node::Text(t) => group(ctx, t.flattened(), out)?,
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The SVG as a document: one page of the SVG's size (in points), one vector layer holding one group.
|
||||
pub fn import(data: &[u8], fontdb: Arc<fontdb::Database>) -> Result<Document, SvgError> {
|
||||
if data.len() > 64 << 20 {
|
||||
return Err(SvgError::TooLarge);
|
||||
}
|
||||
let opt = usvg::Options { fontdb, ..Default::default() };
|
||||
let tree = usvg::Tree::from_data(data, &opt).map_err(|e| SvgError::Parse(e.to_string()))?;
|
||||
let size = tree.size();
|
||||
let px_to_pt = 0.75;
|
||||
let mut ctx = Ctx { doc: Document::default(), count: 0, images: 0 };
|
||||
let mut objects = Vec::new();
|
||||
group(&mut ctx, tree.root(), &mut objects)?;
|
||||
let mut g = object(&mut ctx, Shape::Group { objects });
|
||||
g.name = "SVG".into();
|
||||
g.transform = [px_to_pt, 0.0, 0.0, px_to_pt, 0.0, 0.0];
|
||||
let pid = ctx.doc.new_id();
|
||||
let lid = ctx.doc.new_id();
|
||||
let mut layer = Layer::vector(lid, "SVG");
|
||||
layer.kind = LayerKind::Vector { objects: vec![g] };
|
||||
ctx.doc.pages.push(Page {
|
||||
id: pid,
|
||||
width: (size.width() * px_to_pt).clamp(1.0, 14_400.0),
|
||||
height: (size.height() * px_to_pt).clamp(1.0, 14_400.0),
|
||||
margins: [0.0; 4],
|
||||
guides: Vec::new(),
|
||||
background: None,
|
||||
layers: vec![layer],
|
||||
});
|
||||
Ok(ctx.doc)
|
||||
}
|
||||
|
||||
/// The system fonts as usvg wants them (for SVG text).
|
||||
pub fn system_fontdb() -> Arc<fontdb::Database> {
|
||||
let mut db = fontdb::Database::new();
|
||||
db.load_system_fonts();
|
||||
Arc::new(db)
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
//! Text: the font book (system fonts through fontdb, plus fonts stored in documents), shaping with rustybuzz, line
|
||||
//! breaking and alignment, glyph outlines with ttf-parser. Both painters and every export use the same layout.
|
||||
use crate::model::{Align, TextStyle};
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write;
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
/// A loaded font face: its data, where it came from and what its licence allows.
|
||||
pub struct Font {
|
||||
pub data: Arc<Vec<u8>>,
|
||||
pub index: u32,
|
||||
pub family: String,
|
||||
pub post_script_name: String,
|
||||
pub weight: u16,
|
||||
pub italic: bool,
|
||||
pub units_per_em: f32,
|
||||
pub ascender: f32,
|
||||
pub descender: f32,
|
||||
pub cap_height: f32,
|
||||
pub embedding: Embedding,
|
||||
/// The file is OpenType with CFF outlines (else TrueType).
|
||||
pub cff: bool,
|
||||
}
|
||||
|
||||
/// What the font's OS/2 `fsType` allows.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Embedding {
|
||||
/// Installable or editable: may be stored in a document and embedded in a PDF.
|
||||
Editable,
|
||||
/// Preview and print: may be embedded in a PDF, not stored for editing.
|
||||
PrintOnly,
|
||||
/// Restricted licence, or bitmap-only embedding: may not be embedded.
|
||||
Forbidden(&'static str),
|
||||
}
|
||||
|
||||
pub type FontKey = usize;
|
||||
|
||||
/// A glyph's outline as path data, or none for an empty glyph.
|
||||
type Outlined = Option<Arc<str>>;
|
||||
|
||||
/// The fonts Pictor can use. Cheap to share between threads.
|
||||
pub struct FontBook {
|
||||
db: RwLock<fontdb::Database>,
|
||||
loaded: RwLock<Vec<Arc<Font>>>,
|
||||
by_id: RwLock<HashMap<fontdb::ID, FontKey>>,
|
||||
outlines: RwLock<HashMap<(FontKey, u16), Outlined>>,
|
||||
}
|
||||
|
||||
/// Fallbacks for characters the chosen font lacks, in order.
|
||||
const FALLBACKS: &[&str] =
|
||||
&["Segoe UI", "Arial", "Segoe UI Symbol", "Segoe UI Emoji", "DejaVu Sans", "Liberation Sans"];
|
||||
|
||||
impl Default for FontBook {
|
||||
fn default() -> Self {
|
||||
FontBook::empty()
|
||||
}
|
||||
}
|
||||
|
||||
impl FontBook {
|
||||
pub fn empty() -> FontBook {
|
||||
FontBook {
|
||||
db: RwLock::new(fontdb::Database::new()),
|
||||
loaded: RwLock::new(Vec::new()),
|
||||
by_id: RwLock::new(HashMap::new()),
|
||||
outlines: RwLock::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The system's fonts (Windows: the Fonts folder and the per-user fonts folder).
|
||||
pub fn system() -> FontBook {
|
||||
let book = FontBook::empty();
|
||||
{
|
||||
let mut db = book.db.write().unwrap();
|
||||
db.load_system_fonts();
|
||||
if let Some(local) = std::env::var_os("LOCALAPPDATA") {
|
||||
let user = std::path::Path::new(&local).join("Microsoft").join("Windows").join("Fonts");
|
||||
if user.is_dir() {
|
||||
db.load_fonts_dir(user);
|
||||
}
|
||||
}
|
||||
}
|
||||
book
|
||||
}
|
||||
|
||||
/// Adds a font from memory (a font stored in a document). Returns false when it is not a font.
|
||||
pub fn add(&self, data: Vec<u8>) -> bool {
|
||||
if ttf_parser::Face::parse(&data, 0).is_err() {
|
||||
return false;
|
||||
}
|
||||
self.db.write().unwrap().load_font_data(data);
|
||||
true
|
||||
}
|
||||
|
||||
/// Family names, sorted, without duplicates.
|
||||
pub fn families(&self) -> Vec<String> {
|
||||
let db = self.db.read().unwrap();
|
||||
let mut v: Vec<String> = db.faces().filter_map(|f| f.families.first().map(|(n, _)| n.clone())).collect();
|
||||
v.sort_by_key(|s| s.to_lowercase());
|
||||
v.dedup();
|
||||
v
|
||||
}
|
||||
|
||||
/// The closest face of a family (none when the family is not installed).
|
||||
pub fn find(&self, family: &str, weight: u16, italic: bool) -> Option<FontKey> {
|
||||
let id = {
|
||||
let db = self.db.read().unwrap();
|
||||
let q = fontdb::Query {
|
||||
families: &[fontdb::Family::Name(family)],
|
||||
weight: fontdb::Weight(weight),
|
||||
stretch: fontdb::Stretch::Normal,
|
||||
style: if italic { fontdb::Style::Italic } else { fontdb::Style::Normal },
|
||||
};
|
||||
let id = db.query(&q)?;
|
||||
// fontdb falls back to any face when nothing matches the name; insist on the family.
|
||||
let face = db.face(id)?;
|
||||
if !face.families.iter().any(|(n, _)| n.eq_ignore_ascii_case(family)) {
|
||||
return None;
|
||||
}
|
||||
id
|
||||
};
|
||||
self.load(id)
|
||||
}
|
||||
|
||||
/// The face for a style, falling back to Segoe UI, then Arial, then any face.
|
||||
pub fn resolve(&self, family: &str, weight: u16, italic: bool) -> Option<FontKey> {
|
||||
self.find(family, weight, italic)
|
||||
.or_else(|| FALLBACKS.iter().find_map(|f| self.find(f, weight, italic)))
|
||||
.or_else(|| {
|
||||
let id = self.db.read().unwrap().faces().next().map(|f| f.id)?;
|
||||
self.load(id)
|
||||
})
|
||||
}
|
||||
|
||||
fn load(&self, id: fontdb::ID) -> Option<FontKey> {
|
||||
if let Some(k) = self.by_id.read().unwrap().get(&id) {
|
||||
return Some(*k);
|
||||
}
|
||||
let (data, index, family, psn) = {
|
||||
let db = self.db.read().unwrap();
|
||||
let info = db.face(id)?;
|
||||
let family = info.families.first().map(|(n, _)| n.clone()).unwrap_or_default();
|
||||
let psn = info.post_script_name.clone();
|
||||
let index = info.index;
|
||||
let data = db.with_face_data(id, |d, _| d.to_vec())?;
|
||||
(data, index, family, psn)
|
||||
};
|
||||
let face = ttf_parser::Face::parse(&data, index).ok()?;
|
||||
let embedding = if !face.is_outline_embedding_allowed() {
|
||||
Embedding::Forbidden("its licence allows only bitmap embedding")
|
||||
} else {
|
||||
match face.permissions() {
|
||||
Some(ttf_parser::Permissions::Restricted) => {
|
||||
Embedding::Forbidden("its licence forbids embedding (fsType: restricted)")
|
||||
}
|
||||
Some(ttf_parser::Permissions::PreviewAndPrint) => Embedding::PrintOnly,
|
||||
_ => Embedding::Editable,
|
||||
}
|
||||
};
|
||||
let font = Font {
|
||||
index,
|
||||
family,
|
||||
post_script_name: psn,
|
||||
weight: face.weight().to_number(),
|
||||
italic: face.is_italic(),
|
||||
units_per_em: face.units_per_em() as f32,
|
||||
ascender: face.ascender() as f32,
|
||||
descender: face.descender() as f32,
|
||||
cap_height: face.capital_height().unwrap_or(face.ascender()) as f32,
|
||||
cff: face.tables().cff.is_some(),
|
||||
embedding,
|
||||
data: Arc::new(data),
|
||||
};
|
||||
let mut loaded = self.loaded.write().unwrap();
|
||||
let key = loaded.len();
|
||||
loaded.push(Arc::new(font));
|
||||
self.by_id.write().unwrap().insert(id, key);
|
||||
Some(key)
|
||||
}
|
||||
|
||||
pub fn font(&self, key: FontKey) -> Arc<Font> {
|
||||
self.loaded.read().unwrap()[key].clone()
|
||||
}
|
||||
|
||||
fn has_glyph(&self, key: FontKey, c: char) -> bool {
|
||||
let f = self.font(key);
|
||||
ttf_parser::Face::parse(&f.data, f.index).ok().and_then(|face| face.glyph_index(c)).is_some()
|
||||
}
|
||||
|
||||
/// A glyph's outline as path data in font units (y up), or none for an empty glyph (a space).
|
||||
pub fn outline(&self, key: FontKey, gid: u16) -> Option<Arc<str>> {
|
||||
if let Some(o) = self.outlines.read().unwrap().get(&(key, gid)) {
|
||||
return o.clone();
|
||||
}
|
||||
let f = self.font(key);
|
||||
let out = ttf_parser::Face::parse(&f.data, f.index).ok().and_then(|face| {
|
||||
let mut b = Outline(String::new());
|
||||
face.outline_glyph(ttf_parser::GlyphId(gid), &mut b)?;
|
||||
Some(Arc::<str>::from(b.0))
|
||||
});
|
||||
self.outlines.write().unwrap().insert((key, gid), out.clone());
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
struct Outline(String);
|
||||
|
||||
impl ttf_parser::OutlineBuilder for Outline {
|
||||
fn move_to(&mut self, x: f32, y: f32) {
|
||||
let _ = write!(self.0, "M{x} {y}");
|
||||
}
|
||||
fn line_to(&mut self, x: f32, y: f32) {
|
||||
let _ = write!(self.0, "L{x} {y}");
|
||||
}
|
||||
fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
|
||||
let _ = write!(self.0, "Q{x1} {y1} {x} {y}");
|
||||
}
|
||||
fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
|
||||
let _ = write!(self.0, "C{x1} {y1} {x2} {y2} {x} {y}");
|
||||
}
|
||||
fn close(&mut self) {
|
||||
self.0.push('Z');
|
||||
}
|
||||
}
|
||||
|
||||
/// A glyph placed in a text box: `x` from the box's left, on its line's baseline.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Glyph {
|
||||
pub font: FontKey,
|
||||
pub gid: u16,
|
||||
pub x: f32,
|
||||
pub advance: f32,
|
||||
/// The characters this glyph stands for (the whole cluster on its first glyph, empty on the rest).
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Line {
|
||||
pub baseline: f32,
|
||||
pub glyphs: Vec<Glyph>,
|
||||
/// From the first glyph to the end of the last visible one.
|
||||
pub width: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Layout {
|
||||
pub lines: Vec<Line>,
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
pub size: f32,
|
||||
/// The face the style asked for (or its fallback): the one the box's metrics come from.
|
||||
pub primary: Option<FontKey>,
|
||||
}
|
||||
|
||||
struct Shaped {
|
||||
font: FontKey,
|
||||
gid: u16,
|
||||
advance: f32,
|
||||
/// Index of the cluster's first char in the paragraph.
|
||||
cluster: usize,
|
||||
}
|
||||
|
||||
/// Lays out a text box `w` points wide (0 = no wrapping).
|
||||
pub fn layout(book: &FontBook, text: &str, style: &TextStyle, w: f32) -> Layout {
|
||||
let size = style.size;
|
||||
let primary = book.resolve(&style.family, style.weight, style.italic);
|
||||
let line_box = size * style.line_height;
|
||||
let (asc, desc) = match primary {
|
||||
Some(k) => {
|
||||
let f = book.font(k);
|
||||
(f.ascender * size / f.units_per_em, -f.descender * size / f.units_per_em)
|
||||
}
|
||||
None => (size * 0.8, size * 0.2),
|
||||
};
|
||||
let baseline_in_box = (line_box - (asc + desc)) / 2.0 + asc;
|
||||
let mut lines = Vec::new();
|
||||
for para in text.split('\n') {
|
||||
let para = para.strip_suffix('\r').unwrap_or(para);
|
||||
let chars: Vec<char> = para.chars().collect();
|
||||
let shaped = match primary {
|
||||
Some(p) => shape(book, &chars, p, style),
|
||||
None => Vec::new(),
|
||||
};
|
||||
let mut start = 0;
|
||||
let is_space = |g: &Shaped| chars.get(g.cluster).is_some_and(|c| c.is_whitespace());
|
||||
let breaks_after = |g: &Shaped| {
|
||||
chars.get(g.cluster).is_some_and(|c| c.is_whitespace() || *c == '-' || *c == '\u{2010}' || *c == '/')
|
||||
};
|
||||
let mut para_lines: Vec<(usize, usize)> = Vec::new();
|
||||
while start < shaped.len() {
|
||||
let mut x = 0.0;
|
||||
let mut end = shaped.len();
|
||||
let mut last_break: Option<usize> = None;
|
||||
for (i, g) in shaped.iter().enumerate().skip(start) {
|
||||
let fits = w <= 0.0 || x + g.advance <= w + 0.01 || is_space(g);
|
||||
if !fits {
|
||||
end = match last_break {
|
||||
Some(b) => b + 1,
|
||||
None if i > start => i,
|
||||
None => i + 1,
|
||||
};
|
||||
break;
|
||||
}
|
||||
x += g.advance;
|
||||
if breaks_after(g) {
|
||||
last_break = Some(i);
|
||||
}
|
||||
}
|
||||
// A break never splits a cluster.
|
||||
while end < shaped.len() && end > start + 1 && shaped[end].cluster == shaped[end - 1].cluster {
|
||||
end -= 1;
|
||||
}
|
||||
para_lines.push((start, end));
|
||||
start = end;
|
||||
}
|
||||
if para_lines.is_empty() {
|
||||
para_lines.push((0, 0));
|
||||
}
|
||||
let n = para_lines.len();
|
||||
for (li, (s, e)) in para_lines.into_iter().enumerate() {
|
||||
let slice = &shaped[s..e];
|
||||
let visible_end = slice.iter().rposition(|g| !is_space(g)).map(|i| i + 1).unwrap_or(0);
|
||||
let natural: f32 = slice[..visible_end].iter().map(|g| g.advance).sum();
|
||||
let spaces = slice[..visible_end].iter().filter(|g| is_space(g)).count();
|
||||
let last = li + 1 == n;
|
||||
let (offset, extra) = match style.align {
|
||||
_ if w <= 0.0 => (0.0, 0.0),
|
||||
Align::Left => (0.0, 0.0),
|
||||
Align::Center => ((w - natural) / 2.0, 0.0),
|
||||
Align::Right => (w - natural, 0.0),
|
||||
Align::Justify if !last && spaces > 0 => (0.0, (w - natural) / spaces as f32),
|
||||
Align::Justify => (0.0, 0.0),
|
||||
};
|
||||
let mut x = offset;
|
||||
let mut glyphs = Vec::with_capacity(slice.len());
|
||||
for (i, g) in slice.iter().enumerate() {
|
||||
let first_of_cluster = i == 0 || slice[i - 1].cluster != g.cluster;
|
||||
let next =
|
||||
slice.get(i + 1..).and_then(|r| r.iter().find(|n| n.cluster != g.cluster)).map(|n| n.cluster);
|
||||
let next = next.unwrap_or_else(|| shaped.get(e).map(|n| n.cluster).unwrap_or(chars.len()));
|
||||
let text: String = if first_of_cluster && next > g.cluster {
|
||||
chars[g.cluster..next].iter().collect()
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let mut advance = g.advance;
|
||||
if extra > 0.0 && i < visible_end && is_space(g) {
|
||||
advance += extra;
|
||||
}
|
||||
glyphs.push(Glyph { font: g.font, gid: g.gid, x, advance, text });
|
||||
x += advance;
|
||||
}
|
||||
let width = if visible_end == 0 {
|
||||
0.0
|
||||
} else {
|
||||
glyphs[visible_end - 1].x + glyphs[visible_end - 1].advance - offset
|
||||
};
|
||||
let baseline = lines.len() as f32 * line_box + baseline_in_box;
|
||||
lines.push(Line { baseline, glyphs, width });
|
||||
}
|
||||
}
|
||||
let width = if w > 0.0 { w } else { lines.iter().map(|l| l.width).fold(0.0, f32::max) };
|
||||
Layout { height: lines.len() as f32 * line_box, lines, width, size, primary }
|
||||
}
|
||||
|
||||
/// Shapes a paragraph, splitting it into runs by the font that has each character.
|
||||
fn shape(book: &FontBook, chars: &[char], primary: FontKey, style: &TextStyle) -> Vec<Shaped> {
|
||||
let mut fonts: Vec<FontKey> = Vec::with_capacity(chars.len());
|
||||
let mut fallback_cache: HashMap<char, FontKey> = HashMap::new();
|
||||
for &c in chars {
|
||||
let k = if c.is_whitespace() || c.is_control() || book.has_glyph(primary, c) {
|
||||
primary
|
||||
} else {
|
||||
*fallback_cache.entry(c).or_insert_with(|| {
|
||||
FALLBACKS
|
||||
.iter()
|
||||
.filter_map(|f| book.find(f, style.weight, style.italic))
|
||||
.find(|k| book.has_glyph(*k, c))
|
||||
.unwrap_or(primary)
|
||||
})
|
||||
};
|
||||
fonts.push(k);
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < chars.len() {
|
||||
let k = fonts[i];
|
||||
let mut j = i + 1;
|
||||
while j < chars.len() && fonts[j] == k {
|
||||
j += 1;
|
||||
}
|
||||
let run: String = chars[i..j].iter().collect();
|
||||
// Byte offset in the run → char index in the paragraph.
|
||||
let mut byte_to_char = vec![0usize; run.len() + 1];
|
||||
for (ci, (b, _)) in run.char_indices().enumerate() {
|
||||
byte_to_char[b] = i + ci;
|
||||
}
|
||||
let f = book.font(k);
|
||||
if let Some(face) = rustybuzz::Face::from_slice(&f.data, f.index) {
|
||||
let mut buf = rustybuzz::UnicodeBuffer::new();
|
||||
buf.push_str(&run);
|
||||
buf.set_direction(rustybuzz::Direction::LeftToRight);
|
||||
buf.guess_segment_properties();
|
||||
let shaped = rustybuzz::shape(&face, &[], buf);
|
||||
let scale = style.size / f.units_per_em;
|
||||
let infos = shaped.glyph_infos();
|
||||
for (gi, (info, pos)) in infos.iter().zip(shaped.glyph_positions()).enumerate() {
|
||||
let cluster = byte_to_char[info.cluster as usize];
|
||||
let starts_cluster = gi == 0 || infos[gi - 1].cluster != info.cluster;
|
||||
let mut advance = pos.x_advance as f32 * scale;
|
||||
if starts_cluster {
|
||||
advance += style.letter_spacing;
|
||||
}
|
||||
out.push(Shaped { font: k, gid: info.glyph_id as u16, advance, cluster });
|
||||
}
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
out
|
||||
}
|
||||
Reference in New Issue
Block a user