PhotoCraft: An open-source, photo editor written by scratch in pure Rust
AF.3: recognize current Affinity artboard properties (#2355)
B?!d1a062e04476
diff --git a/book/src/formats/affinity.md b/book/src/formats/affinity.mdindex 36544c7fc..f77a5f0f3 100644--- a/book/src/formats/affinity.md+++ b/book/src/formats/affinity.md@@ -11,6 +11,11 @@ PhotoCraft opens native Affinity documents: `.af` files from Affinity 3 and `.af- placed JPEG and PNG images become embedded smart objects, and pixel layers become pixel layers;- vector and pixel masks, opacity, visibility, locks, names and blend modes are kept.+Artboards are recognized from both the legacy flag and current Affinity 3 artboard properties.+They keep their names, bounds and editable children when saved as `.pcraft` or PSD; moving an+artboard moves its children together. Nested boards become masked groups, and rotated or curved+boards currently use their bounding rectangle.+The document is 8-bit RGB at the Affinity document's resolution. What PhotoCraft can't reproduce islisted in a warning when the file opens, for example layer effects, adjustment layers and livefilters, brush strokes (drawn as plain strokes), special shapes such as clouds and hearts (drawn asdiff --git a/crates/affinity/README.md b/crates/affinity/README.mdindex 0fcc9647e..a88b85bd4 100644--- a/crates/affinity/README.md+++ b/crates/affinity/README.md@@ -13,7 +13,7 @@ Affinity files.| Affinity | PhotoCraft ||---|---|| Pages, Publisher spreads | one artboard per spread, spreads side by side 64 px apart |-| Artboards (`ShpN` with `ABEn`), with name, solid background, any transform | artboards (nested ones as groups with a vector mask) |+| Artboards (legacy `ABEn`, or current `.af` `phrp`/`aprp` properties, including converted curves), with name, solid background, any transform | artboards (nested ones as groups with a vector mask; rotated/curved boards use their bounding rectangle) || Layers (`Scop`), groups (`Grup`), pass-through or isolated | groups (pass-through or Normal) || Curves (`PCrv`): cubic subpaths, closed flags, live corners (`CnrD`) | shape layers (multi-subpath curves fill even-odd) || Rectangles with corner radii (relative or absolute), ellipses, polygons (smooth too), stars, square stars, pies, triangles, trapezoids, clouds, hearts, cogs, rounded and elliptical callouts, arrows, double stars, tears, crescents, diamonds and circular segments | shape layers |diff --git a/crates/affinity/src/model.rs b/crates/affinity/src/model.rsindex 3579152ac..07d0adf78 100644--- a/crates/affinity/src/model.rs+++ b/crates/affinity/src/model.rs@@ -431,7 +431,13 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {b"Scop" => Kind::Layer,b"Grup" => Kind::Group,b"PCrv" | b"ShpN" | b"Comp" | b"SNEN" | b"SNRR" | b"ShRN" => {- if class == Tag::of(b"ShpN") && s.bool(id, b"ABEn") == Some(true) {+ // Current .af boards carry artboard properties (aprp) in phrp; older+ // documents use ABEn. Converted curve boards keep those properties too.+ // Other property classes also use phrp, so the field alone is not a marker.+ if s.bool(id, b"ABEn") == Some(true) || s.obj(id, b"phrp").is_some_and(|p| s.is(p, b"aprp")) {+ if class != Tag::of(b"ShpN") {+ self.warn("a converted artboard outline (imported at its bounding box)");+ }return Ok(self.artboard(id, world));}let Some((local, even_odd)) = crate::geometry::outline(self, id, class, world) else {diff --git a/crates/engine/tests/current_affinity_artboards.rs b/crates/engine/tests/current_affinity_artboards.rsnew file mode 100644index 000000000..e3b27e856--- /dev/null+++ b/crates/engine/tests/current_affinity_artboards.rs@@ -0,0 +1,47 @@+//! Artboards recognized from current .af properties move with their children and undo together.+#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]++#[path = "../../io/tests/support/current_affinity.rs"]+mod fixture;++use fixture::{Marker, document};+use photocraft_affinity::synth::Method;+use photocraft_doc::{LayerContent, LayerId};+use photocraft_engine::{Session, file_cmds::open_bytes_as};+use photocraft_geom::{Point, Rect};+use serde_json::json;++fn state(s: &Session, id: LayerId) -> (Rect, Point) {+ let layer = s.active().unwrap().doc.layer(id).unwrap();+ let LayerContent::Group(group) = &layer.content else { panic!("not an artboard group") };+ let LayerContent::Shape(child) = &group.children[0].content else { panic!("not an editable child") };+ (group.artboard.as_ref().unwrap().rect, child.path.subpaths[0].knots[0].anchor)+}++#[test]+fn imported_current_boards_move_with_their_art_and_undo_without_moving_the_other_board() {+ for marker in [Marker::Legacy, Marker::Current, Marker::OtherProperties] {+ let mut s = Session::new();+ let bytes = document(marker, false, Method::Zlib);+ open_bytes_as(&mut s, "synthetic.af", &bytes, None, None).unwrap();+ let ids: Vec<_> = s.active().unwrap().doc.artboards().into_iter().map(|(id, _, _)| id).collect();+ if matches!(marker, Marker::OtherProperties) {+ assert!(ids.is_empty());+ assert!(!s.is_enabled("file.export.artboardsToFiles"));+ continue;+ }+ assert_eq!(ids.len(), 2);+ let before = state(&s, ids[0]);+ let other = state(&s, ids[1]);+ s.execute("layer.artboard.set", json!({"layer": ids[0].0, "x": 3, "y": 5})).unwrap();+ let (board, child) = state(&s, ids[0]);+ assert_eq!(board, Rect::new(3, 5, 19, 21));+ assert_eq!(child, Point::new(before.1.x + 3.0, before.1.y + 5.0));+ assert_eq!(state(&s, ids[1]), other);+ s.execute("edit.undo", json!({})).unwrap();+ assert_eq!(state(&s, ids[0]), before);+ assert_eq!(state(&s, ids[1]), other);+ s.execute("edit.redo", json!({})).unwrap();+ assert_eq!(state(&s, ids[0]), (board, child));+ }+}diff --git a/crates/io/tests/affinity_artboards.rs b/crates/io/tests/affinity_artboards.rsnew file mode 100644index 000000000..67e373904--- /dev/null+++ b/crates/io/tests/affinity_artboards.rs@@ -0,0 +1,57 @@+//! Current .af artboards stay separate, editable and clipped through native/PSD saves.+#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]++#[path = "support/current_affinity.rs"]+mod fixture;++use fixture::{Marker, document};+use photocraft_affinity::synth::Method;+use photocraft_doc::Document;+use photocraft_geom::Rect;+use photocraft_io::{ExportOptions, export, import};++fn boards(doc: &Document) -> Vec<(String, Rect)> {+ doc.artboards().into_iter().map(|(_, name, a)| (name.to_string(), a.rect)).collect()+}++fn pixels(doc: &Document) -> Vec<u8> {+ let bytes = export(doc, "boards.png", &ExportOptions::default()).unwrap().bytes;+ photocraft_codecs::decode(&bytes).unwrap().data().to_vec()+}++#[test]+fn current_property_artboards_keep_bounds_clipping_and_roundtrips() {+ for marker in [Marker::Legacy, Marker::Current] {+ for method in [Method::Stored, Method::Zlib, Method::Zstd] {+ let loaded = import("synthetic.af", &document(marker, false, method)).unwrap();+ assert!(!loaded.preview_only && loaded.source_read_only);+ let d = &loaded.document;+ assert_eq!(boards(d), [("Board 100".into(), Rect::new(0, 0, 16, 16)), ("Board 200".into(), Rect::new(24, 0, 40, 16))]);+ let expected = pixels(d);+ assert_eq!(expected.len(), 40 * 16 * 4);+ for (i, px) in expected.as_chunks::<4>().0.iter().enumerate() {+ let x = i % 40;+ assert_eq!(px, if (16..24).contains(&x) { &[0, 0, 0, 0] } else { &[255, 0, 0, 255] }, "overflow must be clipped at the board edges");+ }+ for name in ["copy.pcraft", "copy.psd"] {+ let bytes = export(d, name, &ExportOptions::default()).unwrap().bytes;+ let reopened = import(name, &bytes).unwrap().document;+ assert_eq!(boards(&reopened), boards(d), "{name}");+ assert_eq!(pixels(&reopened), expected, "{name}");+ }+ }+ }+}++#[test]+fn current_properties_mark_converted_curve_artboards_too() {+ let loaded = import("curves.af", &document(Marker::Current, true, Method::Stored)).unwrap();+ assert_eq!(loaded.document.artboards().len(), 2);+ assert!(loaded.warnings.iter().any(|w| w.contains("converted artboard outline")));+}++#[test]+fn other_properties_do_not_turn_ordinary_shapes_into_artboards() {+ let d = import("shapes.af", &document(Marker::OtherProperties, false, Method::Stored)).unwrap().document;+ assert!(!d.has_artboards());+}diff --git a/crates/io/tests/support/current_affinity.rs b/crates/io/tests/support/current_affinity.rsnew file mode 100644index 000000000..73588f9aa--- /dev/null+++ b/crates/io/tests/support/current_affinity.rs@@ -0,0 +1,74 @@+//! Original synthetic reader fixtures. No private document bytes or artwork are used.+#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]++use photocraft_affinity::synth::{self, F, Method, tag};++#[derive(Clone, Copy)]+pub enum Marker {+ Legacy,+ Current,+ OtherProperties,+}++fn solid(id: u32) -> F {+ F::Def(+ id,+ vec![tag(b"FDsc")],+ vec![(+ tag(b"FDeF"),+ F::Def(+ id + 1,+ vec![tag(b"FilS")],+ vec![(+ tag(b"Colr"),+ F::Def(id + 2, vec![tag(b"RGBA")], vec![(tag(b"_col"), F::Struct([1f32, 0.0, 0.0, 1.0].into_iter().flat_map(f32::to_le_bytes).collect()))]),+ )],+ ),+ )],+ )+}++fn board(id: u32, x: f64, marker: Marker, curve: bool) -> F {+ let child = F::Def(+ id + 10,+ vec![tag(b"ShpN")],+ vec![+ (tag(b"Desc"), F::Str("Overflow".into())),+ (tag(b"Shpe"), F::Def(id + 11, vec![tag(b"ShNR")], vec![])),+ (tag(b"ShpB"), F::F64s(vec![-4.0, -4.0, 20.0, 20.0])),+ (tag(b"BFFl"), F::Shared(vec![solid(id + 12)])),+ ],+ );+ let mut fields = vec![+ (tag(b"Desc"), F::Str(format!("Board {id}"))),+ (tag(b"Shpe"), F::Def(id + 1, vec![tag(b"ShNR")], vec![])),+ (tag(b"ShpB"), F::F64s(vec![0.0, 0.0, 16.0, 16.0])),+ (tag(b"Xfrm"), F::F64s(vec![1.0, 0.0, x, 0.0, 1.0, 0.0])),+ (tag(b"Chld"), F::Shared(vec![child])),+ ];+ match marker {+ Marker::Legacy => fields.push((tag(b"ABEn"), F::Bool(true))),+ Marker::Current | Marker::OtherProperties => {+ fields.push((tag(b"ABEn"), F::Bool(false)));+ fields.push((tag(b"phrp"), F::Def(id + 2, vec![tag(if matches!(marker, Marker::Current) { b"aprp" } else { b"prps" })], vec![])));+ }+ }+ F::Def(id, vec![tag(if curve { b"PCrv" } else { b"ShpN" })], fields)+}++pub fn document(marker: Marker, curve: bool, method: Method) -> Vec<u8> {+ let spread = F::Def(+ 2,+ vec![tag(b"Sprd")],+ vec![+ (tag(b"SprB"), F::F64s(vec![0.0, 0.0, 40.0, 16.0])),+ (tag(b"SprT"), F::Bool(true)),+ (tag(b"Chld"), F::Shared(vec![board(100, 0.0, marker, curve), board(200, 24.0, marker, curve)])),+ ],+ );+ let stream = synth::stream(&[+ (tag(b"UVCn"), F::Obj(tag(b"UVCn"), vec![(tag(b"UPPI"), F::F64(144.0))])),+ (tag(b"DocR"), F::Def(1, vec![tag(b"DocN")], vec![(tag(b"Chld"), F::Shared(vec![spread]))])),+ ]);+ synth::container(&[("doc.dat", &stream, method)], None)+}diff --git a/docs/roadmap.md b/docs/roadmap.mdindex d55b7e483..97693407b 100644--- a/docs/roadmap.md+++ b/docs/roadmap.md@@ -39,6 +39,12 @@ approximated or left out, each with a warning; damaged or unknown files fall bacpreview. Affinity writing is not implemented: no Affinity installation was available to checkwritten files, so `.af` export stays unsupported.+2026-10-10: current `.af` artboard properties (`phrp`/`aprp`) are recognized alongside the+legacy flag, including converted curve boards. Synthetic two-board regressions check separate+bounds, overflow clipping, `.pcraft`/PSD board and pixel round trips, and moving one board with its+children through undo/redo. Nested boards remain masked groups; rotated/curved board outlines+still import at their bounding rectangle.+2026-10-09: `corpus/affinity/` now has 39 pinned documents and 21 PNGs (20 rendered references andone bitmap-fill texture): the prior 21 public documents plus 18 CC0 samples for #1606. The newsamples compare against their exported PNGs;