1use std::collections::{BTreeMap, HashSet};
6
7use crate::paint::{self, Paint, Stroke};
8use crate::stream::{ObjId, Stream, Tag};
9use crate::{stream, Archive, Error, Limits};
10
11#[derive(Debug, Clone, Copy, PartialEq)]
13pub struct Affine(pub [f64; 6]);
14
15impl Affine {
16 pub const IDENTITY: Self = Self([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
17
18 pub(crate) fn from_xfrm(m: [f64; 6]) -> Self {
20 Self([m[0], m[3], m[1], m[4], m[2], m[5]])
21 }
22
23 pub fn then(self, outer: Self) -> Self {
24 let [a, b, c, d, e, f] = self.0;
25 let [oa, ob, oc, od, oe, of] = outer.0;
26 Self([
27 oa * a + oc * b,
28 ob * a + od * b,
29 oa * c + oc * d,
30 ob * c + od * d,
31 oa * e + oc * f + oe,
32 ob * e + od * f + of,
33 ])
34 }
35
36 pub fn apply(&self, p: Point) -> Point {
37 let [a, b, c, d, e, f] = self.0;
38 Point {
39 x: a * p.x + c * p.y + e,
40 y: b * p.x + d * p.y + f,
41 }
42 }
43
44 pub fn scale(&self) -> f64 {
46 let [a, b, c, d, ..] = self.0;
47 (a * d - b * c).abs().sqrt()
48 }
49
50 pub fn is_finite(&self) -> bool {
51 self.0.iter().all(|v| v.is_finite())
52 }
53}
54
55#[derive(Debug, Clone, Copy, PartialEq)]
56pub struct Point {
57 pub x: f64,
58 pub y: f64,
59}
60
61#[derive(Debug, Clone, Copy, PartialEq)]
62pub struct Rect {
63 pub x0: f64,
64 pub y0: f64,
65 pub x1: f64,
66 pub y1: f64,
67}
68
69#[derive(Debug, Clone, PartialEq)]
71pub struct SubPath {
72 pub start: Point,
73 pub segments: Vec<[Point; 3]>,
75 pub closed: bool,
76}
77
78#[derive(Debug, Clone, Default, PartialEq)]
80pub struct Path {
81 pub subpaths: Vec<SubPath>,
82}
83
84impl Path {
85 pub fn transformed(&self, m: Affine) -> Self {
86 Self {
87 subpaths: self
88 .subpaths
89 .iter()
90 .map(|s| SubPath {
91 start: m.apply(s.start),
92 segments: s
93 .segments
94 .iter()
95 .map(|seg| seg.map(|p| m.apply(p)))
96 .collect(),
97 closed: s.closed,
98 })
99 .collect(),
100 }
101 }
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
106pub enum Blend {
107 #[default]
108 Normal,
109 PassThrough,
110 Darken,
111 DarkerColor,
112 Multiply,
113 ColorBurn,
114 Lighten,
115 LighterColor,
116 Screen,
117 ColorDodge,
118 Add,
119 Overlay,
120 SoftLight,
121 HardLight,
122 VividLight,
123 PinLight,
124 LinearLight,
125 HardMix,
126 Difference,
127 Exclusion,
128 Subtract,
129 Hue,
130 Saturation,
131 Luminosity,
132 Color,
133 Average,
134 Negation,
135 Reflect,
136 Glow,
137 Erase,
138}
139
140impl Blend {
141 fn from_enum(id: u16, version: u16) -> Option<Self> {
143 use Blend::*;
144 Some(match (id, version) {
145 (0, _) => Normal,
146 (1, 0) => Darken,
147 (2, 1) => DarkerColor,
148 (2, 0) => Multiply,
149 (3, 0) => ColorBurn,
150 (4, 0) => Lighten,
151 (6, 1) => LighterColor,
152 (5, 0) => Screen,
153 (6, 0) => ColorDodge,
154 (7, 0) => Add,
155 (8, 0) => Overlay,
156 (9, 0) => SoftLight,
157 (10, 0) => HardLight,
158 (11, 0) => VividLight,
159 (12, 0) => PinLight,
160 (15, 1) => LinearLight,
161 (13, 0) => HardMix,
162 (14, 0) => Difference,
163 (15, 0) => Exclusion,
164 (16, 0) => Subtract,
165 (17, 0) => Hue,
166 (18, 0) => Saturation,
167 (19, 0) => Luminosity,
168 (20, 0) => Color,
169 (21, 0) => Average,
170 (22, 0) => Negation,
171 (23, 0) => Reflect,
172 (24, 0) => Glow,
173 (25, 0) => Erase,
174 _ => return None,
175 })
176 }
177}
178
179#[derive(Debug, Clone, PartialEq)]
181pub struct TextRun {
182 pub text: String,
183 pub postscript: String,
185 pub family: String,
186 pub weight: i64,
188 pub italic: bool,
189 pub size: f64,
191 pub tracking: f64,
193 pub leading: Option<f64>,
195 pub fill: Paint,
196}
197
198#[derive(Debug, Clone, Copy, PartialEq, Eq)]
199pub enum Align {
200 Left,
201 Center,
202 Right,
203 Justify,
204}
205
206#[derive(Debug, Clone, PartialEq)]
207pub struct Text {
208 pub runs: Vec<TextRun>,
209 pub align: Align,
210 pub anchor: Point,
213 pub frame: Option<Rect>,
214 pub transform: Affine,
216}
217
218#[derive(Debug, Clone, PartialEq)]
219pub enum Pixels {
220 Rgba8(Vec<u8>),
222 Encoded(Vec<u8>),
224}
225
226#[derive(Debug, Clone, PartialEq)]
227pub struct Image {
228 pub width: u32,
229 pub height: u32,
230 pub pixels: Pixels,
231 pub transform: Affine,
233}
234
235#[derive(Debug, Clone, PartialEq)]
236pub enum Kind {
237 Layer,
239 Group,
240 Artboard {
242 rect: Rect,
243 background: Vec<Paint>,
244 },
245 Shape {
248 path: Path,
249 fills: Vec<Paint>,
250 strokes: Vec<Stroke>,
251 even_odd: bool,
252 },
253 Text(Text),
254 Image(Image),
255 Unsupported,
257}
258
259#[derive(Debug, Clone, PartialEq)]
260pub struct Node {
261 pub class: Tag,
262 pub name: String,
263 pub visible: bool,
264 pub locked: bool,
265 pub opacity: f64,
266 pub blend: Blend,
267 pub kind: Kind,
268 pub mask: Option<Path>,
270 pub pixel_mask: Option<Image>,
272 pub children: Vec<Node>,
274}
275
276#[derive(Debug, Clone, PartialEq)]
277pub struct Spread {
278 pub bounds: Rect,
280 pub pages: Vec<Rect>,
282 pub transparent: bool,
284 pub nodes: Vec<Node>,
286}
287
288#[derive(Debug, Clone, PartialEq)]
289pub struct Document {
290 pub dpi: f64,
292 pub spreads: Vec<Spread>,
293 pub saved_by: Option<String>,
295 pub warnings: Vec<String>,
297}
298
299const MAX_TREE_DEPTH: usize = 128;
301const MAX_NODES: usize = 500_000;
303
304pub fn read(bytes: &[u8], limits: Limits) -> Result<Document, Error> {
306 let mut archive = Archive::open(bytes, limits)?;
307 let doc = archive.read("doc.dat")?;
308 let s = stream::parse(&doc)?;
309 Reader::new(&s, &mut archive, limits).document()
310}
311
312pub(crate) struct Reader<'s, 'a, 'b> {
313 pub(crate) s: &'s Stream,
314 pub(crate) archive: &'b mut Archive<'a>,
315 pub(crate) dpi: f64,
316 warnings: BTreeMap<String, usize>,
317 nodes: usize,
318 active: HashSet<ObjId>,
319 pixels_left: usize,
322}
323
324impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
325 fn new(s: &'s Stream, archive: &'b mut Archive<'a>, limits: Limits) -> Self {
326 Self {
327 s,
328 archive,
329 dpi: 72.0,
330 warnings: BTreeMap::new(),
331 nodes: 0,
332 active: HashSet::new(),
333 pixels_left: limits.max_pixel_bytes,
334 }
335 }
336
337 pub(crate) fn admit_pixels(&mut self, rgba: usize, planes: usize) -> Result<(), Error> {
342 let peak = rgba.saturating_add(planes);
343 if peak > self.pixels_left {
344 return Err(Error::Limit("decoded pixel layers exceed the pixel budget"));
345 }
346 self.pixels_left -= rgba;
347 Ok(())
348 }
349
350 pub(crate) fn warn(&mut self, what: impl Into<String>) {
351 *self.warnings.entry(what.into()).or_default() += 1;
352 }
353
354 fn document(mut self) -> Result<Document, Error> {
355 let s = self.s;
356 let root = s.root;
357 self.dpi = s
358 .obj(root, b"UVCn")
359 .and_then(|u| s.f64(u, b"UPPI"))
360 .filter(|d| *d > 0.0 && *d < 100_000.0)
361 .unwrap_or(72.0);
362 let saved_by = s.obj(root, b"NVer").map(|v| {
363 let product = s.str(v, b"Prod").unwrap_or("Affinity");
364 match (s.int(v, b"Majr"), s.int(v, b"Minr"), s.int(v, b"Bild")) {
365 (Some(a), Some(b), Some(c)) => format!("{product} {a}.{b}.{c}"),
366 _ => product.to_string(),
367 }
368 });
369 let doc = s
370 .obj(root, b"DocR")
371 .ok_or(Error::Malformed("document has no root node"))?;
372 let mut spreads = Vec::new();
373 for spread in s.objs(doc, b"Chld") {
374 if !s.is(spread, b"Sprd") {
375 self.warn("an unknown kind of page");
376 continue;
377 }
378 let pages = pages(s, spread);
379 let default_size = s
380 .floats::<2>(doc, b"DfSz")
381 .filter(|[w, h]| *w > 0.0 && *h > 0.0)
382 .map(|[w, h]| Rect {
383 x0: 0.0,
384 y0: 0.0,
385 x1: w,
386 y1: h,
387 });
388 let bounds = s
389 .floats::<4>(spread, b"SprB")
390 .map(rect)
391 .or_else(|| pages.iter().copied().reduce(union))
392 .or(default_size)
393 .unwrap_or(Rect {
394 x0: 0.0,
395 y0: 0.0,
396 x1: 0.0,
397 y1: 0.0,
398 });
399 let transparent = s.bool(spread, b"SprT").unwrap_or(false);
400 let (nodes, mask) = self.children(spread, Affine::IDENTITY, 0)?;
401 if mask.is_some() {
402 self.warn("mask layers directly on a page (imported without them)");
403 }
404 spreads.push(Spread {
405 bounds,
406 pages,
407 transparent,
408 nodes,
409 });
410 }
411 if spreads.is_empty() {
412 return Err(Error::Malformed("document has no pages"));
413 }
414 if !s.objs(doc, b"MpCh").is_empty() {
415 self.warn("master pages (their content is not placed on the pages that use them)");
416 }
417 let warnings = self
418 .warnings
419 .into_iter()
420 .map(|(w, n)| if n > 1 { format!("{w} ({n}×)") } else { w })
421 .collect();
422 Ok(Document {
423 dpi: self.dpi,
424 spreads,
425 saved_by,
426 warnings,
427 })
428 }
429
430 fn children(
432 &mut self,
433 parent: ObjId,
434 world: Affine,
435 depth: usize,
436 ) -> Result<(Vec<Node>, Option<Image>), Error> {
437 let s = self.s;
438 let mut out = Vec::new();
439 let mut mask = None;
440 for c in s.objs(parent, b"Chld") {
441 if s.is(c, b"MRst") {
442 if s.bool(c, b"Visi") == Some(false) {
444 continue;
445 }
446 let local = s
447 .floats::<6>(c, b"Xfrm")
448 .map(Affine::from_xfrm)
449 .unwrap_or(Affine::IDENTITY);
450 match crate::raster::mask(self, c, local.then(world))? {
451 Some(m) if mask.is_none() => mask = Some(m),
452 Some(_) => {
453 self.warn("several pixel masks on one layer (only the first is used)")
454 }
455 None => {}
456 }
457 continue;
458 }
459 if let Some(n) = self.node(c, world, depth + 1)? {
460 out.push(n);
461 }
462 }
463 Ok((out, mask))
464 }
465
466 fn node(&mut self, id: ObjId, parent: Affine, depth: usize) -> Result<Option<Node>, Error> {
467 let s = self.s;
468 if depth > MAX_TREE_DEPTH {
469 self.warn("layers nested deeper than 128 levels");
470 return Ok(None);
471 }
472 self.nodes += 1;
473 if self.nodes > MAX_NODES {
474 return Err(Error::Limit("too many layers"));
475 }
476 if !self.active.insert(id) {
478 self.warn("a layer that contains itself");
479 return Ok(None);
480 }
481 let local = s
482 .floats::<6>(id, b"Xfrm")
483 .map(Affine::from_xfrm)
484 .unwrap_or(Affine::IDENTITY);
485 let world = local.then(parent);
486 let class = s.class(id).unwrap_or(Tag(0));
487 let name = s.str(id, b"Desc").unwrap_or_default().to_string();
488 let visible = s.bool(id, b"Visi").unwrap_or(true);
489 let locked = s.bool(id, b"Edtb").is_some_and(|e| !e);
490 let opacity = s.f64(id, b"Opac").map_or(1.0, |o| o.clamp(0.0, 1.0));
491 let blend = match s.enumeration(id, b"Blnd") {
492 None if s.bool(id, b"PasT") != Some(false) && is_container(class) => Blend::PassThrough,
493 None => Blend::Normal,
494 Some((i, v)) => Blend::from_enum(i, v).unwrap_or_else(|| {
495 self.warn("an unknown blend mode (imported as Normal)");
496 Blend::Normal
497 }),
498 };
499 let kind = if !world.is_finite() {
500 self.warn("a layer with an invalid transform");
501 Kind::Unsupported
502 } else {
503 self.kind(id, class, world, parent)?
504 };
505 let (children, child_mask) = if class == Tag::of(b"Comp") {
507 (Vec::new(), None)
508 } else {
509 self.children(id, world, depth)?
510 };
511 let (mask, attached_mask) = self.attached_masks(id, world)?;
512 let pixel_mask = attached_mask.or(child_mask);
513 self.active.remove(&id);
514 if s.objs(id, b"FiEf")
515 .iter()
516 .any(|e| s.bool(*e, b"Enab") != Some(false))
517 {
518 self.warn("layer effects (shadows, glows, outlines, bevels…)");
519 }
520 Ok(Some(Node {
521 class,
522 name,
523 visible,
524 locked,
525 opacity,
526 blend,
527 kind,
528 mask,
529 pixel_mask,
530 children,
531 }))
532 }
533
534 fn kind(
535 &mut self,
536 id: ObjId,
537 class: Tag,
538 world: Affine,
539 parent: Affine,
540 ) -> Result<Kind, Error> {
541 let s = self.s;
542 Ok(match &class.0.to_be_bytes() {
543 b"Scop" => Kind::Layer,
544 b"Grup" => Kind::Group,
545 b"PCrv" | b"ShpN" | b"Comp" | b"SNEN" | b"SNRR" | b"ShRN" => {
546 if s.bool(id, b"ABEn") == Some(true)
550 || s.obj(id, b"phrp").is_some_and(|p| s.is(p, b"aprp"))
551 {
552 if class != Tag::of(b"ShpN") {
553 self.warn("a converted artboard outline (imported at its bounding box)");
554 }
555 return Ok(self.artboard(id, world));
556 }
557 let Some((local, even_odd)) = crate::geometry::outline(self, id, class, world)
558 else {
559 self.warn(format!("a {} that could not be read", describe(class)));
560 return Ok(Kind::Unsupported);
561 };
562 let (fills, strokes) = paint::node_paint(self, id, world);
563 Kind::Shape {
564 path: local.transformed(world),
565 fills,
566 strokes,
567 even_odd,
568 }
569 }
570 b"TxtA" | b"TxtF" | b"TxtC" => match crate::text::read(self, id, world) {
571 Some(t) => Kind::Text(t),
572 None => {
573 self.warn("text whose story could not be read (master-page text, or an unknown layout)");
574 Kind::Unsupported
575 }
576 },
577 b"ImgN" | b"Rstr" => match crate::raster::node_image(self, id, world)? {
578 Some(img) => Kind::Image(img),
579 None => Kind::Unsupported,
580 },
581 b"EmbN" => match crate::raster::embedded(self, id, world)? {
582 Some(img) => {
583 self.warn("embedded documents and symbols (imported as pictures of them)");
584 Kind::Image(img)
585 }
586 None => {
587 self.warn("embedded documents and symbols without a cached picture");
588 Kind::Unsupported
589 }
590 },
591 b"FRst" => {
592 let b = s.obj(id, b"Bitm");
594 let size = |t: &[u8; 4]| {
595 b.and_then(|b| s.int(b, t))
596 .map(|v| v as f64)
597 .filter(|v| *v > 0.0)
598 };
599 match (size(b"BmpW"), size(b"BmpH")) {
600 (Some(w), Some(h)) => {
601 let local = Path {
602 subpaths: vec![crate::shapes::rectangle(0.0, 0.0, w, h)],
603 };
604 let fills = paint::fills(self, id, parent, b"BFFl");
605 Kind::Shape {
606 path: local.transformed(world),
607 fills,
608 strokes: Vec::new(),
609 even_odd: false,
610 }
611 }
612 _ => {
613 self.warn("fill layers without an area");
614 Kind::Unsupported
615 }
616 }
617 }
618 _ => {
619 self.warn(format!("{} layers", describe(class)));
620 Kind::Unsupported
621 }
622 })
623 }
624
625 fn attached_masks(
628 &mut self,
629 id: ObjId,
630 world: Affine,
631 ) -> Result<(Option<Path>, Option<Image>), Error> {
632 let s = self.s;
633 let attached = s.objs(id, b"AdCh");
634 let mut mask: Option<Path> = None;
635 let mut pixels: Option<Image> = None;
636 for a in attached {
637 let class = s.class(a).unwrap_or(Tag(0));
638 if s.bool(a, b"Visi") == Some(false) {
639 continue;
640 }
641 if class == Tag::of(b"PCrv") || class == Tag::of(b"ShpN") || class == Tag::of(b"Comp") {
642 let local = s
643 .floats::<6>(a, b"Xfrm")
644 .map(Affine::from_xfrm)
645 .unwrap_or(Affine::IDENTITY)
646 .then(world);
647 if let Some((p, _)) = crate::geometry::outline(self, a, class, local) {
648 mask.get_or_insert_with(Path::default)
649 .subpaths
650 .extend(p.transformed(local).subpaths);
651 }
652 } else if class == Tag::of(b"MRst") {
653 let local = s
654 .floats::<6>(a, b"Xfrm")
655 .map(Affine::from_xfrm)
656 .unwrap_or(Affine::IDENTITY)
657 .then(world);
658 match crate::raster::mask(self, a, local)? {
659 Some(m) if pixels.is_none() => pixels = Some(m),
660 Some(_) => {
661 self.warn("several pixel masks on one layer (only the first is used)")
662 }
663 None => {}
664 }
665 } else {
666 self.warn(format!(
667 "{} layers attached to other layers (imported without them)",
668 describe(class)
669 ));
670 }
671 }
672 Ok((mask, pixels))
673 }
674
675 fn artboard(&mut self, id: ObjId, world: Affine) -> Kind {
676 let s = self.s;
677 let b = s.floats::<4>(id, b"ShpB").map(rect).unwrap_or(Rect {
678 x0: 0.0,
679 y0: 0.0,
680 x1: 0.0,
681 y1: 0.0,
682 });
683 let corners = [
684 Point { x: b.x0, y: b.y0 },
685 Point { x: b.x1, y: b.y0 },
686 Point { x: b.x1, y: b.y1 },
687 Point { x: b.x0, y: b.y1 },
688 ]
689 .map(|p| world.apply(p));
690 let [a, b2, c, d, ..] = world.0;
691 if b2.abs() > 1e-9 || c.abs() > 1e-9 || a <= 0.0 || d <= 0.0 {
692 self.warn("a rotated or flipped artboard (imported at its bounding box)");
693 }
694 let xs = corners.map(|p| p.x);
695 let ys = corners.map(|p| p.y);
696 let rect = Rect {
697 x0: xs.iter().copied().fold(f64::INFINITY, f64::min),
698 y0: ys.iter().copied().fold(f64::INFINITY, f64::min),
699 x1: xs.iter().copied().fold(f64::NEG_INFINITY, f64::max),
700 y1: ys.iter().copied().fold(f64::NEG_INFINITY, f64::max),
701 };
702 let background = paint::fills(self, id, world, b"BFFl");
703 Kind::Artboard { rect, background }
704 }
705}
706
707fn pages(s: &Stream, spread: ObjId) -> Vec<Rect> {
710 if let Some(md) = s.obj(spread, b"SpMd") {
711 let v: Vec<Rect> = s
712 .objs(md, b"PagR")
713 .into_iter()
714 .filter_map(|p| s.floats::<4>(p, b"rctp").map(rect))
715 .filter(|r| r.x1 > r.x0 && r.y1 > r.y0)
716 .collect();
717 if !v.is_empty() {
718 return v;
719 }
720 }
721 match (
722 s.floats::<4>(spread, b"SprB").map(rect),
723 s.int(spread, b"PagC"),
724 ) {
725 (Some(b), Some(n @ 2..=16)) => {
726 let w = (b.x1 - b.x0) / n as f64;
727 (0..n)
728 .map(|i| Rect {
729 x0: b.x0 + w * i as f64,
730 x1: b.x0 + w * (i + 1) as f64,
731 ..b
732 })
733 .collect()
734 }
735 _ => Vec::new(),
736 }
737}
738
739pub(crate) fn union(a: Rect, b: Rect) -> Rect {
740 Rect {
741 x0: a.x0.min(b.x0),
742 y0: a.y0.min(b.y0),
743 x1: a.x1.max(b.x1),
744 y1: a.y1.max(b.y1),
745 }
746}
747
748fn is_container(class: Tag) -> bool {
749 class == Tag::of(b"Scop") || class == Tag::of(b"Grup")
750}
751
752pub(crate) fn rect(v: [f64; 4]) -> Rect {
753 Rect {
754 x0: v[0],
755 y0: v[1],
756 x1: v[2],
757 y1: v[3],
758 }
759}
760
761pub(crate) fn describe(class: Tag) -> &'static str {
763 match &class.0.to_be_bytes() {
764 b"PCrv" => "curve",
765 b"ShpN" | b"SNEN" | b"SNRR" | b"ShRN" => "shape",
766 b"Comp" => "compound",
767 b"Rstr" => "pixel",
768 b"ImgN" => "image",
769 b"EmbN" => "embedded document",
770 b"MPIN" => "master page instance",
771 b"FRst" => "fill",
772 b"MRst" => "mask",
773 b"Slic" | b"SlcP" => "slice",
774 b"3DLA" => "3D",
775 [_, _, b'R', b'A'] => "adjustment",
776 _ => "unknown",
777 }
778}