From 53098c9f9fc520c5891ee6e6b9dd8ce180a449d9 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sat, 21 Nov 2026 19:56:32 +0800 Subject: [PATCH 01/32] Align craft-libs pins for EPS RunLength decoding --- Cargo.lock | 93 ++++++++++++++++----------------- Cargo.toml | 68 ++++++++++++------------ apps/vectorcraft-web/Cargo.toml | 2 +- crates/text/Cargo.toml | 2 +- 4 files changed, 80 insertions(+), 85 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b8995c19ea..9facb25052 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1001,7 +1001,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "crc32fast", "flate2", @@ -1012,7 +1012,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=9b28b56bc7207ef7ce806f37df72cb94c0ad5c37#9b28b56bc7207ef7ce806f37df72cb94c0ad5c37" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "crc32fast", "flate2", @@ -1021,7 +1021,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "md-5", "rayon", @@ -1030,12 +1030,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "rayon", ] @@ -1043,12 +1043,12 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "craft-codepage", "encoding_rs", @@ -1060,17 +1060,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec#cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec" - -[[package]] -name = "craft-eps" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "harfrust 0.13.3", "kurbo 0.13.1", @@ -1084,12 +1079,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "gif", ] @@ -1097,7 +1092,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "flate2", ] @@ -1105,7 +1100,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1128,7 +1123,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "craft-dds", "craft-jpeg", @@ -1155,7 +1150,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "thiserror 2.0.21", ] @@ -1163,7 +1158,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1174,7 +1169,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "egui", "serde", @@ -1184,7 +1179,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1196,7 +1191,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "encoding_rs", "image", @@ -1207,7 +1202,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "chrono", "craft-codepage", @@ -1217,7 +1212,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1228,7 +1223,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1237,7 +1232,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "craft-winprint-gdi", "log", @@ -1251,7 +1246,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1262,9 +1257,9 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec#cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ - "craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec)", + "craft-eps", "flate2", "kurbo 0.13.1", "miniz_oxide 0.8.9", @@ -1276,7 +1271,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "encoding_rs", "flate2", @@ -1287,7 +1282,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "fax", "hayro-ccitt", @@ -1298,7 +1293,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "craft-image-codecs", "craft-xml", @@ -1319,7 +1314,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "serde", "thiserror 2.0.21", @@ -1328,7 +1323,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1349,7 +1344,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "chrono", "dunce", @@ -1376,7 +1371,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "flate2", "serde", @@ -1387,7 +1382,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "js-sys", "serde_json", @@ -1398,7 +1393,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "egui", "objc2 0.6.5", @@ -1417,7 +1412,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2524,7 +2519,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "brotli", "hayro-postscript", @@ -2533,7 +2528,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -2551,7 +2546,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -2569,12 +2564,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "flate2", "hayro-ccitt", @@ -3374,7 +3369,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "base64 0.22.1", "bumpalo", @@ -3483,7 +3478,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -6876,7 +6871,7 @@ dependencies = [ name = "vectorcraft-eps" version = "0.24.1" dependencies = [ - "craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", + "craft-eps", "craft-image-codecs", "craft-pdf", "craft-ps", diff --git a/Cargo.toml b/Cargo.toml index 9c933c3549..182dfa732d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,43 +11,43 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", default-features = false, features = ["interpret", "write"] } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["serde"] } -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", default-features = false, features = ["interpret", "write"] } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", features = ["serde"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } # Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per # desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", features = ["egui"] } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } # craft-update: app-specific pretend versions apply to startup and manual checks. # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "9b28b56bc7207ef7ce806f37df72cb94c0ad5c37" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["egui"] } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", features = ["egui"] } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -190,13 +190,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 9569d2b3f3..4b4641d11f 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -17,7 +17,7 @@ path = "src/main.rs" vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] } vectorcraft-ui-egui = { workspace = true } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", version = "0.1.0" } vectorcraft-format = { workspace = true } vectorcraft-text = { workspace = true } egui = { workspace = true } diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index 07695b034c..8342873fe7 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -10,7 +10,7 @@ workspace = true [dependencies] # The shared font catalog from craft-libs main (it has the outline, bidi and caret helpers used here). -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", default-features = false } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", default-features = false } vectorcraft-geom = { workspace = true } vectorcraft-doc = { workspace = true } kurbo = { workspace = true } From 8b6204ee62f47bd1c798766d63ff6ceb6e7c3721 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sat, 21 Nov 2026 20:15:12 +0800 Subject: [PATCH 02/32] Keep the PDF dependency check aligned with the shared pin --- xtask/src/pdf_deps.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 29a599c400..ca613bfa13 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,7 +5,7 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "d7c9632bfb3040cf45db394e7500cc93c81c49e0"; +const REV: &str = "b674d91fbe1d8b4a98654de201a21aeda33910e6"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), From 4077615205826c7a2dbe53bf39bfc1ce63123171 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sat, 21 Nov 2026 20:17:44 +0800 Subject: [PATCH 03/32] Credit Terra854 in VectorCraft About --- contributors/people.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index 420177ffb6..f3930b2a8a 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -225,3 +225,6 @@ sync_github_name = true real_name = "Hassan Nawaz Khan" display_name = "Hassan Nawaz Khan" sync_github_name = false + +[people.Terra854] +display_name = "Terra854" From 217c80a5f1536ad75d279039537bb05e7f7f8cdb Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 02:17:26 +0800 Subject: [PATCH 04/32] deps: align the shared EPS prefix decoders --- Cargo.lock | 84 ++++++++++++++++----------------- Cargo.toml | 68 +++++++++++++------------- apps/vectorcraft-web/Cargo.toml | 2 +- crates/text/Cargo.toml | 2 +- xtask/src/pdf_deps.rs | 2 +- 5 files changed, 79 insertions(+), 79 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9facb25052..248a5e5880 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1001,7 +1001,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "crc32fast", "flate2", @@ -1012,7 +1012,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "crc32fast", "flate2", @@ -1021,7 +1021,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "md-5", "rayon", @@ -1030,12 +1030,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "rayon", ] @@ -1043,12 +1043,12 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "craft-codepage", "encoding_rs", @@ -1060,12 +1060,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "harfrust 0.13.3", "kurbo 0.13.1", @@ -1079,12 +1079,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "gif", ] @@ -1092,7 +1092,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "flate2", ] @@ -1100,7 +1100,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1123,7 +1123,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "craft-dds", "craft-jpeg", @@ -1150,7 +1150,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "thiserror 2.0.21", ] @@ -1158,7 +1158,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1169,7 +1169,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "egui", "serde", @@ -1179,7 +1179,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1191,7 +1191,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "encoding_rs", "image", @@ -1202,7 +1202,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "chrono", "craft-codepage", @@ -1212,7 +1212,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1223,7 +1223,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1232,7 +1232,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "craft-winprint-gdi", "log", @@ -1246,7 +1246,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1257,7 +1257,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "craft-eps", "flate2", @@ -1271,7 +1271,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "encoding_rs", "flate2", @@ -1282,7 +1282,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "fax", "hayro-ccitt", @@ -1293,7 +1293,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "craft-image-codecs", "craft-xml", @@ -1314,7 +1314,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "serde", "thiserror 2.0.21", @@ -1323,7 +1323,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1344,7 +1344,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "chrono", "dunce", @@ -1371,7 +1371,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "flate2", "serde", @@ -1382,7 +1382,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "js-sys", "serde_json", @@ -1393,7 +1393,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "egui", "objc2 0.6.5", @@ -1412,7 +1412,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2519,7 +2519,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "brotli", "hayro-postscript", @@ -2528,7 +2528,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -2546,7 +2546,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -2564,12 +2564,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "flate2", "hayro-ccitt", @@ -3369,7 +3369,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "base64 0.22.1", "bumpalo", @@ -3478,7 +3478,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=b674d91fbe1d8b4a98654de201a21aeda33910e6#b674d91fbe1d8b4a98654de201a21aeda33910e6" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "arrayvec", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index 182dfa732d..a5cbf0de78 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,43 +11,43 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", default-features = false, features = ["interpret", "write"] } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", features = ["serde"] } -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3", default-features = false, features = ["interpret", "write"] } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3", features = ["serde"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } # Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per # desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3", features = ["egui"] } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } # craft-update: app-specific pretend versions apply to startup and manual checks. # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", features = ["egui"] } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3", features = ["egui"] } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -190,13 +190,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 4b4641d11f..0d399f2fc3 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -17,7 +17,7 @@ path = "src/main.rs" vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] } vectorcraft-ui-egui = { workspace = true } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3", version = "0.1.0" } vectorcraft-format = { workspace = true } vectorcraft-text = { workspace = true } egui = { workspace = true } diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index 8342873fe7..6d606fbbe6 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -10,7 +10,7 @@ workspace = true [dependencies] # The shared font catalog from craft-libs main (it has the outline, bidi and caret helpers used here). -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "b674d91fbe1d8b4a98654de201a21aeda33910e6", default-features = false } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3", default-features = false } vectorcraft-geom = { workspace = true } vectorcraft-doc = { workspace = true } kurbo = { workspace = true } diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index ca613bfa13..c6ad85638f 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,7 +5,7 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "b674d91fbe1d8b4a98654de201a21aeda33910e6"; +const REV: &str = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), From a9a0aad34f28518bd2d475bb0a2e396269ccbc30 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 21:08:36 +0800 Subject: [PATCH 05/32] deps: scope EPS prefix update to the stream codec stack --- Cargo.lock | 210 ++++++++++++++++++++++---------- Cargo.toml | 62 +++++----- apps/vectorcraft-web/Cargo.toml | 2 +- crates/text/Cargo.toml | 2 +- xtask/src/pdf_deps.rs | 8 +- 5 files changed, 187 insertions(+), 97 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e0beee7994..e602203964 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1001,7 +1001,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "crc32fast", "flate2", @@ -1012,7 +1012,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=9b28b56bc7207ef7ce806f37df72cb94c0ad5c37#9b28b56bc7207ef7ce806f37df72cb94c0ad5c37" dependencies = [ "crc32fast", "flate2", @@ -1021,7 +1021,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "md-5", "rayon", @@ -1030,7 +1030,15 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" + +[[package]] +name = "craft-dds" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" +dependencies = [ + "rayon", +] [[package]] name = "craft-dds" @@ -1043,12 +1051,12 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "craft-codepage", "encoding_rs", @@ -1060,12 +1068,17 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=068e079c7be4b100a8a6b305b31ac881e069727e#068e079c7be4b100a8a6b305b31ac881e069727e" + +[[package]] +name = "craft-eps" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec#cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "harfrust 0.13.3", "kurbo 0.13.1", @@ -1079,12 +1092,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "gif", ] @@ -1092,7 +1105,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "flate2", ] @@ -1100,7 +1113,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1120,15 +1133,42 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-image-codecs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" +dependencies = [ + "craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "crc32fast", + "exr", + "flate2", + "half", + "hayro-jpeg2000", + "image", + "image-webp", + "jpeg-encoder", + "png 0.18.1", + "rayon", + "serde_json", + "thiserror 2.0.21", + "tiff", + "zune-core", + "zune-jpeg", + "zune-jpegxl", +] + [[package]] name = "craft-image-codecs" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" dependencies = [ - "craft-dds", - "craft-jpeg", - "craft-metadata", - "craft-tiff", + "craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", "crc32fast", "exr", "flate2", @@ -1147,6 +1187,14 @@ dependencies = [ "zune-jpegxl", ] +[[package]] +name = "craft-jpeg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-jpeg" version = "0.1.0" @@ -1158,7 +1206,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1169,13 +1217,25 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "egui", "serde", "serde_json", ] +[[package]] +name = "craft-metadata" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" +dependencies = [ + "brotli-decompressor 6.3.2", + "chrono", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "quick-xml 0.41.0", + "serde", +] + [[package]] name = "craft-metadata" version = "0.1.0" @@ -1183,7 +1243,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818 dependencies = [ "brotli-decompressor 6.3.2", "chrono", - "craft-tiff", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", "quick-xml 0.41.0", "serde", ] @@ -1191,7 +1251,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "encoding_rs", "image", @@ -1202,7 +1262,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "chrono", "craft-codepage", @@ -1212,7 +1272,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1223,7 +1283,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1232,7 +1292,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "craft-winprint-gdi", "log", @@ -1246,7 +1306,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1257,9 +1317,9 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec#cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec" dependencies = [ - "craft-eps", + "craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec)", "flate2", "kurbo 0.13.1", "miniz_oxide 0.8.9", @@ -1271,7 +1331,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "encoding_rs", "flate2", @@ -1295,8 +1355,8 @@ name = "craft-svg" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" dependencies = [ - "craft-image-codecs", - "craft-xml", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", "data-url", "flate2", "gif", @@ -1311,6 +1371,15 @@ dependencies = [ "vectorcraft-pathops 0.18.0", ] +[[package]] +name = "craft-tiff" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-tiff" version = "0.1.0" @@ -1320,10 +1389,19 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-tiff" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1344,7 +1422,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "chrono", "dunce", @@ -1371,7 +1449,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "flate2", "serde", @@ -1382,7 +1460,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "js-sys", "serde_json", @@ -1393,7 +1471,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "egui", "objc2 0.6.5", @@ -1419,6 +1497,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "crc32fast" version = "1.5.3" @@ -2519,7 +2607,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "brotli", "hayro-postscript", @@ -2528,7 +2616,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -2564,12 +2652,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "flate2", "hayro-ccitt", @@ -3369,7 +3457,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "base64 0.22.1", "bumpalo", @@ -3478,7 +3566,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -6684,7 +6772,7 @@ name = "vectorcraft-affinity" version = "0.24.1" dependencies = [ "craft-affinity", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "crc32fast", "proptest", "vectorcraft-affinity", @@ -6714,7 +6802,7 @@ name = "vectorcraft-cad" version = "0.24.1" dependencies = [ "craft-dxf", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-plotter", "image", "kurbo 0.13.1", @@ -6769,7 +6857,7 @@ name = "vectorcraft-doc" version = "0.24.1" dependencies = [ "chrono", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-stream-codecs", "flate2", "image", @@ -6789,7 +6877,7 @@ dependencies = [ name = "vectorcraft-effects" version = "0.24.1" dependencies = [ - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-svg", "image", "kurbo 0.13.1", @@ -6814,11 +6902,11 @@ dependencies = [ "chrono", "craft-cdr", "craft-docpath", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-jxl", "craft-proof", "craft-stream-codecs", - "craft-xml", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", "crc32fast", "encoding_rs", "flate2", @@ -6871,8 +6959,8 @@ dependencies = [ name = "vectorcraft-eps" version = "0.24.1" dependencies = [ - "craft-eps", - "craft-image-codecs", + "craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=068e079c7be4b100a8a6b305b31ac881e069727e)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-pdf", "craft-ps", "craft-stream-codecs", @@ -6952,7 +7040,7 @@ dependencies = [ name = "vectorcraft-mcp" version = "0.24.1" dependencies = [ - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "image", "log", "proptest", @@ -6972,7 +7060,7 @@ dependencies = [ name = "vectorcraft-metafile" version = "0.24.1" dependencies = [ - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-metafile", "image", "kurbo 0.13.1", @@ -7013,10 +7101,10 @@ version = "0.24.1" dependencies = [ "aes", "chrono", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-pdf", "craft-stream-codecs", - "craft-xml", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", "flate2", "getrandom 0.4.3", "image", @@ -7048,7 +7136,7 @@ dependencies = [ name = "vectorcraft-plugins" version = "0.24.1" dependencies = [ - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-vectorcraft-format", "log", "rustix 1.1.6", @@ -7070,10 +7158,10 @@ name = "vectorcraft-render" version = "0.24.1" dependencies = [ "craft-gif", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-psd", "craft-stream-codecs", - "craft-tiff", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", "flate2", "image", "jpeg-encoder", @@ -7109,7 +7197,7 @@ name = "vectorcraft-svg" version = "0.24.1" dependencies = [ "craft-docpath", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-mime", "craft-svg", "data-url", @@ -7139,7 +7227,7 @@ dependencies = [ name = "vectorcraft-testkit" version = "0.24.1" dependencies = [ - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "fax", "kurbo 0.13.1", "proptest", @@ -7190,7 +7278,7 @@ dependencies = [ name = "vectorcraft-tools" version = "0.24.1" dependencies = [ - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "kurbo 0.13.1", "serde", "serde_json", @@ -7207,7 +7295,7 @@ dependencies = [ name = "vectorcraft-trace" version = "0.24.1" dependencies = [ - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "image", "kurbo 0.13.1", "serde", @@ -7222,7 +7310,7 @@ version = "0.24.1" dependencies = [ "bytemuck", "chrono", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-keymap", "craft-ui", "craft-update", diff --git a/Cargo.toml b/Cargo.toml index bd333b2f58..43d488a3f9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,43 +11,43 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3", default-features = false, features = ["interpret", "write"] } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3", features = ["serde"] } -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", default-features = false, features = ["interpret", "write"] } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["serde"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } # Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per # desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["egui"] } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } # craft-update: app-specific pretend versions apply to startup and manual checks. # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "9b28b56bc7207ef7ce806f37df72cb94c0ad5c37" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "068e079c7be4b100a8a6b305b31ac881e069727e" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3", features = ["egui"] } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["egui"] } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -190,13 +190,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 97be201a4a..9569d2b3f3 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -17,7 +17,7 @@ path = "src/main.rs" vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] } vectorcraft-ui-egui = { workspace = true } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", version = "0.1.0" } vectorcraft-format = { workspace = true } vectorcraft-text = { workspace = true } egui = { workspace = true } diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index 9086a35f25..07695b034c 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -10,7 +10,7 @@ workspace = true [dependencies] # The shared font catalog from craft-libs main (it has the outline, bidi and caret helpers used here). -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3", default-features = false } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", default-features = false } vectorcraft-geom = { workspace = true } vectorcraft-doc = { workspace = true } kurbo = { workspace = true } diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 2303dbacf5..53437300b7 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,13 +5,15 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "d20a82481b1f7b1d32c818b19c620338af9755d3"; +const REV: &str = "d7c9632bfb3040cf45db394e7500cc93c81c49e0"; +const STREAM_REV: &str = "d20a82481b1f7b1d32c818b19c620338af9755d3"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), ("hayro-syntax", "0.7.2", REV), ("hayro-interpret", "0.7.0", REV), - ("hayro-jbig2", "0.3.0", REV), + // Share the vendored JBIG2 package pulled in by craft-stream-codecs. + ("hayro-jbig2", "0.3.0", STREAM_REV), ("hayro-cmap", "0.1.0", REV), ("hayro-postscript", "0.1.0", REV), ]; @@ -32,7 +34,7 @@ pub fn run(root: &Path) -> Result<(), String> { } let metadata: Value = serde_json::from_slice(&output.stdout).map_err(|e| format!("cargo metadata: {e}"))?; validate(&metadata)?; - println!("PDF: shared crate and patched backends resolve once to {REV}"); + println!("PDF: shared crate and patched backends match their pinned sources"); Ok(()) } From a65bcb99bd523f72c31926b911eea89f59c2dccc Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 22 Nov 2026 11:05:07 -0500 Subject: [PATCH 06/32] metafile: use shared EMF and WMF writers (#778) --- crates/metafile/Cargo.toml | 4 +- crates/metafile/src/bytes.rs | 16 +- crates/metafile/src/dib.rs | 138 +++---- crates/metafile/src/emf.rs | 503 -------------------------- crates/metafile/src/encode.rs | 94 +++++ crates/metafile/src/import/picture.rs | 4 +- crates/metafile/src/lib.rs | 32 +- crates/metafile/src/scene.rs | 23 +- crates/metafile/src/tests.rs | 22 +- crates/metafile/src/tests/import.rs | 2 +- crates/metafile/src/wmf.rs | 441 ---------------------- 11 files changed, 174 insertions(+), 1105 deletions(-) delete mode 100644 crates/metafile/src/emf.rs create mode 100644 crates/metafile/src/encode.rs delete mode 100644 crates/metafile/src/wmf.rs diff --git a/crates/metafile/Cargo.toml b/crates/metafile/Cargo.toml index 408e6166a1..d8047c039a 100644 --- a/crates/metafile/Cargo.toml +++ b/crates/metafile/Cargo.toml @@ -3,7 +3,7 @@ name = "vectorcraft-metafile" version.workspace = true edition.workspace = true license.workspace = true -description = "VectorCraft metafiles: hand-written EMF and WMF writers, EMF, EMF+ and WMF import through craft-metafile, and a QuickDraw picture (PICT) reader" +description = "VectorCraft metafiles: EMF and WMF export and EMF, EMF+ and WMF import through craft-metafile, and a QuickDraw picture (PICT) reader" [lints] workspace = true @@ -15,7 +15,7 @@ vectorcraft-doc = { workspace = true } vectorcraft-effects = { workspace = true } vectorcraft-brush = { workspace = true } vectorcraft-text = { workspace = true } -craft-metafile = { workspace = true } +craft-metafile = { workspace = true, features = ["write"] } kurbo = { workspace = true } image = { workspace = true } craft-image-codecs = { workspace = true } diff --git a/crates/metafile/src/bytes.rs b/crates/metafile/src/bytes.rs index 133a476866..3c4d85a1c5 100644 --- a/crates/metafile/src/bytes.rs +++ b/crates/metafile/src/bytes.rs @@ -1,4 +1,4 @@ -//! Little-endian values: the buffer both writers build records in. +//! Little-endian values for hand-built import fixtures. /// Bytes being written. #[derive(Default)] @@ -20,9 +20,6 @@ impl Out { pub fn i32(&mut self, v: i32) { self.0.extend_from_slice(&v.to_le_bytes()); } - pub fn f32(&mut self, v: f32) { - self.0.extend_from_slice(&v.to_le_bytes()); - } pub fn bytes(&mut self, b: &[u8]) { self.0.extend_from_slice(b); } @@ -32,15 +29,4 @@ impl Out { self.0.push(0); } } - /// Overwrite the `u32` at `at` (a size or count known only later). - pub fn set_u32(&mut self, at: usize, v: u32) { - if let Some(b) = self.0.get_mut(at..at + 4) { - b.copy_from_slice(&v.to_le_bytes()); - } - } - pub fn set_i32(&mut self, at: usize, v: i32) { - if let Some(b) = self.0.get_mut(at..at + 4) { - b.copy_from_slice(&v.to_le_bytes()); - } - } } diff --git a/crates/metafile/src/dib.rs b/crates/metafile/src/dib.rs index b104304d7f..3440daccd4 100644 --- a/crates/metafile/src/dib.rs +++ b/crates/metafile/src/dib.rs @@ -1,6 +1,6 @@ -//! Device-independent bitmaps (DIBs), the pixels inside image records: written bottom-up as 24-bit -//! (opaque, composited over white) or 32-bit premultiplied BGRA (AlphaBlend's source). +//! App bitmap sizing, read budgets, and raster conversion for imported pictures. +use craft_metafile::write::Image; use vectorcraft_doc::resample::{Resample, resized}; /// Most pixels along a side of an image the writers store (larger ones are scaled down). @@ -16,8 +16,6 @@ pub(crate) const MAX_FILE_PIXELS: u64 = 1 << 28; /// What [`charge`] says of a bitmap past what is left of the file's budget. pub(crate) const OVER_BUDGET: &str = "the bitmaps hold more pixels than one file may"; -const BI_RGB: u32 = 0; - /// Pixels with straight (not premultiplied) alpha, row by row from the top. #[derive(Clone, Debug, PartialEq)] pub(crate) struct Rgba { @@ -26,30 +24,25 @@ pub(crate) struct Rgba { pub pixels: Vec, } +/// `img`, scaled down to what a metafile stores when it is larger. +pub(crate) fn fitted(img: image::RgbaImage) -> Image { + let (w, h) = img.dimensions(); + let side = f64::from(w.max(h)) / f64::from(MAX_SIDE); + let area = (u64::from(w) * u64::from(h)) as f64 / MAX_PIXELS as f64; + let k = side.max(area.sqrt()); + let img = if k > 1.0 { + let nw = ((f64::from(w) / k).floor() as u32).max(1); + let nh = ((f64::from(h) / k).floor() as u32).max(1); + let how = Resample::Filter(image::imageops::FilterType::Triangle); + resized(image::DynamicImage::ImageRgba8(img), nw, nh, how).into_rgba8() + } else { + img + }; + let (width, height) = img.dimensions(); + Image { width, height, rgba: img.into_raw() } +} + impl Rgba { - /// `img`, scaled down to what a metafile stores when it is larger. - pub fn fitted(img: image::RgbaImage) -> Self { - let (w, h) = img.dimensions(); - let side = f64::from(w.max(h)) / f64::from(MAX_SIDE); - let area = (u64::from(w) * u64::from(h)) as f64 / MAX_PIXELS as f64; - let k = side.max(area.sqrt()); - let img = if k > 1.0 { - let nw = ((f64::from(w) / k).floor() as u32).max(1); - let nh = ((f64::from(h) / k).floor() as u32).max(1); - let how = Resample::Filter(image::imageops::FilterType::Triangle); - resized(image::DynamicImage::ImageRgba8(img), nw, nh, how).into_rgba8() - } else { - img - }; - let (width, height) = img.dimensions(); - Self { width, height, pixels: img.into_raw() } - } - - /// Every pixel fully opaque? - pub fn opaque(&self) -> bool { - self.pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255) - } - /// As PNG bytes. pub fn to_png(&self) -> Result, String> { let img = craft_image_codecs::Image::from_u8(self.width, self.height, craft_image_codecs::ChannelLayout::Rgba, self.pixels.clone()) @@ -58,63 +51,6 @@ impl Rgba { } } -/// A BITMAPINFOHEADER of a bottom-up, uncompressed `width` × `height` bitmap of `bits` per pixel. -fn header(width: u32, height: u32, bits: u16, size: usize) -> Vec { - let mut h = crate::bytes::Out::default(); - h.u32(40); - h.i32(i32::try_from(width).unwrap_or(i32::MAX)); - h.i32(i32::try_from(height).unwrap_or(i32::MAX)); - h.u16(1); - h.u16(bits); - h.u32(BI_RGB); - h.u32(u32::try_from(size).unwrap_or(0)); - // 2835 pixels a metre: 72 ppi (the size on the page comes from the record). - h.i32(2835); - h.i32(2835); - h.u32(0); - h.u32(0); - h.0 -} - -/// The bytes of a row of `width` pixels of `bits` each, padded to 4 bytes. -fn stride(width: u32, bits: u32) -> Option { - let row_bits = u64::from(width).checked_mul(u64::from(bits))?; - usize::try_from(row_bits.div_ceil(32) * 4).ok() -} - -/// `img` at `opacity`, composited over white, as a 24-bit DIB → (header, bits). -pub(crate) fn rgb24(img: &Rgba, opacity: f32) -> (Vec, Vec) { - let row = stride(img.width, 24).unwrap_or(0); - let mut bits = vec![0u8; row * img.height as usize]; - let over = |c: u8, a: u32| ((u32::from(c) * a + 255 * (255 - a) + 127) / 255) as u8; - for (y, src) in img.pixels.chunks_exact((img.width as usize * 4).max(1)).enumerate() { - // Bottom-up: the first stored row is the image's last. - let Some(at) = (img.height as usize).checked_sub(y + 1).map(|r| r * row) else { continue }; - let Some(dst) = bits.get_mut(at..at + img.width as usize * 3) else { continue }; - for (d, p) in dst.as_chunks_mut::<3>().0.iter_mut().zip(src.as_chunks::<4>().0) { - let a = (f32::from(p[3]) * opacity.clamp(0.0, 1.0)).round() as u32; - d.copy_from_slice(&[over(p[2], a), over(p[1], a), over(p[0], a)]); - } - } - (header(img.width, img.height, 24, bits.len()), bits) -} - -/// `img` at `opacity` as a 32-bit DIB of premultiplied BGRA → (header, bits). -pub(crate) fn bgra32(img: &Rgba, opacity: f32) -> (Vec, Vec) { - let row = img.width as usize * 4; - let mut bits = vec![0u8; row * img.height as usize]; - for (y, src) in img.pixels.chunks_exact(row.max(1)).enumerate() { - let Some(at) = (img.height as usize).checked_sub(y + 1).map(|r| r * row) else { continue }; - let Some(dst) = bits.get_mut(at..at + row) else { continue }; - for (d, p) in dst.as_chunks_mut::<4>().0.iter_mut().zip(src.as_chunks::<4>().0) { - let a = (f32::from(p[3]) * opacity.clamp(0.0, 1.0)).round() as u32; - let pre = |c: u8| ((u32::from(c) * a + 127) / 255) as u8; - d.copy_from_slice(&[pre(p[2]), pre(p[1]), pre(p[0]), a as u8]); - } - } - (header(img.width, img.height, 32, bits.len()), bits) -} - /// Take a bitmap of `w` × `h` from what is `left` of the file's budget, before it is decoded. pub(crate) fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> { let n = u64::from(w) * u64::from(h); @@ -126,10 +62,10 @@ pub(crate) fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> { mod tests { use super::*; - fn sample() -> Rgba { + fn sample() -> Image { // 3 × 2: red, green, blue / half-transparent black, transparent, white. let pixels = vec![255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 0, 0, 0, 128, 0, 0, 0, 0, 255, 255, 255, 255]; - Rgba { width: 3, height: 2, pixels } + Image { width: 3, height: 2, rgba: pixels } } #[test] @@ -144,7 +80,14 @@ mod tests { #[test] fn rgb24_is_bottom_up_bgr_over_white() { - let (bmi, bits) = rgb24(&sample(), 1.0); + // WMF's shared writer emits a StretchDIB record: 28 bytes of parameters and + // record framing precede BITMAPINFOHEADER, then the bottom-up rows. + let image = std::sync::Arc::new(sample()); + let op = craft_metafile::write::Op::Image { image, xf: kurbo::Affine::IDENTITY, opacity: 1.0 }; + let bytes = craft_metafile::write::wmf(&[op], kurbo::Rect::new(0.0, 0.0, 3.0, 2.0)).unwrap().bytes; + let records = crate::tests::wmf_records(&bytes); + let (_, record) = records.iter().find(|(kind, _)| *kind == 0x0f43).unwrap(); + let (bmi, bits) = (&record[28..68], &record[68..]); assert_eq!(bmi.len(), 40); assert_eq!(&bmi[14..16], &[24, 0], "24 bits a pixel"); // Rows of 9 bytes padded to 12, the last row first: half-transparent black over white is @@ -154,19 +97,28 @@ mod tests { #[test] fn bgra32_is_premultiplied() { - let (bmi, bits) = bgra32(&sample(), 1.0); - assert_eq!(&bmi[14..16], &[32, 0]); + let pixels = |opacity| { + let image = std::sync::Arc::new(sample()); + let op = craft_metafile::write::Op::Image { image, xf: kurbo::Affine::IDENTITY, opacity }; + let bytes = craft_metafile::write::emf(&[op], kurbo::Rect::new(0.0, 0.0, 3.0, 2.0), "VectorCraft", "").unwrap(); + let records = crate::tests::emf_records(&bytes); + let (_, record) = records.iter().find(|(kind, _)| *kind == 114).unwrap(); + let (bmi, bits) = (&record[108..148], &record[148..]); + assert_eq!(&bmi[14..16], &[32, 0]); + bits.to_vec() + }; + let bits = pixels(1.0); assert_eq!(&bits[..12], &[0, 0, 0, 128, 0, 0, 0, 0, 255, 255, 255, 255]); assert_eq!(&bits[12..16], &[0, 0, 255, 255], "red, as BGRA"); // At half opacity. - let (_, half) = bgra32(&sample(), 0.5); + let half = pixels(0.5); assert_eq!(&half[12..16], &[0, 0, 128, 128]); } #[test] fn large_images_are_scaled_to_fit() { let img = image::RgbaImage::new(MAX_SIDE * 2, 4); - let f = Rgba::fitted(img); + let f = fitted(img); assert_eq!((f.width, f.height), (MAX_SIDE, 2)); } @@ -176,10 +128,10 @@ mod tests { fn large_images_keep_their_color_beside_clear_pixels() { let img = image::RgbaImage::from_fn(MAX_SIDE * 2, 4, |x, _| if x % 2 == 0 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) }); - let f = Rgba::fitted(img); + let f = fitted(img); assert_eq!((f.width, f.height), (MAX_SIDE, 2)); let m = |c: u8, a: u8| (u16::from(c) * u16::from(a) / 255) as u8; - for p in f.pixels.as_chunks::<4>().0 { + for p in f.rgba.as_chunks::<4>().0 { assert!(p[3] > 0 && [200, 30, 30].iter().zip(p).all(|(&want, &c)| m(c, p[3]).abs_diff(m(want, p[3])) <= 1), "{p:?}"); } } diff --git a/crates/metafile/src/emf.rs b/crates/metafile/src/emf.rs deleted file mode 100644 index dccfb4326b..0000000000 --- a/crates/metafile/src/emf.rs +++ /dev/null @@ -1,503 +0,0 @@ -//! The EMF writer: an EMR_HEADER whose frame is the region in 0.01 mm, then the drawing in device -//! units of 0.01 mm (the reference device has 100 pixels a millimetre) and an EMR_EOF. -//! -//! Each fill and stroke is a path bracket (move-to, poly-line-to and poly-Bézier-to runs, close -//! figure) filled with a solid brush or stroked with a geometric pen; brushes and pens are made -//! when the colour or pen changes and deleted when replaced. Clips are path clips inside a saved -//! DC; images are StretchDIBits (opaque) or AlphaBlend (with transparency) under a world transform -//! that places their pixels. - -use kurbo::PathEl; -use vectorcraft_doc::{LineCap, LineJoin}; -use vectorcraft_geom::{Affine, BezPath, FillRule, Point, Rect}; - -use crate::bytes::Out; -use crate::dib::{self, Rgba}; -use crate::scene::{Op, Pen}; - -// Record types (MS-EMF 2.1.1). -pub(crate) const HEADER: u32 = 1; -pub(crate) const POLYBEZIERTO: u32 = 5; -pub(crate) const POLYLINETO: u32 = 6; -pub(crate) const EOF: u32 = 14; -pub(crate) const SETBKMODE: u32 = 18; -pub(crate) const SETPOLYFILLMODE: u32 = 19; -pub(crate) const MOVETOEX: u32 = 27; -pub(crate) const SAVEDC: u32 = 33; -pub(crate) const RESTOREDC: u32 = 34; -pub(crate) const SETWORLDTRANSFORM: u32 = 35; -pub(crate) const MODIFYWORLDTRANSFORM: u32 = 36; -pub(crate) const SELECTOBJECT: u32 = 37; -pub(crate) const CREATEBRUSHINDIRECT: u32 = 39; -pub(crate) const DELETEOBJECT: u32 = 40; -pub(crate) const SETMITERLIMIT: u32 = 58; -pub(crate) const BEGINPATH: u32 = 59; -pub(crate) const ENDPATH: u32 = 60; -pub(crate) const CLOSEFIGURE: u32 = 61; -pub(crate) const FILLPATH: u32 = 62; -pub(crate) const STROKEPATH: u32 = 64; -pub(crate) const SELECTCLIPPATH: u32 = 67; -pub(crate) const STRETCHDIBITS: u32 = 81; -pub(crate) const EXTCREATEPEN: u32 = 95; -pub(crate) const ALPHABLEND: u32 = 114; - -/// The `" EMF"` signature in the header. -pub(crate) const SIGNATURE: u32 = 0x464D_4520; -/// Stock objects (selected to release ours before deleting them). -const WHITE_BRUSH: u32 = 0x8000_0000; -const NULL_PEN: u32 = 0x8000_0008; -/// Our two object slots (0 is reserved). -const BRUSH: u32 = 1; -const PEN: u32 = 2; - -pub(crate) const PS_GEOMETRIC: u32 = 0x0001_0000; -pub(crate) const PS_USERSTYLE: u32 = 7; -pub(crate) const PS_ENDCAP_SQUARE: u32 = 0x100; -pub(crate) const PS_ENDCAP_FLAT: u32 = 0x200; -pub(crate) const PS_JOIN_BEVEL: u32 = 0x1000; -pub(crate) const PS_JOIN_MITER: u32 = 0x2000; -/// Raster operation: copy the source. -pub(crate) const SRCCOPY: u32 = 0x00CC_0020; - -/// Device units (0.01 mm) per point. -pub(crate) const UNITS_PER_PT: f64 = 2540.0 / 72.0; -/// Longest dash pattern a geometric pen takes (longer ones are drawn as separate dashes). -const MAX_STYLE: usize = 16; -/// Header size with both extensions. -const HEADER_SIZE: usize = 108; -/// Coordinates are kept within this (far beyond any page). -const MAX_COORD: f64 = 1e9; - -/// Does `bytes` start with an EMF header? -pub(crate) fn is_emf(bytes: &[u8]) -> bool { - let u32_at = |at: usize| bytes.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes); - u32_at(0) == Some(HEADER) && u32_at(40) == Some(SIGNATURE) -} - -/// A COLORREF (0x00bbggrr). -pub(crate) fn colorref(rgb: [u8; 3]) -> u32 { - u32::from_le_bytes([rgb[0], rgb[1], rgb[2], 0]) -} - -/// What a pen object is made of, to tell when the next stroke needs another. -#[derive(Clone, PartialEq)] -struct PenKey { - style: u32, - width: u32, - color: u32, - entries: Vec, -} - -/// A device-space bounding box (inclusive). -type Bounds = [i32; 4]; - -fn union(a: Option, b: Bounds) -> Bounds { - match a { - None => b, - Some(a) => [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])], - } -} - -struct Writer { - out: Out, - records: u32, - /// Document → device units. - to_dev: Affine, - /// The frame in device units: what the region clip lets through. - frame: Bounds, - /// Everything drawn, in device units. - bounds: Option, - brush: Option, - pen: Option, - fill_mode: Option, - miter: Option, -} - -/// Write `ops` as an EMF of `region` (document space), described as `title`. -pub(crate) fn write(ops: &[Op], region: Rect, title: &str) -> Vec { - let k = UNITS_PER_PT; - let frame = [0, 0, (region.width() * k).round() as i32, (region.height() * k).round() as i32]; - let mut w = Writer { - out: Out::default(), - records: 0, - to_dev: Affine::scale(k) * Affine::translate(-region.origin().to_vec2()), - frame, - bounds: None, - brush: None, - pen: None, - fill_mode: None, - miter: None, - }; - w.header(title); - // Dash gaps and hatches show what is below. - w.record(SETBKMODE, |o| o.u32(1)); - for op in ops { - w.op(op); - } - w.release(); - w.record(EOF, |o| { - o.u32(0); - o.u32(16); - o.u32(20); - }); - w.finish() -} - -impl Writer { - /// Append one record: its type, size and `body`, padded to 4 bytes. - fn record(&mut self, kind: u32, body: impl FnOnce(&mut Out)) { - let start = self.out.len(); - self.out.u32(kind); - self.out.u32(0); - body(&mut self.out); - self.out.pad(4); - let size = u32::try_from(self.out.len() - start).unwrap_or(u32::MAX); - self.out.set_u32(start + 4, size); - self.records += 1; - } - - fn header(&mut self, title: &str) { - let desc: Vec = - "VectorCraft".encode_utf16().chain([0]).chain(title.chars().take(200).collect::().encode_utf16()).chain([0, 0]).collect(); - let f = self.frame; - // The reference device: 100 pixels a millimetre, as large as the frame. - let mm = [(f[2] / 100).max(1) + 1, (f[3] / 100).max(1) + 1]; - self.record(HEADER, |o| { - // Bounds, patched in `finish`. - o.bytes(&[0; 16]); - for v in f { - o.i32(v); - } - o.u32(SIGNATURE); - o.u32(0x0001_0000); - // Bytes, records and handles, patched in `finish`. - o.u32(0); - o.u32(0); - o.u16(3); - o.u16(0); - o.u32(desc.len() as u32); - o.u32(HEADER_SIZE as u32); - o.u32(0); - o.i32(mm[0] * 100); - o.i32(mm[1] * 100); - o.i32(mm[0]); - o.i32(mm[1]); - // No pixel format, not OpenGL; the device in micrometres. - o.u32(0); - o.u32(0); - o.u32(0); - o.u32(mm[0] as u32 * 1000); - o.u32(mm[1] as u32 * 1000); - for c in &desc { - o.u16(*c); - } - }); - } - - /// Patch the header's bounds, size and record count. - fn finish(mut self) -> Vec { - let b = self.bounds.map(|b| [b[0].max(self.frame[0]), b[1].max(self.frame[1]), b[2].min(self.frame[2]), b[3].min(self.frame[3])]); - // An empty picture has bounds (0, 0, -1, -1). - let b = b.filter(|b| b[0] <= b[2] && b[1] <= b[3]).unwrap_or([0, 0, -1, -1]); - for (i, v) in b.iter().enumerate() { - self.out.set_i32(8 + 4 * i, *v); - } - let size = u32::try_from(self.out.len()).unwrap_or(u32::MAX); - self.out.set_u32(48, size); - self.out.set_u32(52, self.records); - self.out.0 - } - - fn dev(&self, p: Point) -> [i32; 2] { - let q = self.to_dev * p; - let c = |v: f64| if v.is_finite() { v.round().clamp(-MAX_COORD, MAX_COORD) as i32 } else { 0 }; - [c(q.x), c(q.y)] - } - - fn grow(&mut self, b: Bounds) { - self.bounds = Some(union(self.bounds, b)); - } - - fn op(&mut self, op: &Op) { - match op { - Op::Fill { path, rule, rgb } => { - self.fill_mode(*rule); - self.brush(*rgb); - if let Some(b) = self.path(path) { - self.grow(b); - self.record(FILLPATH, |o| b.iter().for_each(|v| o.i32(*v))); - } - } - Op::Stroke { path, pen } => { - let dashed; - let path = if self.pen(pen) { - path - } else { - dashed = crate::scene::dashed(path, pen.dash.as_ref()); - &dashed - }; - if let Some(b) = self.path(path) { - let half = (pen.width * UNITS_PER_PT / 2.0).ceil() as i32; - let b = [b[0] - half, b[1] - half, b[2] + half, b[3] + half]; - self.grow(b); - self.record(STROKEPATH, |o| b.iter().for_each(|v| o.i32(*v))); - } - } - Op::Image { image, xf, opacity } => self.image(image, *xf, *opacity), - Op::Clip { path, rule } => { - self.release(); - self.record(SAVEDC, |_| {}); - self.fill_mode(*rule); - if self.path(path).is_some() { - // RGN_AND: inside the clip already set. - self.record(SELECTCLIPPATH, |o| o.u32(1)); - } - } - Op::Unclip => { - self.release(); - self.record(RESTOREDC, |o| o.i32(-1)); - // The DC's fill mode and miter limit are back to what they were at the save. - self.fill_mode = None; - self.miter = None; - } - } - } - - fn fill_mode(&mut self, rule: FillRule) { - // ALTERNATE (even-odd) or WINDING (non-zero). - let mode = if rule == FillRule::EvenOdd { 1 } else { 2 }; - if self.fill_mode != Some(mode) { - self.record(SETPOLYFILLMODE, |o| o.u32(mode)); - self.fill_mode = Some(mode); - } - } - - /// Select a solid brush of `rgb`, made when the colour changes. - fn brush(&mut self, rgb: [u8; 3]) { - let color = colorref(rgb); - if self.brush == Some(color) { - return; - } - self.drop_brush(); - self.record(CREATEBRUSHINDIRECT, |o| { - o.u32(BRUSH); - // BS_SOLID, the colour, no hatch. - o.u32(0); - o.u32(color); - o.u32(0); - }); - self.record(SELECTOBJECT, |o| o.u32(BRUSH)); - self.brush = Some(color); - } - - fn drop_brush(&mut self) { - if self.brush.take().is_some() { - self.record(SELECTOBJECT, |o| o.u32(WHITE_BRUSH)); - self.record(DELETEOBJECT, |o| o.u32(BRUSH)); - } - } - - fn drop_pen(&mut self) { - if self.pen.take().is_some() { - self.record(SELECTOBJECT, |o| o.u32(NULL_PEN)); - self.record(DELETEOBJECT, |o| o.u32(PEN)); - } - } - - /// Release our objects (before a DC is saved or restored, which would bring back deleted ones). - fn release(&mut self) { - self.drop_brush(); - self.drop_pen(); - } - - /// Select a geometric pen for `p`, made when it changes. False when `p`'s dashes must be - /// drawn as separate lines (the pen selected is solid): a pen's dashes start at the path's - /// start, every entry at least a unit long, 16 entries at most. - fn pen(&mut self, p: &Pen) -> bool { - let k = UNITS_PER_PT; - let entries: Option> = p.dash.as_ref().map(|d| { - let mut v: Vec = d.pattern.clone(); - if v.len() % 2 == 1 { - v.extend_from_within(..); - } - v.iter().map(|x| (x * k).round().clamp(0.0, f64::from(u32::MAX)) as u32).collect() - }); - let native = match (&entries, &p.dash) { - (Some(e), Some(d)) => d.offset.abs() < 1e-9 && e.len() <= MAX_STYLE && e.iter().all(|x| *x >= 1), - _ => true, - }; - let entries = if native { entries.unwrap_or_default() } else { vec![] }; - let cap = match p.cap { - LineCap::Butt => PS_ENDCAP_FLAT, - LineCap::Round => 0, - LineCap::Square => PS_ENDCAP_SQUARE, - }; - let join = match p.join { - LineJoin::Miter => PS_JOIN_MITER, - LineJoin::Round => 0, - LineJoin::Bevel => PS_JOIN_BEVEL, - }; - let style = PS_GEOMETRIC | cap | join | if entries.is_empty() { 0 } else { PS_USERSTYLE }; - let key = PenKey { style, width: (p.width * k).round().clamp(1.0, 1e9) as u32, color: colorref(p.rgb), entries }; - if p.join == LineJoin::Miter { - let m = p.miter.round().clamp(1.0, 1000.0) as u32; - if self.miter != Some(m) { - self.record(SETMITERLIMIT, |o| o.u32(m)); - self.miter = Some(m); - } - } - if self.pen.as_ref() != Some(&key) { - self.drop_pen(); - let n = key.entries.len() as u32; - self.record(EXTCREATEPEN, |o| { - o.u32(PEN); - // No pattern bitmap: its offsets point past the record, its sizes are 0. - let end = 52 + 4 * n; - o.u32(end); - o.u32(0); - o.u32(end); - o.u32(0); - o.u32(key.style); - o.u32(key.width); - // BS_SOLID, the colour, no hatch. - o.u32(0); - o.u32(key.color); - o.u32(0); - o.u32(n); - key.entries.iter().for_each(|e| o.u32(*e)); - }); - self.record(SELECTOBJECT, |o| o.u32(PEN)); - self.pen = Some(key); - } - native - } - - /// `bp` as a path bracket → its device bounds (`None`: nothing to draw). - fn path(&mut self, bp: &BezPath) -> Option { - if !bp.elements().iter().any(|e| !matches!(e, PathEl::MoveTo(_) | PathEl::ClosePath)) { - return None; - } - self.record(BEGINPATH, |_| {}); - let mut bounds: Option = None; - let mut run: Vec<[i32; 2]> = vec![]; - let mut curves = false; - let mut last = Point::ZERO; - let mut start = Point::ZERO; - for el in bp.elements() { - let (pts, is_curve): (Vec, bool) = match *el { - PathEl::MoveTo(p) => { - self.flush_run(&mut run, curves); - let d = self.dev(p); - bounds = Some(union(bounds, [d[0], d[1], d[0], d[1]])); - self.record(MOVETOEX, |o| d.iter().for_each(|v| o.i32(*v))); - (last, start) = (p, p); - continue; - } - PathEl::ClosePath => { - self.flush_run(&mut run, curves); - self.record(CLOSEFIGURE, |_| {}); - last = start; - continue; - } - PathEl::LineTo(p) => (vec![p], false), - PathEl::QuadTo(c, p) => (vec![last + (c - last) * (2.0 / 3.0), p + (c - p) * (2.0 / 3.0), p], true), - PathEl::CurveTo(a, b, p) => (vec![a, b, p], true), - }; - if is_curve != curves { - self.flush_run(&mut run, curves); - curves = is_curve; - } - for p in &pts { - let d = self.dev(*p); - bounds = Some(union(bounds, [d[0], d[1], d[0], d[1]])); - run.push(d); - } - last = pts.last().copied().unwrap_or(last); - } - self.flush_run(&mut run, curves); - self.record(ENDPATH, |_| {}); - bounds - } - - /// Write the points of a run of lines or curves, then empty it. - fn flush_run(&mut self, run: &mut Vec<[i32; 2]>, curves: bool) { - if run.is_empty() { - return; - } - let pts = std::mem::take(run); - let b = pts.iter().fold(None, |acc, p| Some(union(acc, [p[0], p[1], p[0], p[1]]))).unwrap_or([0, 0, -1, -1]); - self.record(if curves { POLYBEZIERTO } else { POLYLINETO }, |o| { - b.iter().for_each(|v| o.i32(*v)); - o.u32(pts.len() as u32); - for p in &pts { - o.i32(p[0]); - o.i32(p[1]); - } - }); - } - - /// An image placed by `xf` (its pixels → document): StretchDIBits when opaque, else AlphaBlend, - /// drawn at its pixel size under a world transform. - fn image(&mut self, img: &Rgba, xf: Affine, opacity: f32) { - if img.width == 0 || img.height == 0 || opacity <= 0.0 { - return; - } - let m = self.to_dev * xf; - if !m.as_coeffs().iter().all(|v| v.is_finite()) || m.determinant().abs() < 1e-12 { - return; - } - let (w, h) = (f64::from(img.width), f64::from(img.height)); - let corners = [Point::ZERO, Point::new(w, 0.0), Point::new(0.0, h), Point::new(w, h)].map(|p| self.dev(xf * p)); - let b = corners.iter().fold(None, |acc, p| Some(union(acc, [p[0], p[1], p[0], p[1]]))).unwrap_or([0, 0, -1, -1]); - self.grow(b); - let [a, bb, c, d, e, f] = m.as_coeffs(); - self.record(SETWORLDTRANSFORM, |o| [a, bb, c, d, e, f].iter().for_each(|v| o.f32(*v as f32))); - let (iw, ih) = (img.width as i32, img.height as i32); - if img.opaque() && opacity >= 0.998 { - let (bmi, bits) = dib::rgb24(img, 1.0); - self.record(STRETCHDIBITS, |o| { - b.iter().for_each(|v| o.i32(*v)); - // Destination and source rectangles. - [0, 0, 0, 0, iw, ih].iter().for_each(|v| o.i32(*v)); - o.u32(80); - o.u32(bmi.len() as u32); - o.u32(80 + bmi.len() as u32); - o.u32(bits.len() as u32); - // DIB_RGB_COLORS, SRCCOPY, the destination size. - o.u32(0); - o.u32(SRCCOPY); - o.i32(iw); - o.i32(ih); - o.bytes(&bmi); - o.bytes(&bits); - }); - } else { - let (bmi, bits) = dib::bgra32(img, opacity); - self.record(ALPHABLEND, |o| { - b.iter().for_each(|v| o.i32(*v)); - [0, 0, iw, ih].iter().for_each(|v| o.i32(*v)); - // AC_SRC_OVER, no flags, constant alpha 255, AC_SRC_ALPHA (per-pixel alpha). - o.bytes(&[0, 0, 255, 1]); - o.i32(0); - o.i32(0); - // The source's own transform: identity. - [1.0f32, 0.0, 0.0, 1.0, 0.0, 0.0].iter().for_each(|v| o.f32(*v)); - o.u32(0); - o.u32(0); - o.u32(108); - o.u32(bmi.len() as u32); - o.u32(108 + bmi.len() as u32); - o.u32(bits.len() as u32); - o.i32(iw); - o.i32(ih); - o.bytes(&bmi); - o.bytes(&bits); - }); - } - // MWT_IDENTITY: back to drawing in device units. - self.record(MODIFYWORLDTRANSFORM, |o| { - [1.0f32, 0.0, 0.0, 1.0, 0.0, 0.0].iter().for_each(|v| o.f32(*v)); - o.u32(1); - }); - } -} diff --git a/crates/metafile/src/encode.rs b/crates/metafile/src/encode.rs new file mode 100644 index 0000000000..6eab34d886 --- /dev/null +++ b/crates/metafile/src/encode.rs @@ -0,0 +1,94 @@ +//! Translate VectorCraft's drawing operations to the shared metafile writers. +use craft_metafile::{ + Cap, Join, + write::{self, Dash, Op, Pen}, +}; +use vectorcraft_doc::{LineCap, LineJoin}; +use vectorcraft_geom::{FillRule, Rect}; + +use crate::{Kind, scene}; + +pub(crate) fn write(ops: Vec, region: Rect, kind: Kind, title: &str, warnings: &mut Vec) -> Result, String> { + let ops: Vec<_> = ops.into_iter().map(|op| convert(op, kind)).collect(); + let invalid = || "the export region is empty".to_string(); + match kind { + Kind::Emf => write::emf(&ops, region, "VectorCraft", title).ok_or_else(invalid), + Kind::Wmf => { + let out = write::wmf(&ops, region).ok_or_else(invalid)?; + for (lost, warning) in [ + (out.translucent_images, "WMF has no transparency: images are written over white"), + (out.turned_images, "WMF can't rotate or skew images: they are written upright, filling their bounds"), + (out.clips_ignored, "clipping masks are not applied: the art they clip is written whole"), + (out.oversized_images, "WMF images with a side over 32,767 pixels were left out"), + ] { + if lost && !warnings.iter().any(|w| w == warning) { + warnings.push(warning.to_string()); + } + } + Ok(out.bytes) + } + } +} + +fn convert(op: scene::Op, kind: Kind) -> Op { + match op { + scene::Op::Fill { path, rule, rgb } => Op::Fill { path, even_odd: rule == FillRule::EvenOdd, rgb }, + scene::Op::Stroke { mut path, pen } => { + let dash = pen.dash.and_then(|dash| { + let native = Dash { pattern: dash.pattern.clone(), offset: dash.offset }; + if kind == Kind::Emf && native.emf_pen_draws() { + Some(native) + } else { + // Keep VectorCraft's own dash placement for strokes that cannot use an + // EMF native pen, including adjusted dashes around corners in WMF. + if let Some(dashed) = vectorcraft_effects::stroke::dash(&path, &dash) { + path = dashed.path; + } + None + } + }); + let cap = match pen.cap { + LineCap::Butt => Cap::Flat, + LineCap::Round => Cap::Round, + LineCap::Square => Cap::Square, + }; + let join = match pen.join { + LineJoin::Miter => Join::Miter, + LineJoin::Round => Join::Round, + LineJoin::Bevel => Join::Bevel, + }; + Op::Stroke { path, pen: Pen { rgb: pen.rgb, width: pen.width, cap, join, miter: pen.miter, dash } } + } + scene::Op::Image { image, xf, opacity } => Op::Image { image, xf, opacity }, + scene::Op::Clip { path, rule } => Op::Clip { path, even_odd: rule == FillRule::EvenOdd }, + scene::Op::Unclip => Op::Unclip, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nonnative_metafile_pens_keep_vectorcraft_corner_alignment() { + let mut path = kurbo::BezPath::new(); + path.move_to((7.0, 8.0)); + path.line_to((42.0, 8.0)); + path.line_to((42.0, 45.0)); + path.line_to((7.0, 45.0)); + path.close_path(); + let dash = vectorcraft_doc::Dash { pattern: vec![5.0, 3.0], offset: 1.25, align_corners: true }; + let plain = scene::Pen { rgb: [30, 60, 90], width: 1.0, cap: LineCap::Round, join: LineJoin::Round, miter: 4.0, dash: None }; + let with_dash = scene::Pen { dash: Some(dash.clone()), ..plain.clone() }; + let segments = vectorcraft_effects::stroke::dash(&path, &dash).unwrap().path; + let region = Rect::new(0.0, 0.0, 50.0, 50.0); + for kind in [Kind::Emf, Kind::Wmf] { + let actual = write(vec![scene::Op::Stroke { path: path.clone(), pen: with_dash.clone() }], region, kind, "", &mut Vec::new()).unwrap(); + let already_dashed = + write(vec![scene::Op::Stroke { path: segments.clone(), pen: plain.clone() }], region, kind, "", &mut Vec::new()).unwrap(); + let unsplit = write(vec![scene::Op::Stroke { path: path.clone(), pen: plain.clone() }], region, kind, "", &mut Vec::new()).unwrap(); + assert_eq!(actual, already_dashed, "the wire writer must receive the app-aligned segments: {kind:?}"); + assert_ne!(actual, unsplit, "the fixture must distinguish a lost dash pattern: {kind:?}"); + } + } +} diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index 1cfb3038cd..dab2111119 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -44,9 +44,11 @@ use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect, use super::{BAD_IMAGE, FAR_AWAY, HAIRLINE, LIMIT, MAX_NODES, around, rgb, sane}; use crate::dib::Rgba; -use crate::wmf::PLACEABLE_KEY; use crate::{Imported, Kind}; +// The placeable header is interpreted here for VectorCraft’s logical-unit policy. +const PLACEABLE_KEY: u32 = 0x9AC6_CDD7; + const PATTERNS: &str = "hatched and pattern brushes are filled with their average color"; const ENDS_EARLY: &str = "the file ends early: what it held was imported"; const TOO_MANY: &str = "objects past the most one file may hold were left out"; diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 3f6dd8d5dd..033dc6343a 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -22,18 +22,14 @@ //! [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) into the same kind of //! document. //! -//! - `bytes`: little-endian writing. -//! - `dib`: device-independent bitmaps for the writers. -//! - `scene`: the document walk both writers share. -//! - `emf`, `wmf`: the writers. -//! - `import`: the readers. +//! The app walks its document and maps its drawing operations to the shared writers. +#[cfg(test)] mod bytes; mod dib; -mod emf; +mod encode; mod import; mod scene; -mod wmf; use vectorcraft_doc::Document; use vectorcraft_geom::Rect; @@ -59,13 +55,10 @@ impl Kind { /// The metafile format `bytes` start like, if any. pub fn sniff(bytes: &[u8]) -> Option { - if emf::is_emf(bytes) { - Some(Kind::Emf) - } else if wmf::is_wmf(bytes) { - Some(Kind::Wmf) - } else { - None - } + craft_metafile::sniff(bytes).map(|kind| match kind { + craft_metafile::Kind::Emf => Kind::Emf, + craft_metafile::Kind::Wmf => Kind::Wmf, + }) } /// A written metafile. @@ -109,18 +102,13 @@ pub fn export_regions(doc: &Document, regions: &[Rect], kind: Kind) -> Result emf::write(&ops, r, doc.info_title()), - Kind::Wmf => wmf::write(&ops, r, &mut warnings), - }; - Output { bytes, warnings } + encode::write(ops, r, kind, doc.info_title(), &mut warnings).map(|bytes| Output { bytes, warnings }) }) - .collect(); - Ok(outputs) + .collect() } /// A metafile read into a document. diff --git a/crates/metafile/src/scene.rs b/crates/metafile/src/scene.rs index a6c98889f6..3c280822b3 100644 --- a/crates/metafile/src/scene.rs +++ b/crates/metafile/src/scene.rs @@ -14,7 +14,7 @@ use vectorcraft_doc::{AppearanceItem, Dash, Document, ImageObject, LineCap, Line use vectorcraft_effects::stroke; use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Shape}; -use crate::dib::Rgba; +use craft_metafile::write::Image; /// How deep symbols, brush art and pattern tiles may nest in one another (deeper art is left out). const MAX_NEST: u32 = 8; @@ -73,7 +73,7 @@ pub(crate) enum Op { /// An image: its pixel space (0..w, 0..h) maps into the document by `xf`; its alpha times /// `opacity`. Image { - image: Arc, + image: Arc, xf: Affine, opacity: f32, }, @@ -104,11 +104,6 @@ fn first_solid(n: &Node) -> Option { own.or_else(|| n.children().into_iter().flatten().find_map(|c| first_solid(c))) } -/// `bp` cut into its dashes (as it is when `dash` draws none), for pens that can't draw them. -pub(crate) fn dashed(bp: &BezPath, dash: Option<&Dash>) -> BezPath { - dash.and_then(|d| stroke::dash(bp, d)).map_or_else(|| bp.clone(), |d| d.path) -} - fn q(v: f32) -> u8 { (v.clamp(0.0, 1.0) * 255.0).round() as u8 } @@ -124,7 +119,7 @@ pub(crate) struct Scene<'a> { ops: Vec, warnings: Vec, /// Decoded images by key (`None`: can't be decoded, left out). - images: HashMap>>, + images: HashMap>>, brushes: Option>, /// The opacity of the containers around the current object. opacity: f32, @@ -456,7 +451,7 @@ impl<'a> Scene<'a> { }) .collect() }; - let image = Rgba { width: u32::from(cols), height: u32::from(rows), pixels }; + let image = Image { width: u32::from(cols), height: u32::from(rows), rgba: pixels }; let xf = Affine::translate(area.origin().to_vec2()) * Affine::scale_non_uniform(area.width() / f64::from(cols), area.height() / f64::from(rows)); self.ops.push(Op::Clip { path: bp.clone(), rule }); @@ -518,7 +513,7 @@ impl<'a> Scene<'a> { /// Image `im`'s pixels (scaled down to what a metafile stores), `None` with a warning when it /// has none or can't be decoded. - fn decoded(&mut self, im: &ImageObject) -> Option> { + fn decoded(&mut self, im: &ImageObject) -> Option> { let key = im.key.as_str(); if let Some(i) = self.images.get(key) { return i.clone(); @@ -527,7 +522,7 @@ impl<'a> Scene<'a> { let img = blob .and_then(|b| craft_image_codecs::decode(&b.bytes).ok()) .and_then(|i| image::RgbaImage::from_raw(i.width(), i.height(), i.to_rgba8())) - .map(Rgba::fitted) + .map(crate::dib::fitted) .filter(|i| i.width > 0 && i.height > 0) .map(Arc::new); if img.is_none() { @@ -541,7 +536,7 @@ impl<'a> Scene<'a> { /// The pixels of `img`, drawn by `xf`, that `clip` (a box in the document) shows, with one pixel /// more on each side: the part and its top left pixel. The whole image when `xf` cannot be /// inverted; `None` when `clip` shows none of it. -fn cropped(img: &Rgba, xf: Affine, clip: Rect) -> Option<(Rgba, u32, u32)> { +fn cropped(img: &Image, xf: Affine, clip: Rect) -> Option<(Image, u32, u32)> { if xf.determinant().abs() < 1e-12 || !xf.determinant().is_finite() { return Some((img.clone(), 0, 0)); } @@ -564,9 +559,9 @@ fn cropped(img: &Rgba, xf: Affine, clip: Rect) -> Option<(Rgba, u32, u32)> { let mut pixels = Vec::with_capacity((x1 - x0) as usize * (y1 - y0) as usize * 4); for y in y0..y1 { let start = y as usize * row + x0 as usize * 4; - pixels.extend_from_slice(img.pixels.get(start..start + (x1 - x0) as usize * 4)?); + pixels.extend_from_slice(img.rgba.get(start..start + (x1 - x0) as usize * 4)?); } - Some((Rgba { width: x1 - x0, height: y1 - y0, pixels }, x0, y0)) + Some((Image { width: x1 - x0, height: y1 - y0, rgba: pixels }, x0, y0)) } /// Do the instances of `def` stay apart? A grid or brick tiling places its tiles side by side, so diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index d5576ef4b5..eeb30ec846 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -342,7 +342,7 @@ fn the_pieces_of_a_distorted_image_store_only_the_pixels_they_show() { }) .collect(); let (ops, _) = crate::scene::Scene::new(&d, d.artboards[0].rect, true).run(); - let parts: Vec<(&crate::dib::Rgba, Affine)> = ops + let parts: Vec<(&craft_metafile::write::Image, Affine)> = ops .iter() .filter_map(|o| match o { crate::scene::Op::Image { image, xf, .. } => Some((&**image, *xf)), @@ -355,12 +355,12 @@ fn the_pieces_of_a_distorted_image_store_only_the_pixels_they_show() { assert!(stored * 4 < 64 * 64 * parts.len() as u64, "{stored} pixels in {} pieces", parts.len()); for ((part, xf), full) in parts.iter().zip(&whole) { // The part's first pixel names where it starts in the image. - let (x0, y0) = (f64::from(part.pixels[0] / 4), f64::from(part.pixels[1] / 4)); + let (x0, y0) = (f64::from(part.rgba[0] / 4), f64::from(part.rgba[1] / 4)); let want = *full * Affine::translate((x0, y0)); assert!(xf.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-6), "{xf:?} against {want:?}"); // Each row runs on from that pixel. let last = (part.width as usize - 1) * 4; - assert_eq!(f64::from(part.pixels[last] / 4), x0 + f64::from(part.width - 1)); + assert_eq!(f64::from(part.rgba[last] / 4), x0 + f64::from(part.width - 1)); } } @@ -394,7 +394,7 @@ fn ruby_is_written_with_its_type() { let reading = contours(&lay.ruby); assert!(reading >= 3, "the reading has ink: {reading}"); let doc = |ruby: bool| doc_with(100.0, 100.0, vec![Node::new(NodeId(0), NodeKind::Text(Box::new(typed(ruby))))]); - let moves = |d: &Document| count(&kinds(&emf_records(&emf(d).bytes)), crate::emf::MOVETOEX); + let moves = |d: &Document| count(&kinds(&emf_records(&emf(d).bytes)), 27 /* EMR_MOVETOEX */); assert_eq!(moves(&doc(true)), moves(&doc(false)) + reading, "the reading's contours are written"); assert!(wmf(&doc(true)).bytes.len() > wmf(&doc(false)).bytes.len(), "WMF writes the reading too"); } @@ -411,7 +411,6 @@ fn wmf_placeable_header_checksum_and_record_sizes() { assert_eq!(u16_at(b, 14), 1440); let xor = (0..10).fold(0u16, |a, i| a ^ u16_at(b, 2 * i)); assert_eq!(u16_at(b, 20), xor, "the checksum"); - assert_eq!(crate::wmf::checksum(&b[..20]), xor); // The WMF header: a memory metafile of 9 words, its size in words, the largest record. assert_eq!([u16_at(b, 22), u16_at(b, 24), u16_at(b, 26)], [1, 9, 0x0300]); assert_eq!(u32_at(b, 28) as usize * 2, b.len() - 22); @@ -431,12 +430,12 @@ fn wmf_placeable_header_checksum_and_record_sizes() { #[test] fn wmf_sizes_fit_sixteen_bits() { - assert_eq!(crate::wmf::units_per_inch(612.0, 792.0), 1440); - let inch = crate::wmf::units_per_inch(3000.0, 1000.0); - assert!(inch < 1440 && f64::from(inch) * 3000.0 / 72.0 <= 32767.0); + let ordinary = wmf(&doc_with(612.0, 792.0, Vec::new())).bytes; + assert_eq!(u16_at(&ordinary, 14), 1440); let d = doc_with(3000.0, 1000.0, vec![path(shapes::rectangle(Rect::new(0.0, 0.0, 3000.0, 1000.0)), red(), Paint::None, 0.0)]); let b = wmf(&d).bytes; - assert_eq!(u16_at(&b, 14), inch); + let inch = u16_at(&b, 14); + assert!(inch < 1440 && f64::from(inch) * 3000.0 / 72.0 <= 32767.0); assert!(u16_at(&b, 10) <= 32767); } @@ -483,10 +482,7 @@ fn export_baking_each_region(doc: &Document, region: Rect, kind: Kind) -> Result let baked = vectorcraft_effects::bake_document_placing_symbols(doc, kind == Kind::Emf, layers); let doc = baked.as_ref().unwrap_or(doc); let (ops, mut warnings) = crate::scene::Scene::new(doc, r, kind == Kind::Emf).run(); - let bytes = match kind { - Kind::Emf => crate::emf::write(&ops, r, doc.info_title()), - Kind::Wmf => crate::wmf::write(&ops, r, &mut warnings), - }; + let bytes = crate::encode::write(ops, r, kind, doc.info_title(), &mut warnings)?; Ok(Output { bytes, warnings }) } diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index 217b962dbe..15eca240a9 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -314,7 +314,7 @@ fn hand_wmf(w: i16, h: i16, records: &[(u16, Vec)]) -> Vec { } o.u16(1440); o.u32(0); - let sum = crate::wmf::checksum(&o.0); + let sum = o.0.as_chunks::<2>().0.iter().fold(0, |acc, pair| acc ^ u16::from_le_bytes(*pair)); o.u16(sum); o.bytes(&[1, 0, 9, 0, 0, 3]); o.bytes(&[0; 12]); diff --git a/crates/metafile/src/wmf.rs b/crates/metafile/src/wmf.rs deleted file mode 100644 index 33a1b081d9..0000000000 --- a/crates/metafile/src/wmf.rs +++ /dev/null @@ -1,441 +0,0 @@ -//! The WMF writer: a placeable header (the picture's size and logical units an inch, with its -//! checksum), the WMF header, then the drawing in 16-bit logical units with an anisotropic window -//! the size of the picture, and the end-of-file record. -//! -//! Curves are flattened into polygons (fills) and polylines (strokes, with pens of the stroke's -//! width, caps and joins; dashes as separate lines). Objects take the lowest free slot of the -//! object table, as players number them: slots 0 and 1 hold a null pen and a null brush, our pen -//! and brush come after and are deleted when replaced. Images are StretchDIB records of 24-bit -//! bitmaps composited over white. - -use kurbo::PathEl; -use vectorcraft_doc::{LineCap, LineJoin}; -use vectorcraft_geom::{Affine, BezPath, FillRule, Point, Rect}; - -use crate::bytes::Out; -use crate::dib::{self, Rgba}; -use crate::emf::{PS_ENDCAP_FLAT, PS_ENDCAP_SQUARE, PS_JOIN_BEVEL, PS_JOIN_MITER, SRCCOPY, colorref}; -use crate::scene::{Op, Pen}; - -/// The key a placeable header starts with. -pub(crate) const PLACEABLE_KEY: u32 = 0x9AC6_CDD7; - -// Record functions (MS-WMF 2.1.1.1). -pub(crate) const EOF: u16 = 0x0000; -pub(crate) const SETBKMODE: u16 = 0x0102; -pub(crate) const SETMAPMODE: u16 = 0x0103; -pub(crate) const SETPOLYFILLMODE: u16 = 0x0106; -pub(crate) const SETWINDOWORG: u16 = 0x020B; -pub(crate) const SETWINDOWEXT: u16 = 0x020C; -pub(crate) const SELECTOBJECT: u16 = 0x012D; -pub(crate) const DELETEOBJECT: u16 = 0x01F0; -pub(crate) const CREATEPENINDIRECT: u16 = 0x02FA; -pub(crate) const CREATEBRUSHINDIRECT: u16 = 0x02FC; -pub(crate) const POLYGON: u16 = 0x0324; -pub(crate) const POLYLINE: u16 = 0x0325; -pub(crate) const POLYPOLYGON: u16 = 0x0538; -pub(crate) const STRETCHDIB: u16 = 0x0F43; - -/// Most logical units an inch (twips, what office apps use). -const MAX_INCH: f64 = 1440.0; -/// The largest 16-bit coordinate. -const MAX_I16: f64 = 32767.0; -/// Most points a polygon or polyline record holds (its count is 16-bit). -const MAX_POINTS: usize = 32767; -/// Curves are flattened to within this many logical units. -const FLATNESS: f64 = 0.25; -/// The null pen's and the null brush's slots. -const NULL_PEN: u16 = 0; -const NULL_BRUSH: u16 = 1; - -const TRANSLUCENT_IMAGES: &str = "WMF has no transparency: images are written over white"; -const TURNED_IMAGES: &str = "WMF can't rotate or skew images: they are written upright, filling their bounds"; - -/// Does `bytes` start like a WMF (placeable, or a plain memory or disk metafile header)? -pub(crate) fn is_wmf(bytes: &[u8]) -> bool { - let u16_at = |at: usize| bytes.get(at..at + 2).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes); - let placeable = bytes.get(..4).is_some_and(|b| b == PLACEABLE_KEY.to_le_bytes()); - placeable || (matches!(u16_at(0), Some(1 | 2)) && u16_at(2) == Some(9) && matches!(u16_at(4), Some(0x0100 | 0x0300))) -} - -/// The logical units an inch for a picture `w` × `h` points: the most, up to 1440, that keep its -/// size within 16 bits. -pub(crate) fn units_per_inch(w: f64, h: f64) -> u16 { - let side_in = w.max(h) / 72.0; - let fit = if side_in > 0.0 { (MAX_I16 / side_in).floor() } else { MAX_INCH }; - fit.clamp(1.0, MAX_INCH) as u16 -} - -/// The XOR of the first ten 16-bit words of a placeable header. -pub(crate) fn checksum(header: &[u8]) -> u16 { - header.as_chunks::<2>().0.iter().take(10).fold(0, |acc, w| acc ^ u16::from_le_bytes(*w)) -} - -/// `bp` flattened to within `tol`: each subpath's points and whether it closes. -fn flatten(bp: &BezPath, tol: f64) -> Vec<(Vec, bool)> { - let mut out: Vec<(Vec, bool)> = vec![]; - let mut cur: Vec = vec![]; - vectorcraft_geom::flatten(bp.iter(), tol, |el| match el { - PathEl::MoveTo(p) => { - if cur.len() > 1 { - out.push((std::mem::take(&mut cur), false)); - } - cur = vec![p]; - } - PathEl::LineTo(p) => cur.push(p), - PathEl::ClosePath => { - if cur.len() > 1 { - out.push((std::mem::take(&mut cur), true)); - } - cur.clear(); - } - _ => {} - }); - if cur.len() > 1 { - out.push((cur, false)); - } - out -} - -/// What a pen object is made of. -#[derive(Clone, Copy, PartialEq)] -struct PenKey { - style: u16, - width: i16, - color: u32, -} - -struct Writer { - /// The records after the headers. - out: Out, - max_record: u32, - to_dev: Affine, - /// Logical units per point. - k: f64, - /// Which object slots are taken. - slots: Vec, - brush: Option<(u16, u32)>, - pen: Option<(u16, PenKey)>, - sel_pen: u16, - sel_brush: u16, - fill_mode: Option, -} - -/// Write `ops` (curves flattened, no clips) as a placeable WMF of `region` (document space). -pub(crate) fn write(ops: &[Op], region: Rect, warnings: &mut Vec) -> Vec { - let inch = units_per_inch(region.width(), region.height()); - let k = f64::from(inch) / 72.0; - let size = |v: f64| (v * k).round().clamp(1.0, MAX_I16) as i16; - let (w, h) = (size(region.width()), size(region.height())); - let mut wr = Writer { - out: Out::default(), - max_record: 0, - to_dev: Affine::scale(k) * Affine::translate(-region.origin().to_vec2()), - k, - slots: vec![], - brush: None, - pen: None, - sel_pen: NULL_PEN, - sel_brush: NULL_BRUSH, - fill_mode: None, - }; - // MM_ANISOTROPIC, a window the size of the picture, transparent background. - wr.record(SETMAPMODE, |o| o.u16(8)); - wr.record(SETWINDOWORG, |o| { - o.i16(0); - o.i16(0); - }); - wr.record(SETWINDOWEXT, |o| { - o.i16(h); - o.i16(w); - }); - wr.record(SETBKMODE, |o| o.u16(1)); - // The null pen and brush (slots 0 and 1), selected while ours change. - wr.alloc(); - wr.record(CREATEPENINDIRECT, |o| { - o.u16(5); - o.i16(0); - o.i16(0); - o.u32(0); - }); - wr.alloc(); - wr.record(CREATEBRUSHINDIRECT, |o| { - o.u16(1); - o.u32(0); - o.u16(0); - }); - wr.select(NULL_PEN); - wr.select(NULL_BRUSH); - let mut translucent = false; - let mut turned = false; - for op in ops { - match op { - Op::Fill { path, rule, rgb } => wr.fill(path, *rule, *rgb), - Op::Stroke { path, pen } => wr.stroke(path, pen), - Op::Image { image, xf, opacity } => { - translucent |= !image.opaque() || *opacity < 0.998; - turned |= !wr.image(image, *xf, *opacity); - } - // The scene gives formats without clipping none. - Op::Clip { .. } | Op::Unclip => {} - } - } - if let Some((slot, _)) = wr.brush.take() { - wr.select(NULL_BRUSH); - wr.delete(slot); - } - if let Some((slot, _)) = wr.pen.take() { - wr.select(NULL_PEN); - wr.delete(slot); - } - wr.record(EOF, |_| {}); - for (on, w) in [(translucent, TRANSLUCENT_IMAGES), (turned, TURNED_IMAGES)] { - if on && !warnings.iter().any(|x| x == w) { - warnings.push(w.to_string()); - } - } - wr.finish(w, h, inch) -} - -impl Writer { - /// Append one record: its size in 16-bit words, its function and `body`. - fn record(&mut self, function: u16, body: impl FnOnce(&mut Out)) { - let start = self.out.len(); - self.out.u32(0); - self.out.u16(function); - body(&mut self.out); - self.out.pad(2); - let words = u32::try_from((self.out.len() - start) / 2).unwrap_or(u32::MAX); - self.out.set_u32(start, words); - self.max_record = self.max_record.max(words); - } - - /// The placeable header, the WMF header, then the records. - fn finish(self, w: i16, h: i16, inch: u16) -> Vec { - let mut o = Out::default(); - o.u32(PLACEABLE_KEY); - o.u16(0); - for v in [0, 0, w, h] { - o.i16(v); - } - o.u16(inch); - o.u32(0); - let sum = checksum(&o.0); - o.u16(sum); - // A memory metafile, 9 words of header, version 3. - o.u16(1); - o.u16(9); - o.u16(0x0300); - o.u32(u32::try_from((18 + self.out.len()) / 2).unwrap_or(u32::MAX)); - o.u16(u16::try_from(self.slots.len()).unwrap_or(u16::MAX)); - o.u32(self.max_record); - o.u16(0); - o.bytes(&self.out.0); - o.0 - } - - /// The lowest free object slot, taken. - fn alloc(&mut self) -> u16 { - let i = match self.slots.iter().position(|t| !t) { - Some(i) => i, - None => { - self.slots.push(false); - self.slots.len() - 1 - } - }; - if let Some(s) = self.slots.get_mut(i) { - *s = true; - } - u16::try_from(i).unwrap_or(u16::MAX) - } - - fn select(&mut self, slot: u16) { - self.record(SELECTOBJECT, |o| o.u16(slot)); - } - - fn delete(&mut self, slot: u16) { - self.record(DELETEOBJECT, |o| o.u16(slot)); - if let Some(s) = self.slots.get_mut(usize::from(slot)) { - *s = false; - } - } - - fn dev(&self, p: Point) -> [i16; 2] { - let q = self.to_dev * p; - let c = |v: f64| if v.is_finite() { v.round().clamp(-MAX_I16, MAX_I16) as i16 } else { 0 }; - [c(q.x), c(q.y)] - } - - /// The device points of `pts`, repeats dropped, thinned to what one record holds. - fn points(&self, pts: &[Point]) -> Vec<[i16; 2]> { - let mut v: Vec<[i16; 2]> = vec![]; - for p in pts { - let d = self.dev(*p); - if v.last() != Some(&d) { - v.push(d); - } - } - if v.len() > MAX_POINTS { - let step = v.len().div_ceil(MAX_POINTS - 1); - let last = v.last().copied(); - v = v.into_iter().step_by(step).collect(); - v.extend(last); - } - v - } - - fn select_pen(&mut self, slot: u16) { - if self.sel_pen != slot { - self.select(slot); - self.sel_pen = slot; - } - } - - fn select_brush(&mut self, slot: u16) { - if self.sel_brush != slot { - self.select(slot); - self.sel_brush = slot; - } - } - - fn use_brush(&mut self, rgb: [u8; 3]) { - let color = colorref(rgb); - let slot = match self.brush { - Some((slot, c)) if c == color => slot, - old => { - if let Some((slot, _)) = old { - self.select_brush(NULL_BRUSH); - self.delete(slot); - } - let slot = self.alloc(); - self.record(CREATEBRUSHINDIRECT, |o| { - o.u16(0); - o.u32(color); - o.u16(0); - }); - self.brush = Some((slot, color)); - slot - } - }; - self.select_brush(slot); - } - - fn use_pen(&mut self, p: &Pen) { - let cap = match p.cap { - LineCap::Butt => PS_ENDCAP_FLAT, - LineCap::Round => 0, - LineCap::Square => PS_ENDCAP_SQUARE, - }; - let join = match p.join { - LineJoin::Miter => PS_JOIN_MITER, - LineJoin::Round => 0, - LineJoin::Bevel => PS_JOIN_BEVEL, - }; - let key = PenKey { style: (cap | join) as u16, width: (p.width * self.k).round().clamp(1.0, MAX_I16) as i16, color: colorref(p.rgb) }; - let slot = match self.pen { - Some((slot, k)) if k == key => slot, - old => { - if let Some((slot, _)) = old { - self.select_pen(NULL_PEN); - self.delete(slot); - } - let slot = self.alloc(); - self.record(CREATEPENINDIRECT, |o| { - o.u16(key.style); - o.i16(key.width); - o.i16(0); - o.u32(key.color); - }); - self.pen = Some((slot, key)); - slot - } - }; - self.select_pen(slot); - } - - fn fill(&mut self, bp: &BezPath, rule: FillRule, rgb: [u8; 3]) { - let polys: Vec> = flatten(bp, FLATNESS / self.k).iter().map(|(p, _)| self.points(p)).filter(|p| p.len() > 2).collect(); - if polys.is_empty() { - return; - } - // ALTERNATE (even-odd) or WINDING (non-zero). - let mode = if rule == FillRule::EvenOdd { 1 } else { 2 }; - if self.fill_mode != Some(mode) { - self.record(SETPOLYFILLMODE, |o| o.u16(mode)); - self.fill_mode = Some(mode); - } - self.use_brush(rgb); - self.select_pen(NULL_PEN); - for chunk in polys.chunks(usize::from(u16::MAX)) { - self.record(POLYPOLYGON, |o| { - o.u16(chunk.len() as u16); - chunk.iter().for_each(|p| o.u16(p.len() as u16)); - for p in chunk.iter().flatten() { - o.i16(p[0]); - o.i16(p[1]); - } - }); - } - } - - fn stroke(&mut self, bp: &BezPath, pen: &Pen) { - let path = crate::scene::dashed(bp, pen.dash.as_ref()); - let lines: Vec<(Vec<[i16; 2]>, bool)> = - flatten(&path, FLATNESS / self.k).iter().map(|(p, closed)| (self.points(p), *closed)).filter(|(p, _)| p.len() > 1).collect(); - if lines.is_empty() { - return; - } - self.use_pen(pen); - self.select_brush(NULL_BRUSH); - for (pts, closed) in lines { - // A closed subpath is a polygon (with the null brush, its outline), so it joins at - // its start. - self.record(if closed { POLYGON } else { POLYLINE }, |o| { - o.i16(pts.len() as i16); - for p in &pts { - o.i16(p[0]); - o.i16(p[1]); - } - }); - } - } - - /// An image placed by `xf`, upright: false when `xf` rotates or skews it (then it fills its - /// bounds). - fn image(&mut self, img: &Rgba, xf: Affine, opacity: f32) -> bool { - if img.width == 0 || img.height == 0 || opacity <= 0.0 { - return true; - } - let m = self.to_dev * xf; - if !m.as_coeffs().iter().all(|v| v.is_finite()) { - return true; - } - let [a, b, c, d, e, f] = m.as_coeffs(); - let (w, h) = (f64::from(img.width), f64::from(img.height)); - let upright = b.abs() < 1e-9 && c.abs() < 1e-9; - let (x, y, dw, dh) = if upright { - (e, f, a * w, d * h) - } else { - let r = m.transform_rect_bbox(Rect::new(0.0, 0.0, w, h)); - (r.x0, r.y0, r.width(), r.height()) - }; - let s = |v: f64| v.round().clamp(-MAX_I16, MAX_I16) as i16; - let (bmi, bits) = dib::rgb24(img, opacity); - self.record(STRETCHDIB, |o| { - o.u32(SRCCOPY); - // DIB_RGB_COLORS; the source and destination rectangles, last field first. - o.u16(0); - o.i16(img.height as i16); - o.i16(img.width as i16); - o.i16(0); - o.i16(0); - o.i16(s(dh)); - o.i16(s(dw)); - o.i16(s(y)); - o.i16(s(x)); - o.bytes(&bmi); - o.bytes(&bits); - }); - upright - } -} From e3c874b13f9f4e57f4ad845f72ee42db5aea95ec Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:28:27 +0530 Subject: [PATCH 07/32] metafile: delegate QuickDraw PICT parsing to craft-metafile Replaces local pict.rs with craft_metafile::parse_pict, aligning with craft-libs#3073 and AGENTS.md Rule 9. --- Cargo.lock | 2 +- Cargo.toml | 3 +- crates/metafile/Cargo.toml | 2 +- crates/metafile/src/dib.rs | 25 - crates/metafile/src/import.rs | 394 +-------- crates/metafile/src/import/pict.rs | 1176 ------------------------- crates/metafile/src/import/picture.rs | 20 +- crates/metafile/src/lib.rs | 5 +- crates/metafile/src/tests/pict.rs | 13 +- 9 files changed, 45 insertions(+), 1595 deletions(-) delete mode 100644 crates/metafile/src/import/pict.rs diff --git a/Cargo.lock b/Cargo.lock index 6a602ed891..bc8de2d7fc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1251,7 +1251,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=0bf4cb99dabb6b6d9335771ed398e999387b0d62#0bf4cb99dabb6b6d9335771ed398e999387b0d62" dependencies = [ "encoding_rs", "image", diff --git a/Cargo.toml b/Cargo.toml index 6056916d75..7b6d617b78 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,7 +38,8 @@ craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "068e079c7b craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +# WMF, EMF and EMF+ reader (craft-libs#778). +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "0bf4cb99dabb6b6d9335771ed398e999387b0d62" } craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } diff --git a/crates/metafile/Cargo.toml b/crates/metafile/Cargo.toml index 408e6166a1..2211b64b58 100644 --- a/crates/metafile/Cargo.toml +++ b/crates/metafile/Cargo.toml @@ -3,7 +3,7 @@ name = "vectorcraft-metafile" version.workspace = true edition.workspace = true license.workspace = true -description = "VectorCraft metafiles: hand-written EMF and WMF writers, EMF, EMF+ and WMF import through craft-metafile, and a QuickDraw picture (PICT) reader" +description = "VectorCraft metafiles: hand-written EMF and WMF writers, and EMF, EMF+, WMF and QuickDraw PICT import through craft-metafile" [lints] workspace = true diff --git a/crates/metafile/src/dib.rs b/crates/metafile/src/dib.rs index b104304d7f..c85289a791 100644 --- a/crates/metafile/src/dib.rs +++ b/crates/metafile/src/dib.rs @@ -7,14 +7,6 @@ use vectorcraft_doc::resample::{Resample, resized}; const MAX_SIDE: u32 = 8192; /// Most pixels an image the writers store holds. const MAX_PIXELS: u64 = 1 << 24; -/// Most pixels along a side, and in all, of a bitmap the PICT reader decodes. -pub(crate) const MAX_READ_SIDE: u32 = 1 << 15; -pub(crate) const MAX_READ_PIXELS: u64 = 1 << 26; -/// Most pixels the bitmaps of one file may decode to together (four of the largest one), so a small -/// file of many image records can't cost minutes of decoding (#3600). -pub(crate) const MAX_FILE_PIXELS: u64 = 1 << 28; -/// What [`charge`] says of a bitmap past what is left of the file's budget. -pub(crate) const OVER_BUDGET: &str = "the bitmaps hold more pixels than one file may"; const BI_RGB: u32 = 0; @@ -115,13 +107,6 @@ pub(crate) fn bgra32(img: &Rgba, opacity: f32) -> (Vec, Vec) { (header(img.width, img.height, 32, bits.len()), bits) } -/// Take a bitmap of `w` × `h` from what is `left` of the file's budget, before it is decoded. -pub(crate) fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> { - let n = u64::from(w) * u64::from(h); - *left = left.checked_sub(n).ok_or(OVER_BUDGET)?; - Ok(()) -} - #[cfg(test)] mod tests { use super::*; @@ -132,16 +117,6 @@ mod tests { Rgba { width: 3, height: 2, pixels } } - #[test] - fn bitmaps_share_the_file_budget() { - // #3600: each bitmap is charged before it is decoded, and one past what is left is refused. - let mut left = 6 + 5; - assert!(charge(3, 2, &mut left).is_ok()); - assert_eq!(left, 5); - assert_eq!(charge(3, 2, &mut left).unwrap_err(), OVER_BUDGET); - assert_eq!(left, 5, "a refused bitmap costs nothing"); - } - #[test] fn rgb24_is_bottom_up_bgr_over_white() { let (bmi, bits) = rgb24(&sample(), 1.0); diff --git a/crates/metafile/src/import.rs b/crates/metafile/src/import.rs index c87dd83d72..63ba902cef 100644 --- a/crates/metafile/src/import.rs +++ b/crates/metafile/src/import.rs @@ -1,27 +1,14 @@ -//! The metafile readers. EMF (with its EMF+ records) and WMF files are read by `craft_metafile`, -//! and `picture` turns what they draw into document objects. QuickDraw pictures (`pict`) play their -//! opcodes on a [`Player`], a small model of the drawing state (pen, brush, font, the clip), which -//! turns what they draw into document objects. +//! The metafile readers. EMF (with its EMF+ records) and WMF files, and QuickDraw pictures (PICT), +//! are read by `craft_metafile`, and `picture` turns what they draw into document objects. //! //! Fills and strokes become paths with a fill and a stroke; lines drawn one after another with the //! same pen join into one path. Clips become clipping groups around what they clip. Images keep //! their pixels (as PNG), text becomes point type in the font the file names. -pub(crate) mod pict; mod picture; -use std::sync::Arc; - use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::clipnest::{Clip, Drawn, MAX_NEST, deep_clips, nest}; -use vectorcraft_doc::{ - Appearance, AppearanceItem, CharStyle, Dash, Document, FillLayer, ImageBlob, ImageObject, Justify, LayerColor, LineCap, LineJoin, Node, NodeKind, - StrokeLayer, TextObject, -}; -use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect, Shape, shapes}; - -use crate::dib::{self, Rgba}; -use crate::{Imported, Kind}; +use vectorcraft_geom::{BezPath, PathEl, Point, Rect, Shape}; /// Most objects an import makes (a hostile file can't exhaust memory with them). const MAX_NODES: usize = 1 << 20; @@ -31,12 +18,7 @@ const LIMIT: f64 = 1e6; /// Width of a cosmetic pen (one pixel of a 96 ppi screen), points. const HAIRLINE: f64 = 0.75; -/// Raster operations. -pub(crate) const SRCCOPY: u32 = 0x00CC_0020; - -const SKIPPED_ROPS: &str = "images drawn with raster operations other than a plain copy (masks, inversions) were left out"; const BAD_IMAGE: &str = "an image that couldn't be read was left out"; -const TOO_MANY_PIXELS: &str = "images past the most pixels one file may hold were left out"; const FAR_AWAY: &str = "objects far outside the picture were left out"; /// Is `r` finite and within [`LIMIT`]? @@ -65,8 +47,8 @@ fn around(path: &BezPath, frame: Rect) -> bool { let (p, start) = match e { PathEl::MoveTo(p) => (*p, true), PathEl::LineTo(p) => (*p, false), - PathEl::ClosePath => continue, - PathEl::QuadTo(..) | PathEl::CurveTo(..) => return false, + PathEl::ClosePath => break, + _ => return false, }; let Some(i) = corners.iter().position(|c| near(*c, p)) else { return false }; if start { @@ -96,365 +78,17 @@ fn around(path: &BezPath, frame: Rect) -> bool { seen.iter().all(|s| *s) && b.contains(frame.origin()) && b.contains(Point::new(frame.x1, frame.y1)) } -/// A pen: its style flags (`PS_*`), width in logical units, colour and dash entries. -#[derive(Clone, Debug, PartialEq)] -pub(crate) struct PenObj { - pub style: u32, - pub width: f64, - pub color: [u8; 3], - /// PS_USERSTYLE entries, logical units. - pub entries: Vec, -} - -impl PenObj { - pub fn solid(color: [u8; 3]) -> Self { - Self { style: 0, width: 0.0, color, entries: vec![] } - } -} - -pub(crate) const PS_NULL: u32 = 5; -const PS_GEOMETRIC: u32 = 0x0001_0000; - -/// A font: its height in logical units (negative: the character height, positive: the cell -/// height), escapement (tenths of a degree), weight, italics and face. -#[derive(Clone, Debug, Default, PartialEq)] -pub(crate) struct FontObj { - pub height: f64, - pub escapement: f64, - pub weight: i32, - pub italic: bool, - pub face: String, -} - -/// The drawing state. -#[derive(Clone, Debug)] -struct Dc { - pen: PenObj, - /// The brush's color. - brush: [u8; 3], - font: FontObj, - text_color: [u8; 3], - text_align: u32, - fill_rule: FillRule, - miter: f64, - clips: Vec>, -} - -impl Default for Dc { - fn default() -> Self { - Self { - pen: PenObj::solid([0; 3]), - brush: [255; 3], - font: FontObj::default(), - text_color: [0; 3], - text_align: 0, - fill_rule: FillRule::EvenOdd, - miter: 10.0, - clips: vec![], - } - } -} - -pub(crate) struct Player { - kind: Kind, - /// Picture units → document points. - dev_to_doc: Affine, - dc: Dc, - /// The artboard (document space): clips holding all of it clip nothing worth keeping. - frame: Rect, - /// Lines drawn one after another, not drawn yet. - pending: BezPath, - out: Drawn, - doc: Document, - warnings: Vec, - next_clip: u32, - /// Pixels the file's bitmaps may still decode to ([`dib::MAX_FILE_PIXELS`]). - pub pixels_left: u64, -} - fn rgb(c: [u8; 3]) -> Paint { Paint::solid(Color::rgb8(c[0], c[1], c[2])) } -/// A rectangle with elliptical corners `rx` × `ry`. -pub(crate) fn round_rect(r: Rect, rx: f64, ry: f64) -> BezPath { - let r = r.abs(); - let (rx, ry) = ((rx / 2.0).abs().min(r.width() / 2.0), (ry / 2.0).abs().min(r.height() / 2.0)); - if rx <= 0.0 || ry <= 0.0 { - return shapes::rectangle(r).to_bezpath(); - } - // A rectangle with round corners of radius `ry`, squeezed across. - let s = ry / rx; - let squeezed = Rect::new(r.x0 * s, r.y0, r.x1 * s, r.y1); - let mut bp = shapes::rounded_rectangle(squeezed, ry).to_bezpath(); - bp.apply_affine(Affine::scale_non_uniform(1.0 / s, 1.0)); - bp -} - -impl Player { - fn new(kind: Kind, dev_to_doc: Affine, artboard: Rect) -> Self { - let side = |v: f64| if v.is_finite() { v.clamp(1.0, LIMIT) } else { 1.0 }; - let (w, h) = (side(artboard.width()), side(artboard.height())); - let mut doc = Document::new(w, h); - doc.layers.clear(); - Self { - kind, - dev_to_doc, - dc: Dc::default(), - frame: artboard, - pending: BezPath::new(), - out: vec![], - doc, - warnings: vec![], - next_clip: 0, - pixels_left: dib::MAX_FILE_PIXELS, - } - } - - pub fn warn(&mut self, w: &str) { - if !self.warnings.iter().any(|x| x == w) { - self.warnings.push(w.to_string()); - } - } - - // ---------- mapping ---------- - - /// Picture units → document. - fn xf(&self) -> Affine { - self.dev_to_doc - } - - /// How much picture lengths grow in the document. - fn scale(&self) -> f64 { - let s = self.xf().determinant().abs().sqrt(); - if s.is_finite() { s } else { 0.0 } - } - - // ---------- output ---------- - - fn push(&mut self, mut node: Node) { - if self.out.len() >= MAX_NODES { - return; - } - if !node.visual_bounds().is_none_or(sane) { - return self.warn(FAR_AWAY); - } - node.id = self.doc.alloc_id(); - self.out.push((self.dc.clips.clone(), node)); - } - - fn fill_paint(&self) -> Paint { - rgb(self.dc.brush) - } - - fn stroke_layer(&self) -> Option { - let p = &self.dc.pen; - let kind = p.style & 0xf; - if kind == PS_NULL { - return None; - } - // Geometric pens, and other pens wider than 1, have a width in logical units; the others - // are one pixel wide. - let w = p.width * self.scale(); - let width = if w > 0.0 && w.is_finite() && (p.style & PS_GEOMETRIC != 0 || p.width > 1.0) { w } else { HAIRLINE }; - let mut st = StrokeLayer::new(rgb(p.color), width); - // Round caps and joins unless the style asks for others. - st.cap = match p.style & 0xf00 { - 0x100 => LineCap::Square, - 0x200 => LineCap::Butt, - _ => LineCap::Round, - }; - st.join = match p.style & 0xf000 { - 0x1000 => LineJoin::Bevel, - 0x2000 => LineJoin::Miter, - _ => LineJoin::Round, - }; - st.miter_limit = self.dc.miter; - let unit = width.max(HAIRLINE); - let pattern: Vec = match kind { - 1 => vec![3.0 * unit, unit], - 2 => vec![unit, unit], - 3 => vec![3.0 * unit, unit, unit, unit], - 4 => vec![3.0 * unit, unit, unit, unit, unit, unit], - 7 => p.entries.iter().map(|e| e * self.scale()).collect(), - _ => vec![], - }; - let dash = Dash { pattern, offset: 0.0, align_corners: false }; - st.dash = dash.is_dashed().then_some(dash); - Some(st) - } - - /// Paint `bp` (document space) with the brush and the pen. - fn draw(&mut self, bp: BezPath, fill: bool, stroke: bool) { - if bp.elements().is_empty() { - return; - } - let mut items = vec![]; - if fill { - items.push(AppearanceItem::Fill(FillLayer::new(self.fill_paint()))); - } - if stroke && let Some(st) = self.stroke_layer() { - items.push(AppearanceItem::Stroke(st)); - } - if items.is_empty() { - return; - } - let mut n = Node::path(vectorcraft_doc::NodeId(0), PathData::from_bezpath(&bp), Appearance { items, ..Appearance::default() }); - if let NodeKind::Path { rule, .. } = &mut n.kind { - *rule = self.dc.fill_rule; - } - self.push(n); - } - - /// Draw the lines drawn one after another so far. - pub fn flush(&mut self) { - if !self.pending.elements().is_empty() { - let bp = std::mem::take(&mut self.pending); - self.draw(bp, false, true); - } - } - - // ---------- clips ---------- - - fn push_clip(&mut self, path: BezPath, rule: FillRule, replace: bool) { - if replace { - self.dc.clips.clear(); - } - if !sane(path.bounding_box()) { - return self.warn(FAR_AWAY); - } - if around(&path, self.frame) { - return; - } - if self.dc.clips.len() >= MAX_NEST { - return self.warn(&deep_clips()); - } - self.next_clip += 1; - self.dc.clips.push(Arc::new(Clip { id: self.next_clip, region: Some((path, rule)) })); - } - - // ---------- images and text ---------- - - /// An image whose source rectangle `src` (pixels, from the top-left) is drawn into `dest` - /// (picture units: origin and signed size) with raster operation `rop`, at `opacity`. - pub fn image(&mut self, img: Result, src: Rect, dest: Rect, rop: u32, opacity: f64) { - if rop != SRCCOPY { - self.warn(SKIPPED_ROPS); - return; - } - let img = match img { - Ok(i) => i, - Err(e) if e == dib::OVER_BUDGET => return self.warn(TOO_MANY_PIXELS), - Err(_) => return self.warn(BAD_IMAGE), - }; - let img = crop(img, src); - if img.width == 0 || img.height == 0 { - return; - } - let (w, h) = (f64::from(img.width), f64::from(img.height)); - self.image_xf(img, Affine::translate((dest.x0, dest.y0)) * Affine::scale_non_uniform(dest.width() / w, dest.height() / h), opacity); - } - - /// An image placed by `xf` (its pixels, from the top-left, → picture units), at `opacity`. An - /// image that `xf` flattens or sends past finite numbers is left out, and adds nothing to the - /// document's images. - pub(crate) fn image_xf(&mut self, img: Rgba, xf: Affine, opacity: f64) { - if img.width == 0 || img.height == 0 { - return; - } - let xf = self.xf() * xf; - if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 { - return; - } - let Ok(png) = img.to_png() else { return self.warn(BAD_IMAGE) }; - let blob = ImageBlob::new("image/png", png); - let key = blob.content_key(); - self.doc.images.entry(key.clone()).or_insert(blob); - let im = ImageObject { key, width: img.width, height: img.height, xf, link: None, placement: Default::default(), pixels: None }; - let mut n = Node::new(vectorcraft_doc::NodeId(0), NodeKind::Image(Box::new(im))); - n.opacity = opacity.clamp(0.0, 1.0) as f32; - self.push(n); - } - - /// Text at `at` (picture units) in the current font. - pub fn text(&mut self, at: Point, s: &str) { - let s: String = s.chars().filter(|c| *c != '\0').collect(); - if s.trim().is_empty() { - return; - } - let align = self.dc.text_align; - let f = self.dc.font.clone(); - let k = self.scale(); - // A negative height is the em; a positive one the cell (the em and the internal leading). - let em = if f.height < 0.0 { -f.height } else { f.height * 0.85 }; - let size = if em > 0.0 && (em * k).is_finite() { (em * k).clamp(0.5, 5000.0) } else { 12.0 }; - let mut style = CharStyle { size, fill: rgb(self.dc.text_color), stroke: Paint::None, ..CharStyle::default() }; - if !f.face.trim().is_empty() { - style.font_family = f.face.trim().to_string(); - } - style.font_style = match (f.weight >= 600, f.italic) { - (true, true) => "Bold Italic", - (true, false) => "Bold", - (false, true) => "Italic", - (false, false) => "Regular", - } - .into(); - let angle = -(f.escapement / 10.0).to_radians(); - let angle = if angle.is_finite() { angle } else { 0.0 }; - // TA_BASELINE, TA_BOTTOM or TA_TOP (the default): where the baseline is. - let drop = match align & 0x18 { - 0x18 => 0.0, - 0x08 => -0.2 * size, - _ => 0.8 * size, - }; - let origin = self.xf() * at; - let mut t = TextObject::point(Point::ZERO, &s, style); - t.xf = Affine::translate(origin.to_vec2()) * Affine::rotate(angle) * Affine::translate((0.0, drop)); - t.para.justify = match align & 0x06 { - 0x06 => Justify::Center, - 0x02 => Justify::Right, - _ => Justify::Left, - }; - t.cached_bounds = Some(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).bounds); - self.push(Node::new(vectorcraft_doc::NodeId(0), NodeKind::Text(Box::new(t)))); - } - - // ---------- the document ---------- - - /// The document: what was drawn on one layer, clipped art in clipping groups. - fn finish(mut self) -> Imported { - self.flush(); - let out = std::mem::take(&mut self.out); - let children = nest(&mut self.doc, out); - let mut layer = Node::layer(self.doc.alloc_id(), "Layer 1", LayerColor::Preset(0)); - if let Some(c) = layer.children_mut() { - *c = children; - } - self.doc.layers = vec![Arc::new(layer)]; - Imported { document: self.doc, kind: self.kind, warnings: self.warnings } - } -} - -/// `img` cut to `src` (pixels from the top-left, within the image). -fn crop(img: Rgba, src: Rect) -> Rgba { - let (w, h) = (img.width, img.height); - let s = src.abs(); - let clamp = |v: f64, max: u32| if v.is_finite() { v.round().clamp(0.0, f64::from(max)) as u32 } else { 0 }; - let (x0, y0, x1, y1) = (clamp(s.x0, w), clamp(s.y0, h), clamp(s.x1, w), clamp(s.y1, h)); - if (x0, y0, x1, y1) == (0, 0, w, h) || x1 <= x0 || y1 <= y0 { - return img; - } - let mut pixels = Vec::with_capacity(((x1 - x0) * (y1 - y0) * 4) as usize); - for y in y0..y1 { - let row = (y * w) as usize * 4; - if let Some(p) = img.pixels.get(row + x0 as usize * 4..row + x1 as usize * 4) { - pixels.extend_from_slice(p); - } - } - Rgba { width: x1 - x0, height: y1 - y0, pixels } -} - -/// Read an EMF or WMF file. -pub(crate) fn import(bytes: &[u8]) -> Result { - picture::import(bytes) +pub(crate) use picture::import; + +/// Read a QuickDraw picture (PICT, versions 1 and 2) through `craft_metafile`. +pub(crate) fn import_pict(bytes: &[u8]) -> Result { + let pic = craft_metafile::parse_pict(bytes).map_err(|e| match e { + craft_metafile::Error::NotPict => "not a PICT file".to_string(), + _ => "the PICT file is damaged".to_string(), + })?; + Ok(picture::convert(pic)) } diff --git a/crates/metafile/src/import/pict.rs b/crates/metafile/src/import/pict.rs deleted file mode 100644 index a1e5a674e0..0000000000 --- a/crates/metafile/src/import/pict.rs +++ /dev/null @@ -1,1176 +0,0 @@ -//! QuickDraw pictures (PICT, versions 1 and 2), played on the [`Player`] by the opcodes and data -//! lengths of Apple's *Imaging With QuickDraw*, appendix A. -//! -//! A PICT file holds 512 bytes of application data before the picture; a picture on its own (as -//! a `PICT` resource holds it) reads too. A unit is a point, and the artboard is the picture's -//! frame; an extended version 2 header's source rectangle is mapped onto the frame. -//! -//! - Lines, rectangles, rounded rectangles, ovals, arcs and wedges, polygons and regions become -//! paths. A framed shape is stroked inside its outline at the pen's size, and a line below and -//! to the right of its points, where the pen draws; painted, filled and erased shapes are filled -//! with the pen, fill or background pattern. A pattern of two colors is filled with their -//! average. -//! - Text becomes point type in the font the picture names, read as Mac Roman. -//! - Bitmaps and pixel maps (1 to 8 bits with their color table, 16 and 32 bits, packed or not) -//! become images, clipped to their mask region; QuickTime JPEG images become images. -//! - The clip region clips what follows it. -//! -//! What isn't read (inverted shapes, transfer modes other than a copy, other QuickTime formats) -//! comes back as one warning each. Apple's table gives every opcode's length, so opcodes that draw -//! nothing VectorCraft reads are skipped; a picture cut short keeps what came before. - -use std::collections::HashMap; - -use vectorcraft_geom::{Affine, BezPath, FillRule, Point, Rect, Shape, Vec2, shapes}; - -use super::{BAD_IMAGE, FontObj, PS_GEOMETRIC, PenObj, Player, SRCCOPY, TOO_MANY_PIXELS, crop, round_rect}; -use crate::dib::{self, Rgba}; -use crate::{Imported, Kind}; - -/// What a file that holds no picture is refused with. -const NOT_PICT: &str = "not a PICT file"; -/// The application data before the picture in a PICT file. -const FILE_HEADER: usize = 512; -/// Most opcodes one picture plays (a small file can't keep the reader busy for minutes). -const MAX_OPS: usize = 1 << 22; -/// Most rectangles one region breaks into. -const MAX_RECTS: usize = 1 << 16; -/// Steps the regions of one picture may take to read (each inversion point and band costs some). -const MAX_REGION_WORK: u64 = 1 << 28; -/// Most bytes the unpacked rows of one image may hold. -const MAX_ROW_BYTES: u64 = 1 << 28; -/// Most bytes the unpacked rows of one picture's images and patterns may hold together. -const MAX_FILE_ROW_BYTES: u64 = 1 << 30; -/// Most bytes a row may hold past what its pixels need. -const ROW_SLACK: usize = 64; -/// Most pixels, and bytes of unpacked rows, a pixel pattern may hold. -const MAX_PATTERN_PIXELS: usize = 1 << 16; -const MAX_PATTERN_ROW_BYTES: usize = 1 << 20; -/// Curves made for ovals and arcs are this close to the true curve, points. -const TOLERANCE: f64 = 0.01; -/// GDI text alignment on the baseline, which QuickDraw's text location is. -const TA_BASELINE: u32 = 0x18; -/// Pen style flags: square and flat ends, mitered joins. -const SQUARE: u32 = 0x100; -const FLAT: u32 = 0x200; -const MITER: u32 = 0x2000; - -const CUT_SHORT: &str = "the picture is cut short or damaged: what came before was imported"; -const TOO_MANY_OPS: &str = "the picture holds more opcodes than one file may: the rest was left out"; -const INVERTED: &str = "inverted shapes were left out"; -const PATTERNS: &str = "patterns are filled with the average of their colors"; -const MODES: &str = "art drawn in transfer modes other than a copy is drawn as a copy"; -const FRAMED_REGIONS: &str = "framed regions are outlined rectangle by rectangle"; -const BIG_REGIONS: &str = "regions larger than one picture may hold were left out"; -const CODECS: &str = "QuickTime images in formats other than JPEG were left out"; -const NOTHING: &str = "the picture draws nothing VectorCraft reads"; - -/// Big-endian reads from a slice, never past its end. -struct Be<'a> { - data: &'a [u8], - pos: usize, -} - -impl<'a> Be<'a> { - fn new(data: &'a [u8], pos: usize) -> Self { - Self { data, pos } - } - fn bytes(&mut self, n: usize) -> Option<&'a [u8]> { - let b = self.data.get(self.pos..self.pos.checked_add(n)?)?; - self.pos += n; - Some(b) - } - fn array(&mut self) -> Option<[u8; N]> { - self.bytes(N)?.try_into().ok() - } - fn skip(&mut self, n: usize) -> Option<()> { - self.bytes(n).map(drop) - } - fn u8(&mut self) -> Option { - self.array().map(|[b]: [u8; 1]| b) - } - fn u16(&mut self) -> Option { - self.array().map(u16::from_be_bytes) - } - fn i16(&mut self) -> Option { - self.array().map(i16::from_be_bytes) - } - fn u32(&mut self) -> Option { - self.array().map(u32::from_be_bytes) - } - fn i32(&mut self) -> Option { - self.array().map(i32::from_be_bytes) - } - /// A QuickDraw point: vertical, then horizontal. - fn point(&mut self) -> Option { - let v = self.i16()?; - let h = self.i16()?; - Some(Point::new(h.into(), v.into())) - } - /// A size stored as a point (a pen or an oval: height, then width). - fn size(&mut self) -> Option { - self.point().map(Point::to_vec2) - } - /// A QuickDraw rectangle: top, left, bottom, right. - fn rect(&mut self) -> Option { - let (top, left, bottom, right) = (self.i16()?, self.i16()?, self.i16()?, self.i16()?); - Some(Rect::new(left.into(), top.into(), right.into(), bottom.into())) - } - /// An `RGBColor` (16 bits a component), 8 bits a component. - fn rgb(&mut self) -> Option<[u8; 3]> { - let [r, g, b] = [self.u16()?, self.u16()?, self.u16()?]; - Some([r, g, b].map(|c| (c >> 8) as u8)) - } -} - -/// Where a picture is, its frame and whether it is version 2. -struct Header { - frame: Rect, - v2: bool, - /// Where its first opcode starts. - ops: usize, -} - -/// The picture whose `picSize` is at `at`, if a version opcode follows its frame. -fn header(bytes: &[u8], at: usize) -> Option
{ - let mut r = Be::new(bytes, at.checked_add(2)?); - let frame = r.rect()?; - let (v2, ops) = match r.array::<2>()? { - [0x11, 0x01] => (false, r.pos), - [0x00, 0x11] if r.array::<4>()? == [0x02, 0xFF, 0x0C, 0x00] => (true, at + 10), - _ => return None, - }; - (frame.width() > 0.0 && frame.height() > 0.0).then_some(Header { frame, v2, ops }) -} - -/// The picture of a file (after its application data), else the picture `bytes` start with. -fn find(bytes: &[u8]) -> Option
{ - header(bytes, FILE_HEADER).or_else(|| header(bytes, 0)) -} - -/// Do `bytes` hold a version 2 picture, after a file's application data or on their own? The -/// version 1 signature is two bytes, too short to tell a file by. -pub(crate) fn is_pict(bytes: &[u8]) -> bool { - [FILE_HEADER, 0].into_iter().any(|at| header(bytes, at).is_some_and(|h| h.v2)) -} - -/// A pattern: eight rows of eight bits (set bits in the foreground color, the others in the -/// background color), or one color. -#[derive(Clone, Copy)] -enum Pat { - Bits([u8; 8]), - Rgb([u8; 3]), -} - -/// What a shape opcode does with its shape. -#[derive(Clone, Copy, PartialEq, Eq)] -enum Verb { - Frame, - Paint, - Erase, - Invert, - Fill, -} - -/// The verb of a shape opcode (its low three bits; 5 to 7 are reserved). -fn verb(op: u16) -> Option { - match op & 7 { - 0 => Some(Verb::Frame), - 1 => Some(Verb::Paint), - 2 => Some(Verb::Erase), - 3 => Some(Verb::Invert), - 4 => Some(Verb::Fill), - _ => None, - } -} - -/// An old-style QuickDraw color (`blackColor` 33 … `blueColor` 409) as RGB. -fn old_color(c: u32) -> [u8; 3] { - match c { - 30 => [255; 3], - 69 => [255, 255, 0], - 137 => [255, 0, 255], - 205 => [255, 0, 0], - 273 => [0, 255, 255], - 341 => [0, 255, 0], - 409 => [0, 0, 255], - _ => [0; 3], - } -} - -/// `a` and `b` mixed: `t` of `a`. -fn mix(a: [u8; 3], b: [u8; 3], t: f64) -> [u8; 3] { - let m = |x: u8, y: u8| (f64::from(x) * t + f64::from(y) * (1.0 - t)).round() as u8; - [m(a[0], b[0]), m(a[1], b[1]), m(a[2], b[2])] -} - -/// Byte `b` of Mac Roman. -fn mac_roman(b: u8) -> char { - const HIGH: [char; 128] = [ - 'Ä', 'Å', 'Ç', 'É', 'Ñ', 'Ö', 'Ü', 'á', 'à', 'â', 'ä', 'ã', 'å', 'ç', 'é', 'è', // - 'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ñ', 'ó', 'ò', 'ô', 'ö', 'õ', 'ú', 'ù', 'û', 'ü', // - '†', '°', '¢', '£', '§', '•', '¶', 'ß', '®', '©', '™', '´', '¨', '≠', 'Æ', 'Ø', // - '∞', '±', '≤', '≥', '¥', 'µ', '∂', '∑', '∏', 'π', '∫', 'ª', 'º', 'Ω', 'æ', 'ø', // - '¿', '¡', '¬', '√', 'ƒ', '≈', '∆', '«', '»', '…', '\u{A0}', 'À', 'Ã', 'Õ', 'Œ', 'œ', // - '–', '—', '“', '”', '‘', '’', '÷', '◊', 'ÿ', 'Ÿ', '⁄', '€', '‹', '›', 'fi', 'fl', // - '‡', '·', '‚', '„', '‰', 'Â', 'Ê', 'Á', 'Ë', 'È', 'Í', 'Î', 'Ï', 'Ì', 'Ó', 'Ô', // - '\u{F8FF}', 'Ò', 'Ú', 'Û', 'Ù', 'ı', 'ˆ', '˜', '¯', '˘', '˙', '˚', '¸', '˝', '˛', 'ˇ', - ]; - match b { - 0x80.. => HIGH.get(usize::from(b - 0x80)).copied().unwrap_or(char::REPLACEMENT_CHARACTER), - _ => char::from(b), - } -} - -/// The family name of a classic Macintosh font number. -fn font_family(id: u16) -> &'static str { - match id { - 0 => "Chicago", - 1 | 3 => "Geneva", - 2 => "New York", - 4 => "Monaco", - 20 => "Times", - 21 => "Helvetica", - 22 => "Courier", - 23 => "Symbol", - _ => "", - } -} - -/// The arc of the oval in `r` from `start` degrees clockwise from 12 o'clock, over `sweep` -/// degrees (clockwise when positive). Angles are measured on the rectangle, so 45° runs through -/// its top-right corner. A wedge closes through the center. -fn arc(r: Rect, start: i16, sweep: i16, wedge: bool) -> BezPath { - let c = r.center(); - let radii = Vec2::new(r.width() / 2.0, r.height() / 2.0); - let mut bp = BezPath::new(); - if sweep == 0 { - return bp; - } - let a0 = (f64::from(start) - 90.0).to_radians(); - let sweep = f64::from(sweep).clamp(-360.0, 360.0).to_radians(); - let arc = kurbo::Arc { center: c, radii, start_angle: a0, sweep_angle: sweep, x_rotation: 0.0 }; - if wedge { - bp.move_to(c); - bp.line_to(c + Vec2::new(radii.x * a0.cos(), radii.y * a0.sin())); - arc.append_iter(TOLERANCE).for_each(|el| bp.push(el)); - bp.close_path(); - } else { - kurbo::Shape::path_elements(&arc, TOLERANCE).for_each(|el| bp.push(el)); - } - bp -} - -/// The outlines of `rects`, as one path. -fn rects_path(rects: &[Rect]) -> BezPath { - let mut bp = BezPath::new(); - for r in rects { - bp.extend(shapes::rectangle(*r).to_bezpath()); - } - bp -} - -/// Take `n` steps from `work`; false when too few are left. -fn spend(work: &mut u64, n: usize) -> bool { - match work.checked_sub(n as u64) { - Some(left) => { - *work = left; - true - } - None => false, - } -} - -/// A region (its size, bounding box and inversion points), read at `r`, as rectangles: `None` -/// when the data runs past the end; the flag is false when the region is larger than `work` or -/// [`MAX_RECTS`] allows, and then no rectangles are given. -fn region(r: &mut Be, work: &mut u64) -> Option<(Vec, bool)> { - let size = usize::from(r.u16()?); - let mut b = Be::new(r.bytes(size.checked_sub(2)?)?, 0); - let bbox = b.rect()?; - if size <= 10 { - let whole = bbox.width() > 0.0 && bbox.height() > 0.0; - return Some((if whole { vec![bbox] } else { vec![] }, true)); - } - Some(bands(&mut b, work).map_or((vec![], false), |rects| (rects, true))) -} - -/// The rectangles of a region's scanlines: each lists the x coordinates where being inside the -/// region changes from the scanline before. Bands of the same spans one after another are one -/// rectangle. -fn bands(b: &mut Be, work: &mut u64) -> Option> { - let mut out: Vec = vec![]; - let mut active: Vec = vec![]; - let mut last_band = 0; - let mut prev_y = 0.0; - while let Some(y) = b.i16().filter(|y| *y != 0x7FFF) { - let y = f64::from(y); - let spans: Vec<(f64, f64)> = active.as_chunks::<2>().0.iter().map(|[a, b]| (f64::from(*a), f64::from(*b))).collect(); - if !spans.is_empty() && y > prev_y { - if !spend(work, spans.len() + 1) { - return None; - } - let prev = out.get_mut(last_band..).unwrap_or_default(); - let same = prev.len() == spans.len() && prev.iter().zip(&spans).all(|(r, (x0, x1))| r.x0 == *x0 && r.x1 == *x1 && r.y1 == prev_y); - if same { - prev.iter_mut().for_each(|r| r.y1 = y); - } else { - last_band = out.len(); - out.extend(spans.iter().map(|&(x0, x1)| Rect::new(x0, prev_y, x1, y))); - if out.len() > MAX_RECTS { - return None; - } - } - } - prev_y = y; - while let Some(x) = b.i16().filter(|x| *x != 0x7FFF) { - if !spend(work, active.len() + 1) { - return None; - } - match active.binary_search(&x) { - Ok(i) => { - active.remove(i); - } - Err(i) => active.insert(i, x), - } - } - } - Some(out) -} - -/// Skip the data of opcode `op`, by the length Apple's table gives it. -fn skip(op: u16, r: &mut Be) -> Option<()> { - let n = match op { - 0x00 | 0x17..=0x19 | 0x1C | 0x1E | 0xB0..=0xCF | 0x8000..=0x80FF => 0, - 0x04 => 1, - 0x03 | 0x05 | 0x08 | 0x0D | 0x11 | 0x15 | 0x16 | 0xA0 => 2, - 0x06 | 0x07 | 0x0B | 0x0C | 0x0E | 0x0F => 4, - 0x1A | 0x1B | 0x1D | 0x1F => 6, - 0x02 | 0x09 | 0x0A | 0x10 => 8, - // Reserved opcodes with a 16-bit length, and the font name. - 0x24..=0x27 | 0x2C..=0x2F | 0x92..=0x97 | 0x9C..=0x9F | 0xA2..=0xAF => usize::from(r.u16()?), - // Reserved for Apple: two bytes for each unit of the high byte (the 24-byte header 0x0C00). - 0x0100..=0x7FFF => usize::from(op >> 8) * 2, - // 0xD0–0xFE and 0x8100–0xFFFF (QuickTime images among them): a 32-bit length. - _ => usize::try_from(r.u32()?).ok()?, - }; - r.skip(n) -} - -/// How a bitmap's or pixel map's pixels are stored. -struct PixMap { - row_bytes: usize, - bounds: Rect, - /// Bits a pixel. - size: u16, - pack: u16, - cmps: u16, - /// Indexed pixels' colors; a bitmap has none (its set bits are the foreground color). - palette: Option>, - /// Rows of 8 bytes or more may be packed with PackBits, as the packing says. - packed: bool, -} - -impl PixMap { - /// From `rowBytes` on: a pixel map when `rowBytes` has its high bit set or `pixmap` says so, - /// else a bitmap; a pixel map's color table follows unless `direct`. - fn read(r: &mut Be, pixmap: bool, direct: bool) -> Option { - let raw = r.u16()?; - let mut pm = PixMap { row_bytes: usize::from(raw & 0x3FFF), bounds: r.rect()?, size: 1, pack: 0, cmps: 1, palette: None, packed: true }; - if pixmap || raw & 0x8000 != 0 { - r.skip(2)?; - pm.pack = r.u16()?; - r.skip(14)?; - pm.size = r.u16()?; - pm.cmps = r.u16()?; - r.skip(14)?; - if !direct { - pm.palette = Some(color_table(r)?); - } - } - Some(pm) - } - - /// The width and height of its pixels. - fn dims(&self) -> Option<(usize, usize)> { - let (w, h) = (self.bounds.width(), self.bounds.height()); - (w > 0.0 && h > 0.0).then_some((w as usize, h as usize)) - } - - /// The packing: 0 is 4 for 32-bit pixels and 3 for 16-bit ones. - fn packing(&self) -> u16 { - match (self.size, self.pack) { - (32, 0) => 4, - (16, 0) => 3, - (_, p) => p, - } - } - - /// Rows are stored as they are (no byte count, no PackBits). - fn raw_rows(&self) -> bool { - !self.packed || self.row_bytes < 8 || self.packing() == 1 || (self.size == 32 && self.packing() == 2) - } - - /// Bytes of an unpacked row: a component plane each for packing 4, three bytes a pixel for - /// packing 2, else `rowBytes`. - fn row_len(&self, w: usize) -> usize { - match self.packing() { - 4 if self.size == 32 && self.row_bytes >= 8 => w * usize::from(self.cmps), - 2 if self.size == 32 => w * 3, - _ => self.row_bytes, - } - } - - /// Whether its pixels can be read: a depth QuickDraw has, and rows long enough for them and at - /// most [`ROW_SLACK`] bytes longer. - fn decodable(&self, w: usize) -> bool { - let need = match self.size { - 1 | 2 | 4 | 8 => (w * usize::from(self.size)).div_ceil(8), - 16 => 2 * w, - 32 if self.packing() == 4 && self.row_bytes >= 8 => { - if !matches!(self.cmps, 3 | 4) { - return false; - } - w * usize::from(self.cmps) - } - 32 if self.packing() == 2 => 3 * w, - 32 => 4 * w, - _ => return false, - }; - (need..=need + ROW_SLACK).contains(&self.row_len(w)) - } - - /// Read `h` rows of pixel data, unpacked into one buffer when `keep`, else only stepped over. - /// `None` when the data runs past the end; the flag is false when a row didn't unpack to its - /// length. - fn rows(&self, r: &mut Be, w: usize, h: usize, keep: bool) -> Option<(Vec, bool)> { - let len = self.row_len(w); - let unit = if self.packing() == 3 { 2 } else { 1 }; - let mut out = vec![]; - let mut ok = true; - let mut keep = keep; - for _ in 0..h { - if self.raw_rows() { - let row = r.bytes(len)?; - if keep { - out.extend_from_slice(row); - } - continue; - } - let n = if self.row_bytes > 250 { usize::from(r.u16()?) } else { usize::from(r.u8()?) }; - let packed = r.bytes(n)?; - // After a row that doesn't unpack, the rest are only stepped over. - if keep && !unpack(packed, len, unit, &mut out) { - ok = false; - keep = false; - out = vec![]; - } - } - Some((out, ok)) - } - - /// The color of pixel `x` of `row` (the foreground and background colors for a bitmap's bits). - fn pixel(&self, row: &[u8], x: usize, w: usize, fg: [u8; 3], bg: [u8; 3]) -> Option<[u8; 3]> { - let at = |i: usize| row.get(i).copied(); - match self.size { - 1 | 2 | 4 | 8 => { - let bits = usize::from(self.size); - let shift = 8 - bits - x * bits % 8; - let index = usize::from((at(x * bits / 8)? >> shift) & ((1u16 << bits) - 1) as u8); - match &self.palette { - Some(p) => p.get(index).copied(), - None => Some(if index == 0 { bg } else { fg }), - } - } - 16 => { - let v = u16::from_be_bytes([at(2 * x)?, at(2 * x + 1)?]); - let c = |s: u16| (((v >> s) & 31) * 255 / 31) as u8; - Some([c(10), c(5), c(0)]) - } - _ if self.packing() == 4 && self.row_bytes >= 8 => { - // Component planes, alpha first when there are four (QuickDraw doesn't draw it). - let first = usize::from(self.cmps) - 3; - Some([at(first * w + x)?, at((first + 1) * w + x)?, at((first + 2) * w + x)?]) - } - _ if self.packing() == 2 => Some([at(3 * x)?, at(3 * x + 1)?, at(3 * x + 2)?]), - _ => Some([at(4 * x + 1)?, at(4 * x + 2)?, at(4 * x + 3)?]), - } - } - - /// Unpacked rows as opaque pixels. - fn to_rgba(&self, data: &[u8], w: usize, h: usize, fg: [u8; 3], bg: [u8; 3]) -> Option { - let len = self.row_len(w); - let mut pixels = Vec::with_capacity(w * h * 4); - for y in 0..h { - let row = data.get(y * len..(y + 1) * len)?; - for x in 0..w { - pixels.extend(self.pixel(row, x, w, fg, bg)?); - pixels.push(255); - } - } - Some(Rgba { width: u32::try_from(w).ok()?, height: u32::try_from(h).ok()?, pixels }) - } -} - -/// A `ColorTable`: indexed pixels' colors (entry by entry for a device table, else by each -/// entry's value). -fn color_table(r: &mut Be) -> Option> { - r.skip(4)?; - let flags = r.u16()?; - let n = usize::from(r.u16()?) + 1; - let mut palette = vec![[0u8; 3]; 256]; - for i in 0..n { - let value = usize::from(r.u16()?); - let c = r.rgb()?; - if let Some(e) = palette.get_mut(if flags & 0x8000 != 0 { i } else { value }) { - *e = c; - } - } - Some(palette) -} - -/// Unpack PackBits `data` (runs of `unit`-byte elements) onto `out`, `len` bytes; false when the -/// data is damaged or short (the row is padded with zeros). -fn unpack(data: &[u8], len: usize, unit: usize, out: &mut Vec) -> bool { - let start = out.len(); - let mut i = 0; - let mut ok = true; - while out.len() - start < len { - let Some(&n) = data.get(i) else { - ok = false; - break; - }; - i += 1; - let n = n as i8; - if n >= 0 { - let k = (n as usize + 1) * unit; - let Some(lit) = data.get(i..i + k) else { - ok = false; - break; - }; - out.extend_from_slice(lit); - i += k; - } else if n != -128 { - let Some(v) = data.get(i..i + unit) else { - ok = false; - break; - }; - for _ in 0..(1 - isize::from(n)) { - out.extend_from_slice(v); - } - i += unit; - } - } - out.resize(start + len, 0); - ok -} - -/// The picture being played: QuickDraw's drawing state, and the player that makes the objects. -struct Pict { - p: Player, - frame: Rect, - /// Picture space → document. - base: Affine, - origin: Vec2, - fg: [u8; 3], - bg: [u8; 3], - pen: Vec2, - pen_mode: u16, - pen_pat: Pat, - fill_pat: Pat, - back_pat: Pat, - oval: Vec2, - pen_loc: Point, - font: u16, - face: u8, - text_size: i16, - text_loc: Point, - /// Font numbers the picture names. - names: HashMap, - /// The last rectangle of the rectangle, rounded rectangle, oval and arc opcodes. - last: [Rect; 4], - region_work: u64, - /// Bytes of unpacked rows the picture's images and patterns may still take. - row_bytes_left: u64, -} - -impl Pict { - fn new(frame: Rect) -> Self { - let base = Affine::translate(-frame.origin().to_vec2()); - let artboard = Rect::new(0.0, 0.0, frame.width(), frame.height()); - // A picture's coordinates map straight onto the document, as a WMF's do. - let p = Player::new(Kind::Wmf, base, artboard); - Self { - p, - frame, - base, - origin: Vec2::ZERO, - fg: [0; 3], - bg: [255; 3], - pen: Vec2::new(1.0, 1.0), - pen_mode: 8, - pen_pat: Pat::Bits([0xFF; 8]), - fill_pat: Pat::Bits([0xFF; 8]), - back_pat: Pat::Bits([0; 8]), - oval: Vec2::ZERO, - pen_loc: Point::ZERO, - font: 0, - face: 0, - text_size: 0, - text_loc: Point::ZERO, - names: HashMap::new(), - last: [Rect::ZERO; 4], - region_work: MAX_REGION_WORK, - row_bytes_left: MAX_FILE_ROW_BYTES, - } - } - - /// Charge the `w` × `h` pixels of `pm`, and the bytes of its unpacked rows, to the picture's - /// budgets: false, and nothing charged, when either is spent. - fn charge(&mut self, pm: &PixMap, w: usize, h: usize) -> bool { - let bytes = (pm.row_len(w) as u64).saturating_mul(h as u64); - let Some(rows_left) = self.row_bytes_left.checked_sub(bytes) else { return false }; - let (Ok(wide), Ok(high)) = (u32::try_from(w), u32::try_from(h)) else { return false }; - if dib::charge(wide, high, &mut self.p.pixels_left).is_err() { - return false; - } - self.row_bytes_left = rows_left; - true - } - - /// Play opcode `op`, its data at `r`; `None` when the data runs past the end. - fn op(&mut self, op: u16, r: &mut Be) -> Option<()> { - if !matches!(op, 0x20..=0x23) { - self.p.flush(); - } - match op { - 0x01 => self.clip(r), - 0x0C => self.move_origin(r), - 0x20..=0x23 => self.line(op, r), - 0x28..=0x2B => self.text(op, r), - 0x2C => self.font_name(r), - 0x30..=0x6F => self.shape(op, r), - 0x70..=0x77 => self.poly(verb(op), r), - 0x80..=0x87 => self.region_shape(verb(op), r), - // The same polygon and region: Apple's table gives them no data and no drawing. - 0x78..=0x7F | 0x88..=0x8F => Some(()), - 0x90 | 0x91 | 0x98..=0x9B => self.bits(op, r), - 0xA1 => { - r.skip(2)?; - let n = usize::from(r.u16()?); - r.skip(n) - } - 0x0C00 => self.header(r), - 0x8200 => self.quicktime(r), - _ => self.state(op, r), - } - } - - /// The opcodes that set the drawing state; the others are skipped. - fn state(&mut self, op: u16, r: &mut Be) -> Option<()> { - match op { - 0x02 => self.back_pat = Pat::Bits(r.array()?), - 0x03 => self.font = r.u16()?, - 0x04 => self.face = r.u8()?, - 0x07 => self.pen = r.size()?, - 0x08 => self.pen_mode = r.u16()?, - 0x09 => self.pen_pat = Pat::Bits(r.array()?), - 0x0A => self.fill_pat = Pat::Bits(r.array()?), - 0x0B => self.oval = r.size()?, - 0x0D => self.text_size = r.i16()?, - 0x0E => self.fg = old_color(r.u32()?), - 0x0F => self.bg = old_color(r.u32()?), - 0x12 => self.back_pat = self.pix_pat(r)?, - 0x13 => self.pen_pat = self.pix_pat(r)?, - 0x14 => self.fill_pat = self.pix_pat(r)?, - 0x1A => self.fg = r.rgb()?, - 0x1B => self.bg = r.rgb()?, - _ => return skip(op, r), - } - Some(()) - } - - /// The version 2 header: an extended one's source rectangle maps onto the frame. - fn header(&mut self, r: &mut Be) -> Option<()> { - let mut b = Be::new(r.bytes(24)?, 0); - if b.i16() == Some(-2) - && let Some(src) = b.skip(10).and_then(|()| b.rect()) - && src.width() > 0.0 - && src.height() > 0.0 - { - let k = Vec2::new(self.frame.width() / src.width(), self.frame.height() / src.height()); - self.base = Affine::scale_non_uniform(k.x, k.y) * Affine::translate(-src.origin().to_vec2()); - self.p.dev_to_doc = self.base * Affine::translate(-self.origin); - } - Some(()) - } - - /// The origin moves by (dh, dv): a point drawn after it is that much nearer the top left. - fn move_origin(&mut self, r: &mut Be) -> Option<()> { - let (dh, dv) = (r.i16()?, r.i16()?); - self.origin += Vec2::new(dh.into(), dv.into()); - self.p.dev_to_doc = self.base * Affine::translate(-self.origin); - Some(()) - } - - /// A pixel pattern: its color (the average of a color pattern's pixels), else its bitmap. - fn pix_pat(&mut self, r: &mut Be) -> Option { - let kind = r.u16()?; - let bits: [u8; 8] = r.array()?; - match kind { - 1 => { - let pm = PixMap::read(r, true, false)?; - let (w, h) = pm.dims()?; - let small = w * h <= MAX_PATTERN_PIXELS && pm.row_len(w) * h <= MAX_PATTERN_ROW_BYTES; - let keep = small && pm.decodable(w) && self.charge(&pm, w, h); - let (data, _) = pm.rows(r, w, h, keep)?; - let avg = keep.then(|| pm.to_rgba(&data, w, h, self.fg, self.bg)).flatten().map(|img| self.average(&img)); - Some(avg.map_or(Pat::Bits(bits), Pat::Rgb)) - } - 2 => Some(Pat::Rgb(r.rgb()?)), - _ => Some(Pat::Bits(bits)), - } - } - - /// The average color of `img`, with a warning when its pixels differ. - fn average(&mut self, img: &Rgba) -> [u8; 3] { - let px = img.pixels.as_chunks::<4>().0; - if px.windows(2).any(|w| w[0] != w[1]) { - self.p.warn(PATTERNS); - } - let n = px.len().max(1) as u64; - let sum = |i: usize| (px.iter().map(|p| u64::from(p[i])).sum::() / n) as u8; - [sum(0), sum(1), sum(2)] - } - - /// The color a pattern fills with: its own, or its two colors mixed as its bits are. - fn pat_color(&mut self, pat: Pat) -> [u8; 3] { - match pat { - Pat::Rgb(c) => c, - Pat::Bits(b) => { - let ones: u32 = b.iter().map(|x| x.count_ones()).sum(); - if ones != 0 && ones != 64 { - self.p.warn(PATTERNS); - } - mix(self.fg, self.bg, f64::from(ones) / 64.0) - } - } - } - - /// The pen's color (a warning when its mode isn't a copy). - fn pen_color(&mut self) -> [u8; 3] { - if !matches!(self.pen_mode, 0 | 8) { - self.p.warn(MODES); - } - self.pat_color(self.pen_pat) - } - - /// The color painting, erasing or filling an area takes; `None` for the other verbs. - fn area_color(&mut self, verb: Verb) -> Option<[u8; 3]> { - match verb { - Verb::Paint => Some(self.pen_color()), - Verb::Erase => Some(self.pat_color(self.back_pat)), - Verb::Fill => Some(self.pat_color(self.fill_pat)), - Verb::Frame | Verb::Invert => None, - } - } - - fn has_pen(&self) -> bool { - self.pen.x > 0.0 && self.pen.y > 0.0 - } - - /// Fill `bp` (picture space) with `color`. - fn fill(&mut self, mut bp: BezPath, color: [u8; 3], rule: FillRule) { - bp.apply_affine(self.p.xf()); - self.p.dc.brush = color; - self.p.dc.fill_rule = rule; - self.p.draw(bp, true, false); - } - - /// The pen as a stroke of `color` with `ends`, as wide as the pen's average side. - fn set_pen(&mut self, color: [u8; 3], ends: u32) { - let width = (self.pen.x + self.pen.y) / 2.0; - self.p.dc.pen = PenObj { style: PS_GEOMETRIC | ends | MITER, width, color, entries: vec![] }; - } - - /// Stroke `bp` (picture space) with the pen in `color`. - fn stroke(&mut self, mut bp: BezPath, color: [u8; 3], ends: u32) { - self.set_pen(color, ends); - bp.apply_affine(self.p.xf()); - self.p.draw(bp, false, true); - } - - /// Draw a framed shape: its outline (from `outline` of a rectangle and an oval size) stroked - /// inside `r`, or filled when the pen is as large as the shape. - fn frame(&mut self, r: Rect, outline: impl Fn(Rect, Vec2) -> BezPath, ends: u32) { - if !self.has_pen() { - return; - } - let color = self.pen_color(); - let half = self.pen / 2.0; - let inner = Rect::new(r.x0 + half.x, r.y0 + half.y, r.x1 - half.x, r.y1 - half.y); - if inner.width() <= 0.0 || inner.height() <= 0.0 { - return self.fill(outline(r, self.oval), color, FillRule::NonZero); - } - self.stroke(outline(inner, self.oval - self.pen), color, ends); - } - - /// The rectangle, rounded rectangle, oval and arc opcodes. - fn shape(&mut self, op: u16, r: &mut Be) -> Option<()> { - let family = op >> 4; - let slot = usize::from(family - 3); - let rect = if op & 8 != 0 { self.last.get(slot).copied()? } else { r.rect()? }; - let angles = if family == 6 { Some((r.i16()?, r.i16()?)) } else { None }; - let Some(verb) = verb(op) else { return Some(()) }; - if let Some(l) = self.last.get_mut(slot) { - *l = rect; - } - if rect.width() <= 0.0 || rect.height() <= 0.0 { - return Some(()); - } - let outline = move |r: Rect, oval: Vec2, wedge: bool| match family { - 3 => shapes::rectangle(r).to_bezpath(), - 4 => round_rect(r, oval.x, oval.y), - 5 => kurbo::Ellipse::from_rect(r).to_path(TOLERANCE), - _ => angles.map_or_else(BezPath::new, |(start, sweep)| arc(r, start, sweep, wedge)), - }; - match verb { - Verb::Frame => self.frame(rect, |r, oval| outline(r, oval, false), if family == 6 { FLAT } else { SQUARE }), - Verb::Invert => self.p.warn(INVERTED), - _ => { - if let Some(c) = self.area_color(verb) { - self.fill(outline(rect, self.oval, true), c, FillRule::NonZero); - } - } - } - Some(()) - } - - /// A polygon opcode: framed along its points, else filled. - fn poly(&mut self, verb: Option, r: &mut Be) -> Option<()> { - let size = usize::from(r.u16()?); - let mut b = Be::new(r.bytes(size.checked_sub(2)?)?, 8); - let Some(verb) = verb else { return Some(()) }; - let mut pts = vec![]; - while let Some(p) = b.point() { - pts.push(p); - } - let Some((first, rest)) = pts.split_first() else { return Some(()) }; - let closed = pts.len() > 2 && pts.first() == pts.last(); - match verb { - Verb::Frame if self.has_pen() => { - let half = self.pen / 2.0; - let mut bp = BezPath::new(); - bp.move_to(*first + half); - rest.iter().for_each(|p| bp.line_to(*p + half)); - if closed { - bp.close_path(); - } - let color = self.pen_color(); - self.stroke(bp, color, SQUARE); - } - Verb::Frame => {} - Verb::Invert => self.p.warn(INVERTED), - _ => { - let mut bp = BezPath::new(); - bp.move_to(*first); - rest.iter().for_each(|p| bp.line_to(*p)); - bp.close_path(); - if let Some(c) = self.area_color(verb) { - self.fill(bp, c, FillRule::EvenOdd); - } - } - } - Some(()) - } - - /// A region's rectangles, with a warning when it was too large to read. - fn read_region(&mut self, r: &mut Be) -> Option> { - let (rects, whole) = region(r, &mut self.region_work)?; - if !whole { - self.p.warn(BIG_REGIONS); - } - Some(rects) - } - - /// A region opcode: each rectangle framed, else the region filled. - fn region_shape(&mut self, verb: Option, r: &mut Be) -> Option<()> { - let rects = self.read_region(r)?; - let Some(verb) = verb.filter(|_| !rects.is_empty()) else { return Some(()) }; - match verb { - Verb::Frame if self.has_pen() => { - if rects.len() > 1 { - self.p.warn(FRAMED_REGIONS); - } - let half = self.pen / 2.0; - let inner: Vec = rects.iter().map(|r| Rect::new(r.x0 + half.x, r.y0 + half.y, r.x1 - half.x, r.y1 - half.y)).collect(); - let color = self.pen_color(); - self.stroke(rects_path(&inner), color, SQUARE); - } - Verb::Frame => {} - Verb::Invert => self.p.warn(INVERTED), - _ => { - if let Some(c) = self.area_color(verb) { - self.fill(rects_path(&rects), c, FillRule::NonZero); - } - } - } - Some(()) - } - - /// The clip region: it replaces the clip. An empty region clips away everything after it, as - /// a clip of no area at the frame's corner; one too large to read leaves the clip as it was. - fn clip(&mut self, r: &mut Be) -> Option<()> { - let (mut rects, whole) = region(r, &mut self.region_work)?; - if !whole { - self.p.warn(BIG_REGIONS); - return Some(()); - } - if rects.is_empty() { - let corner = Point::new(self.frame.x0, self.frame.y0); - rects.push(Rect::from_points(corner, corner)); - } - let mut bp = rects_path(&rects); - bp.apply_affine(self.p.xf()); - self.p.push_clip(bp, FillRule::NonZero, true); - Some(()) - } - - /// The line opcodes: the pen drawn from point to point, hanging below and to the right of - /// the line; lines one after another join into one path. - fn line(&mut self, op: u16, r: &mut Be) -> Option<()> { - let delta = |r: &mut Be| Some(Vec2::new(f64::from(r.u8()? as i8), f64::from(r.u8()? as i8))); - let (from, to) = match op { - 0x20 => (r.point()?, r.point()?), - 0x21 => (self.pen_loc, r.point()?), - 0x22 => { - let a = r.point()?; - (a, a + delta(r)?) - } - _ => (self.pen_loc, self.pen_loc + delta(r)?), - }; - self.pen_loc = to; - if !self.has_pen() { - return Some(()); - } - let color = self.pen_color(); - if from == to { - // A dot: the pen's rectangle. - self.p.flush(); - self.fill(shapes::rectangle(Rect::from_points(from, from + self.pen)).to_bezpath(), color, FillRule::NonZero); - return Some(()); - } - let pen = PenObj { style: PS_GEOMETRIC | SQUARE | MITER, width: (self.pen.x + self.pen.y) / 2.0, color, entries: vec![] }; - if self.p.dc.pen != pen { - self.p.flush(); - self.p.dc.pen = pen; - } - let half = self.pen / 2.0; - let xf = self.p.xf(); - let (a, b) = (xf * (from + half), xf * (to + half)); - if self.p.pending.elements().last().and_then(|e| e.end_point()) != Some(a) { - self.p.pending.move_to(a); - } - self.p.pending.line_to(b); - Some(()) - } - - /// The text opcodes: a string at the text location, moved to or by the opcode's data. - fn text(&mut self, op: u16, r: &mut Be) -> Option<()> { - match op { - 0x28 => self.text_loc = r.point()?, - 0x29 => self.text_loc.x += f64::from(r.u8()?), - 0x2A => self.text_loc.y += f64::from(r.u8()?), - _ => { - self.text_loc.x += f64::from(r.u8()?); - self.text_loc.y += f64::from(r.u8()?); - } - } - let n = usize::from(r.u8()?); - let s: String = r.bytes(n)?.iter().map(|&b| mac_roman(b)).filter(|c| !c.is_control()).collect(); - let size = if self.text_size > 0 { self.text_size } else { 12 }; - let face = self.names.get(&self.font).cloned().unwrap_or_else(|| font_family(self.font).to_string()); - self.p.dc.font = FontObj { - height: -f64::from(size), - escapement: 0.0, - weight: if self.face & 1 != 0 { 700 } else { 400 }, - italic: self.face & 2 != 0, - face, - }; - self.p.dc.text_color = self.fg; - self.p.dc.text_align = TA_BASELINE; - self.p.text(self.text_loc, &s); - Some(()) - } - - /// A font's name for its number. - fn font_name(&mut self, r: &mut Be) -> Option<()> { - let n = usize::from(r.u16()?); - let mut b = Be::new(r.bytes(n)?, 0); - if let Some(id) = b.u16() - && let Some(len) = b.u8() - && let Some(name) = b.bytes(usize::from(len)) - { - let name: String = name.iter().map(|&c| mac_roman(c)).collect(); - self.names.insert(id, name.trim().to_string()); - } - Some(()) - } - - /// A bitmap or pixel map copied into a rectangle (`Rgn` opcodes: clipped to a mask region). - fn bits(&mut self, op: u16, r: &mut Be) -> Option<()> { - let direct = matches!(op, 0x9A | 0x9B); - if direct { - r.skip(4)?; - } - let mut pm = PixMap::read(r, direct, direct)?; - // BitsRect and BitsRgn store their rows unpacked. - pm.packed = op >= 0x98; - let (src, dst, mode) = (r.rect()?, r.rect()?, r.u16()?); - let mask = if op & 1 != 0 { Some(self.read_region(r)?) } else { None }; - let (w, h) = pm.dims()?; - let (wide, high) = (w as u64, h as u64); - let fits = wide * high <= dib::MAX_READ_PIXELS && pm.row_len(w) as u64 * high <= MAX_ROW_BYTES; - let readable = pm.decodable(w); - let keep = fits && readable && self.charge(&pm, w, h); - let (data, ok) = pm.rows(r, w, h, keep)?; - if !keep { - self.p.warn(if readable { TOO_MANY_PIXELS } else { BAD_IMAGE }); - return Some(()); - } - let Some(mut img) = pm.to_rgba(&data, w, h, self.fg, self.bg).filter(|_| ok) else { - self.p.warn(BAD_IMAGE); - return Some(()); - }; - self.transfer(&mut img, mode, pm.size == 1 && pm.palette.is_none()); - if dst.width() <= 0.0 || dst.height() <= 0.0 || mask.as_ref().is_some_and(Vec::is_empty) { - return Some(()); - } - let saved = self.p.dc.clips.clone(); - if let Some(rects) = &mask { - let mut bp = rects_path(rects); - bp.apply_affine(self.p.xf()); - self.p.push_clip(bp, FillRule::NonZero, false); - } - self.p.image(Ok(img), src - pm.bounds.origin().to_vec2(), dst, SRCCOPY, 1.0); - self.p.dc.clips = saved; - Some(()) - } - - /// Transfer mode `mode` on copied pixels: OR of a bitmap and the transparent mode leave the - /// background color out; the others are copied, with a warning. - fn transfer(&mut self, img: &mut Rgba, mode: u16, bitmap: bool) { - // 64 dithers, which doesn't change what is copied. - let clear = match mode & !64 { - 0 => false, - 1 if bitmap => true, - 36 => true, - _ => { - self.p.warn(MODES); - false - } - }; - if clear { - let bg = self.bg; - img.pixels.as_chunks_mut::<4>().0.iter_mut().filter(|p| [p[0], p[1], p[2]] == bg).for_each(|p| p[3] = 0); - } - } - - /// A compressed QuickTime image: a JPEG one becomes an image placed by its matrix. - fn quicktime(&mut self, r: &mut Be) -> Option<()> { - let n = usize::try_from(r.u32()?).ok()?; - let data = r.bytes(n)?; - match qt_image(data) { - Some((ctype, xf, src, image)) if &ctype == b"jpeg" => match self.jpeg(image) { - Ok(img) => { - let img = crop(img, src); - self.p.image_xf(img, xf * Affine::translate(src.origin().to_vec2()), 1.0); - } - Err(w) => self.p.warn(w), - }, - Some(_) => self.p.warn(CODECS), - None => self.p.warn(BAD_IMAGE), - } - Some(()) - } - - /// A JPEG stream's pixels, taken from the file's pixel budget. - fn jpeg(&mut self, data: &[u8]) -> Result { - let mut opts = craft_image_codecs::DecodeOptions::default(); - opts.limits.max_width = dib::MAX_READ_SIDE; - opts.limits.max_height = dib::MAX_READ_SIDE; - opts.limits.max_pixels = dib::MAX_READ_PIXELS.min(self.p.pixels_left); - let img = match craft_image_codecs::decode_as_with(craft_image_codecs::Format::Jpeg, data, &opts) { - Ok(img) => img, - Err(craft_image_codecs::CodecError::LimitExceeded(_)) => return Err(TOO_MANY_PIXELS), - Err(_) => return Err(BAD_IMAGE), - }; - let (w, h) = img.dimensions(); - dib::charge(w, h, &mut self.p.pixels_left).map_err(|_| TOO_MANY_PIXELS)?; - Ok(Rgba { width: w, height: h, pixels: img.to_rgba8() }) - } -} - -/// A QuickTime image's compressor type, matrix (image → picture space), source rectangle and -/// compressed data, from its header and image description. -fn qt_image(d: &[u8]) -> Option<([u8; 4], Affine, Rect, &[u8])> { - let mut b = Be::new(d, 2); - let mut m = [0.0; 9]; - for v in &mut m { - *v = f64::from(b.i32()?) / 65536.0; - } - let matte = usize::try_from(b.u32()?).ok()?; - b.skip(10)?; - let src = b.rect()?; - b.skip(4)?; - let mask = usize::try_from(b.u32()?).ok()?; - b.skip(matte)?; - b.skip(mask)?; - let start = b.pos; - let id_size = usize::try_from(b.u32()?).ok()?; - let ctype = b.array::<4>()?; - b.skip(36)?; - let size = usize::try_from(b.u32()?).ok()?; - let at = start.checked_add(id_size)?; - let data = d.get(at..at.checked_add(size)?).or_else(|| d.get(at..))?; - // The rows of a QuickTime matrix are [a b u] [c d v] [tx ty w]; u, v and w (perspective) are - // left out. - let xf = Affine::new([m[0], m[1], m[3], m[4], m[6], m[7]]); - Some((ctype, xf, src, data)) -} - -/// Read a picture. -pub(crate) fn play(bytes: &[u8]) -> Result { - let h = find(bytes).ok_or(NOT_PICT)?; - let mut q = Pict::new(h.frame); - let mut r = Be::new(bytes, h.ops); - // Why the picture stopped before its end opcode, if it did. - let mut stopped = Some(TOO_MANY_OPS); - for _ in 0..MAX_OPS { - // Version 2 opcodes start on even bytes. - if h.v2 && r.pos % 2 == 1 && r.skip(1).is_none() { - stopped = Some(CUT_SHORT); - break; - } - let Some(op) = (if h.v2 { r.u16() } else { r.u8().map(u16::from) }) else { - stopped = Some(CUT_SHORT); - break; - }; - if op == 0x00FF { - stopped = None; - break; - } - if q.op(op, &mut r).is_none() { - stopped = Some(CUT_SHORT); - break; - } - } - if let Some(why) = stopped { - q.p.warn(why); - } - q.p.flush(); - if q.p.out.is_empty() { - q.p.warn(NOTHING); - } - Ok(q.p.finish()) -} diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index 1cfb3038cd..932b7636cc 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -1206,7 +1206,7 @@ fn ends_early(bytes: &[u8], kind: Kind) -> bool { pub(crate) fn import(bytes: &[u8]) -> Result { let kind = crate::sniff(bytes).ok_or("not an EMF or WMF file")?; let pic = craft_metafile::parse(bytes).map_err(|e| match e { - craft_metafile::Error::NotMetafile => "not an EMF or WMF file".to_string(), + craft_metafile::Error::NotMetafile | craft_metafile::Error::NotPict => "not an EMF or WMF file".to_string(), craft_metafile::Error::BadHeader => format!("the {} header is damaged", kind.id().to_uppercase()), craft_metafile::Error::NoRecords => format!("the {} file holds no records", kind.id().to_uppercase()), })?; @@ -1224,3 +1224,21 @@ pub(crate) fn import(bytes: &[u8]) -> Result { } Ok(m.finish(kind, lost)) } + +/// Turn a metafile picture into a document. +pub(crate) fn convert(pic: craft_metafile::Picture) -> crate::Picture { + let mut m = Mapper::new(f64::from(pic.width), f64::from(pic.height), (1.0, 1.0)); + if pic.truncated { + m.warn(AT_LIMIT); + } + let lost = Lost { skipped: pic.skipped_records, images: pic.dropped_images, clips: pic.ignored_clips, rops: pic.unplayed_raster_ops }; + for item in pic.items { + m.item(item); + } + let imported = m.finish(Kind::Wmf, lost); + let mut p = crate::Picture { document: imported.document, warnings: imported.warnings }; + if p.document.layers.iter().all(|l| l.children().is_none_or(|c| c.is_empty())) { + p.warnings.push("the picture draws nothing VectorCraft reads".to_string()); + } + p +} diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 3f6dd8d5dd..90309d5f01 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -151,14 +151,13 @@ pub struct Picture { /// Do `bytes` hold a version 2 QuickDraw picture, after a PICT file's 512 bytes of application /// data or on their own? A version 1 picture is known by its file's name. pub fn is_pict(bytes: &[u8]) -> bool { - import::pict::is_pict(bytes) + craft_metafile::is_pict(bytes) } /// Read a QuickDraw picture (version 1 or 2; a PICT file, or a picture on its own) into a document /// whose one artboard is the picture's frame. pub fn import_pict(bytes: &[u8]) -> Result { - let i = import::pict::play(bytes)?; - let mut p = Picture { document: i.document, warnings: i.warnings }; + let mut p = import::import_pict(bytes)?; p.document.limit_depth_noting(&mut p.warnings); Ok(p) } diff --git a/crates/metafile/src/tests/pict.rs b/crates/metafile/src/tests/pict.rs index 0d8b48c939..b8024b3515 100644 --- a/crates/metafile/src/tests/pict.rs +++ b/crates/metafile/src/tests/pict.rs @@ -147,7 +147,7 @@ fn a_bare_picture_and_a_version_1_picture_open() { v1.extend([0xA0, 0x00, 0x05, 0x50]); v1.extend(rect(20, 20, 30, 30)); v1.push(0xFF); - assert!(!crate::is_pict(&v1)); + assert!(crate::is_pict(&v1)); let p = import_pict(&v1).unwrap(); assert!(p.warnings.is_empty(), "{:?}", p.warnings); assert_eq!(p.document.artboards[0].rect.size(), (60.0, 40.0).into()); @@ -231,7 +231,6 @@ fn patterns_fill_with_their_average_color() { assert_eq!(fill_rgb(&v[0]), Some([128, 128, 128])); // eraseRect with an RGB background pattern. assert_eq!(fill_rgb(&v[1]), Some([0, 255, 0])); - assert!(p.warnings.iter().any(|w| w.contains("average of their colors")), "{:?}", p.warnings); } #[test] @@ -401,7 +400,7 @@ fn quicktime_jpeg_images_are_placed_by_their_matrix() { let [r, g, b, _] = px.get_pixel(1, 1).0; assert!(r > 240 && g < 16 && b < 16, "{r} {g} {b}"); assert!(near(n.geometric_bounds().unwrap(), Rect::new(10.0, 5.0, 18.0, 9.0), 1e-9)); - assert!(p.warnings.iter().any(|w| w.contains("other than JPEG")), "{:?}", p.warnings); + assert!(p.warnings.iter().any(|w| w.contains("couldn't be read was left out")), "{:?}", p.warnings); } /// An image whose matrix flattens it is left out, and adds nothing to the document's images. @@ -419,11 +418,11 @@ fn pictures_cut_short_keep_what_came_before() { let cut = &full[..full.len() - 6]; let p = import_pict(cut).unwrap(); assert_eq!(paths(&p.document).len(), 1); - assert!(p.warnings.iter().any(|w| w.contains("cut short")), "{:?}", p.warnings); + assert!(p.warnings.iter().any(|w| w.contains("limit on what one file may hold")), "{:?}", p.warnings); // A long comment longer than the file. let p = import_pict(&v2([0, 0, 50, 50], &[(0x31, rect(0, 0, 10, 10)), (0xA1, be(&[100, 5000]))])).unwrap(); assert_eq!(paths(&p.document).len(), 1); - assert!(p.warnings.iter().any(|w| w.contains("cut short")), "{:?}", p.warnings); + assert!(p.warnings.iter().any(|w| w.contains("limit on what one file may hold")), "{:?}", p.warnings); // Nothing drawn. let p = import_pict(&v2([0, 0, 50, 50], &[(0xA0, be(&[100]))])).unwrap(); assert!(p.warnings.iter().any(|w| w.contains("draws nothing")), "{:?}", p.warnings); @@ -451,7 +450,7 @@ fn a_picture_that_never_ends_stops_at_the_opcode_limit() { b.resize(b.len() + 2 * ((1 << 22) + 1), 0); let p = import_pict(&b).unwrap(); assert_eq!(paths(&p.document).len(), 1); - assert!(p.warnings.iter().any(|w| w.contains("more opcodes")), "{:?}", p.warnings); + assert!(p.warnings.iter().any(|w| w.contains("limit on what one file may hold")), "{:?}", p.warnings); } /// Regions share one budget of inversion points per picture: past it, a region is left out. @@ -464,7 +463,7 @@ fn regions_past_the_picture_budget_are_left_out() { let body = [rect(0, 0, 1, 16_000), be(&words)].concat(); let region = [be(&[(body.len() + 2) as i16]), body].concat(); let p = import_pict(&v2([0, 0, 300, 300], &[(0x81, region.clone()), (0x81, region.clone()), (0x81, region)])).unwrap(); - assert!(p.warnings.iter().any(|w| w.contains("regions larger")), "{:?}", p.warnings); + assert!(p.warnings.iter().any(|w| w.contains("clip couldn't be applied")), "{:?}", p.warnings); let v = paths(&p.document); assert_eq!(v.len(), 2); let NodeKind::Path { path, .. } = &v[0].kind else { panic!("a path") }; From 946f33c8783729541aef39deb46f48e0b1c31f09 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:00:42 +0530 Subject: [PATCH 08/32] metafile: address CodeRabbit feedback on truncation warnings, patterns, and region shapes --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/metafile/src/import/picture.rs | 10 ++++++++-- crates/metafile/src/tests/pict.rs | 7 ++++--- 4 files changed, 14 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bc8de2d7fc..b8cd54c77c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1251,7 +1251,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0bf4cb99dabb6b6d9335771ed398e999387b0d62#0bf4cb99dabb6b6d9335771ed398e999387b0d62" +source = "git+https://github.com/storytold/craft-libs?rev=ccd093d2316c1445ab3bdeecbecfacaaae4093d4#ccd093d2316c1445ab3bdeecbecfacaaae4093d4" dependencies = [ "encoding_rs", "image", diff --git a/Cargo.toml b/Cargo.toml index 7b6d617b78..f9f7acbe3c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,7 +39,7 @@ craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "d7c963 craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } # WMF, EMF and EMF+ reader (craft-libs#778). # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "0bf4cb99dabb6b6d9335771ed398e999387b0d62" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "ccd093d2316c1445ab3bdeecbecfacaaae4093d4" } craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index 932b7636cc..738bbbdf6d 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -51,6 +51,7 @@ const PATTERNS: &str = "hatched and pattern brushes are filled with their averag const ENDS_EARLY: &str = "the file ends early: what it held was imported"; const TOO_MANY: &str = "objects past the most one file may hold were left out"; const AT_LIMIT: &str = "the file or a picture inside it reached a limit on what one file may hold: what came after the limit was not read"; +const PICT_TRUNCATED: &str = "the picture is cut short or reached a limit on what one file may hold: what came after was not read"; /// Points a unit of a WMF without a placeable header (1440 units an inch). const WMF_UNIT: f64 = 72.0 / 1440.0; @@ -272,7 +273,12 @@ fn average(rgba: &[u8]) -> Option<[u8; 4]> { } let a = sum[3]; let alpha = (a / pixels.len().max(1) as u64) as u8; - (a > 0).then(|| [(sum[0] / a) as u8, (sum[1] / a) as u8, (sum[2] / a) as u8, alpha.max(1)]) + (a > 0).then(|| [ + ((sum[0] + a / 2) / a) as u8, + ((sum[1] + a / 2) / a) as u8, + ((sum[2] + a / 2) / a) as u8, + alpha.max(1), + ]) } impl Mapper { @@ -1229,7 +1235,7 @@ pub(crate) fn import(bytes: &[u8]) -> Result { pub(crate) fn convert(pic: craft_metafile::Picture) -> crate::Picture { let mut m = Mapper::new(f64::from(pic.width), f64::from(pic.height), (1.0, 1.0)); if pic.truncated { - m.warn(AT_LIMIT); + m.warn(PICT_TRUNCATED); } let lost = Lost { skipped: pic.skipped_records, images: pic.dropped_images, clips: pic.ignored_clips, rops: pic.unplayed_raster_ops }; for item in pic.items { diff --git a/crates/metafile/src/tests/pict.rs b/crates/metafile/src/tests/pict.rs index b8024b3515..812f1ef56d 100644 --- a/crates/metafile/src/tests/pict.rs +++ b/crates/metafile/src/tests/pict.rs @@ -231,6 +231,7 @@ fn patterns_fill_with_their_average_color() { assert_eq!(fill_rgb(&v[0]), Some([128, 128, 128])); // eraseRect with an RGB background pattern. assert_eq!(fill_rgb(&v[1]), Some([0, 255, 0])); + assert!(p.warnings.iter().any(|w| w.contains("their average color")), "{:?}", p.warnings); } #[test] @@ -418,11 +419,11 @@ fn pictures_cut_short_keep_what_came_before() { let cut = &full[..full.len() - 6]; let p = import_pict(cut).unwrap(); assert_eq!(paths(&p.document).len(), 1); - assert!(p.warnings.iter().any(|w| w.contains("limit on what one file may hold")), "{:?}", p.warnings); + assert!(p.warnings.iter().any(|w| w.contains("cut short")), "{:?}", p.warnings); // A long comment longer than the file. let p = import_pict(&v2([0, 0, 50, 50], &[(0x31, rect(0, 0, 10, 10)), (0xA1, be(&[100, 5000]))])).unwrap(); assert_eq!(paths(&p.document).len(), 1); - assert!(p.warnings.iter().any(|w| w.contains("limit on what one file may hold")), "{:?}", p.warnings); + assert!(p.warnings.iter().any(|w| w.contains("cut short")), "{:?}", p.warnings); // Nothing drawn. let p = import_pict(&v2([0, 0, 50, 50], &[(0xA0, be(&[100]))])).unwrap(); assert!(p.warnings.iter().any(|w| w.contains("draws nothing")), "{:?}", p.warnings); @@ -463,7 +464,7 @@ fn regions_past_the_picture_budget_are_left_out() { let body = [rect(0, 0, 1, 16_000), be(&words)].concat(); let region = [be(&[(body.len() + 2) as i16]), body].concat(); let p = import_pict(&v2([0, 0, 300, 300], &[(0x81, region.clone()), (0x81, region.clone()), (0x81, region)])).unwrap(); - assert!(p.warnings.iter().any(|w| w.contains("clip couldn't be applied")), "{:?}", p.warnings); + assert!(p.warnings.iter().any(|w| w.contains("skipped")), "{:?}", p.warnings); let v = paths(&p.document); assert_eq!(v.len(), 2); let NodeKind::Path { path, .. } = &v[0].kind else { panic!("a path") }; From edf449c379f96995009fdf6236558375169357a7 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:37:02 +0530 Subject: [PATCH 09/32] chore: update craft-metafile rev to 6d02a9d79 --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 195f0cc958..881fdedd2c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1251,7 +1251,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e0f7f787ce18e745eadd205b07e0a3759ef61f81#e0f7f787ce18e745eadd205b07e0a3759ef61f81" +source = "git+https://github.com/storytold/craft-libs?rev=6d02a9d7918fa4877aa17191865571fd157dae5e#6d02a9d7918fa4877aa17191865571fd157dae5e" dependencies = [ "encoding_rs", "image", diff --git a/Cargo.toml b/Cargo.toml index e8dc51f1f3..d8c33feec9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,7 +39,7 @@ craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "d7c963 craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } # WMF, EMF and EMF+ reader (craft-libs#778). # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "e0f7f787ce18e745eadd205b07e0a3759ef61f81" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "6d02a9d7918fa4877aa17191865571fd157dae5e" } craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } From 2cc47a707e994a6786a855b85e587d1dcc23396e Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:44:19 +0530 Subject: [PATCH 10/32] vectorcraft-metafile: format picture.rs --- crates/metafile/src/import/picture.rs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index 318da121c7..aae4e4b339 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -275,12 +275,7 @@ fn average(rgba: &[u8]) -> Option<[u8; 4]> { } let a = sum[3]; let alpha = (a / pixels.len().max(1) as u64) as u8; - (a > 0).then(|| [ - ((sum[0] + a / 2) / a) as u8, - ((sum[1] + a / 2) / a) as u8, - ((sum[2] + a / 2) / a) as u8, - alpha.max(1), - ]) + (a > 0).then(|| [((sum[0] + a / 2) / a) as u8, ((sum[1] + a / 2) / a) as u8, ((sum[2] + a / 2) / a) as u8, alpha.max(1)]) } impl Mapper { From eb3a9ba335ee4b9376a888b5f804f4b7be062062 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Mon, 23 Nov 2026 04:37:59 +0800 Subject: [PATCH 11/32] Import: share Mac Roman decoding across legacy formats (#9042) --- Cargo.lock | 2 ++ Cargo.toml | 1 + crates/engine/Cargo.toml | 1 + crates/engine/src/cmd/fileio/tests_psdlayers.rs | 4 ++-- crates/engine/src/cmd/place/rtf.rs | 4 ++-- crates/engine/src/cmd/place/text.rs | 17 ++--------------- crates/metafile/Cargo.toml | 1 + crates/metafile/src/import/pict.rs | 15 +-------------- crates/metafile/src/tests/pict.rs | 14 ++++++++++---- 9 files changed, 22 insertions(+), 37 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6a602ed891..01e7d2ebfc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6901,6 +6901,7 @@ dependencies = [ "cfb", "chrono", "craft-cdr", + "craft-codepage", "craft-docpath", "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-jxl", @@ -7060,6 +7061,7 @@ dependencies = [ name = "vectorcraft-metafile" version = "0.24.1" dependencies = [ + "craft-codepage", "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-metafile", "image", diff --git a/Cargo.toml b/Cargo.toml index 6056916d75..29b7c94503 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -48,6 +48,7 @@ craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["egui"] } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 075211dc1a..cf21c25e46 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -19,6 +19,7 @@ bundled-fonts = ["vectorcraft-text/bundled-fonts"] heif = ["dep:heic-rs", "dep:rayon"] [dependencies] +craft-codepage = { workspace = true } # Which paths stored in documents may be opened. craft-docpath = { workspace = true } craft-proof = { workspace = true } diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index 09acabbfa0..8660eee992 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -405,9 +405,9 @@ fn zipped_and_32_bit_layers_read() { /// A layer without a Unicode name takes the name its Pascal string holds, read as Mac Roman. #[test] fn names_without_a_unicode_name_read_as_mac_roman() { - let l = L { legacy: Some(b"Caf\x8E \xD2Old\xD3"), ..layer("", [0, 0, 1, 1], [0, 0, 0, 255]) }; + let l = L { legacy: Some(b"Caf\x8E\xCA\xD2Old\xD3\xDB"), ..layer("", [0, 0, 1, 1], [0, 0, 0, 255]) }; let (s, r) = open(&file(1, 1, &[l], 8, false, false), json!({})); - assert_eq!(name(&s.doc().unwrap().doc.layers[0]), "Café “Old”", "{r}"); + assert_eq!(name(&s.doc().unwrap().doc.layers[0]), "Café\u{a0}“Old”€", "{r}"); } #[test] diff --git a/crates/engine/src/cmd/place/rtf.rs b/crates/engine/src/cmd/place/rtf.rs index 5af9519521..f9282abd5d 100644 --- a/crates/engine/src/cmd/place/rtf.rs +++ b/crates/engine/src/cmd/place/rtf.rs @@ -651,8 +651,8 @@ mod tests { let s = read(concat!(r"{\rtf1\ansi\uc1 caf\u233?\uc2 \u", "8364", r"\'80\'80 \uc1\u-10179?\u-8704? end\'93q\'94}")); assert_eq!(text_of(&s), "café€ 😀 end“q”"); assert_eq!(text_of(&read(r"{\rtf1\uc1\u233\bin1 ?X}")), "éX", "binary data is one fallback character"); - let mac = read(r"{\rtf1\mac \'8e\'a5}"); - assert_eq!(text_of(&mac), "é•", "Mac Roman"); + let mac = read(r"{\rtf1\mac \'8e\'ca\'a5\'db\'de}"); + assert_eq!(text_of(&mac), "é\u{a0}•€fi", "Mac Roman"); } #[test] diff --git a/crates/engine/src/cmd/place/text.rs b/crates/engine/src/cmd/place/text.rs index 78261a8804..06ab1af83f 100644 --- a/crates/engine/src/cmd/place/text.rs +++ b/crates/engine/src/cmd/place/text.rs @@ -185,20 +185,7 @@ pub(in crate::cmd) fn windows_1252(b: u8) -> char { /// Byte `b` of Mac Roman. pub(in crate::cmd) fn mac_roman(b: u8) -> char { - const HIGH: [char; 128] = [ - 'Ä', 'Å', 'Ç', 'É', 'Ñ', 'Ö', 'Ü', 'á', 'à', 'â', 'ä', 'ã', 'å', 'ç', 'é', 'è', // - 'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ñ', 'ó', 'ò', 'ô', 'ö', 'õ', 'ú', 'ù', 'û', 'ü', // - '†', '°', '¢', '£', '§', '•', '¶', 'ß', '®', '©', '™', '´', '¨', '≠', 'Æ', 'Ø', // - '∞', '±', '≤', '≥', '¥', 'µ', '∂', '∑', '∏', 'π', '∫', 'ª', 'º', 'Ω', 'æ', 'ø', // - '¿', '¡', '¬', '√', 'ƒ', '≈', '∆', '«', '»', '…', '\u{A0}', 'À', 'Ã', 'Õ', 'Œ', 'œ', // - '–', '—', '“', '”', '‘', '’', '÷', '◊', 'ÿ', 'Ÿ', '⁄', '€', '‹', '›', 'fi', 'fl', // - '‡', '·', '‚', '„', '‰', 'Â', 'Ê', 'Á', 'Ë', 'È', 'Í', 'Î', 'Ï', 'Ì', 'Ó', 'Ô', // - '\u{F8FF}', 'Ò', 'Ú', 'Û', 'Ù', 'ı', 'ˆ', '˜', '¯', '˘', '˙', '˚', '¸', '˝', '˛', 'ˇ', - ]; - match b { - 0x80.. => HIGH.get(usize::from(b - 0x80)).copied().unwrap_or(char::REPLACEMENT_CHARACTER), - _ => char::from(b), - } + craft_codepage::windows_byte(craft_codepage::MAC_ROMAN_CODE_PAGE, b) } /// `text` with its line breaks (CR LF, CR or LF) as paragraph breaks, cleaned up as `o` says: @@ -344,7 +331,7 @@ mod tests { let ansi = TextOptions { character_set: CharacterSet::Ansi, ..TextOptions::default() }; assert_eq!(decode(&[0x93, b'q', 0x94, 0xE9], ansi), "“q”é"); let mac = TextOptions { character_set: CharacterSet::Ansi, mac: true, ..TextOptions::default() }; - assert_eq!(decode(&[0xD2, b'q', 0xD3, 0x8E, 0xA5, 0xDB], mac), "“q”é•€"); + assert_eq!(decode(&[0xD2, b'q', 0xD3, 0x8E, 0xCA, 0xA5, 0xDB, 0xDE, 0xF0], mac), "“q”é\u{a0}•€fi\u{f8ff}"); } /// The other character sets decode by their Encoding Standard decoders: the platform matters diff --git a/crates/metafile/Cargo.toml b/crates/metafile/Cargo.toml index d8047c039a..1026a54c4b 100644 --- a/crates/metafile/Cargo.toml +++ b/crates/metafile/Cargo.toml @@ -9,6 +9,7 @@ description = "VectorCraft metafiles: EMF and WMF export and EMF, EMF+ and WMF i workspace = true [dependencies] +craft-codepage = { workspace = true } vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } vectorcraft-doc = { workspace = true } diff --git a/crates/metafile/src/import/pict.rs b/crates/metafile/src/import/pict.rs index a1e5a674e0..a5ef46316f 100644 --- a/crates/metafile/src/import/pict.rs +++ b/crates/metafile/src/import/pict.rs @@ -206,20 +206,7 @@ fn mix(a: [u8; 3], b: [u8; 3], t: f64) -> [u8; 3] { /// Byte `b` of Mac Roman. fn mac_roman(b: u8) -> char { - const HIGH: [char; 128] = [ - 'Ä', 'Å', 'Ç', 'É', 'Ñ', 'Ö', 'Ü', 'á', 'à', 'â', 'ä', 'ã', 'å', 'ç', 'é', 'è', // - 'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ñ', 'ó', 'ò', 'ô', 'ö', 'õ', 'ú', 'ù', 'û', 'ü', // - '†', '°', '¢', '£', '§', '•', '¶', 'ß', '®', '©', '™', '´', '¨', '≠', 'Æ', 'Ø', // - '∞', '±', '≤', '≥', '¥', 'µ', '∂', '∑', '∏', 'π', '∫', 'ª', 'º', 'Ω', 'æ', 'ø', // - '¿', '¡', '¬', '√', 'ƒ', '≈', '∆', '«', '»', '…', '\u{A0}', 'À', 'Ã', 'Õ', 'Œ', 'œ', // - '–', '—', '“', '”', '‘', '’', '÷', '◊', 'ÿ', 'Ÿ', '⁄', '€', '‹', '›', 'fi', 'fl', // - '‡', '·', '‚', '„', '‰', 'Â', 'Ê', 'Á', 'Ë', 'È', 'Í', 'Î', 'Ï', 'Ì', 'Ó', 'Ô', // - '\u{F8FF}', 'Ò', 'Ú', 'Û', 'Ù', 'ı', 'ˆ', '˜', '¯', '˘', '˙', '˚', '¸', '˝', '˛', 'ˇ', - ]; - match b { - 0x80.. => HIGH.get(usize::from(b - 0x80)).copied().unwrap_or(char::REPLACEMENT_CHARACTER), - _ => char::from(b), - } + craft_codepage::windows_byte(craft_codepage::MAC_ROMAN_CODE_PAGE, b) } /// The family name of a classic Macintosh font number. diff --git a/crates/metafile/src/tests/pict.rs b/crates/metafile/src/tests/pict.rs index 0d8b48c939..54ca33de89 100644 --- a/crates/metafile/src/tests/pict.rs +++ b/crates/metafile/src/tests/pict.rs @@ -236,17 +236,23 @@ fn patterns_fill_with_their_average_color() { #[test] fn text_comes_in_as_point_type_in_the_named_font() { - let name = [be(&[9, 300]), vec![6], b"Geneva".to_vec()].concat(); + let name = [be(&[9, 300]), vec![6], b"Gen\x8Eva".to_vec()].concat(); let bytes = v2( [0, 0, 100, 200], - &[(0x2C, name), (0x03, be(&[300])), (0x0D, be(&[18])), (0x04, vec![1]), (0x28, [be(&[50, 10]), vec![4], b"Caf\x8E".to_vec()].concat())], + &[ + (0x2C, name), + (0x03, be(&[300])), + (0x0D, be(&[18])), + (0x04, vec![1]), + (0x28, [be(&[50, 10]), vec![8], b"Caf\x8E\xCA\xDB\xDE\xF0".to_vec()].concat()), + ], ); let p = import_pict(&bytes).unwrap(); let texts: Vec<_> = all(&p.document).into_iter().filter(|n| matches!(n.kind, NodeKind::Text(_))).collect(); let NodeKind::Text(t) = &texts[0].kind else { panic!("text") }; - assert_eq!(t.plain_text(), "Café"); + assert_eq!(t.plain_text(), "Café\u{a0}€fi\u{f8ff}"); let st = &t.runs[0].style; - assert_eq!((st.font_family.as_str(), st.font_style.as_str(), st.size), ("Geneva", "Bold", 18.0)); + assert_eq!((st.font_family.as_str(), st.font_style.as_str(), st.size), ("Genéva", "Bold", 18.0)); // The text location is the baseline's start. assert_eq!(t.xf.translation(), Point::new(10.0, 50.0).to_vec2()); } From 76b8839448dee862ea65c118dc5b587d2a36da9d Mon Sep 17 00:00:00 2001 From: Terra854 Date: Mon, 23 Nov 2026 06:13:39 +0800 Subject: [PATCH 12/32] SVG: share XML attribute escaping (#9030) Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- Cargo.lock | 1 + crates/svg/Cargo.toml | 1 + crates/svg/src/export/nodes.rs | 4 ++-- crates/svg/src/export/output.rs | 15 +++++---------- crates/svg/src/export/text.rs | 4 ++-- crates/svg/tests/it/data_attributes.rs | 6 ++++-- 6 files changed, 15 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 01e7d2ebfc..1c00b127f1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7202,6 +7202,7 @@ dependencies = [ "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-mime", "craft-svg", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", "data-url", "flate2", "image", diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index c1a59d7022..310b9c8e6f 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -10,6 +10,7 @@ workspace = true [dependencies] craft-svg = { workspace = true } +craft-xml = { workspace = true } craft-mime = { workspace = true } # Which paths stored in documents may be opened. craft-docpath = { workspace = true } diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index b92e888b57..481db1f8a2 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -1,4 +1,4 @@ -use super::output::{sanitize_id, valid_xml_value, xml_attr_escape, xml_attr_valid}; +use super::output::{sanitize_id, valid_xml_value, xml_attr_escape}; use super::paint::{StrokePlan, has_raster, pixel_gradient}; use super::text::OUTLINE_TOLERANCE; use super::{ @@ -888,7 +888,7 @@ impl Writer<'_> { if !valid_xml_value(url) { self.warn("Link URLs containing invalid XML characters had those characters removed"); } - self.line(&format!("", xml_attr_valid(url))); + self.line(&format!("", xml_attr_escape(url))); self.depth += 1; self.node_body(n); self.depth -= 1; diff --git a/crates/svg/src/export/output.rs b/crates/svg/src/export/output.rs index 3ed101340a..00fb760c03 100644 --- a/crates/svg/src/export/output.rs +++ b/crates/svg/src/export/output.rs @@ -1,8 +1,9 @@ use super::*; -/// XML 1.0 literal attribute whitespace is normalized to spaces; references retain the value. +/// Escape a double-quoted attribute, retaining VectorCraft's apostrophe entity spelling. pub(super) fn xml_attr_escape(s: &str) -> String { - xml_escape(s).replace('\t', " ").replace('\n', " ").replace('\r', " ") + let escaped = craft_xml::esc_attr(s); + if escaped.contains('\'') { escaped.replace('\'', "'") } else { escaped } } /// Escape type for XML content. Characters XML 1.0 does not allow are dropped, except the line @@ -12,21 +13,15 @@ pub(super) fn xml_text(s: &str) -> String { .chars() .filter_map(|c| match c { '\u{b}' | '\u{c}' => Some(' '), - c if valid_xml_value(c.encode_utf8(&mut [0; 4])) => Some(c), + c if craft_xml::is_xml_char(c) => Some(c), _ => None, }) .collect(); xml_escape(&s) } -/// `s` without the characters XML 1.0 does not allow, ready for a double-quoted attribute. -pub(super) fn xml_attr_valid(s: &str) -> String { - let s: String = s.chars().filter(|c| valid_xml_value(c.encode_utf8(&mut [0; 4]))).collect(); - xml_attr_escape(&s) -} - pub(super) fn valid_xml_value(s: &str) -> bool { - s.chars().all(|c| matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{d7ff}' | '\u{e000}'..='\u{fffd}' | '\u{10000}'..='\u{10ffff}')) + s.chars().all(craft_xml::is_xml_char) } /// An XML name without a colon (an NCName): a letter or `_`, then [`xml_name_char`]s. diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index f8bc712117..289fcb81ba 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -1,4 +1,4 @@ -use super::output::{xml_attr_escape, xml_attr_valid, xml_text}; +use super::output::{xml_attr_escape, xml_text}; use super::{ Affine, AppearanceItem, Arc, BTreeSet, BezPath, BlendMode, CharStyle, FillRule, FontDb, FontFace, GradientKind, HashMap, Justify, Node, NodeId, NodeKind, Paint, PathData, Props, Rect, StrokeAlign, Styling, TextKind, TextObject, Writer, base64_encode, css, css_string, fmt_num, @@ -199,7 +199,7 @@ impl Writer<'_> { Some(named) if !id.is_empty() && !id.contains(" data-name=\"") => format!(" data-name=\"{}\"", xml_attr_escape(named)), _ => String::new(), }; - format!("{name} role=\"img\" aria-label=\"{}\"", xml_attr_valid(&text)) + format!("{name} role=\"img\" aria-label=\"{}\"", xml_attr_escape(&text)) } else { String::new() }; diff --git a/crates/svg/tests/it/data_attributes.rs b/crates/svg/tests/it/data_attributes.rs index 60edf3dd60..1d411143f0 100644 --- a/crates/svg/tests/it/data_attributes.rs +++ b/crates/svg/tests/it/data_attributes.rs @@ -32,10 +32,10 @@ fn native_data(raw: &str) -> Document { } #[test] fn imported_decimal_whitespace_references_survive_export() { - let doc = import(&svg(r#""#)).unwrap(); + let doc = import(&svg(r#""#)).unwrap(); assert_eq!( named(&doc, "shape").extras().attrs.as_deref().unwrap().data, - [("value".into(), "a\nb".into()), ("tab".into(), "a\tb".into()), ("cr".into(), "a\rb".into())] + [("value".into(), "a\nb".into()), ("tab".into(), "a\tb".into()), ("cr".into(), "a\rb".into()), ("mixed".into(), "a\t\"'<>&\r\n雲".into()),] ); for styling in styles() { for minify in [false, true] { @@ -45,6 +45,8 @@ fn imported_decimal_whitespace_references_survive_export() { for (key, value) in [("data-value", "a\nb"), ("data-tab", "a\tb"), ("data-cr", "a\rb")] { assert_eq!(n.attribute(key), Some(value)); } + assert_eq!(n.attribute("data-mixed"), Some("a\t\"'<>&\r\n雲")); + assert!(text.contains(r#"data-mixed="a "'<>& 雲""#)); let back = import(&text).unwrap(); assert_eq!(named(&back, "shape").extras().attrs.as_deref().unwrap().data, named(&doc, "shape").extras().attrs.as_deref().unwrap().data); } From 409d821751b9504d780b849b79a31233a07a22ce Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 22 Nov 2026 17:21:09 -0500 Subject: [PATCH 13/32] Use the shared EMF and WMF EOF diagnostic (#9125) --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/metafile/src/import/picture.rs | 46 +++------------------------ 3 files changed, 7 insertions(+), 43 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1c00b127f1..56f2e6688c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1251,7 +1251,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=c56fbd8271a42ffcc82b07c8f31d714e345fdcd9#c56fbd8271a42ffcc82b07c8f31d714e345fdcd9" dependencies = [ "encoding_rs", "image", diff --git a/Cargo.toml b/Cargo.toml index 29b7c94503..b29e0bdfc2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,7 +38,7 @@ craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "068e079c7b craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "c56fbd8271a42ffcc82b07c8f31d714e345fdcd9" } craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index dab2111119..0b72246b54 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -1164,46 +1164,6 @@ fn retracked(t: &TextObject, laid: &vectorcraft_text::TextLayout, dx: &[f64]) -> Some(out) } -/// Does the file stop before its end-of-file record? -fn ends_early(bytes: &[u8], kind: Kind) -> bool { - let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); - let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]])); - let mut at = match kind { - Kind::Emf => 0, - Kind::Wmf => { - let start = if u32_at(0) == Some(PLACEABLE_KEY) { 22 } else { 0 }; - let Some(words) = u16_at(start + 2) else { return true }; - start + usize::from(words) * 2 - } - }; - loop { - let size = match kind { - Kind::Emf => { - let (Some(kind), Some(size)) = (u32_at(at), u32_at(at.saturating_add(4))) else { return true }; - if kind == 14 { - return false; - } - // Records are a multiple of 4 bytes long; reading stops at one that isn't. - if !size.is_multiple_of(4) { - return true; - } - size as usize - } - Kind::Wmf => { - let (Some(words), Some(function)) = (u32_at(at), u16_at(at.saturating_add(4))) else { return true }; - if function == 0 { - return false; - } - (words as usize).saturating_mul(2) - } - }; - if size < 6 { - return true; - } - at = at.saturating_add(size); - } -} - /// Read an EMF or WMF file. pub(crate) fn import(bytes: &[u8]) -> Result { let kind = crate::sniff(bytes).ok_or("not an EMF or WMF file")?; @@ -1214,7 +1174,11 @@ pub(crate) fn import(bytes: &[u8]) -> Result { })?; let k = unit(bytes, kind); let mut m = Mapper::new(f64::from(pic.width), f64::from(pic.height), k); - if ends_early(bytes, kind) { + let wire_kind = match kind { + Kind::Emf => craft_metafile::Kind::Emf, + Kind::Wmf => craft_metafile::Kind::Wmf, + }; + if craft_metafile::ends_early(bytes, wire_kind) { m.warn(ENDS_EARLY); } if pic.truncated { From e563e271a017c0d2fceab97be65958b97d4dd86d Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:55:39 +0700 Subject: [PATCH 14/32] build: pin craft-libs to main 33be356 (craft-libs#778) Move every craft-libs crate to one rev merged on craft-libs main, so the metafile unit facts from craft-libs#3071 are available. --- Cargo.lock | 231 ++++++++++---------------------- Cargo.toml | 70 +++++----- apps/vectorcraft-web/Cargo.toml | 2 +- crates/text/Cargo.toml | 2 +- xtask/src/pdf_deps.rs | 2 +- 5 files changed, 110 insertions(+), 197 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 56f2e6688c..08d1135fb7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1001,7 +1001,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "crc32fast", "flate2", @@ -1012,7 +1012,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=9b28b56bc7207ef7ce806f37df72cb94c0ad5c37#9b28b56bc7207ef7ce806f37df72cb94c0ad5c37" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "crc32fast", "flate2", @@ -1021,7 +1021,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "md-5", "rayon", @@ -1030,20 +1030,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" -dependencies = [ - "rayon", -] - -[[package]] -name = "craft-dds" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "rayon", ] @@ -1051,12 +1043,12 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "craft-codepage", "encoding_rs", @@ -1068,17 +1060,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=068e079c7be4b100a8a6b305b31ac881e069727e#068e079c7be4b100a8a6b305b31ac881e069727e" - -[[package]] -name = "craft-eps" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec#cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "harfrust 0.13.3", "kurbo 0.13.1", @@ -1092,12 +1079,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "gif", ] @@ -1105,7 +1092,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "flate2", ] @@ -1113,7 +1100,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1136,39 +1123,12 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ - "craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", - "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", - "crc32fast", - "exr", - "flate2", - "half", - "hayro-jpeg2000", - "image", - "image-webp", - "jpeg-encoder", - "png 0.18.1", - "rayon", - "serde_json", - "thiserror 2.0.21", - "tiff", - "zune-core", - "zune-jpeg", - "zune-jpegxl", -] - -[[package]] -name = "craft-image-codecs" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" -dependencies = [ - "craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", - "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", + "craft-dds", + "craft-jpeg", + "craft-metadata", + "craft-tiff", "crc32fast", "exr", "flate2", @@ -1190,15 +1150,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" -dependencies = [ - "thiserror 2.0.21", -] - -[[package]] -name = "craft-jpeg" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "thiserror 2.0.21", ] @@ -1206,7 +1158,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1217,7 +1169,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "egui", "serde", @@ -1227,23 +1179,11 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "brotli-decompressor 6.3.2", "chrono", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", - "quick-xml 0.41.0", - "serde", -] - -[[package]] -name = "craft-metadata" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" -dependencies = [ - "brotli-decompressor 6.3.2", - "chrono", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", + "craft-tiff", "quick-xml 0.41.0", "serde", ] @@ -1251,7 +1191,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c56fbd8271a42ffcc82b07c8f31d714e345fdcd9#c56fbd8271a42ffcc82b07c8f31d714e345fdcd9" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "encoding_rs", "image", @@ -1262,7 +1202,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "chrono", "craft-codepage", @@ -1272,7 +1212,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1283,7 +1223,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1292,7 +1232,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "craft-winprint-gdi", "log", @@ -1306,7 +1246,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1317,9 +1257,9 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec#cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ - "craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec)", + "craft-eps", "flate2", "kurbo 0.13.1", "miniz_oxide 0.8.9", @@ -1331,7 +1271,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "encoding_rs", "flate2", @@ -1342,7 +1282,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "fax", "hayro-ccitt", @@ -1353,10 +1293,10 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", + "craft-image-codecs", + "craft-xml", "data-url", "flate2", "gif", @@ -1374,34 +1314,17 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" -dependencies = [ - "serde", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-tiff" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" -dependencies = [ - "serde", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-tiff" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "serde", "thiserror 2.0.21", + "tiff", ] [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1422,7 +1345,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "chrono", "dunce", @@ -1449,7 +1372,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "flate2", "serde", @@ -1460,7 +1383,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "js-sys", "serde_json", @@ -1471,7 +1394,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "egui", "objc2 0.6.5", @@ -1490,17 +1413,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" -dependencies = [ - "quick-xml 0.41.0", - "serde", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-xml" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2607,7 +2520,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "brotli", "hayro-postscript", @@ -2616,7 +2529,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -2634,7 +2547,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -2652,12 +2565,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "flate2", "hayro-ccitt", @@ -3457,7 +3370,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "base64 0.22.1", "bumpalo", @@ -3566,7 +3479,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -6772,7 +6685,7 @@ name = "vectorcraft-affinity" version = "0.24.1" dependencies = [ "craft-affinity", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "crc32fast", "proptest", "vectorcraft-affinity", @@ -6802,7 +6715,7 @@ name = "vectorcraft-cad" version = "0.24.1" dependencies = [ "craft-dxf", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "craft-plotter", "image", "kurbo 0.13.1", @@ -6857,7 +6770,7 @@ name = "vectorcraft-doc" version = "0.24.1" dependencies = [ "chrono", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "craft-stream-codecs", "flate2", "image", @@ -6877,7 +6790,7 @@ dependencies = [ name = "vectorcraft-effects" version = "0.24.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "craft-svg", "image", "kurbo 0.13.1", @@ -6903,11 +6816,11 @@ dependencies = [ "craft-cdr", "craft-codepage", "craft-docpath", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "craft-jxl", "craft-proof", "craft-stream-codecs", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", + "craft-xml", "crc32fast", "encoding_rs", "flate2", @@ -6960,8 +6873,8 @@ dependencies = [ name = "vectorcraft-eps" version = "0.24.1" dependencies = [ - "craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=068e079c7be4b100a8a6b305b31ac881e069727e)", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-eps", + "craft-image-codecs", "craft-pdf", "craft-ps", "craft-stream-codecs", @@ -7041,7 +6954,7 @@ dependencies = [ name = "vectorcraft-mcp" version = "0.24.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "image", "log", "proptest", @@ -7062,7 +6975,7 @@ name = "vectorcraft-metafile" version = "0.24.1" dependencies = [ "craft-codepage", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "craft-metafile", "image", "kurbo 0.13.1", @@ -7103,10 +7016,10 @@ version = "0.24.1" dependencies = [ "aes", "chrono", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "craft-pdf", "craft-stream-codecs", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", + "craft-xml", "flate2", "getrandom 0.4.3", "image", @@ -7138,7 +7051,7 @@ dependencies = [ name = "vectorcraft-plugins" version = "0.24.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "craft-vectorcraft-format", "log", "rustix 1.1.6", @@ -7160,10 +7073,10 @@ name = "vectorcraft-render" version = "0.24.1" dependencies = [ "craft-gif", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "craft-psd", "craft-stream-codecs", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", + "craft-tiff", "flate2", "image", "jpeg-encoder", @@ -7199,10 +7112,10 @@ name = "vectorcraft-svg" version = "0.24.1" dependencies = [ "craft-docpath", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "craft-mime", "craft-svg", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", + "craft-xml", "data-url", "flate2", "image", @@ -7230,7 +7143,7 @@ dependencies = [ name = "vectorcraft-testkit" version = "0.24.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "fax", "kurbo 0.13.1", "proptest", @@ -7281,7 +7194,7 @@ dependencies = [ name = "vectorcraft-tools" version = "0.24.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "kurbo 0.13.1", "serde", "serde_json", @@ -7298,7 +7211,7 @@ dependencies = [ name = "vectorcraft-trace" version = "0.24.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "image", "kurbo 0.13.1", "serde", @@ -7313,7 +7226,7 @@ version = "0.24.1" dependencies = [ "bytemuck", "chrono", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "craft-keymap", "craft-ui", "craft-update", diff --git a/Cargo.toml b/Cargo.toml index b29e0bdfc2..79cba7f471 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,44 +11,44 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", default-features = false, features = ["interpret", "write"] } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["serde"] } -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", default-features = false, features = ["interpret", "write"] } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", features = ["serde"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } # Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per # desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", features = ["egui"] } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } # craft-update: app-specific pretend versions apply to startup and manual checks. # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "9b28b56bc7207ef7ce806f37df72cb94c0ad5c37" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "068e079c7be4b100a8a6b305b31ac881e069727e" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "c56fbd8271a42ffcc82b07c8f31d714e345fdcd9" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["egui"] } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "33be35625e252cc4f06aa375b3b428521faea37d", features = ["egui"] } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -191,13 +191,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 9569d2b3f3..e6695c45ea 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -17,7 +17,7 @@ path = "src/main.rs" vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] } vectorcraft-ui-egui = { workspace = true } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "0.1.0" } vectorcraft-format = { workspace = true } vectorcraft-text = { workspace = true } egui = { workspace = true } diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index 07695b034c..6663a7f892 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -10,7 +10,7 @@ workspace = true [dependencies] # The shared font catalog from craft-libs main (it has the outline, bidi and caret helpers used here). -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", default-features = false } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", default-features = false } vectorcraft-geom = { workspace = true } vectorcraft-doc = { workspace = true } kurbo = { workspace = true } diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 29a599c400..ddf7950ded 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,7 +5,7 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "d7c9632bfb3040cf45db394e7500cc93c81c49e0"; +const REV: &str = "33be35625e252cc4f06aa375b3b428521faea37d"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), From cde70af446bf4c8a059ece1f6c9ffc26e4da2a31 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:58:44 +0700 Subject: [PATCH 15/32] metafile: take WMF and EMF unit facts from craft-metafile (craft-libs#778) Use craft_metafile::unit_facts from craft-libs#3071 for the placeable frame, metric map-mode scan and EMF calibration; the fallback scales stay VectorCraft's policy. --- crates/metafile/src/import/picture.rs | 156 +++++--------------------- 1 file changed, 25 insertions(+), 131 deletions(-) diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index 0b72246b54..d78714dd4a 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -46,9 +46,6 @@ use super::{BAD_IMAGE, FAR_AWAY, HAIRLINE, LIMIT, MAX_NODES, around, rgb, sane}; use crate::dib::Rgba; use crate::{Imported, Kind}; -// The placeable header is interpreted here for VectorCraft’s logical-unit policy. -const PLACEABLE_KEY: u32 = 0x9AC6_CDD7; - const PATTERNS: &str = "hatched and pattern brushes are filled with their average color"; const ENDS_EARLY: &str = "the file ends early: what it held was imported"; const TOO_MANY: &str = "objects past the most one file may hold were left out"; @@ -56,148 +53,45 @@ const AT_LIMIT: &str = "the file or a picture inside it reached a limit on what /// Points a unit of a WMF without a placeable header (1440 units an inch). const WMF_UNIT: f64 = 72.0 / 1440.0; -/// The SAVEDC levels `craft_metafile` keeps; it stops reading at a SAVEDC past them. -const SAVED_LEVELS: usize = 1024; /// Points a pixel at 96 pixels an inch. const PT_PER_PX: f64 = 72.0 / 96.0; /// Points a millimetre. const PT_PER_MM: f64 = 72.0 / 25.4; -/// WMF records that draw lines and shapes, which `craft_metafile` plays only when the mix mode -/// lets them draw. -const WMF_SHAPES: [u16; 10] = [0x0213, 0x0324, 0x0325, 0x0418, 0x041B, 0x0538, 0x061C, 0x0817, 0x081A, 0x0830]; -/// WMF records that draw text and bitmaps, which `craft_metafile` plays whatever the mix mode. -const WMF_DRAWS: [u16; 5] = [0x0521, 0x0940, 0x0A32, 0x0B41, 0x0F43]; -/// SETROP2 mix modes under which `craft_metafile` draws no lines, shapes or brush fills: R2_XORPEN -/// and R2_NOP. -const WMF_MIX_SKIPS: [u16; 2] = [7, 11]; -/// The mix mode a WMF starts in (R2_COPYPEN). -const WMF_MIX_START: u16 = 13; -/// PATBLT raster operations `craft_metafile` draws: PATCOPY (with the brush, as the mix mode -/// allows), BLACKNESS and WHITENESS. -const PATCOPY: u32 = 0x00F0_0021; -const BLACKNESS: u32 = 0x0000_0042; -const WHITENESS: u32 = 0x00FF_0062; - -/// Does a WMF draw in a metric map mode (MM_LOMETRIC to MM_TWIPS)? `craft_metafile` plays those -/// at 96 pixels an inch, whatever the window. The mode that more drawing records are played in -/// decides, counting only records the reader draws (not lines and shapes under R2_NOP or -/// R2_XORPEN, nor a PATBLT it does not fill); a file that draws nothing goes by its last mode. -/// `start` is where the standard header begins. -fn wmf_metric(bytes: &[u8], start: usize) -> bool { - let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]])); - let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); - let Some(words) = start.checked_add(2).and_then(u16_at) else { return false }; - let mut at = start.saturating_add(usize::from(words) * 2); - let mut mode = 1; - let mut mix = WMF_MIX_START; - let metric = |mode: u16| (2..=6).contains(&mode); - // Drawing records played in a metric mode, and in any other. - let (mut in_metric, mut in_other) = (0usize, 0usize); - // The map and mix modes SAVEDC kept, which RESTOREDC brings back as the reader does. - let mut saved: Vec<(u16, u16)> = Vec::new(); - // The records as the reader walks them: it stops at the end record, a record shorter than its - // header, one that runs past the file and a SAVEDC past its 1,024 levels. - while let (Some(words), Some(function)) = (u32_at(at), u16_at(at.saturating_add(4))) { - let size = (words as usize).saturating_mul(2); - let Some(next) = at.checked_add(size) else { break }; - if function == 0 || size < 6 || next > bytes.len() { - break; - } - match function { - // SETMAPMODE, when the record holds its mode. - 0x0103 if size >= 8 => mode = u16_at(at + 6).unwrap_or(mode), - // SETROP2, when the record holds its mix mode. - 0x0104 if size >= 8 => mix = u16_at(at + 6).unwrap_or(mix), - // SAVEDC. - 0x001E => { - if saved.len() >= SAVED_LEVELS { - break; - } - saved.push((mode, mix)); - } - // RESTOREDC: a negative count pops that many levels, a positive one goes back to that - // level. One that names no saved level changes nothing. - 0x0127 if size >= 8 => { - let n = u16_at(at + 6).map_or(0, |v| i32::from(i16::from_le_bytes(v.to_le_bytes()))); - let level = if n < 0 { saved.len().checked_sub(n.unsigned_abs() as usize) } else { (n as usize).checked_sub(1) }; - if let Some(level) = level - && let Some((m, x)) = saved.get(level).copied() - { - mode = m; - mix = x; - saved.truncate(level); - } - } - f => { - let draws = match f { - _ if WMF_DRAWS.contains(&f) => true, - _ if WMF_SHAPES.contains(&f) => !WMF_MIX_SKIPS.contains(&mix), - // PATBLT: its raster operation, when the record holds one. - 0x061D => match u32_at(at + 6).filter(|_| size >= 10) { - Some(PATCOPY) => !WMF_MIX_SKIPS.contains(&mix), - Some(rop) => rop == BLACKNESS || rop == WHITENESS, - None => false, - }, - _ => false, - }; - if draws && metric(mode) { - in_metric += 1; - } else if draws { - in_other += 1; - } - } - } - at = next; - } - if in_metric == in_other { metric(mode) } else { in_metric > in_other } -} - /// Points a picture unit across and down. `craft_metafile` gives a placeable WMF with a box and an /// EMF with a frame in points, and other files in their logical units (WMF; pixels in a metric map -/// mode) or device units (EMF). -fn unit(bytes: &[u8], kind: Kind) -> (f64, f64) { - let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]])); - let i16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| i16::from_le_bytes([b[0], b[1]])); - let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); - let i32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]])); - let positive = |v: Option| v.filter(|v| *v > 0).map(f64::from); - match kind { - Kind::Wmf => { - let placeable = bytes.get(..4) == Some(&PLACEABLE_KEY.to_le_bytes()[..]); - if placeable - && let (Some(l), Some(t), Some(r), Some(b)) = (i16_at(6), i16_at(8), i16_at(10), i16_at(12)) - && r > l - && b > t - { - return (1.0, 1.0); - } - if wmf_metric(bytes, if placeable { 22 } else { 0 }) { - return (PT_PER_PX, PT_PER_PX); - } - if !placeable { - return (WMF_UNIT, WMF_UNIT); - } - let k = 72.0 / u16_at(14).filter(|v| *v > 0).map_or(1440.0, f64::from); +/// mode) or device units (EMF). The file's frame and unit facts come from +/// [`craft_metafile::unit_facts`]; the fallback scales here are VectorCraft's policy. +fn unit(bytes: &[u8]) -> (f64, f64) { + use craft_metafile::{EmfPhysicalSize, UnitFacts}; + match craft_metafile::unit_facts(bytes) { + Some(UnitFacts::WmfPlaceableFrame) => (1.0, 1.0), + // `craft_metafile` plays the metric map modes at 96 pixels an inch, whatever the window. + Some(UnitFacts::WmfMetricMap) => (PT_PER_PX, PT_PER_PX), + // Without a placeable header, or with no units an inch in it: 1440 units an inch. + Some(UnitFacts::WmfLogical { units_per_inch }) => { + let k = units_per_inch.map_or(WMF_UNIT, |inch| 72.0 / f64::from(inch)); (k, k) } - Kind::Emf => { - // Device pixels a millimetre on each axis: szlDevice over szlMicrometers when the header - // has them, else over szlMillimeters (both sizes must be positive). - let device = positive(i32_at(72)).zip(positive(i32_at(76))); - let micro = (u32_at(4).is_some_and(|s| s >= 108)) - .then(|| u32_at(100).zip(u32_at(104)).filter(|(w, h)| *w > 0 && *h > 0).map(|(w, h)| (f64::from(w) / 1000.0, f64::from(h) / 1000.0))) - .flatten(); - let mm = micro.or_else(|| positive(i32_at(80)).zip(positive(i32_at(84)))); - let px_mm = device.zip(mm).map(|((w, h), (mw, mh))| (w / mw, h / mh)); - let frame = matches!((i32_at(24), i32_at(28), i32_at(32), i32_at(36)), (Some(l), Some(t), Some(r), Some(b)) if r > l && b > t); + Some(UnitFacts::Emf { has_frame, device }) => { + // Device pixels a millimetre on each axis. + let px_mm = device.map(|d| { + let (w, h) = (f64::from(d.pixels.0), f64::from(d.pixels.1)); + let (mw, mh) = match d.physical_size { + EmfPhysicalSize::Micrometres(w, h) => (f64::from(w) / 1000.0, f64::from(h) / 1000.0), + EmfPhysicalSize::Millimetres(w, h) => (f64::from(w), f64::from(h)), + }; + (w / mw, h / mh) + }); let ok = |v: f64| v.is_finite() && v > 0.0; match px_mm { - Some(_) if frame => (1.0, 1.0), + Some(_) if has_frame => (1.0, 1.0), Some((x, y)) if ok(x) && ok(y) => (PT_PER_MM / x, PT_PER_MM / y), _ => (PT_PER_PX, PT_PER_PX), } } + // Not reached: `crate::sniff` accepted the file through the same shared sniff. + None => (PT_PER_PX, PT_PER_PX), } } @@ -1172,7 +1066,7 @@ pub(crate) fn import(bytes: &[u8]) -> Result { craft_metafile::Error::BadHeader => format!("the {} header is damaged", kind.id().to_uppercase()), craft_metafile::Error::NoRecords => format!("the {} file holds no records", kind.id().to_uppercase()), })?; - let k = unit(bytes, kind); + let k = unit(bytes); let mut m = Mapper::new(f64::from(pic.width), f64::from(pic.height), k); let wire_kind = match kind { Kind::Emf => craft_metafile::Kind::Emf, From 5af36bae87a694b1e8a23eea15f0f8bd7f0578d0 Mon Sep 17 00:00:00 2001 From: Taha <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:48:18 +0430 Subject: [PATCH 16/32] Fix #4568: PDF import keeps embedded fonts for text whose family isn't installed (#4569) * PDF import: keep embedded fonts for text whose family isn't installed Glyphs drawn in an embedded font whose family isn't available are gathered during import and built into one small TrueType font per family and style, kept with the document (font/ttf blob). Text objects record the fonts and a hash of their text: layout and rendering draw them in the kept font until the text is edited (undo restores it) or the family is installed. Lines are spaced against the file's own widths with per-glyph placement (#3756). * PDF import: satisfy crate layering constraints without format dev-dep * FileFont: negate us_win_descent in i32 to prevent overflow on extreme negative descenders * PDF import: a kept font carries the file font's licence flags, and the docs say what that means Review of #4569: the fsType of the file's font is copied to the font built from its glyphs (a test pins it against Embedding), so exports honour it; the docs state the limits, that the file's font program is not parsed, and that a saved file carries third-party glyphs. * PDF import: a glyph curve far outside any glyph is left out; docs say what the limits and the font program mean CodeRabbit on #4569: coordinates beyond 1e6 font units are refused before the curve is subdivided. The docs say the 64-font limit is what draws one type object and that the file's font program is read only for its licence flags and metrics. * PDF import: two programs of one font keep the stricter licence flags; the docs cite their sources CodeRabbit on #4569: embedded programs of one family and style share one built font, which kept the first program's fsType; it now takes the stricter of the two, whichever came first. The docs entry cites the Acrobat Help pages and the OpenType fsType specification. * fmt * PDF import: embedded fonts are on by default, with an opt-out preference Owner decision on #4568. Preferences > File Handling > Use fonts embedded in imported PDFs (pdfImportEmbeddedFonts, on by default) and the embeddedFonts param of document.open and file.place: off, a PDF's type in a font the machine lacks is set in the fallback font with the missing-font warning, as before. One test each for on and off, one for the preference reaching the options. * fmt after merging main * docs: restore the status lines damaged by merges (main's line plus this PR's note) * PDF import: set embedded_fonts through a builder method (keeps read_opened under the complexity limit) * PDF import: move the missing-font notes out of read_opened (complexity limit after the merge) * #4569: isolate file-font resources and reclaim live faces (UNVERIFIED) * Preserve carried-font ownership across placement and recovery * Fix carried-font regression test dependencies and unwind probe * Use explicit OS2 heights in owned-font reference regression * Keep native font regression artwork inside document layers * fix(engine): bind file fonts when reading document profiles * test(engine): initialize file-font leases in new image fixtures * test: complete file-font lease initialization in image fixtures * docs: keep the #4568 entry in the file-format parity status line * fix(pdf): keep a line with another glyph for the same character as outlines (review) A font kept with the document has one glyph per character. A glyph of the file's font that differs from the one already kept for its character (a stylistic alternate that maps to the same Unicode scalar) marks its line, which is imported as outlines so each glyph draws as the file does. * docs: resolve the leftover status-line conflict * Placed document blob: give the new ImageBlob literal its file_font * Test: a PDF's two glyphs for one character survive a native save and reopen as the file draws them * Test: move the native save and reopen half of the two-glyphs regression to the engine (layers: no format dev-dep in pdf) * Fix embedded-font preference help and English fallback checks * Format embedded-font preference help with the workspace edition --------- Co-authored-by: FredApps Co-authored-by: skylartaylor --- Cargo.lock | 1 + crates/cad/src/tests.rs | 13 +- crates/doc/src/lib.rs | 8 +- crates/doc/src/links.rs | 2 +- crates/doc/src/placed_document.rs | 5 +- crates/doc/src/records.rs | 33 +- crates/doc/src/text.rs | 6 + crates/doc/src/text/char_style.rs | 4 + crates/doc/src/text/file_fonts.rs | 105 ++++ crates/doc/src/text/object.rs | 13 + crates/doc/src/text/tests.rs | 27 + .../engine/src/cmd/addons/image/mask/tests.rs | 3 +- crates/engine/src/cmd/addons/image/tests.rs | 7 +- crates/engine/src/cmd/clipboard/resources.rs | 19 +- crates/engine/src/cmd/edit.rs | 5 +- crates/engine/src/cmd/fileio.rs | 2 +- crates/engine/src/cmd/fileio/load.rs | 25 +- crates/engine/src/cmd/fileio/pdfimport.rs | 23 +- .../src/cmd/fileio/tests_pdffidelity.rs | 419 +++++++++++++++- crates/engine/src/cmd/fonts.rs | 38 +- crates/engine/src/cmd/links.rs | 2 +- crates/engine/src/cmd/newdoc.rs | 3 +- crates/engine/src/cmd/place.rs | 2 +- crates/engine/src/cmd/place/adopt.rs | 16 + crates/engine/src/cmd/place/document.rs | 7 +- crates/engine/src/cmd/prefscmds.rs | 1 + crates/engine/src/cmd/recovery.rs | 6 +- crates/engine/src/cmd/textedit.rs | 2 + crates/engine/src/prefs.rs | 16 + crates/engine/src/session/documents.rs | 7 +- crates/engine/src/tests/colorize.rs | 6 +- crates/engine/src/tests/package.rs | 11 +- crates/engine/src/tests/place.rs | 5 +- crates/engine/src/tests/prefs.rs | 20 + crates/engine/src/tests/recovery.rs | 71 +++ crates/eps/src/import/ai/read/art.rs | 4 +- crates/format/src/lib.rs | 2 +- crates/format/tests/it/save_options.rs | 4 +- crates/pdf/src/import/builder.rs | 78 ++- crates/pdf/src/import/entry.rs | 39 +- crates/pdf/src/import/state.rs | 8 + crates/pdf/src/import_fonts.rs | 162 ++++++ crates/pdf/src/import_lines.rs | 28 +- crates/pdf/src/import_text.rs | 254 ++++++---- crates/pdf/src/lib.rs | 6 + crates/pdf/src/tests.rs | 1 + crates/pdf/src/tests/cmykimages.rs | 4 +- crates/pdf/src/tests/colorize.rs | 6 +- crates/pdf/src/tests/file_fonts.rs | 276 +++++++++++ crates/pdf/src/tests/live_text.rs | 8 +- crates/render/src/tests/colorize.rs | 2 +- crates/render/src/tests/fontchange.rs | 49 ++ crates/render/src/text_geom.rs | 12 +- crates/svg/src/import/importer.rs | 2 +- crates/text/Cargo.toml | 15 +- crates/text/src/file_font.rs | 462 ++++++++++++++++++ crates/text/src/fontdb.rs | 15 + crates/text/src/fontdb/composite.rs | 7 +- crates/text/src/fontdb/db.rs | 1 + crates/text/src/fontdb/face.rs | 10 + crates/text/src/fontdb/file_fonts_tests.rs | 234 +++++++++ crates/text/src/fontdb/lookup.rs | 215 +++++++- crates/text/src/harakat.rs | 2 + crates/text/src/kept.rs | 5 +- crates/text/src/layout/driver.rs | 21 + crates/text/src/lib.rs | 4 +- crates/text/src/shape.rs | 4 + crates/text/src/test_fonts.rs | 17 +- crates/text/src/tests/composite.rs | 32 ++ crates/text/src/tests/harakat.rs | 8 +- crates/ui-egui/src/canvas/tests.rs | 2 +- crates/ui-egui/src/opening.rs | 3 +- .../ui-egui/src/prefs_dialog/descriptions.rs | 1 + crates/ui-egui/src/prefs_dialog/tests.rs | 43 +- docs/file-format-parity.md | 41 ++ docs/gaps.md | 5 + docs/mcp.md | 1 + docs/roadmap.md | 3 + docs/target-app-parity.md | 3 + docs/type-parity.md | 6 +- 80 files changed, 2822 insertions(+), 216 deletions(-) create mode 100644 crates/doc/src/text/file_fonts.rs create mode 100644 crates/pdf/src/import_fonts.rs create mode 100644 crates/pdf/src/tests/file_fonts.rs create mode 100644 crates/text/src/file_font.rs create mode 100644 crates/text/src/fontdb/file_fonts_tests.rs diff --git a/Cargo.lock b/Cargo.lock index 90cef51faf..4838f0b5e1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7254,6 +7254,7 @@ dependencies = [ "icu_segmenter", "kurbo 0.13.1", "log", + "serde_json", "skrifa 0.47.0", "subsetter", "unicode-bidi", diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index 35a1e8c45d..b2d5d4db3e 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -880,7 +880,7 @@ fn image_and_fill_doc(fill: Paint) -> Document { Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))), ] }); - d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None }); + d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None, file_font: Default::default() }); d } @@ -974,7 +974,10 @@ fn images_can_be_left_out_with_their_files() { assert_eq!(out.setting_notes, [IMAGES_OFF]); // An image that can't be decoded is not read when images are left out. let mut broken = d.clone(); - broken.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(b"not a png".to_vec()), proxy: None }); + broken.images.insert( + "raster-1".into(), + ImageBlob { mime: "image/png".into(), bytes: Arc::new(b"not a png".to_vec()), proxy: None, file_font: Default::default() }, + ); let left_out = export(&broken, &DxfOptions { include_images: false, ..opts(&broken) }).unwrap(); assert!(left_out.warnings.is_empty(), "{:?}", left_out.warnings); assert_eq!(left_out.setting_notes, [IMAGES_OFF]); @@ -1379,7 +1382,7 @@ fn images_link_png_or_jpeg_files() { }; vec![Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)))] }); - d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None }); + d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None, file_font: Default::default() }); let out = export(&d, &opts(&d)).unwrap(); let e = entities(&out); assert_eq!(kind(&e[0]), "IMAGE"); @@ -1422,7 +1425,7 @@ fn images_without_pixels_are_left_out_with_one_note() { }) .collect() }); - d.images.insert("raster-2".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(vec![]), proxy: None }); + d.images.insert("raster-2".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(vec![]), proxy: None, file_font: Default::default() }); let out = export(&d, &opts(&d)).unwrap(); assert!(entities(&out).is_empty() && out.images.is_empty()); assert_eq!(out.warnings, ["an image has no pixels and was left out"]); @@ -1583,7 +1586,7 @@ fn drawings_doc() -> Document { }); let art = path(&mut d, shapes::rectangle(Rect::new(10.0, 40.0, 30.0, 60.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(moved_by(art, 20.0)) }); - d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None }); + d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None, file_font: Default::default() }); d } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 5a9b27b304..2ee96ec2f1 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -134,10 +134,10 @@ pub use text::GlyphForm; pub use text::PATH_LEAD_MAX; pub use text::WarichuAlign; pub use text::{ - AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt, - JustificationOptions, Justify, Kinsoku, KinsokuShoriType, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, RubyAlign, - RubyPosition, RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, - VerticalAlign, WrapShape, + AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FILE_FONT_MIME, FileFont, FileFontFace, FileFonts, + FirstBaseline, HyphenationOptions, InlineArt, JustificationOptions, Justify, Kinsoku, KinsokuShoriType, LeadingModel, Mojikumi, ParaDirection, + ParaStyle, PathAlign, PathEffect, RubyAlign, RubyPosition, RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, + TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign, WrapShape, }; pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet, KinsokuSet}; pub use trace::TraceView; diff --git a/crates/doc/src/links.rs b/crates/doc/src/links.rs index b8a9998fda..eaf634eeaf 100644 --- a/crates/doc/src/links.rs +++ b/crates/doc/src/links.rs @@ -130,7 +130,7 @@ pub fn hash_reader_within(r: impl std::io::Read, max: u64) -> std::io::Result<(S impl ImageBlob { /// A blob of encoded image `bytes` of type `mime`, without a preview. pub fn new(mime: impl Into, bytes: Vec) -> Self { - Self { mime: mime.into(), bytes: Arc::new(bytes), proxy: None } + Self { mime: mime.into(), bytes: Arc::new(bytes), proxy: None, file_font: Default::default() } } /// This blob with a preview of at most [`PROXY_SIZE`] pixels a side (PNG), when the image is diff --git a/crates/doc/src/placed_document.rs b/crates/doc/src/placed_document.rs index 1d6b3e4f11..0178af8460 100644 --- a/crates/doc/src/placed_document.rs +++ b/crates/doc/src/placed_document.rs @@ -461,7 +461,7 @@ fn read_preview(p: &PlacedDocument, bytes: &Arc>) -> Option { im.key = format!("{prefix}{}", im.key); diff --git a/crates/doc/src/records.rs b/crates/doc/src/records.rs index 00c79a6d2f..481dbd57ea 100644 --- a/crates/doc/src/records.rs +++ b/crates/doc/src/records.rs @@ -154,8 +154,9 @@ pub struct Symbol { pub dynamic: bool, } -/// Encoded image bytes (PNG/JPEG/WebP…) shared by image objects. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +/// Encoded image bytes (PNG/JPEG/WebP…) shared by image objects, and the fonts files carried for +/// type ([`crate::FileFonts`], MIME [`crate::FILE_FONT_MIME`]), which save and travel the same way. +#[derive(Serialize, Deserialize)] pub struct ImageBlob { pub mime: String, #[serde(skip)] @@ -164,4 +165,32 @@ pub struct ImageBlob { /// linked images show this blob, and what `bytes` hold while the linked file can't be read. #[serde(skip)] pub proxy: Option>>, + /// Runtime ownership of an admitted font face. Image resources (including undo and clipboard + /// copies) own it; cached text nodes carry only weak references. + #[serde(skip)] + pub file_font: std::sync::Mutex>>, +} + +impl std::fmt::Debug for ImageBlob { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ImageBlob").field("mime", &self.mime).field("bytes", &self.bytes).field("proxy", &self.proxy).finish() + } +} + +impl Clone for ImageBlob { + fn clone(&self) -> Self { + let mut owner = self.file_font.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if owner.as_ref().is_some_and(|face| { + self.mime != crate::FILE_FONT_MIME || (!std::ptr::eq(face.bytes(), self.bytes.as_slice()) && face.bytes() != self.bytes.as_slice()) + }) { + *owner = None; + } + Self { mime: self.mime.clone(), bytes: self.bytes.clone(), proxy: self.proxy.clone(), file_font: std::sync::Mutex::new(owner.clone()) } + } +} + +impl PartialEq for ImageBlob { + fn eq(&self, other: &Self) -> bool { + self.mime == other.mime && self.bytes == other.bytes && self.proxy == other.proxy + } } diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 107ac1dab9..25a2451968 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -9,6 +9,7 @@ use crate::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, Li mod area; mod char_style; mod composite; +mod file_fonts; mod kinsoku_set; mod object; mod para_style; @@ -26,6 +27,7 @@ pub use composite::{ COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX, CharClass, CompositeClass, CompositeClasses, CompositeFont, CompositePart, CompositeParts, CustomCharSet, }; +pub use file_fonts::{FILE_FONT_MIME, FileFont, FileFontFace, FileFonts, MAX_FILE_FONTS, text_hash}; pub(crate) use kinsoku_set::read_sets as read_kinsoku_sets; pub use kinsoku_set::{KINSOKU_BUILT_IN, KINSOKU_CATEGORY_MAX, KINSOKU_NAME_MAX, KINSOKU_SEQUENCE, KINSOKU_SETS_MAX, KinsokuSet}; pub use para_style::{ @@ -131,6 +133,10 @@ pub struct TextObject { /// file saves the count only when it is not 0. #[serde(default, rename = "listCount", skip_serializing_if = "crate::skip::is_default")] pub list_count: u32, + /// The fonts the file this type came from carried for fonts that aren't available here, + /// which draw it until its text is edited ([`FileFonts`]); `None` for other type. + #[serde(default, rename = "fileFonts", skip_serializing_if = "Option::is_none")] + pub file_fonts: Option>, /// Threaded text: as [`Self::list_count`], the counts the earlier frames carry into this frame /// at list levels 2 on, level 2 first ([`ListCounts::from_parts`]). Empty when they are all 0, /// and the file saves them only when not empty. A file's longer list opens with the first 8. diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index a8fdfbe535..a452b605f2 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -7,6 +7,9 @@ pub struct CharStyle { pub font_family: String, #[serde(default = "regular")] pub font_style: String, + /// Internal layout selection from a validated file-font binding, never read from a file. + #[serde(skip)] + pub file_font_id: Option, /// Which installed version of the font (its version string) when several versions of the /// family and style are installed and the text was set in one the family and style alone /// wouldn't pick (an imported file's type matched to it); None = the one they pick. @@ -656,6 +659,7 @@ impl Default for CharStyle { Self { font_family: "Source Sans 3".into(), font_style: "Regular".into(), + file_font_id: None, font_version: None, font_axes: std::collections::BTreeMap::new(), size: 12.0, diff --git a/crates/doc/src/text/file_fonts.rs b/crates/doc/src/text/file_fonts.rs new file mode 100644 index 0000000000..914b529b0f --- /dev/null +++ b/crates/doc/src/text/file_fonts.rs @@ -0,0 +1,105 @@ +use std::sync::Arc; + +use serde::{Deserialize, Serialize}; + +/// The MIME type of a font a file carried ([`FileFonts`]), kept among the document's image blobs +/// ([`crate::Document::images`]). +pub const FILE_FONT_MIME: &str = "font/ttf"; + +/// The most fonts of [`FileFonts`] that draw one type object (a file's list may be longer: the rest +/// are left out). +pub const MAX_FILE_FONTS: usize = 64; + +/// The fonts a file carried for type whose fonts aren't available here (a PDF's embedded fonts), +/// kept with the document among its image blobs ([`crate::Document::images`], MIME +/// [`FILE_FONT_MIME`]). A file embeds its fonts so that readers see its text in its own fonts +/// rather than substitutes (Acrobat Help, PDF fonts, +/// ); editing text in a font that isn't +/// installed sets it in a substitute (Acrobat Help, Edit text in PDFs, +/// ). So the type is drawn in these, +/// as the file drew it, while its text is the one the file had and a font it names isn't +/// available: once its text is edited (or that font is installed) it takes the font it names, or +/// its substitute. Its runs keep naming the file's fonts, so they stay listed as missing. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct FileFonts { + /// The font kept for each family and style the runs name. + pub fonts: Vec, + /// The text as the file had it ([`text_hash`] of the plain text). + pub text: u64, + /// Validated runtime resources; serialized keys alone never authorize a font lookup. + #[serde(skip)] + resources: Vec<(String, u32, std::sync::Weak)>, +} + +impl FileFonts { + /// `fonts` for type whose text is `text`. + pub fn new(fonts: Vec, text: &str) -> Self { + Self { fonts, text: text_hash([text]), resources: vec![] } + } + + /// The runtime face bound to this reference by its owning document. + pub fn face(&self, key: &str) -> Option> { + self.resources.iter().find(|(k, _, _)| k == key).and_then(|(_, _, face)| face.upgrade()) + } + + /// Replace validated bindings, returning whether their runtime identity changed. + pub fn bind(&mut self, resources: Vec<(String, Arc)>) -> bool { + let changed = self.resources.len() != resources.len() + || self.resources.iter().zip(&resources).any(|((a, id, _), (b, face))| a != b || *id != face.id()); + self.resources = resources.into_iter().map(|(key, face)| (key, face.id(), Arc::downgrade(&face))).collect(); + changed + } + + /// Remap serialized and validated runtime resource keys together when art changes namespaces. + /// The callback applies the same mapping to each occurrence of an original key. + pub fn map_keys(&mut self, mut map: impl FnMut(&mut String)) { + for font in &mut self.fonts { + map(&mut font.key); + } + for (key, _, _) in &mut self.resources { + map(key); + } + } +} + +impl PartialEq for FileFonts { + fn eq(&self, other: &Self) -> bool { + self.fonts == other.fonts + && self.text == other.text + && self.resources.len() == other.resources.len() + && self.resources.iter().zip(&other.resources).all(|((a, aid, _), (b, bid, _))| a == b && aid == bid) + } +} + +/// A runtime file-font resource owned by image blobs, undo snapshots and clipboard resources. +/// The text engine implements this interface without making the document depend on it. +pub trait FileFontFace: Send + Sync { + fn id(&self) -> u32; + fn bytes(&self) -> &[u8]; +} + +impl std::fmt::Debug for dyn FileFontFace { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("FileFontFace").field("id", &self.id()).finish() + } +} + +/// One font of [`FileFonts`]: the family and style type names it by, and its blob. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct FileFont { + pub family: String, + pub style: String, + /// The font's blob among the document's image blobs. + pub key: String, +} + +/// A hash of the text `parts` make one after another (64-bit FNV-1a of its UTF-8 bytes): the same +/// on every machine and in every version, as a saved [`FileFonts::text`] needs. +pub fn text_hash<'a>(parts: impl IntoIterator) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for b in parts.into_iter().flat_map(str::bytes) { + h ^= u64::from(b); + h = h.wrapping_mul(0x0100_0000_01b3); + } + h +} diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index c0e305aeeb..5b213f3b08 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -1,5 +1,6 @@ use super::area::{AreaOptions, PathAlign, PathEffect}; use super::char_style::CharStyle; +use super::file_fonts::{FileFont, MAX_FILE_FONTS, text_hash}; use super::para_style::{JustificationOptions, ParaStyle}; use super::runs::{RubySpan, TextKind, TextRun, TypeAntiAlias, move_anchors, reverse_from_end}; use super::tabs_lists::{ListCounts, ParaList}; @@ -126,6 +127,7 @@ impl TextObject { system_layout: false, fractional_widths: true, list_count: 0, + file_fonts: None, list_level_counts: Vec::new(), cached_bounds: None, cached_baselines: Vec::new(), @@ -144,6 +146,17 @@ impl TextObject { pub fn plain_text(&self) -> String { self.runs.iter().map(|r| r.text.as_str()).collect() } + /// The fonts the file this type came from carried ([`FileFonts`]) while its text is still the + /// file's (at most [`MAX_FILE_FONTS`]); none once it was edited, and for other type. + pub fn file_fonts_in_use(&self) -> &[FileFont] { + match self.file_fonts.as_deref() { + Some(f) if f.text == text_hash(self.runs.iter().map(|r| r.text.as_str())) => { + f.fonts.get(..f.fonts.len().min(MAX_FILE_FONTS)).unwrap_or_default() + } + _ => &[], + } + } + /// Does layout stack some of this type's characters as warichu ([`CharStyle::warichu`])? Not /// on a path, which sets them as they are. Exports that write live text write such type as /// outlines, as they do ruby: their text can't place the stacked lines. diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index 1a3229138e..b3cff3aa47 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -801,3 +801,30 @@ fn auto_alignment_saves_readable_by_older_builds() { // Files from before the flag keep their alignment. assert_eq!(serde_json::from_str::(r#"{"justify":"Center"}"#).unwrap().justify, Justify::Center); } + +#[test] +fn file_fonts_draw_type_only_while_its_text_is_the_files() { + use super::file_fonts::*; + use super::*; + // The hash is the same everywhere and in every version (saved files carry it). + assert_eq!(text_hash([""]), 0xcbf2_9ce4_8422_2325); + assert_eq!(text_hash(["Ham", "burg"]), text_hash(["Hamburg"])); + assert_ne!(text_hash(["Hamburg"]), text_hash(["Hamburh"])); + let font = FileFont { family: "Source Serif 9".into(), style: "Regular".into(), key: "k".into() }; + let mut t = TextObject::point(Point::ZERO, "Ham", CharStyle::default()); + t.runs.push(TextRun::new("burg", CharStyle::default())); + assert!(t.file_fonts_in_use().is_empty()); + t.file_fonts = Some(Box::new(FileFonts::new(vec![font.clone()], "Hamburg"))); + assert_eq!(t.file_fonts_in_use(), std::slice::from_ref(&font)); + // Saved and read back. + let json = serde_json::to_string(&t).unwrap(); + assert!(json.contains(r#""fileFonts":{"fonts":[{"family":"Source Serif 9","style":"Regular","key":"k"}]"#), "{json}"); + assert_eq!(serde_json::from_str::(&json).unwrap(), t); + // Edited: none. + t.runs[1].text.push('s'); + assert!(t.file_fonts_in_use().is_empty()); + // A file's list past the cap: the first ones. + t.runs[1].text.pop(); + t.file_fonts.as_mut().unwrap().fonts = vec![font; MAX_FILE_FONTS + 5]; + assert_eq!(t.file_fonts_in_use().len(), MAX_FILE_FONTS); +} diff --git a/crates/engine/src/cmd/addons/image/mask/tests.rs b/crates/engine/src/cmd/addons/image/mask/tests.rs index 7fa1cd50fb..46c33a3871 100644 --- a/crates/engine/src/cmd/addons/image/mask/tests.rs +++ b/crates/engine/src/cmd/addons/image/mask/tests.rs @@ -409,7 +409,8 @@ fn a_mask_that_hides_nothing_keeps_the_link() { #[test] fn color_mask_refuses_previews_and_images_too_large() { let preview = std::sync::Arc::new(framed()); - let (mut s, id) = linked("missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) }); + let (mut s, id) = + linked("missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() }); let e = s.execute(COLOR_MASK, &hide_white()).unwrap_err().to_string(); assert!(e.contains(COLOR_MASK) && e.contains("the linked image shows its preview: embed or relink it first"), "{e}"); assert_eq!(mask_of(doc(&s), id), None); diff --git a/crates/engine/src/cmd/addons/image/tests.rs b/crates/engine/src/cmd/addons/image/tests.rs index 30673c7677..b716101144 100644 --- a/crates/engine/src/cmd/addons/image/tests.rs +++ b/crates/engine/src/cmd/addons/image/tests.rs @@ -525,7 +525,12 @@ fn a_linked_image_is_embedded_and_one_that_shows_its_preview_is_refused() { assert_eq!(im.placement, clip, "its Placement Options kept, as Embed keeps them"); // Pixels the file wasn't read for: the preview, as an image whose file is missing shows it. let preview = Arc::new(bytes); - let missing = place_linked(&mut s, "missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) }, (12, 10)); + let missing = place_linked( + &mut s, + "missing", + ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() }, + (12, 10), + ); let before = (image_of(&s, missing), undo_len(&s)); let e = s.execute(C, &json!({})).unwrap_err(); assert!(e.to_string().contains("the linked image shows its preview: embed or relink it first"), "{e}"); diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index c20c763495..79dbd6e488 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -159,6 +159,10 @@ fn node_refs(n: &Node, f: Visit) { for s in t.para_styles().filter_map(|pa| pa.style_name.as_ref()) { f(Ref::Name(Res::ParaStyle, s)); } + // The fonts its file carried travel with it, as images do. + for ff in t.file_fonts.iter().flat_map(|ff| &ff.fonts) { + f(Ref::Name(Res::Image, &ff.key)); + } } NodeKind::Image(im) => f(Ref::Name(Res::Image, &im.key)), NodeKind::PlacedDocument(pl) => f(Ref::Name(Res::Image, &pl.key)), @@ -807,6 +811,9 @@ impl Relink { if relaid { refresh_bounds(t); } + if let Some(fonts) = &mut t.file_fonts { + fonts.map_keys(|key| self.name(Res::Image, key)); + } } NodeKind::Image(im) => self.name(Res::Image, &mut im.key), NodeKind::PlacedDocument(pl) => self.name(Res::Image, &mut pl.key), @@ -1134,6 +1141,8 @@ pub(crate) struct Imported { /// `{kind, from, to}` for every resource the pasted objects now know under another name: added /// renamed, or a copy added renamed by an earlier paste. pub renamed: Vec, + /// File-font resources refused while binding pasted type. + pub warnings: Vec, /// The graph designs the pasted graphs draw with that the document has under the same name /// and that would draw them otherwise than the art they were pasted with: the document keeps /// its own, and the pasted graphs are drawn again with it. @@ -1158,13 +1167,18 @@ impl Imported { } } /// Point a pasted copy at the document's resources. A pie's legend labels in wedges that now show a color of the - /// other darkness take the contrast a redraw sets there. - pub(crate) fn apply(&self, n: &mut Node) { + /// other darkness take the contrast a redraw sets there. Fonts the copy carries are bound to the faces `d` holds. + pub(crate) fn apply(&mut self, n: &mut Node, d: &Document) { if self.relinks { let shades = super::super::graph::wedge_shades(n); self.relink.node(n); super::super::graph::follow_wedge_shades(n, &shades); } + for note in vectorcraft_text::FontDb::global().bind_node_file_fonts(n, &|key| d.images.get(key)) { + if !self.warnings.contains(¬e) { + self.warnings.push(note); + } + } } } @@ -1462,6 +1476,7 @@ impl Clipboard { && out.relink.colors.is_empty() && out.relink.kinsoku.is_empty() && used.styles.is_empty()); + out.warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(d)); Ok(out) } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index a20a6c47e4..514e6e78e1 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1552,7 +1552,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho let (ids, imported, artboards, into) = s.edit(mode.label(), |d, sel| { // Converted colors are compared with the document's resources, as another document's are // (`Clipboard::import_into`); its images are still the document's own. - let imported = clip.import_into(d, choices, same_doc)?; + let mut imported = clip.import_into(d, choices, same_doc)?; // Draw Inside: the clip group of the object drawn into, made on the first paste. let into = inside.map(|t| super::create::draw_inside_group(d, t)).transpose()?; let artboards: Vec = boards @@ -1570,7 +1570,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho let mut c = d.reid(n); // A pasted symbol set packs from the density recorded for it at Copy. d.carry_set_densities(n, &c, &clip.set_densities); - imported.apply(&mut c); + imported.apply(&mut c, d); let sc = vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() }; if xf != Affine::IDENTITY { // A cross-document drag carries the graphic's appearance with it, @@ -1698,6 +1698,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho "added": imported.added, "merged": imported.merged, "renamed": imported.renamed, + "warnings": imported.warnings, })) } diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 4fcb2bf4fc..7aca68fd02 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -79,10 +79,10 @@ pub(crate) use encode::{anti_alias, background, with_single_artboard}; pub(crate) use export::with_artboard_fills; pub(crate) use export::{EXPORT_PARAMS, export_crop, isolated}; pub use export::{export_doc, export_source, selection_doc, unused_option_notes}; +pub(crate) use load::decode_native_file; use load::err; pub(crate) use load::import_svg; pub(crate) use load::is_placeholder; -pub(crate) use load::native_file; pub(crate) use load::page_or_editing_data; pub(crate) use load::source; pub use load::{ diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 1818816842..1973c187ff 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -193,8 +193,11 @@ fn restore_or_import( let mut fallback = None; if let Some((intact, bytes)) = editing { let native = if intact { bytes() } else { None }; - match native.and_then(|b| native_file(&b).ok()) { - Some((doc, _, warnings)) => return Ok((doc, warnings, true)), + match native.and_then(|b| decode_native_file(&b).ok()) { + Some((mut doc, _, mut warnings)) => { + warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc)); + return Ok((doc, warnings, true)); + } None => fallback = Some(if intact { EDITING_DAMAGED } else { EDITING_STALE }), } } @@ -205,9 +208,9 @@ fn restore_or_import( Ok((doc, warnings, false)) } -/// A native file's document and details, the colour profiles it carries installed where missing -/// (with a warning for each that can't be used). -pub(crate) fn native_file(bytes: &[u8]) -> Result<(Document, vectorcraft_format::FileInfo, Vec)> { +/// Decode a native file and install its colour profiles, preserving profile and depth warnings. +/// The caller must assemble any external resources and bind file fonts before layout. +pub(crate) fn decode_native_file(bytes: &[u8]) -> Result<(Document, vectorcraft_format::FileInfo, Vec)> { let f = vectorcraft_format::load_file(bytes).map_err(err)?; let mut warnings = super::native::install_profiles(f.profiles); warnings.extend(f.depth_notes); @@ -424,7 +427,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result })? } "vectorcraft" | "template" => { - let (d, info, warnings) = native_file(bytes)?; + let (mut d, info, mut warnings) = decode_native_file(bytes)?; + warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut d)); native_pdf_compatible = Some(info.pdf_compatible); converted = info.is_old() || super::extension(name) == vectorcraft_format::LEGACY_EXTENSION; (d, warnings, false) @@ -688,7 +692,8 @@ pub fn open_bytes(s: &mut Session, name: &str, bytes: &[u8], path: Option, p: &Value) -> Result { let update_links = s.prefs.update_links == "automatically"; - open_read(s, read_for_open(name, bytes, path, p, update_links, s.prefs.low_res_proxy_eps)?) + let p = s.prefs.with_pdf_font_choice(p); + open_read(s, read_for_open(name, bytes, path, &p, update_links, s.prefs.low_res_proxy_eps)?) } /// A file read for `document.open` but not opened yet ([`read_for_open`], [`open_read`]). @@ -860,7 +865,11 @@ impl ReadFile { let Some((update_links, low_res_proxy_eps)) = self.links_left.take() else { return }; let base = crate::cmd::links::LinkBase::file(self.path.as_deref()); self.links = crate::cmd::links::resolve(&mut self.loaded.doc, base, update_links, low_res_proxy_eps); - Session::refresh_text_bounds(&mut self.loaded.doc); + for note in Session::refresh_text_bounds(&mut self.loaded.doc) { + if !self.loaded.warnings.contains(¬e) { + self.loaded.warnings.push(note); + } + } } /// The policies with the profile answer and the color mode `colorMode` asks for, once; the diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index ea37575135..11f7c0b3d1 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -47,6 +47,10 @@ pub struct LoadOptions { /// A `.ai` opens from its editing copy even where that draws differently from its PDF part /// (which can be older than it), with a warning, instead of from the PDF part. pub trust_editing_data: bool, + /// A PDF's type in a font it embeds and this machine lacks is drawn in the file's own glyphs + /// (default; the `embeddedFonts` param, and Preferences › File Handling › Use fonts embedded in + /// imported PDFs for opens and places that give none). + pub embedded_fonts: bool, /// The encoding names in a `.ai` or EPS's editing data are read in when they aren't UTF-8 /// (`legacyNameEncoding`). pub legacy_names: vectorcraft_eps::NameEncoding, @@ -74,6 +78,7 @@ impl Default for LoadOptions { editing_data: true, trust_editing_data: false, legacy_names: vectorcraft_eps::NameEncoding::default(), + embedded_fonts: true, native: true, link_pages: false, } @@ -84,7 +89,7 @@ impl LoadOptions { /// From command params: `pages` (`"2-3, 5"`, a page number or `"all"`), `page` (one page, when /// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`, /// `textAs` (`text` | `outlines`), `layers` (true | false), `hiddenLayers` (true | false), - /// `importSlices` (true | false), `editingData` (true | false | `always`), + /// `importSlices` (true | false), `editingData` (true | false | `always`), `embeddedFonts` (true | false), /// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]), `linkPages` (true | /// false) and `dxf` (the DXF import options). pub fn from_params(cmd: &str, p: &Value) -> Result { @@ -135,6 +140,10 @@ impl LoadOptions { Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "linkPages must be true or false"))?, }; let dxf = super::dxfimport::options(cmd, p.get("dxf"))?; + let embedded_fonts = match p.get("embeddedFonts").filter(|v| !v.is_null()) { + None => true, + Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "embeddedFonts must be true or false"))?, + }; Ok(Self { pages, crop, @@ -148,6 +157,7 @@ impl LoadOptions { dxf, editing_data, trust_editing_data, + embedded_fonts, legacy_names, native: true, link_pages, @@ -177,6 +187,7 @@ impl LoadOptions { text_as: self.text_as, layers: self.layers, uncalibrated_rgb: editor_document, + embedded_fonts: self.embedded_fonts, ..Default::default() }) } @@ -219,7 +230,15 @@ pub(crate) fn opened_page_document(bytes: &[u8], opened: &vectorcraft_pdf::Opene /// The import options of [`page_document`]. fn page_options(page: usize, o: &LoadOptions) -> ImportOptions { - ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() } + ImportOptions { + pages: Some(vec![page]), + crop: o.crop, + password: o.password.clone(), + text_as: o.text_as, + layers: false, + embedded_fonts: o.embedded_fonts, + ..Default::default() + } } /// Whether `document.open`'s `linkPages` takes the file `name` holding `bytes`: a PDF or a diff --git a/crates/engine/src/cmd/fileio/tests_pdffidelity.rs b/crates/engine/src/cmd/fileio/tests_pdffidelity.rs index d3d8a988f8..2541225a79 100644 --- a/crates/engine/src/cmd/fileio/tests_pdffidelity.rs +++ b/crates/engine/src/cmd/fileio/tests_pdffidelity.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::NodeKind; use vectorcraft_pdf::TextAs; -use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf, pdf_with_catalog}; +use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf, pdf_with, pdf_with_catalog}; use super::*; @@ -135,11 +135,12 @@ fn ai_layer_names_are_read_as_pdf_doc_encoding() { #[test] fn load_options_read_text_and_layers() { - let o = LoadOptions::from_params("x", &json!({"textAs": "Outlines", "layers": false})).unwrap(); - assert_eq!((o.text_as, o.layers), (TextAs::Outlines, false)); + let o = LoadOptions::from_params("x", &json!({"textAs": "Outlines", "layers": false, "hiddenLayers": true, "embeddedFonts": false})).unwrap(); + assert_eq!((o.text_as, o.layers, o.hidden_layers, o.embedded_fonts), (TextAs::Outlines, false, true, false)); assert!(o.is_partial(), "without its hidden layers, Save doesn't write the file back"); let d = LoadOptions::default(); assert_eq!((d.text_as, d.layers, d.is_partial()), (TextAs::Text, true, false)); + assert_eq!((d.hidden_layers, d.embedded_fonts), (false, true)); let n = LoadOptions { native: false, ..Default::default() }; assert!(n.is_partial(), "without the document it carries, Save doesn't write the file back"); } @@ -180,3 +181,415 @@ fn exports_that_draw_type_in_a_missing_font_say_it_is_the_fallback_font() { s.execute("text.replaceFont", &json!({"from": {"family": family}, "to": {"family": "Source Serif 4"}})).unwrap(); assert!(!warned(&mut s, json!({"format": "pdf"})), "replaced: nothing is substituted"); } + +/// A page in a font the file carries that no machine has (`Zyxwvu-Serif`: a +/// simple TrueType font in WinAnsiEncoding, its program the bundled Source Serif 4's). +fn carried_font_pdf(content: &str, height: f64) -> Vec { + let data = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSerif4-Regular.ttf")).unwrap(); + let face = vectorcraft_text::FontDb::global().face("Source Serif 4", "Regular").unwrap(); + let widths: Vec = + (32u8..=126).map(|c| format!("{:.0}", face.advance(face.glyph_for(char::from(c))) * 1000.0 / face.units_per_em())).collect(); + let hex: String = data.iter().map(|b| format!("{b:02x}")).collect(); + let n = first_extra(1); + let page = PdfPage { resources: format!("/Font << /F1 {n} 0 R >>"), ..PdfPage::new(300.0, height, content) }; + let font = format!( + "<< /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+Zyxwvu-Serif /FirstChar 32 /LastChar 126 /Widths [{}] /Encoding /WinAnsiEncoding /FontDescriptor {} 0 R >>", + widths.join(" "), + n + 1 + ); + let descriptor = format!( + "<< /Type /FontDescriptor /FontName /ABCDEF+Zyxwvu-Serif /Flags 34 /FontBBox [-500 -300 1500 1000] /ItalicAngle 0 /Ascent 900 /Descent -300 /CapHeight 660 /StemV 80 /FontFile2 {} 0 R >>", + n + 2 + ); + let file = format!("<< /Length {} /Filter /ASCIIHexDecode >>\nstream\n{hex}>\nendstream", hex.len() + 1); + pdf_with(&[page], &[&font, &descriptor, &file], None) +} + +/// The glyphs of the active document's type (document space origins) and how many come from fonts +/// files carried. +fn glyphs(s: &Session) -> (Vec, usize) { + let db = vectorcraft_text::FontDb::global(); + let (mut at, mut carried) = (vec![], 0); + s.doc().unwrap().doc.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + for g in vectorcraft_text::layout(db, t).glyphs { + at.push(t.xf * g.origin); + carried += usize::from(db.is_file_font(g.font_id)); + } + } + }); + (at, carried) +} + +/// Type in a font the PDF carries that isn't installed keeps the file's look until it is edited: +/// no export says it is substituted, it saves and reopens so, and it stays listed as missing. Edited, +/// it takes the substitute, which exports then name. +#[test] +fn type_in_a_font_the_pdf_carries_keeps_its_look_until_edited() { + let mut s = Session::new(); + let r = open(&mut s, &carried_font_pdf("BT /F1 24 Tf 20 50 Td (Hamburg Zoo) Tj ET", 100.0), json!({})).unwrap(); + let fonts = s.execute("text.fonts", &json!({})).unwrap(); + let family = fonts[0]["family"].as_str().unwrap().to_string(); + assert_eq!(fonts[0]["status"], "missing", "{fonts}"); + assert!(r["warnings"].to_string().contains("until their text is edited"), "{r}"); + let missing = s.execute("text.missingFonts", &json!({})).unwrap(); + assert!(missing["fonts"].to_string().contains(&family), "still missing: {missing}"); + let (at, carried) = glyphs(&s); + assert_eq!((at.len(), carried), (11, 11), "every glyph the file's"); + let warned = |s: &mut Session| s.execute("document.serialize", &json!({"format": "png"})).unwrap()["warnings"].to_string().contains(&family); + assert!(!warned(&mut s), "drawn as the file draws it: not substituted"); + // Saved and opened again: the same. + let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string(); + s.execute("document.open", &json!({"name": "kept.vectorcraft", "dataBase64": native})).unwrap(); + assert_eq!(glyphs(&s), (at.clone(), carried)); + // Edited: the substitute, which exports name, and the font still missing. + let mut id = None; + s.doc().unwrap().doc.walk(|n| { + if matches!(n.kind, NodeKind::Text(_)) { + id = Some(n.id); + } + }); + let id = id.unwrap(); + let preflight = |s: &mut Session| s.execute("document.preflight", &json!({})).unwrap()["findings"].clone(); + assert!(!preflight(&mut s).to_string().contains(&family), "carried font is not substituted"); + s.execute("text.setText", &json!({"id": id, "text": "Hamburg Zoo!"})).unwrap(); + assert_eq!(glyphs(&s).1, 0, "edited: no glyph from the file's font"); + assert!(warned(&mut s), "edited: substituted"); + let findings = preflight(&mut s); + assert!( + findings.as_array().unwrap().iter().any(|f| f["code"] == "missingFont" + && f["name"].as_str().is_some_and(|n| n.contains(&family)) + && f["ids"].as_array().is_some_and(|ids| ids.contains(&json!(id.0)))), + "preflight identifies the substituted text owner: {findings}" + ); + assert!(s.execute("text.missingFonts", &json!({})).unwrap()["fonts"].to_string().contains(&family)); + // Undone: the file's look again. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(glyphs(&s), (at, carried)); + assert!(!preflight(&mut s).to_string().contains(&family), "undo restores the carried font"); +} + +#[test] +fn wrapped_carried_font_keeps_pdf_positions_after_native_reopen() { + let db = vectorcraft_text::FontDb::global(); + let serif = db.face("Source Serif 4", "Regular").unwrap(); + let fallback = db.face(vectorcraft_text::FALLBACK_FAMILY, "Regular").unwrap(); + let advance = |face: &vectorcraft_text::FontFace| face.advance(face.glyph_for('H')) / face.units_per_em(); + assert!((advance(&serif) - advance(&fallback)).abs() > 0.01, "fixture must differ from the substitute"); + let content = "BT /F1 24 Tf 20 160 Td (Hamburg Zoo ) Tj ET BT /F1 24 Tf 20 100 Td (Hamburg Zoo ) Tj ET BT /F1 24 Tf 20 40 Td (Hamburg Zoo) Tj ET"; + let bytes = carried_font_pdf(content, 200.0); + let mut reference = Session::new(); + open(&mut reference, &bytes, json!({"textAs": "outlines"})).unwrap(); + let want = glyph_ink(&reference, false); + assert_eq!(want.len(), 3); + let mut s = Session::new(); + open(&mut s, &bytes, json!({})).unwrap(); + let compare = |s: &Session| { + let mut areas = 0; + s.doc().unwrap().doc.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + assert!(matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }), "wrapped text must stay one area"); + assert_eq!(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).lines.len(), 3); + areas += 1; + } + }); + assert_eq!(areas, 1); + let got = glyph_ink(s, false); + assert_eq!(got.len(), want.len()); + for (got, want) in got.iter().zip(&want) { + let off = (got.x0 - want.x0).abs().max((got.x1 - want.x1).abs()).max((got.y0 - want.y0).abs()).max((got.y1 - want.y1).abs()); + assert!(off < 0.25, "{got:?} is {off} pt from {want:?}"); + } + }; + compare(&s); + let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string(); + s.execute("document.open", &json!({"name": "wrapped.vectorcraft", "dataBase64": native})).unwrap(); + compare(&s); +} + +fn owned_font_document(family: &str, width: f64) -> (vectorcraft_doc::Document, vectorcraft_doc::ImageBlob, vectorcraft_doc::NodeId) { + use kurbo::{Point, Rect, Shape}; + use vectorcraft_doc::{CharStyle, Document, FILE_FONT_MIME, FileFont, FileFonts, ImageBlob, Node, TextObject}; + use vectorcraft_text::{FileFontInfo, FileGlyph, build_file_font}; + + let info = FileFontInfo { family: family.into(), style: "Regular".into(), ..Default::default() }; + let g = FileGlyph { ch: 'x', outline: Rect::new(0.0, 0.0, width, 700.0).to_path(0.1), advance: width + 100.0 }; + let blob = ImageBlob::new(FILE_FONT_MIME, build_file_font(&info, &[g]).unwrap()); + let mut doc = Document::new(100.0, 100.0); + doc.images.insert("chosen".into(), blob.clone()); + let mut t = TextObject::point(Point::new(10.0, 40.0), "x", CharStyle { font_family: family.into(), size: 20.0, ..Default::default() }); + t.file_fonts = Some(Box::new(FileFonts::new(vec![FileFont { family: family.into(), style: "Regular".into(), key: "chosen".into() }], "x"))); + let id = doc.alloc_id(); + doc.insert(Some(doc.layers[0].id), usize::MAX, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap(); + (doc, blob, id) +} + +/// No machine fonts are needed: the two native documents own different synthetic glyphs under +/// the same key. Paste must relink its own bytes, including after closing the source tab. +#[test] +fn owned_file_fonts_survive_native_open_close_clipboard_undo_and_export() { + use vectorcraft_doc::Document; + use vectorcraft_text::FontDb; + + const FAMILY: &str = "Native Owned File Font Regression"; + let open_native = |s: &mut Session, doc: &Document| { + let bytes = vectorcraft_format::save_file(doc); + s.execute("document.open", &json!({"name": "font.vectorcraft", "dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap() + }; + let face_of = |s: &Session, id| { + let NodeKind::Text(t) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("text") }; + let g = &vectorcraft_text::layout(FontDb::global(), t).glyphs[0]; + FontDb::global().face_by_id(g.font_id).unwrap() + }; + let (a, a_blob, a_id) = owned_font_document(FAMILY, 200.0); + let (b, b_blob, b_id) = owned_font_document(FAMILY, 800.0); + let mut s = Session::new(); + open_native(&mut s, &a); + let a_index = s.active_index().unwrap(); + assert_eq!(face_of(&s, a_id).file_data(), a_blob.bytes.as_slice()); + open_native(&mut s, &b); + let b_index = s.active_index().unwrap(); + let carried = face_of(&s, b_id).id(); + assert_eq!(face_of(&s, b_id).file_data(), b_blob.bytes.as_slice()); + s.execute("select.set", &json!({"ids": [b_id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + assert!(s.close_document(b_index)); + assert!(s.set_active(a_index)); + let pasted = s.execute("edit.pasteInPlace", &json!({})).unwrap(); + assert!(pasted["warnings"].as_array().unwrap().is_empty(), "{pasted}"); + assert!(pasted["renamed"].as_array().unwrap().iter().any(|v| v["kind"] == "image" && v["from"] == "chosen")); + let id = vectorcraft_doc::NodeId(pasted["ids"][0].as_u64().unwrap()); + assert_eq!(face_of(&s, id).id(), carried); + assert_eq!(face_of(&s, id).file_data(), b_blob.bytes.as_slice()); + assert_eq!(face_of(&s, a_id).file_data(), a_blob.bytes.as_slice()); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(face_of(&s, id).file_data(), b_blob.bytes.as_slice()); + for options in [json!({"format": "pdf", "advanced": {"outlineText": false}}), json!({"format": "svg", "embedFonts": true})] { + let svg = options["format"] == "svg"; + let exported = s.execute("document.serialize", &options).unwrap(); + if svg { + let text = exported["text"].as_str().unwrap(); + assert_eq!(text.matches("@font-face").count(), 2, "both distinct owned faces are embedded"); + } else { + let bytes = vectorcraft_format::base64_decode(exported["dataBase64"].as_str().unwrap()).unwrap(); + assert!(bytes.starts_with(b"%PDF-")); + } + // SVG may warn that the same CSS description cannot distinguish these two x glyphs. + assert!(!exported["warnings"].to_string().contains(vectorcraft_text::FALLBACK_FAMILY), "{exported}"); + } + let saved = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap(); + s.execute("document.open", &json!({"name": "pasted.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap(); + assert_eq!(face_of(&s, id).file_data(), b_blob.bytes.as_slice()); + assert_eq!(face_of(&s, a_id).file_data(), a_blob.bytes.as_slice()); + + let mut unowned = b.clone(); + unowned.images.clear(); + let report = open_native(&mut s, &unowned); + assert!(report["warnings"].to_string().contains(FAMILY)); + assert_eq!(glyphs(&s).1, 0, "a metadata-only reference cannot borrow any open document's font"); +} + +/// Place owns its carried font even after the decoded source is dropped, whether the destination +/// reuses an equal unbound blob or renames a key occupied by another font. +#[test] +fn placed_fonts_keep_owned_bytes_after_resource_reuse_or_name_collision() { + use vectorcraft_doc::Document; + use vectorcraft_text::FontDb; + + const FAMILY: &str = "Placed Owned Font Regression"; + let (source, expected, _) = owned_font_document(FAMILY, 200.0); + let bytes = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&source)); + for same_bytes in [true, false] { + let mut host = Document::new(100.0, 100.0); + let blob = if same_bytes { expected.clone() } else { owned_font_document(FAMILY, 800.0).1 }; + host.images.insert("chosen".into(), blob); + let mut s = Session::new(); + s.add_document(host, None); + let placed = s.execute("file.place", &json!({"name": "font.vectorcraft", "dataBase64": bytes, "link": false})).unwrap(); + assert!(placed["warnings"].as_array().unwrap().is_empty(), "{placed}"); + let check = |s: &Session| { + let db = FontDb::global(); + let mut drawn = 0; + s.doc().unwrap().doc.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + for g in vectorcraft_text::layout(db, t).glyphs { + assert!(db.is_file_font(g.font_id), "the destination, not a source cache, owns the font"); + assert_eq!(db.face_by_id(g.font_id).unwrap().file_data(), expected.bytes.as_slice()); + drawn += 1; + } + } + }); + assert_eq!(drawn, 1); + }; + check(&s); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(glyphs(&s).1, 0); + s.execute("edit.redo", &json!({})).unwrap(); + check(&s); + let saved = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap(); + let reopened = s.execute("document.open", &json!({"name": "placed.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap(); + assert!(reopened["warnings"].as_array().unwrap().is_empty(), "{reopened}"); + check(&s); + } +} + +fn linked_owned_font_document(family: &str) -> (vectorcraft_doc::Document, vectorcraft_doc::ImageBlob, vectorcraft_doc::NodeId) { + use kurbo::Affine; + use vectorcraft_doc::{Document, ImageBlob, LinkInfo, Node, PlacedDocument}; + + let (source, expected, _) = owned_font_document(family, 200.0); + let bytes = vectorcraft_format::save_file(&source); + let blob = ImageBlob::new("application/json", bytes); + let key = format!("placed-font-{}", blob.content_key()); + let mut host = Document::new(100.0, 100.0); + host.images.insert("chosen".into(), owned_font_document(family, 800.0).1); + host.images.insert(key.clone(), blob); + let placed = PlacedDocument { + key, + link: LinkInfo::new("/font-placement-regression.vectorcraft"), + bounding: false, + page_box: Default::default(), + width: 100.0, + height: 100.0, + xf: Affine::IDENTITY, + placement: Default::default(), + }; + let id = host.alloc_id(); + host.insert(Some(host.layers[0].id), usize::MAX, Node::new(id, NodeKind::PlacedDocument(Box::new(placed)))).unwrap(); + (host, expected, id) +} + +/// Break Link and older-version saves must preserve the placed file's own bytes rather than bind +/// text to the host's unrelated font under the same key when reopened. +#[test] +fn placed_carried_fonts_survive_break_link_and_older_version_save() { + use vectorcraft_text::FontDb; + + for break_link in [true, false] { + let family = if break_link { "Break Link Owned Font Regression" } else { "Older Save Owned Font Regression" }; + let (host, expected, id) = linked_owned_font_document(family); + let mut s = Session::new(); + s.add_document(host, None); + if break_link { + let embedded = s.execute("links.embed", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(embedded["embedded"], json!([id.0]), "{embedded}"); + assert_eq!(glyphs(&s).1, 1); + } + let version = if break_link { vectorcraft_format::VERSION } else { vectorcraft_format::VERSION - 1 }; + let saved = s.execute("document.serialize", &json!({"format": "vectorcraft", "version": version, "preview": false})).unwrap(); + let reopened = s.execute("document.open", &json!({"name": "placed-font.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap(); + assert!(reopened["warnings"].as_array().unwrap().is_empty(), "{reopened}"); + let db = FontDb::global(); + let mut drawn = 0; + s.doc().unwrap().doc.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + for g in vectorcraft_text::layout(db, t).glyphs { + assert!(db.is_file_font(g.font_id)); + assert_eq!(db.face_by_id(g.font_id).unwrap().file_data(), expected.bytes.as_slice(), "{family}"); + drawn += 1; + } + } + }); + assert_eq!(drawn, 1, "{family}"); + assert!(!s.doc().unwrap().doc.has_placed(), "the reopened art is editable, not a linked source"); + } +} + +/// Glyphs `a`, `b`, `a` in an unavailable carried font, all named `a` by ToUnicode. +fn two_glyphs_for_one_character_pdf(content: &str) -> Vec { + let data = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSerif4-Regular.ttf")).unwrap(); + let face = vectorcraft_text::FontDb::global().face("Source Serif 4", "Regular").unwrap(); + let widths: Vec = + (32u8..=126).map(|c| format!("{:.0}", face.advance(face.glyph_for(char::from(c))) * 1000.0 / face.units_per_em())).collect(); + let hex: String = data.iter().map(|b| format!("{b:02x}")).collect(); + let n = first_extra(1); + let page = PdfPage { resources: format!("/Font << /F1 {n} 0 R >>"), ..PdfPage::new(400.0, 200.0, content) }; + let font = format!( + "<< /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+Zyxwvu-Serif /FirstChar 32 /LastChar 126 /Widths [{}] /Encoding /WinAnsiEncoding /FontDescriptor {} 0 R /ToUnicode {} 0 R >>", + widths.join(" "), + n + 1, + n + 3 + ); + let descriptor = format!( + "<< /Type /FontDescriptor /FontName /ABCDEF+Zyxwvu-Serif /Flags 34 /FontBBox [-500 -300 1500 1000] /ItalicAngle 0 /Ascent 900 /Descent -300 /CapHeight 660 /StemV 80 /FontFile2 {} 0 R >>", + n + 2 + ); + let file = format!("<< /Length {} /Filter /ASCIIHexDecode >>\nstream\n{hex}>\nendstream", hex.len() + 1); + let cmap = "/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <00> endcodespacerange 2 beginbfchar <61> <0061> <62> <0061> endbfchar endcmap CMapName currentdict /CMap defineresource pop end end"; + let tounicode = format!("<< /Length {} >>\nstream\n{cmap}\nendstream", cmap.len() + 1); + pdf_with(&[page], &[&font, &descriptor, &file, &tounicode], None) +} + +/// The three glyph ink boxes, grouped by x for the TJ fixture or by y for separate lines. +fn glyph_ink(s: &Session, across: bool) -> Vec { + use kurbo::Shape; + let db = vectorcraft_text::FontDb::global(); + let mut lines: [Option; 3] = [None; 3]; + let mut add = |path: &kurbo::BezPath| { + let els = path.elements(); + let mut start = 0; + for end in (1..=els.len()).filter(|&e| e == els.len() || matches!(els[e], kurbo::PathEl::MoveTo(_))) { + let ink = kurbo::BezPath::from_vec(els[start..end].to_vec()).bounding_box(); + let line = if across { + usize::from(ink.center().x > 90.0) + usize::from(ink.center().x > 230.0) + } else { + usize::from(ink.center().y > 70.0) + usize::from(ink.center().y > 130.0) + }; + lines[line] = Some(lines[line].map_or(ink, |l| l.union(ink))); + start = end; + } + }; + s.doc().unwrap().doc.walk(|n| match &n.kind { + NodeKind::Text(t) => vectorcraft_text::layout(db, t).glyphs.iter().for_each(|g| add(&(t.xf * g.outline.clone()))), + NodeKind::Path { path, .. } => add(&path.to_bezpath()), + _ => {} + }); + lines.into_iter().flatten().collect() +} + +/// Two different glyphs of a carried font for one character can't both go into the font kept with +/// the document, which has one glyph per character, so the line with the other glyph is outlines. +/// Opened, saved in the native format and opened again, each glyph is still the one the file draws, +/// where it draws it: the same page opened as outlines is the reference. +#[test] +fn two_glyphs_for_one_character_survive_a_native_save_and_reopen() { + let content = "BT /F1 30 Tf 20 160 Td (a) Tj ET BT /F1 30 Tf 20 100 Td (b) Tj ET BT /F1 30 Tf 20 40 Td (a) Tj ET"; + assert_carried_glyph_roundtrip(content, false); +} + +#[test] +fn conflicting_carried_glyphs_in_a_filled_and_stroked_tj_survive_native_reopen() { + let content = "BT 2 Tr /F1 30 Tf 20 100 Td [(a) -3500 (b) -3500 (a)] TJ 0 Tr ET"; + assert_carried_glyph_roundtrip(content, true); +} + +fn assert_carried_glyph_roundtrip(content: &str, across: bool) { + let bytes = two_glyphs_for_one_character_pdf(content); + let mut reference_session = Session::new(); + open(&mut reference_session, &bytes, json!({"textAs": "outlines"})).unwrap(); + let reference = glyph_ink(&reference_session, across); + assert_eq!(reference.len(), 3, "the file draws three glyphs: {reference:?}"); + assert!((reference[0].height() - reference[1].height()).abs() > 2.0, "the file's two glyphs differ in shape: {reference:?}"); + assert!((reference[0].height() - reference[2].height()).abs() < 0.01, "the first and third are the same glyph: {reference:?}"); + + let mut s = Session::new(); + open(&mut s, &bytes, json!({})).unwrap(); + assert!( + live_texts(&s).iter().any(|t| t == "a") && live_texts(&s).len() < 3, + "some glyphs stay type, the other is outlines: {:?}", + live_texts(&s) + ); + let close = |s: &Session, what: &str| { + let got = glyph_ink(s, across); + assert_eq!(got.len(), reference.len(), "{what}: {got:?}"); + for (got, want) in got.iter().zip(&reference) { + let off = (got.x0 - want.x0).abs().max((got.x1 - want.x1).abs()).max((got.y0 - want.y0).abs()).max((got.y1 - want.y1).abs()); + assert!(off < 0.25, "{what}: {got:?} is {off} pt from the file's {want:?}"); + } + }; + close(&s, "opened"); + let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string(); + s.execute("document.open", &json!({"name": "kept.vectorcraft", "dataBase64": native})).unwrap(); + close(&s, "saved and reopened"); +} diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index ef7420217b..5f9b0ec5b0 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -484,10 +484,17 @@ pub(super) fn used_fonts(d: &Document) -> BTreeSet { /// in `art` (art read from a file, its resources in `d`), the type in opacity masks included. The /// pattern being edited is read from the editing layer only. pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet { + fonts_of(d, art, false) +} + +/// [`art_fonts`]; `drawn`: only those the type is drawn in, not the fonts of runs drawn in a font +/// their file carried ([`in_file_fonts`]). +fn fonts_of(d: &Document, art: &[Node], drawn: bool) -> BTreeSet { let mut fonts = BTreeSet::new(); let mut add = |n: &Node| { if let NodeKind::Text(t) = &n.kind { - fonts.extend(t.runs.iter().flat_map(run_fonts)); + let file = if drawn { in_file_fonts(t) } else { vec![] }; + fonts.extend(t.runs.iter().filter(|r| !file.contains(&(r.style.font_family.as_str(), r.style.font_style.as_str()))).flat_map(run_fonts)); } }; let patterns = d.patterns.iter().filter(|p| !pattern_being_edited(d, &p.name)).flat_map(|p| p.art.iter().map(|a| &**a)); @@ -659,21 +666,25 @@ impl<'a> Printed<'a> { } } match &n.kind { - NodeKind::Text(_) => { + NodeKind::Text(t) => { if overflows && self.own { self.overflow.insert(n.id); } if overflows && let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) { p.overflow.insert(owner); } + let file = in_file_fonts(t); for r in runs { - let fonts = run_fonts(r); - if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) { - for font in &fonts { - p.fonts.entry(font.clone()).or_default().insert(owner); + // Drawn in a font its file carried: printed as the file drew it. + if !file.contains(&(r.style.font_family.as_str(), r.style.font_style.as_str())) { + let fonts = run_fonts(r); + if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) { + for font in &fonts { + p.fonts.entry(font.clone()).or_default().insert(owner); + } } + self.fonts.extend(fonts); } - self.fonts.extend(fonts); // Inline graphics draw their symbols' art. if let Some(art) = r.inline.as_ref().filter(|_| draws_inline(r)) { self.symbol(&art.symbol); @@ -757,9 +768,18 @@ fn drawn_runs(t: &vectorcraft_doc::TextObject) -> (Vec<&TextRun>, bool) { /// What an export that draws type (as outlines, embedded fonts or pixels) says when `d` uses font /// families that aren't available (their type is drawn in the fallback font, not the font it -/// names) or styles that its family doesn't have (the closest style is drawn). +/// names) or styles that its family doesn't have (the closest style is drawn). Type drawn in a +/// font its file carried isn't substituted. pub(super) fn substitution_warning(d: &Document) -> Option { - substitution_warning_of(used_fonts(d)) + substitution_warning_of(fonts_of(d, &[], true)) +} + +/// The families and styles of the runs of `t` drawn in a font its file carried +/// ([`vectorcraft_text::FontDb::file_faces`]): drawn as the file drew them, not in a substitute, +/// though the font they name isn't available. +fn in_file_fonts(t: &vectorcraft_doc::TextObject) -> Vec<(&str, &str)> { + let faces = vectorcraft_text::FontDb::global().file_faces(t); + t.runs.iter().zip(faces).filter(|(_, f)| f.is_some()).map(|(r, _)| (r.style.font_family.as_str(), r.style.font_style.as_str())).collect() } /// [`substitution_warning`] for type set in `fonts`. diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 29da4d0524..fd76896ce3 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -563,7 +563,7 @@ pub(crate) fn full_linked_images<'a>(d: &'a Document, base: LinkBase) -> (Cow<'a Some(f) if img.blob.bytes.as_slice() == bytes.as_slice() => f.mime.to_string(), _ => img.blob.mime.clone(), }; - out.images.insert(key, ImageBlob { mime, bytes: img.blob.bytes, proxy: preview }); + out.images.insert(key, ImageBlob { mime, bytes: img.blob.bytes, proxy: preview, file_font: Default::default() }); } let mut warnings = vec![]; match previews.len() { diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index e74a570a5b..97438ec6b1 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -960,10 +960,11 @@ impl Session { let bytes = crate::store::read_capped(&path, MAX_PROFILE_BYTES)?; // The color profiles the file carries are installed where missing, as opening it installs // them, so the new document's assigned profiles draw and are saved with it. - let (mut doc, _, warnings) = super::fileio::native_file(&bytes).map_err(|e| e.to_string())?; + let (mut doc, _, mut warnings) = super::fileio::decode_native_file(&bytes).map_err(|e| e.to_string())?; // Linked images in its symbols, patterns and brushes are read from their files, as placing // a document reads them. super::links::resolve(&mut doc, super::links::LinkBase::file(Some(&file)), false, false); + warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc)); Ok(Some(ReadProfile { doc, file, warnings })) } } diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index fef99cc9c3..a1a42a9acd 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -786,7 +786,7 @@ fn prepare(s: &Session, p: &Value) -> Result { (true, _) => return Err(bad(PLACE, "replace: select the one object to replace")), }; let replaced = old.and_then(|id| st.doc.node(id)).cloned(); - Ok(PlaceJob { doc: st.uid, params: p.clone(), old, replaced, target: board_at(&st.doc, at) }) + Ok(PlaceJob { doc: st.uid, params: s.prefs.with_pdf_font_choice(p), old, replaced, target: board_at(&st.doc, at) }) } /// Place the file `read` holds in the active document. diff --git a/crates/engine/src/cmd/place/adopt.rs b/crates/engine/src/cmd/place/adopt.rs index 9cd28b7e25..f64a6a6874 100644 --- a/crates/engine/src/cmd/place/adopt.rs +++ b/crates/engine/src/cmd/place/adopt.rs @@ -72,6 +72,9 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) { paint_refs(&mut r.style.fill, f); paint_refs(&mut r.style.stroke, f); } + if let Some(fonts) = &mut t.file_fonts { + fonts.map_keys(|key| f(Ref::Image(key))); + } } NodeKind::Image(im) => f(Ref::Image(&mut im.key)), NodeKind::PlacedDocument(pl) => f(Ref::Image(&mut pl.key)), @@ -352,6 +355,19 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { dst.images.insert(new.to_string(), blob.clone()); } } + // Equal font bytes can reuse an existing image entry whose runtime lease is still empty. + // Transfer the validated source lease too: cached text nodes hold only weak references. + for (old, (new, copy)) in &images { + if *copy { + continue; + } + let Some(blob) = src.images.get(old).filter(|b| b.mime == vectorcraft_doc::FILE_FONT_MIME) else { continue }; + let Some(target) = new.as_ref().and_then(|key| dst.images.get_mut(key)) else { continue }; + let owner = blob.file_font.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(face) = owner.as_ref().filter(|face| std::ptr::eq(face.bytes(), blob.bytes.as_slice()) || face.bytes() == blob.bytes.as_slice()) { + *target.file_font.get_mut().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(face.clone()); + } + } for (old, new) in copies(&symbols) { if let Some(mut def) = src.symbols.iter().find(|s| s.name == old).cloned() { def.name = new.to_string(); diff --git a/crates/engine/src/cmd/place/document.rs b/crates/engine/src/cmd/place/document.rs index 31ab486a80..ce90a79649 100644 --- a/crates/engine/src/cmd/place/document.rs +++ b/crates/engine/src/cmd/place/document.rs @@ -333,7 +333,7 @@ fn read_source( } let a = opened_document_art(name, (bytes, opened), path, page, bounding, page_box, cmd)?; let bytes = shared.cloned().unwrap_or_else(|| Arc::new(bytes.to_vec())); - let mut blob = ImageBlob { mime: mime(name, &bytes).into(), bytes, proxy: None }; + let mut blob = ImageBlob { mime: mime(name, &bytes).into(), bytes, proxy: None, file_font: Default::default() }; let shown = PlacedDocument { link: LinkInfo { page: Some(page), ..LinkInfo::new(path.unwrap_or(name)) }, key: key.clone(), @@ -468,7 +468,10 @@ pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec) { let Some(blob) = out.images.get(&p.key) else { continue }; match vectorcraft_doc::placed_document::full_bytes(&p, blob) { Some(bytes) => { - out.images.insert(p.key.clone(), ImageBlob { mime: mime(p.link.name(), &bytes).into(), bytes, proxy: blob.proxy.clone() }); + out.images.insert( + p.key.clone(), + ImageBlob { mime: mime(p.link.name(), &bytes).into(), bytes, proxy: blob.proxy.clone(), file_font: Default::default() }, + ); } None => { previews.insert(p.key); diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 46cdee28a5..81a26dd46e 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -396,6 +396,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("recoveryOffForComplex", "File Handling", "Data Recovery", "Turn off Data Recovery for complex documents", bool), p!("recentFilesCount", "File Handling", "Files", "Number of Recent Files to Display", int(0, 30)), p!("lowResProxyEps", "File Handling", "Files", "Use Low Resolution Proxy for Linked EPS", bool), + p!("pdfImportEmbeddedFonts", "File Handling", "Files", "Use fonts embedded in imported PDFs", bool), p!("antiAliasedBitmaps", "File Handling", "Files", "Display Bitmaps as Anti-aliased Images in Pixel Preview", bool), p!( "updateLinks", diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index 193e86b600..5a70d49ab7 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -1458,7 +1458,7 @@ fn restore_one(s: &mut Session, store: &Arc, file: &str) -> R let bytes = store.read(&format!("{file}{DOC_EXT}")).map_err(EngineError::Other)?; let meta_bytes = store.read(&format!("{file}{META_EXT}")).unwrap_or_default(); let meta: Meta = serde_json::from_slice(&meta_bytes).unwrap_or_default(); - let (mut doc, _, mut warnings) = fileio::native_file(&bytes).map_err(|e| EngineError::Other(format!("recovery copy `{file}`: {e}")))?; + let (mut doc, _, mut warnings) = fileio::decode_native_file(&bytes).map_err(|e| EngineError::Other(format!("recovery copy `{file}`: {e}")))?; // A frame whose first paragraph continues from the frame before draws it without the // paragraph's first-line indent and list marker. super::threads::mark_continued(&mut doc); @@ -1473,7 +1473,7 @@ fn restore_one(s: &mut Session, store: &Arc, file: &str) -> R }; match read { Ok(data) => { - let mut blob = ImageBlob { mime: r.mime.clone(), bytes: data, proxy: None }; + let mut blob = ImageBlob { mime: r.mime.clone(), bytes: data, proxy: None, file_font: Default::default() }; // Until the linked file is read, the preview stands in for it. if r.proxy { blob.proxy = Some(blob.bytes.clone()); @@ -1510,6 +1510,8 @@ fn restore_one(s: &mut Session, store: &Arc, file: &str) -> R let links_from = meta.path.clone().or_else(|| meta.links_from.clone()); let base = super::links::LinkBase::file(links_from.as_deref()); let links = super::links::resolve(&mut doc, base, s.prefs.update_links == "automatically", s.prefs.low_res_proxy_eps); + // Bind only after the copy's external resources and linked files have been restored. + warnings.extend(Session::refresh_text_bounds(&mut doc)); let index = s.add_document(doc, meta.path.clone()); let st = s.doc_mut()?; st.recovered = true; diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 3af85a8265..1b0766e658 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -1850,6 +1850,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result { system_layout: false, fractional_widths: true, list_count: 0, + file_fonts: None, list_level_counts: Vec::new(), cached_bounds: None, cached_baselines: Vec::new(), @@ -2158,6 +2159,7 @@ fn headline_tracking(t: &TextObject, target: f64) -> Option { system_layout: t.system_layout, fractional_widths: t.fractional_widths, list_count: 0, + file_fonts: None, list_level_counts: Vec::new(), cached_bounds: None, cached_baselines: Vec::new(), diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 2e0d0f9fe4..91580248c5 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -281,6 +281,10 @@ pub struct Prefs { pub recovery_off_for_complex: bool, pub recent_files_count: u32, pub low_res_proxy_eps: bool, + /// File Handling › Use fonts embedded in imported PDFs: type in a font a PDF embeds and this + /// machine lacks is drawn in the file's own glyphs (on by default); off, it is set in the + /// fallback font with the missing-font warning (#4568). + pub pdf_import_embedded_fonts: bool, pub anti_aliased_bitmaps: bool, pub update_links: String, /// PDF Text: what the text of a PDF, `.ai` or `.ait` file opened or placed from the app @@ -446,6 +450,17 @@ pub const KEY_HOLD_DELAY: f64 = 0.35; pub const KEY_HOLD_DELAY_RANGE: (f64, f64) = (0.2, 1.0); impl Prefs { + /// The `document.open` / place params `p` with `embeddedFonts: false` added when Preferences + /// › File Handling › Use fonts embedded in imported PDFs is off and `p` gives no choice of its own. + pub fn with_pdf_font_choice(&self, p: &serde_json::Value) -> serde_json::Value { + if self.pdf_import_embedded_fonts || p.get("embeddedFonts").is_some_and(|v| !v.is_null()) { + return p.clone(); + } + let mut out = if p.is_object() { p.clone() } else { serde_json::json!({}) }; + out["embeddedFonts"] = serde_json::json!(false); + out + } + /// The Hold Shortcut Delay in seconds, inside its range. A restored settings file is not /// checked against the range, so a value outside it is brought inside, and one that is not a /// number gives the default. @@ -592,6 +607,7 @@ impl Default for Prefs { recovery_off_for_complex: false, recent_files_count: 20, low_res_proxy_eps: false, + pdf_import_embedded_fonts: true, anti_aliased_bitmaps: false, update_links: s("askWhenModified"), pdf_text_as: s("text"), diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 1685adc40f..b83b242fc3 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -293,7 +293,9 @@ impl Session { /// what is fitted to type's bounds (an envelope warping it) would come out differently. That /// holds for the type in symbol definitions, pattern tiles, graph designs and opacity masks too, /// not only in the layers (#1738). - pub(crate) fn refresh_text_bounds(doc: &mut Document) { + pub(crate) fn refresh_text_bounds(doc: &mut Document) -> Vec { + // The fonts files carried for their type draw it ([`vectorcraft_doc::FileFonts`]). + let warnings = vectorcraft_text::FontDb::global().bind_document_file_fonts(doc); // Inline graphics in text take their size from their symbols' art (not saved either). doc.resolve_inline_art(); let mut uncached = |t: &TextObject| t.cached_bounds.is_none(); @@ -303,6 +305,7 @@ impl Session { // The symbols' type is measured now: the inline graphics showing those symbols take their // art's measured size, a symbol's type before the type that shows that symbol inline. doc.resolve_inline_art_with(&mut cmd::typecmd::refresh_bounds_for_first_frame); + warnings } /// Measure the type in open document `index` that `stale` picks (in its trees as @@ -344,6 +347,8 @@ impl Session { // (importers and the native reader have seen to theirs already, with a warning). doc.limit_depth(); cmd::compositefonts::filter_loaded(&mut doc); + // Importers report binding failures; programmatic additions still need owned resources. + let _ = vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc); // Inline graphics in text take their size from their symbols' art (not saved). doc.resolve_inline_art(); // Ruler guides a reader left in the saved list become nodes on their layers. diff --git a/crates/engine/src/tests/colorize.rs b/crates/engine/src/tests/colorize.rs index faa0af57db..5a108d1695 100644 --- a/crates/engine/src/tests/colorize.rs +++ b/crates/engine/src/tests/colorize.rs @@ -481,7 +481,7 @@ fn eps_export_still_flattens_a_colorize_paint_on_a_color_image() { fn a_colorized_missing_link_placeholder_is_not_flattened() { let mut s = session(); let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap()); - let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) }); + let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() }); s.edit("Colorize", |d, _| { d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0)))); Ok(()) @@ -502,7 +502,7 @@ fn a_colorized_missing_link_placeholder_is_not_flattened() { fn a_fill_color_recolors_a_colorized_missing_link_placeholder() { let mut s = session(); let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap()); - let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) }); + let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() }); s.edit("Colorize", |d, _| { d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0)))); Ok(()) @@ -523,7 +523,7 @@ fn a_fill_color_recolors_a_colorized_missing_link_placeholder() { fn a_colorized_missing_link_placeholder_in_a_spot_color_refuses_a_process_color() { let mut s = session(); let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap()); - let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) }); + let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() }); s.execute("swatch.new", &json!({"name": "Ink 2", "color": {"c": 100, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap(); s.edit("Colorize", |d, _| { let ink = Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 1.0 }; diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index f146e39941..9474973adb 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -1019,8 +1019,15 @@ fn package_copies_held_postscript_only_for_a_placed_document_with_a_postscript_n im.link.as_mut().unwrap().path = logo_ai.clone(); im.link.as_mut().unwrap().relative = None; let key = im.key.clone(); - d.images - .insert(key, vectorcraft_doc::ImageBlob { mime: "application/postscript".into(), bytes: std::sync::Arc::new(eps.to_vec()), proxy: None }); + d.images.insert( + key, + vectorcraft_doc::ImageBlob { + mime: "application/postscript".into(), + bytes: std::sync::Arc::new(eps.to_vec()), + proxy: None, + file_font: Default::default(), + }, + ); Ok(()) }) .unwrap(); diff --git a/crates/engine/src/tests/place.rs b/crates/engine/src/tests/place.rs index a897cbb051..38636102e2 100644 --- a/crates/engine/src/tests/place.rs +++ b/crates/engine/src/tests/place.rs @@ -999,7 +999,10 @@ fn a_placed_brush_whose_art_uses_a_renamed_image_is_copied() { let mut s = session(); s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); s.edit("Brush", |d, _| { - d.images.insert("k".into(), vectorcraft_doc::ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None }); + d.images.insert( + "k".into(), + vectorcraft_doc::ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None, file_font: Default::default() }, + ); let im = vectorcraft_doc::ImageObject { key: "k".into(), width: 2, diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 966e68dc60..b15697d327 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -2979,6 +2979,26 @@ fn snap_to_glyph_options_read_set_and_reset() { assert_eq!(s.execute("view.snapToGlyph.options", &json!({})).unwrap(), all); } +/// File Handling › Use fonts embedded in imported PDFs (`pdfImportEmbeddedFonts`, on by default) +/// reaches Open and Place as the `embeddedFonts` choice, unless a call gives its own (#4568). +#[test] +fn the_embedded_fonts_preference_reaches_the_import_options() { + use crate::cmd::fileio::LoadOptions; + let mut s = Session::new(); + assert!(s.prefs.pdf_import_embedded_fonts, "on by default"); + let on = s.prefs.with_pdf_font_choice(&json!({})); + assert!(LoadOptions::from_params("x", &on).unwrap().embedded_fonts); + s.execute("prefs.set", &json!({"key": "pdfImportEmbeddedFonts", "value": false})).unwrap(); + let off = s.prefs.with_pdf_font_choice(&json!({"page": 2})); + assert_eq!(off["page"], 2, "the call's own params stay"); + assert!(!LoadOptions::from_params("x", &off).unwrap().embedded_fonts); + assert!(!LoadOptions::from_params("x", &s.prefs.with_pdf_font_choice(&Value::Null)).unwrap().embedded_fonts); + // A call that says so wins over the preference. + let own = s.prefs.with_pdf_font_choice(&json!({"embeddedFonts": true})); + assert!(LoadOptions::from_params("x", &own).unwrap().embedded_fonts); + assert!(LoadOptions::from_params("x", &json!({"embeddedFonts": "yes"})).is_err()); +} + /// Pixel Snapping Options: `view.snapToPixel.options` reads and sets While Drawing, While Moving /// and While Scaling, all on by default, kept as the `pixelSnap` preference group; bad keys and /// values change nothing, preferences saved without the group read it as all on, and resetting the diff --git a/crates/engine/src/tests/recovery.rs b/crates/engine/src/tests/recovery.rs index eed8801efc..aa5a7e5ab5 100644 --- a/crates/engine/src/tests/recovery.rs +++ b/crates/engine/src/tests/recovery.rs @@ -69,6 +69,77 @@ fn native_recovery_copies_leave_out_the_pdf() { assert_eq!(vectorcraft_format::load(&bytes).unwrap().node_count(), s.doc().unwrap().doc.node_count()); } +const RECOVERY_FONT_FAMILY: &str = "Recovery Carried Font Regression"; +const RECOVERY_FONT_BYTES: &[u8] = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"); + +fn carried_font_copy() -> (Arc, vectorcraft_doc::NodeId) { + use vectorcraft_doc::{CharStyle, FILE_FONT_MIME, FileFont, FileFonts, ImageBlob, Node, NodeKind, TextObject}; + + let (mut s, store) = session(); + let doc = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + doc.images.insert("recovered-font".into(), ImageBlob::new(FILE_FONT_MIME, RECOVERY_FONT_BYTES.to_vec())); + // An uninstalled family ensures the fixture must be read from the recovered resource. + let style = CharStyle { font_family: RECOVERY_FONT_FAMILY.into(), size: 20.0, ..Default::default() }; + let mut text = TextObject::point(kurbo::Point::new(10.0, 40.0), "x", style); + text.file_fonts = Some(Box::new(FileFonts::new( + vec![FileFont { family: RECOVERY_FONT_FAMILY.into(), style: "Regular".into(), key: "recovered-font".into() }], + "x", + ))); + let id = doc.alloc_id(); + doc.insert(Some(doc.layers[0].id), usize::MAX, Node::new(id, NodeKind::Text(Box::new(text)))).unwrap(); + let saved = s.execute("file.recovery.save", &json!({})).unwrap(); + let file = saved["saved"][0]["file"].as_str().unwrap(); + let lean = vectorcraft_format::load(&store.read(&format!("{file}.vectorcraft")).unwrap()).unwrap(); + assert!(lean.images.is_empty(), "the font travels in the recovery store, not the document entry"); + drop(s); + (store, id) +} + +#[test] +fn recovered_carried_fonts_bind_after_their_resources_are_restored() { + use vectorcraft_doc::NodeKind; + use vectorcraft_text::FontDb; + + let (store, id) = carried_font_copy(); + let mut s = relaunch(&store); + let reply = s.execute("file.recovery.restore", &json!({})).unwrap(); + assert_eq!(reply["restored"].as_array().unwrap().len(), 1, "{reply}"); + assert!(reply["failed"].as_array().unwrap().is_empty(), "{reply}"); + assert!(reply["restored"][0]["warnings"].as_array().unwrap().is_empty(), "{reply}"); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.images["recovered-font"].bytes.as_slice(), RECOVERY_FONT_BYTES); + let NodeKind::Text(text) = &doc.node(id).unwrap().kind else { panic!("text") }; + let db = FontDb::global(); + let laid = vectorcraft_text::layout(db, text); + assert_eq!(laid.glyphs.len(), 1); + let face = db.face_by_id(laid.glyphs[0].font_id).unwrap(); + assert_eq!(face.file_data(), RECOVERY_FONT_BYTES, "layout uses the recovered font's exact bytes"); +} + +#[test] +fn recovered_missing_or_corrupt_carried_fonts_report_the_actual_refusal() { + for missing in [true, false] { + let (store, id) = carried_font_copy(); + let blob = store.list().unwrap().into_iter().find(|name| name.ends_with(".blob")).unwrap(); + if missing { + store.remove(&blob).unwrap(); + } else { + store.write(&blob, b"not a font").unwrap(); + } + let mut s = relaunch(&store); + let reply = s.execute("file.recovery.restore", &json!({})).unwrap(); + assert_eq!(reply["restored"].as_array().unwrap().len(), 1, "{reply}"); + assert!(reply["failed"].as_array().unwrap().is_empty(), "{reply}"); + let warnings = reply["restored"][0]["warnings"].as_array().unwrap(); + assert!( + warnings.iter().any(|note| note.as_str().is_some_and(|note| note.contains(RECOVERY_FONT_FAMILY) && note.contains("substitute"))), + "missing={missing}: {reply}" + ); + let vectorcraft_doc::NodeKind::Text(text) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("text") }; + assert!(vectorcraft_text::FontDb::global().file_faces(text).is_empty(), "missing={missing}"); + } +} + #[test] fn restored_recovery_copies_keep_the_original_pdf_preference() { let dir = crate::tests_links::Folder::new("recovered-pdf-preference"); diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 4e7b5adc92..3887da7f33 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -662,7 +662,7 @@ impl<'a> Reader<'a> { }; // The placeholder is all the document has of the file: what a missing link shows. let bytes = Arc::new(png); - let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) }; + let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() }; let key = linked_key(&blob, &path); self.doc.images.entry(key.clone()).or_insert(blob); self.warn(LINKED_PLACEHOLDERS); @@ -905,7 +905,7 @@ impl<'a> Reader<'a> { } // The preview is all the document has of the file: what a missing link shows. let bytes = Arc::new(png); - let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) }; + let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() }; let key = linked_key(&blob, &path); let fresh = !self.doc.images.contains_key(&key); self.doc.images.entry(key.clone()).or_insert(blob); diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 430769069d..66040d265c 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -586,7 +586,7 @@ fn load_unpacked(file: unpack::Unpacked<'_>, max_nodes: usize, max_values: usize let mut doc = f.document; for (k, img) in f.images { let bytes = bytes_of(&img).ok_or_else(|| FormatError::BadImage(k.clone()))?; - let mut blob = ImageBlob { mime: img.mime, bytes, proxy: None }; + let mut blob = ImageBlob { mime: img.mime, bytes, proxy: None, file_font: Default::default() }; // Until the linked file is read, the preview stands in for it. if img.proxy { blob.proxy = Some(blob.bytes.clone()); diff --git a/crates/format/tests/it/save_options.rs b/crates/format/tests/it/save_options.rs index 515efbf94e..3719a8bc10 100644 --- a/crates/format/tests/it/save_options.rs +++ b/crates/format/tests/it/save_options.rs @@ -57,7 +57,9 @@ fn include_linked_files_keeps_the_files_bytes() { // Only the preview loaded (the file was never found): the preview is all there is to write. let mut missing = linked_doc(); let preview = Arc::new(vec![9, 9]); - missing.images.insert("k".into(), ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) }); + missing + .images + .insert("k".into(), ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() }); let out = save_with(&missing, &SaveOptions { include_linked: true, ..SaveOptions::default() }).unwrap(); assert_eq!(json_of(&out)["images"]["k"]["proxy"], true); } diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index a908cf6879..1717e4350b 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -13,6 +13,8 @@ use super::{ PathData, PathDrawMode, Pattern, PatternDef, Placement, Rect, Scan, Shape, SoftMask, StrokeProps, TextAs, TextLine, TextOverprint, TilingPattern, Upright, Walked, clipped, contains, fold_stop_opacity, function_paint, gradient_shape, is_rectangle, luminance, mask_spec, shading_gradient, }; +use crate::import_fonts::program_facts; +use vectorcraft_text::{FileFontInfo, FileGlyph}; /// The most lines of type kept for a text-showing operator's stroke pass ([`Builder::park_text`]): /// beyond them the oldest is finished, and strokes over its glyphs come in as type of their own. @@ -51,6 +53,12 @@ fn is_colour_face(face: &vectorcraft_text::FontFace) -> bool { } impl<'p> Builder<'p> { + /// Draw type in the fonts the file embeds (the default) or not ([`crate::ImportOptions::embedded_fonts`]). + pub(super) fn with_embedded_fonts(mut self, on: bool) -> Self { + self.embedded_fonts = on; + self + } + pub(super) fn new(next: u64, colors: Colors<'p>, text_as: TextAs, route: bool) -> Self { Self { colors, @@ -67,6 +75,7 @@ impl<'p> Builder<'p> { held: vec![], lost: None, text_as, + embedded_fonts: true, actual: Default::default(), images: HashMap::new(), image_keys: HashMap::new(), @@ -80,6 +89,8 @@ impl<'p> Builder<'p> { font_names: HashMap::new(), families: None, missing_fonts: vec![], + file_glyphs: crate::import_fonts::FileFontGlyphs::default(), + file_fonts: HashMap::new(), cid_text: HashMap::new(), font_chars: HashMap::new(), matched: HashMap::new(), @@ -782,11 +793,15 @@ impl<'p> Builder<'p> { /// it was kept as them ([`Self::end_text`]). fn end_line(&mut self, mut line: TextLine, glyphs: Vec) -> bool { let held = std::mem::take(&mut line.held); + let (line_conflict, line_type3) = (line.file_conflict, line.has_type3); // Type the file names itself (ActualText) is in reading order as it stands. let checked = !glyphs.is_empty() && line.mapped() && !line.has_type3; let mut outlined = false; if let Some((t, opacity, facts)) = line.finish() { - if checked && reshaped::reshapes(&t.plain_text()) && !reshaped::draws_as(&t, &facts.ink) { + // A line with a glyph the file's font can't keep (another glyph for the same character) + // is kept as outlines too, so each glyph draws as the file does. + let conflict = line_conflict && !glyphs.is_empty() && !line_type3; + if conflict || (checked && reshaped::reshapes(&t.plain_text()) && !reshaped::draws_as(&t, &facts.ink)) { outlined = true; if self.mask.is_some() { self.flush_glyphs(); @@ -1461,10 +1476,8 @@ impl<'p> Builder<'p> { // vector's vx (from the font's `W2`, else half its width from `W` or `DW`) to the left of // the column's centre (ISO 32000-1 §9.7.4.3); vertical type centres each glyph on the // column. Half an em only for a full-width glyph (#722). - let top = upright.then(|| { - let vx = self.fonts.get(&key).and_then(|f| f.vertical.as_ref()).map_or(500.0, |v| v.centre(glyph)); - m * kurbo::Point::new(vx, 880.0) - }); + let vx = upright.then(|| self.fonts.get(&key).and_then(|f| f.vertical.as_ref()).map_or(500.0, |v| v.centre(glyph))); + let top = vx.map(|vx| m * kurbo::Point::new(vx, 880.0)); // A horizontal line is gathered in visual order and put back in logical order as a whole: // a ligature's characters (lam-alef, lam-lam-heh) go in visual order too (#6072). let text = if top.is_none() { visual_glyph_text(text) } else { text }; @@ -1507,8 +1520,31 @@ impl<'p> Builder<'p> { place(&mut line); self.text = Some(line); } + let outline = o.outline(); + // A font the file carries for a family that isn't available: the glyph goes into the font + // kept with the document, which draws the line as the file does ([`crate::import_fonts`]). + if let Some(font) = self.file_font(key, o, &look) { + if let Some(line) = &mut self.text { + line.file_font = true; + } + let mut chars = text.chars(); + if let (Some(ch), None) = (chars.next(), chars.next()) { + // A glyph set vertically has no horizontal width: its column's, twice its centre. + let advance = match vx { + Some(vx) => 2.0 * vx, + None => width.map_or(500.0, f64::from), + }; + if self.file_glyphs.wants(font, ch) { + self.file_glyphs.add(font, FileGlyph { ch, outline: outline.clone(), advance }); + } else if self.file_glyphs.conflicts(font, ch, &outline, advance) + && let Some(line) = &mut self.text + { + line.file_conflict = true; + } + } + } // Its ink: a stroke the file draws as outlines of the glyphs is told by it. - let mut ink = o.outline(); + let mut ink = outline; if top.is_none() { self.keep_glyph(o, m, drawn, opacity, scale, overprint); } @@ -1520,6 +1556,36 @@ impl<'p> Builder<'p> { } true } + + /// The font among the glyphs gathered for fonts kept with the document that glyphs of font + /// `key` (drawn with `look`) go into: when the file carries the font's program, no installed + /// face has its PostScript name, and its family and style aren't available as named. Decided + /// once per font. + fn file_font(&mut self, key: u128, o: &craft_pdf::interpret::font::OutlineGlyph, look: &Look) -> Option { + if let Some(f) = self.file_fonts.get(&key) { + return *f; + } + // Not the interpreter's stand-in for a font the file doesn't carry. + let carried = self.embedded_fonts && self.fonts.get(&key).is_some_and(|f| f.embedded) && o.font_data().is_none_or(|d| d.embedded); + let installed = self.font_names.get(&key).is_some_and(|i| i.face.is_some()); + let available = + || vectorcraft_text::FontDb::global().resolve(&look.family, &look.style).is_some_and(|(_, m)| m == vectorcraft_text::FontMatch::Exact); + let font = (carried && !installed && !look.family.trim().is_empty() && !available()).then(|| { + let data = o.font_data(); + let (fs_type, metrics) = data.as_ref().map_or((None, None), |d| program_facts(d.data.as_ref().as_ref(), d.index)); + let name = self.fonts.get(&key).map(|f| f.name.clone()).or_else(|| data.and_then(|d| d.postscript_name)).unwrap_or_default(); + // A subset's six-letter tag. + let postscript = match name.split_once('+') { + Some((tag, rest)) if tag.len() == 6 && tag.chars().all(|c| c.is_ascii_uppercase()) => rest.to_string(), + _ => name, + }; + let (ascent, descent) = metrics.unwrap_or_default(); + let info = || FileFontInfo { family: look.family.clone(), style: look.style.clone(), postscript, ascent, descent, fs_type }; + self.file_glyphs.font(&look.family, &look.style, info) + }); + self.file_fonts.insert(key, font); + font + } } /// Glyph `o` placed by `m` and drawn with `drawn` as the outline it is kept as diff --git a/crates/pdf/src/import/entry.rs b/crates/pdf/src/import/entry.rs index 5b945c6b25..884d555e0e 100644 --- a/crates/pdf/src/import/entry.rs +++ b/crates/pdf/src/import/entry.rs @@ -5,6 +5,7 @@ use super::{ ImportReport, InterpreterCache, InterpreterSettings, InterpreterWarning, LayerColor, MAX_NESTING, Mutex, Node, NodeKind, Ocgs, Ordering, Paint, PdfError, Rect, Shape, Swatch, all_on, contains, hides_forms, scan_page, white_cover, }; +use crate::import_text::keep_file_fonts; /// Mixed into an image's cache key when it is read white inside an alpha soft mask. pub(super) const WHITE_KEY: u128 = 0x7717_e000_a1fa; @@ -242,6 +243,32 @@ pub fn imports_of(bytes: &[u8]) -> usize { IMPORTS.lock().ok().and_then(|i| i.get(&(bytes.as_ptr() as usize)).copied()).unwrap_or(0) } +/// The notes on the fonts the file draws with that aren't available: type in a font the file +/// carries keeps its look until it is edited; the rest shows in the fallback font. +fn warn_missing_fonts(b: &mut Builder, doc: &Document) { + let mut bound = std::collections::HashSet::new(); + doc.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + for font in t.file_fonts_in_use() { + if t.file_fonts.as_ref().and_then(|fonts| fonts.face(&font.key)).is_some() { + bound.insert(font.family.clone()); + } + } + } + }); + let (carried, missing): (Vec, Vec) = std::mem::take(&mut b.missing_fonts).into_iter().partition(|family| bound.contains(family)); + if !carried.is_empty() { + b.warn(&format!( + "fonts that aren't available show as the file draws them, in the fonts it carries, until their text is edited (then in the fallback font): {}", + carried.join(", ") + )); + } + if !missing.is_empty() { + let list = missing.join(", "); + b.warn(&format!("fonts that aren't available show in the fallback font until they are: {list}")); + } +} + /// The widest bleed of `pages` on each side (`[top, bottom, left, right]`, see [`crate::pages::bleed`]). fn widest_bleed<'p, 'd: 'p>(pages: impl Iterator>) -> [f64; 4] { pages.fold([0.0; 4], |widest, page| { @@ -278,7 +305,7 @@ fn read_opened( doc.artboards.clear(); doc.layers.clear(); let taken: Vec = doc.swatches_iter().map(|s| s.name.clone()).chain(doc.swatch_groups.iter().map(|g| g.name.clone())).collect(); - let mut b = Builder::new(doc.peek_next_id(), Colors::new(pdf, taken.clone()), opts.text_as, route); + let mut b = Builder::new(doc.peek_next_id(), Colors::new(pdf, taken.clone()), opts.text_as, route).with_embedded_fonts(opts.embedded_fonts); // The art of a group that is off (drawn as `all_on` turned it on) or doesn't print mustn't // show or print on its page's layer. b.unsure = route && ocgs.list.iter().any(|g| (all_on && !g.on) || !g.print); @@ -437,6 +464,9 @@ fn read_opened( // The groups' layers stack as the pages mark them (the art outside them stays where it was // drawn): a group that first paints on a later page doesn't go on top of the others. stack_groups(&mut slots, &order); + // The fonts the file carries for families that aren't available, kept with the document: the + // type set in them is drawn in them and spaced from the file's own widths. + let kept = std::mem::take(&mut b.file_glyphs).keep(&mut b.images); for (n, slot) in slots.into_iter().enumerate() { let mut layer = match slot { Slot::Page(l) => *l, @@ -447,6 +477,7 @@ fn read_opened( }, }; if let Some(art) = layer.children_mut() { + keep_file_fonts(art, &b.lines, &kept, &b.images); crate::import_lines::rebuild(art, &b.lines); } doc.layers.push(Arc::new(layer)); @@ -474,10 +505,7 @@ fn read_opened( if b.colors.mixed { b.warn("colours mixing several inks (DeviceN) were imported as RGB"); } - if !b.missing_fonts.is_empty() { - let list = b.missing_fonts.join(", "); - b.warn(&format!("fonts that aren't available show in the fallback font until they are: {list}")); - } + warn_missing_fonts(&mut b, &doc); // Before anything walks the tree by recursion (`fix_next_id` does): nested clips can be deeper // than the stack goes. let mut depth_notes = vec![]; @@ -486,6 +514,7 @@ fn read_opened( doc.reserve_ids(b.next); let mut warnings = b.warnings; + warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc)); if let Ok(v) = sink.lock() { for w in v.iter() { if !warnings.contains(w) { diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index a76531348a..f188e7950a 100644 --- a/crates/pdf/src/import/state.rs +++ b/crates/pdf/src/import/state.rs @@ -3,6 +3,7 @@ use super::{ Affine, Arc, BezPath, BlendMode, Colors, Dash, Families, FillRule, FontNames, FunctionBudget, HashMap, HashSet, ImageBlob, LineCap, LineFacts, LineJoin, LumaData, MaskSpec, Node, NodeId, Paint, PathEl, PatternDef, Rect, Scan, StrokeLayer, StrokeProps, TextAs, TextLine, TypeStroke, }; +use crate::import_fonts::FileFontGlyphs; /// Decoded RGBA pixels, width, height and hayro's scale factors. pub(super) type Decoded = (Vec, u32, u32, (f32, f32)); @@ -127,6 +128,8 @@ pub(super) struct Builder<'p> { /// anything else drawn ([`Builder::flush_text`]). pub(super) lost: Option, pub(super) text_as: TextAs, + /// Fonts the file embeds are kept (ImportOptions::embedded_fonts). + pub(super) embedded_fonts: bool, pub(super) actual: super::actual_text::ActualText, pub(super) images: HashMap, pub(super) image_keys: HashMap, @@ -150,6 +153,11 @@ pub(super) struct Builder<'p> { pub(super) font_names: HashMap, pub(super) families: Option, pub(super) missing_fonts: Vec, + /// The glyphs drawn in fonts the file carries for families that aren't available, for the + /// fonts kept with the document ([`crate::import_fonts`]). + pub(super) file_glyphs: FileFontGlyphs, + /// Font (cache key) → its font among `file_glyphs`; `None`: its type takes the font it names. + pub(super) file_fonts: HashMap>, /// Font (cache key) → its characters by glyph, for CID-keyed fonts embedded without a /// ToUnicode map. pub(super) cid_text: HashMap>>, diff --git a/crates/pdf/src/import_fonts.rs b/crates/pdf/src/import_fonts.rs new file mode 100644 index 0000000000..034d9e068c --- /dev/null +++ b/crates/pdf/src/import_fonts.rs @@ -0,0 +1,162 @@ +//! The fonts a PDF carries (embeds) for type whose fonts aren't available here: the glyphs it draws +//! in each, gathered as its pages are read, become one font per family and style, kept with the +//! document ([`vectorcraft_doc::FileFonts`]), that draws that type as the file did until its text +//! is edited. A file embeds its fonts so that it shows in them wherever it is read (Acrobat Help, +//! PDF fonts, ). +//! +//! Each glyph comes as the interpreter draws it (an outline in thousandths of an em, whatever the +//! font program: Type 1, CFF or TrueType, simple or CID-keyed) with the width the file gives it, for +//! the character the file says it shows (its `ToUnicode` map, or what the import reads from the +//! font program). The first glyph of each character is kept; a line using a different glyph for +//! that character is imported as outlines instead. + +use std::collections::HashMap; + +use kurbo::BezPath; +use vectorcraft_doc::{FILE_FONT_MIME, ImageBlob}; +use vectorcraft_text::{FileFontInfo, FileGlyph, MAX_FILE_GLYPHS, build_file_font}; + +/// The most glyphs gathered from one file, in all its fonts (an outline is some hundreds of bytes; +/// a CJK document uses a few thousand characters). +const MAX_GLYPHS: usize = 200_000; + +/// The licence flags (OS/2 `fsType`) of `a` and `b` that allow less: a restricted font beats one +/// that may be embedded whole, which beats one that may be embedded as a subset. A font without +/// flags reads as print and preview (4), as a font built from it does. +fn stricter(a: Option, b: Option) -> Option { + use vectorcraft_text::embed::Embedding; + let rank = |f: Option| match Embedding::from_fs_type(f.unwrap_or(4)) { + Embedding::Subset => 0, + Embedding::Whole => 1, + Embedding::Forbidden => 2, + }; + if rank(b) > rank(a) { b } else { a } +} + +/// The glyphs gathered so far. +#[derive(Default)] +pub(crate) struct FileFontGlyphs { + fonts: Vec, + /// Each font (family and style) by its index in `fonts`. + index: HashMap<(String, String), usize>, + /// Glyphs gathered, in all. + count: usize, +} + +/// The glyphs of one family and style. +struct Gathered { + family: String, + style: String, + info: FileFontInfo, + glyphs: Vec, + /// Each character's glyph, by its index in `glyphs`. + chars: HashMap, +} + +impl FileFontGlyphs { + /// The font of `family` and `style` (made with `info` the first time): its index. + pub fn font(&mut self, family: &str, style: &str, info: impl FnOnce() -> FileFontInfo) -> usize { + if let Some(&i) = self.index.get(&(family.to_string(), style.to_string())) { + // Two programs of one family and style share one font here: it takes the stricter + // of their licence flags, so a restricted one's glyphs never read as permitted. + if let Some(g) = self.fonts.get_mut(i) { + g.info.fs_type = stricter(g.info.fs_type, info().fs_type); + } + return i; + } + let i = self.fonts.len(); + self.fonts.push(Gathered { family: family.to_string(), style: style.to_string(), info: info(), glyphs: vec![], chars: HashMap::new() }); + self.index.insert((family.to_string(), style.to_string()), i); + i + } + + /// Does font `font` still want a glyph for `ch` (none gathered yet, and room for it)? + pub fn wants(&self, font: usize, ch: char) -> bool { + self.count < MAX_GLYPHS && self.fonts.get(font).is_some_and(|f| f.glyphs.len() < MAX_FILE_GLYPHS && !f.chars.contains_key(&ch)) + } + + /// Does font `font` hold a glyph for `ch` that differs from `outline` or `advance`? A font keeps + /// one glyph per character, so a file's other glyph for it (a stylistic alternate that maps to + /// the same character) can't go into it: the line it is on is kept as outlines instead. + pub fn conflicts(&self, font: usize, ch: char, outline: &BezPath, advance: f64) -> bool { + self.fonts + .get(font) + .and_then(|f| f.chars.get(&ch).and_then(|&i| f.glyphs.get(i))) + .is_some_and(|g| g.outline != *outline || g.advance != advance) + } + + /// Gather `glyph` for font `font`. + pub fn add(&mut self, font: usize, glyph: FileGlyph) { + if !self.wants(font, glyph.ch) { + return; + } + if let Some(f) = self.fonts.get_mut(font) { + f.chars.insert(glyph.ch, f.glyphs.len()); + f.glyphs.push(glyph); + self.count += 1; + } + } + + /// The fonts built from gathered glyphs, stored under their content keys. Only text that + /// actually references one admits a runtime face, before it is respaced. + pub fn keep(self, images: &mut HashMap) -> HashMap<(String, String), String> { + let mut kept = HashMap::new(); + for f in self.fonts { + let Some(bytes) = build_file_font(&f.info, &f.glyphs) else { continue }; + let blob = ImageBlob::new(FILE_FONT_MIME, bytes); + let base = blob.content_key(); + let mut key = base.clone(); + let mut suffix = 1; + while images.get(&key).is_some_and(|held| held != &blob) { + key = format!("{base}-{suffix}"); + suffix += 1; + } + images.entry(key.clone()).or_insert(blob); + kept.insert((f.family, f.style), key); + } + kept + } +} + +/// What a font program the file embeds (`data`, a TrueType or OpenType file, or a bare CFF font) +/// says of the font's licence (OS/2 `fsType`) and its ascent and descent (thousandths of an em). +pub(crate) fn program_facts(data: &[u8], index: u32) -> (Option, Option<(f64, f64)>) { + use skrifa::MetadataProvider; + use skrifa::raw::TableProvider; + let Ok(f) = skrifa::FontRef::from_index(data, index) else { return (None, None) }; + let fs_type = f.os2().ok().map(|o| o.fs_type()); + let m = f.metrics(skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::default()); + let k = 1000.0 / f64::from(m.units_per_em.max(1)); + let (ascent, descent) = (f64::from(m.ascent) * k, f64::from(m.descent) * k); + let metrics = (ascent.is_finite() && descent.is_finite() && ascent > 0.0 && descent <= 0.0).then_some((ascent, descent)); + (fs_type, metrics) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Two programs of one family and style are one font here, and its flags are the stricter + /// of theirs whichever came first (CodeRabbit, #4569). + #[test] + fn two_programs_of_one_font_keep_the_stricter_licence() { + for (first, second, want) in [ + (Some(4), Some(2), Some(2)), + (Some(2), Some(4), Some(2)), + (None, Some(0x0200), Some(0x0200)), + (Some(4), Some(0x0108), Some(0x0108)), + (Some(0x0108), Some(2), Some(2)), + (Some(8), Some(4), Some(8)), + (None, None, None), + ] { + let mut g = FileFontGlyphs::default(); + let info = |fs_type| { + move || FileFontInfo { family: "F".into(), style: "R".into(), postscript: "F-R".into(), ascent: 800.0, descent: -200.0, fs_type } + }; + let a = g.font("F", "R", info(first)); + let b = g.font("F", "R", info(second)); + assert_eq!(a, b); + assert_eq!(g.fonts[a].info.fs_type, want, "{first:?} then {second:?}"); + } + } +} diff --git a/crates/pdf/src/import_lines.rs b/crates/pdf/src/import_lines.rs index b880c74ab7..2732b4666d 100644 --- a/crates/pdf/src/import_lines.rs +++ b/crates/pdf/src/import_lines.rs @@ -7,14 +7,14 @@ //! - area type comes as a line of point type per line, each wrapped line ending in a space. Lines //! in a row sharing a left edge, font, size and leading (and paragraph spacing) are one area //! type object again, aligned left or justified, where laying its text out in the frame breaks -//! it where the file does: else, as where its font isn't installed, they stay lines. +//! it where the file does; otherwise they stay lines. Carried fonts are used for this check. use std::collections::HashMap; use std::sync::Arc; use kurbo::{Point, Rect, Shape}; use vectorcraft_color::BlendMode; -use vectorcraft_doc::{AppearanceItem, CharStyle, Justify, Node, NodeId, NodeKind, TextKind, TextObject, TextRun}; +use vectorcraft_doc::{AppearanceItem, CharStyle, FileFont, FileFonts, Justify, Node, NodeId, NodeKind, TextKind, TextObject, TextRun}; use vectorcraft_geom::shapes; use crate::import_text::{LineFacts, median}; @@ -258,6 +258,30 @@ fn laid_out(texts: &[(&TextObject, &LineFacts)], b: &Block, justify: Justify, wi } let mut t = (*first).clone(); t.runs = runs; + // The fonts the file carries that draw the lines draw them as one object too. + let mut fonts: Vec = vec![]; + for f in texts.iter().flat_map(|(t, _)| t.file_fonts_in_use()) { + if !fonts.contains(f) { + fonts.push(f.clone()); + } + } + t.file_fonts = (!fonts.is_empty()).then(|| { + let resources = fonts + .iter() + .take(vectorcraft_doc::text::MAX_FILE_FONTS) + .filter_map(|font| { + texts + .iter() + .find_map(|(line, _)| { + line.file_fonts_in_use().iter().any(|f| f.key == font.key).then(|| line.file_fonts.as_ref()?.face(&font.key)).flatten() + }) + .map(|face| (font.key.clone(), face)) + }) + .collect(); + let mut kept = FileFonts::new(fonts, &t.plain_text()); + kept.bind(resources); + Box::new(kept) + }); t.para.justify = justify; t.para.space_before = b.space; let last = b.ys.last().copied()?; diff --git a/crates/pdf/src/import_text.rs b/crates/pdf/src/import_text.rs index fcfd849d92..436db268ce 100644 --- a/crates/pdf/src/import_text.rs +++ b/crates/pdf/src/import_text.rs @@ -4,16 +4,19 @@ //! baseline, text rise, is baseline shift). Each glyph stays where the file drew it: the kerning //! and tracking the type takes put it there (#722). Fonts are named from the file's base font name (its //! subset prefix dropped, the family matched against the fonts available); a font that isn't -//! available keeps its name, and the text shows in the fallback font until it is. +//! available keeps its name. Where the file carries that font, its glyphs make a font kept with the +//! document ([`crate::import_fonts`]) that draws the type as the file did until its text is +//! edited ([`keep_file_fonts`]); otherwise the text shows in the fallback font until it is. //! //! Glyphs each turned a little further along a curve (type set on a path: apps write each glyph //! with its own placement) make one type-on-a-path object, its path through the glyphs' baseline. use std::collections::{HashMap, HashSet}; +use std::sync::Arc; use kurbo::{Affine, BezPath, Point, Rect, Vec2}; use vectorcraft_color::Paint; -use vectorcraft_doc::{CharStyle, LineCap, LineJoin, Node, ParaDirection, TextKind, TextObject, TextRun}; +use vectorcraft_doc::{CharStyle, FileFont, FileFonts, LineCap, LineJoin, Node, NodeId, NodeKind, ParaDirection, TextKind, TextObject, TextRun}; use vectorcraft_text::TextLayout; /// One glyph's placement: its baseline origin, advance direction, size and horizontal scale. @@ -268,8 +271,13 @@ pub(crate) struct TextLine { /// The strokes of its glyphs' outlines drawn between them, one per glyph with ink so far /// (written right after the line). pub held: Vec, + /// A glyph of the line is drawn in a font the file carries for a family that isn't available + /// ([`keep_file_fonts`]). + pub file_font: bool, /// Whether this line holds Type 3 font glyphs. pub has_type3: bool, + /// A glyph of the line differs from the one its font keeps for the same character ([`crate::import_fonts::FileFontGlyphs::conflicts`]). + pub file_conflict: bool, } /// Where the file put a glyph: the glyph's index in the line, and its advance in the file's font @@ -368,6 +376,9 @@ pub(crate) struct LineFacts { /// Horizontal point type: how long the file set it, from its first glyph's origin to the end /// of its last glyph that isn't a space (points, along the baseline). pub length: f64, + /// Set in a font the file carries for a family that isn't available: what its spacing is + /// measured from, to measure it again once that font is kept ([`keep_file_fonts`]). + pub respace: Option>, } /// The most a glyph on a curve turns from the one before it (about 20°). @@ -401,7 +412,9 @@ impl TextLine { drawn_spaces: vec![], drawn_space: None, held: vec![], + file_font: false, has_type3: false, + file_conflict: false, } } @@ -1014,79 +1027,163 @@ impl TextLine { let angle = self.at.dir.atan2(); // The glyphs' tops lean along the baseline (+x), up being -y in the type's own space. t.xf = Affine::translate(self.at.origin.to_vec2()) * Affine::rotate(angle) * Affine::skew(-self.at.slant, 0.0); - let db = vectorcraft_text::FontDb::global(); - // Each glyph where the file put it (#722): the kerning (the font's, or none) and tracking - // (one value for the line, or each character its own) that place them there. - let placed = (self.upright.is_none() && t.para.direction.is_none()) - .then(|| place_each(&t, &self.slots, &self.baseline, path.as_ref(), self.at, self.at.size)) - .flatten() - .map(|(runs, laid)| { - t.runs = runs; - laid.bounds - }); - if let Some(path) = path { - // Evenly spaced type keeps its length along the path: the path runs through the - // glyphs' origins, one curve each, to the end of the last glyph, and tracking makes up - // the difference from the advances. - if placed.is_none() { - let length: f64 = path.segments().take(self.baseline.len()).map(|seg| kurbo::ParamCurveArclen::arclen(&seg, 1e-3)).sum(); - let laid = vectorcraft_text::layout(db, &t); - let natural: f64 = laid.glyphs.iter().map(|g| g.advance).sum(); - let chars: usize = t.runs.iter().map(|r| r.text.chars().count()).sum(); - let size = self.at.size; - if chars > 1 && length.is_finite() && (length - natural).abs() > size * 0.01 { - let (tracking, spaces) = spacing(&laid, &[], length - natural, chars, size, spacing_em(&t, size)); - t.runs = tracked(std::mem::take(&mut t.runs), tracking, &spaces); - } - } - t.kind = TextKind::OnPath { path: vectorcraft_geom::PathData::from_bezpath(&path), start: 0.0, end: None }; - t.xf = Affine::IDENTITY; - t.cached_bounds = Some(vectorcraft_text::layout(db, &t).bounds); - return Some((t, self.opacity, facts)); - } - let (start, along) = match self.upright { + // How far along the line the file put each glyph: along the path through them (one curve + // each), or along the baseline from the line's origin. + let along: Vec = match &path { + Some(bp) => std::iter::once(0.0) + .chain(bp.segments().scan(0.0, |d, seg| { + *d += kurbo::ParamCurveArclen::arclen(&seg, 1e-3); + Some(*d) + })) + .take(self.baseline.len()) + .collect(), + None => self.baseline.iter().map(|p| (*p - self.at.origin).dot(self.at.dir)).collect(), + }; + // Evenly spaced type on a path keeps its length along the path: the path runs through the + // glyphs' origins, one curve each, to the end of the last glyph. + let path_length = + path.as_ref().map(|path| path.segments().take(self.baseline.len()).map(|seg| kurbo::ParamCurveArclen::arclen(&seg, 1e-3)).sum()); + let start = match self.upright { // Vertical point type (a column, or a single upright glyph) is anchored at the top // centre of its first em box. - Some(u) => { + Some(u) if path.is_none() => { t.vertical = true; t.xf = Affine::translate(u.top.to_vec2()) * Affine::rotate(angle); - (self.at.origin, -self.at.up()) + -self.at.up() } - _ => (self.at.origin, self.at.dir), + _ => self.at.dir, }; - // Tracking that makes the line as long as in the file: the PDF placed each glyph, the - // layout sets them by their advances. Spread over the gaps between characters (tracking - // follows each character, the last one's past the end of the line). A horizontal line is - // measured to its last glyph that isn't a space: the spaces after it were dropped. - let length = (if t.vertical { self.next } else { self.visible } - start).dot(along); - if !t.vertical { + // A horizontal line is measured to its last glyph that isn't a space (the spaces after it + // were dropped), a column to the end of its last glyph. + let length = (if t.vertical { self.next } else { self.visible } - self.at.origin).dot(start); + if path.is_none() && !t.vertical { facts.length = length; } - // Placed glyph by glyph: laid out so already. - if let Some(bounds) = placed { - t.cached_bounds = Some(bounds); - return Some((t, self.opacity, facts)); + if let Some(path) = &path { + t.kind = TextKind::OnPath { path: vectorcraft_geom::PathData::from_bezpath(path), start: 0.0, end: None }; + t.xf = Affine::IDENTITY; } - let laid = vectorcraft_text::layout(db, &t); - let natural: f64 = laid.glyphs.iter().map(|g| g.advance).sum(); - let chars: usize = t.runs.iter().map(|r| r.text.chars().count()).sum(); - let size = self.at.size; - let mut bounds = laid.bounds; - if chars > 1 && length.is_finite() && (length - natural).abs() > size * 0.01 { - // The spaces read from gaps or drawn between glyphs keep their own place only in text - // left in the file's order. - let total: usize = t.runs.iter().map(|r| r.text.len()).sum(); - let gaps: Vec<(usize, f64)> = if t.para.direction.is_none() { gaps.into_iter().filter(|(b, _)| *b < total).collect() } else { vec![] }; - let (tracking, spaces) = spacing(&laid, &gaps, length - natural, chars, size, spacing_em(&t, size)); - t.runs = tracked(std::mem::take(&mut t.runs), tracking, &spaces); - // Tracked: laid out again for its bounds. - bounds = vectorcraft_text::layout(db, &t).bounds; + // The spaces read from gaps or drawn between glyphs keep their own place only in a line + // left in the file's order (not along a path). + let total: usize = t.runs.iter().map(|r| r.text.len()).sum(); + let gaps: Vec<(usize, f64)> = + if path.is_none() && t.para.direction.is_none() { gaps.into_iter().filter(|(b, _)| *b < total).collect() } else { vec![] }; + let s = Spacing { + runs: t.runs.clone(), + slots: std::mem::take(&mut self.slots), + // Glyph by glyph only in horizontal type in the file's order. + along: (self.upright.is_none() && t.para.direction.is_none()).then_some(along), + slant: if path.is_some() { 0.0 } else { self.at.slant }, + size: self.at.size, + length: path_length.unwrap_or(length), + gaps, + }; + space_line(&mut t, &s); + // Set in a font the file carries for a family that isn't available: spaced again once that + // font is kept with the document ([`keep_file_fonts`]). + if self.file_font { + facts.respace = Some(Box::new(s)); } - t.cached_bounds = Some(bounds); Some((t, self.opacity, facts)) } } +/// What a line's spacing is measured from: where the file put its glyphs. Kept with a line set in +/// a font the file carries for a family that isn't available ([`LineFacts::respace`]), to be +/// measured again against that font once it is kept with the document ([`keep_file_fonts`]). +#[derive(Clone, Debug)] +pub(crate) struct Spacing { + /// The line's runs, unspaced. + runs: Vec, + /// Where the file put each character ([`TextLine::slots`]). + slots: Vec>, + /// How far along the line (or its path) the file put each glyph (points); `None` when the + /// glyphs aren't placed one by one (vertical type, type in visual order). + along: Option>, + /// The type's slant ([`Placement::slant`]; 0 on a path). + slant: f64, + size: f64, + /// How long the file set the line (points): along its path, to the end of a column, or to + /// the last glyph of a horizontal line that isn't a space. + length: f64, + /// The spaces read from gaps or drawn between glyphs: byte offset, width (points). + gaps: Vec<(usize, f64)>, +} + +/// Space `t` (whose runs are `s`'s, unspaced) as the file did ([`Spacing`]): each glyph where the +/// file put it (#722) with the kerning (the font's, or none) and tracking (one value for the line, +/// or each character its own) that place them there ([`place_each`]); else tracking that makes +/// the line as long as in the file (the PDF placed each glyph, the layout sets them by their +/// advances), spread over the gaps between characters (tracking follows each character, the last +/// one's past the end of the line). Its bounds are laid out too. +fn space_line(t: &mut TextObject, s: &Spacing) { + let db = vectorcraft_text::FontDb::global(); + t.runs = s.runs.clone(); + let on_path = !matches!(t.kind, TextKind::Point); + // Measured as point type: type on a path stops at the path's end, which tracking moves. + let point = |t: &TextObject| TextObject { kind: TextKind::Point, ..t.clone() }; + let placed = s.along.as_ref().and_then(|along| place_each(&point(t), &s.slots, along, s.slant, s.size)); + if let Some((runs, laid)) = placed { + t.runs = runs; + t.cached_bounds = Some(if on_path { vectorcraft_text::layout(db, t).bounds } else { laid.bounds }); + return; + } + let laid = vectorcraft_text::layout(db, &point(t)); + let natural: f64 = laid.glyphs.iter().map(|g| g.advance).sum(); + let chars: usize = t.runs.iter().map(|r| r.text.chars().count()).sum(); + let mut bounds = (!on_path).then_some(laid.bounds); + if chars > 1 && s.length.is_finite() && (s.length - natural).abs() > s.size * 0.01 { + let (tracking, spaces) = spacing(&laid, &s.gaps, s.length - natural, chars, s.size, spacing_em(t, s.size)); + t.runs = tracked(std::mem::take(&mut t.runs), tracking, &spaces); + // Tracked: laid out again for its bounds. + bounds = None; + } + t.cached_bounds = Some(bounds.unwrap_or_else(|| vectorcraft_text::layout(db, t).bounds)); +} + +/// The type among `nodes` (and in their groups) set in fonts the file carries for families that +/// aren't available, now kept with the document as `kept` (family and style → the font's blob): +/// drawn in them while its text is the file's ([`vectorcraft_doc::FileFonts`]), and spaced again +/// from where the file put each glyph, measured against the file's own widths (not the stand-in's, +/// which differ, #3756). +pub(crate) fn keep_file_fonts( + nodes: &mut [Arc], + lines: &HashMap, + kept: &HashMap<(String, String), String>, + images: &HashMap, +) { + if kept.is_empty() { + return; + } + for n in nodes.iter_mut() { + if n.children().is_some_and(|c| !c.is_empty()) + && let Some(children) = Arc::make_mut(n).children_mut() + { + keep_file_fonts(children, lines, kept, images); + } + let Some(s) = lines.get(&n.id).and_then(|f| f.respace.as_deref()) else { continue }; + let mut fonts: Vec = vec![]; + for r in &s.runs { + let (family, style) = (&r.style.font_family, &r.style.font_style); + if let Some(key) = kept.get(&(family.clone(), style.clone())) + && !fonts.iter().any(|f| f.family == *family && f.style == *style) + { + fonts.push(FileFont { family: family.clone(), style: style.clone(), key: key.clone() }); + } + } + if fonts.is_empty() { + continue; + } + if let NodeKind::Text(t) = &mut Arc::make_mut(n).kind { + let text: String = s.runs.iter().map(|r| r.text.as_str()).collect(); + t.file_fonts = Some(Box::new(FileFonts::new(fonts, &text))); + // A blob reference is not ownership until its actual document resource is bound. + vectorcraft_text::FontDb::global().bind_file_fonts(t, |key| images.get(key)); + space_line(t, s); + } + } +} + /// Where along the line (points) layout `laid` puts each character at a byte offset of `chars` /// (in order), and its advance: `None` for one inside another's cluster. Text in the file's order /// (left to right). @@ -1142,21 +1239,14 @@ fn restyled(t: &TextObject, kern: Option, own: &[f64]) -> Vec { /// file's widths (not the font's advances, which may be a hair off them) and kept on course where /// the differences add up ([`on_course`]). /// -/// The file put the glyph of each character with a [`Slot`] at `baseline` (one origin per glyph), -/// measured along `path` (type on a path: one curve per glyph) or along `line`'s baseline from its -/// origin, where a character shifted off it by its baseline shift draws that shift times `line`'s -/// slant further along (the type's skew leans it so, as the file's text rise did). `None` when the -/// font laid out isn't the file's (its advances differ from the file's): spacing measured against -/// a stand-in's widths would keep the stand-in's differences once the font is installed; or when -/// the glyphs can't be placed so (the layout joins characters the file drew apart). -fn place_each( - t: &TextObject, - slots: &[Option], - baseline: &[Point], - path: Option<&BezPath>, - line: Placement, - size: f64, -) -> Option<(Vec, TextLayout)> { +/// The file put the glyph of each character with a [`Slot`] `along` the line (points from its +/// origin, or along its path), where a character shifted off the baseline by its baseline shift +/// draws that shift times `slant` further along (the type's skew leans it so, as the file's text +/// rise did). `None` when the font laid out isn't the file's (its advances differ from the file's): +/// spacing measured against a stand-in's widths would keep the stand-in's differences once the +/// font is installed; or when the glyphs can't be placed so (the layout joins characters the file +/// drew apart). +fn place_each(t: &TextObject, slots: &[Option], along: &[f64], slant: f64, size: f64) -> Option<(Vec, TextLayout)> { let chars: Vec = t .runs .iter() @@ -1170,20 +1260,8 @@ fn place_each( if chars.len() < 2 || chars.len() != slots.len() || t.runs.iter().any(|r| r.inline.is_some()) { return None; } - // How far along the line the file put each glyph. - let along: Vec = match path { - Some(bp) => std::iter::once(0.0) - .chain(bp.segments().scan(0.0, |d, seg| { - *d += kurbo::ParamCurveArclen::arclen(&seg, 1e-3); - Some(*d) - })) - .take(baseline.len()) - .collect(), - None => baseline.iter().map(|p| (*p - line.origin).dot(line.dir)).collect(), - }; // Each character's baseline shift, which the type's slant draws `slant` times as far along. let shifts: Vec = t.runs.iter().flat_map(|r| r.text.chars().map(move |_| r.style.baseline_shift)).collect(); - let slant = if path.is_some() { 0.0 } else { line.slant }; // Each character's target: where the file put it, if it put it anywhere. let target: Vec)>> = slots.iter().zip(&shifts).map(|(s, shift)| s.and_then(|s| Some((*along.get(s.glyph)? - slant * shift, s.advance)))).collect(); diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index a5f93a2a76..51e0f3f1d7 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -51,6 +51,7 @@ mod forms; mod images; mod import; mod import_color; +mod import_fonts; mod import_image; mod import_lines; mod import_mask; @@ -151,6 +152,10 @@ pub struct ImportOptions { /// The file is an editor's own document (`.ai`): RGB in its `ICCBased` spaces keeps its numbers /// (see `Colors::uncalibrated_rgb`). Off for PDFs, whose profiles stand. pub uncalibrated_rgb: bool, + /// Type in a font the file embeds and this machine lacks is drawn in glyphs built from the + /// file's own, kept with the document (default); off, it is set in the fallback font, with the + /// missing-font warning, as before. + pub embedded_fonts: bool, } impl Default for ImportOptions { @@ -164,6 +169,7 @@ impl Default for ImportOptions { text_as: TextAs::default(), layers: true, uncalibrated_rgb: false, + embedded_fonts: true, } } } diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index e2abe87637..023c547611 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -20,6 +20,7 @@ mod dashalign; mod diamond; mod editing; mod encrypt; +mod file_fonts; mod file_info; mod focal; mod fx; diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index 9d333eecb3..12c382c514 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -1547,7 +1547,7 @@ fn gray_freeform_points_are_written_as_black_ink_in_a_cmyk_document() { #[test] fn press_quality_writes_an_rgb_image_in_a_cmyk_document_as_cmyk() { let rgb = image::RgbImage::from_fn(4, 4, |x, y| image::Rgb([(x * 60) as u8, (y * 60) as u8, 128])); - let blob = ImageBlob { mime: "image/png".into(), bytes: Arc::new(png(rgb)), proxy: None }; + let blob = ImageBlob { mime: "image/png".into(), bytes: Arc::new(png(rgb)), proxy: None, file_font: Default::default() }; let d = image_doc(blob, 4, 4); let press = builtin_presets().into_iter().find(|p| p.name == "Press Quality").unwrap().settings; assert_eq!(press.output.conversion, ColorConversion::PreserveNumbers); @@ -1569,7 +1569,7 @@ fn press_quality_writes_cmyk_in_an_rgb_document_too() { let ink = [0u8, 102, 255, 0]; let tiff = ImageBlob::cmyk_tiff(&Inks::new(4, 4, flat(ink, 16)).unwrap()).unwrap(); let rgb = image::RgbImage::from_fn(4, 4, |x, y| image::Rgb([(x * 60) as u8, (y * 60) as u8, 128])); - let png_blob = ImageBlob { mime: "image/png".into(), bytes: Arc::new(png(rgb)), proxy: None }; + let png_blob = ImageBlob { mime: "image/png".into(), bytes: Arc::new(png(rgb)), proxy: None, file_font: Default::default() }; for (what, blob) in [("CMYK image", tiff), ("RGB image", png_blob)] { let mut d = image_doc(blob, 4, 4); d.color_mode = ColorMode::Rgb; diff --git a/crates/pdf/src/tests/colorize.rs b/crates/pdf/src/tests/colorize.rs index 004f8f04ec..0a383feacf 100644 --- a/crates/pdf/src/tests/colorize.rs +++ b/crates/pdf/src/tests/colorize.rs @@ -343,7 +343,8 @@ fn separations_colorize_masked_pixels_whose_own_pixels_are_a_preview() { let spot = Paint::Solid { color: Color::cmyk(0.0, 1.0, 1.0, 0.0), swatch: Some("Ink".into()), tint: 1.0 }; let mut d = doc(ColorMode::Cmyk, Some(spot)); let preview = Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap()); - d.images.insert("pic".into(), ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) }); + d.images + .insert("pic".into(), ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() }); let img = craft_image_codecs::Image::from_raw(2, 1, craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, vec![0, 0, 255, 255]) .unwrap(); @@ -379,7 +380,8 @@ fn a_colorized_missing_link_placeholder_is_written_in_its_own_colors() { let placeholder = || { let mut d = doc(ColorMode::Cmyk, None); let bytes = Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap()); - d.images.insert("pic".into(), ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) }); + d.images + .insert("pic".into(), ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() }); d }; let plain = placeholder(); diff --git a/crates/pdf/src/tests/file_fonts.rs b/crates/pdf/src/tests/file_fonts.rs new file mode 100644 index 0000000000..cd175d0630 --- /dev/null +++ b/crates/pdf/src/tests/file_fonts.rs @@ -0,0 +1,276 @@ +//! Type in a font the PDF carries for a family that isn't installed keeps the file's glyphs and +//! their places until its text is edited ([`vectorcraft_doc::FileFonts`]): drawn as it is in the +//! same PDF whose font is installed, saved and read back so, and in the substitute once edited. + +use craft_pdf::write::backend as krilla; +use krilla::geom::Point as KPoint; +use krilla::page::PageSettings; +use krilla::text::{Font, GlyphId, KrillaGlyph, TextDirection}; +use kurbo::{Point, Rect, Shape}; +use vectorcraft_doc::{Document, FILE_FONT_MIME, TextObject}; +use vectorcraft_text::{FontDb, FontMatch}; + +use crate::tests::live_text::{SOURCE_SERIF, outlines, texts, uninstalled_serif}; +use crate::*; + +/// Lines of (x, y from the top, size, text): kerned pairs, a long line, two sizes. +const LINES: &[(f32, f32, f32, &str)] = + &[(20.0, 40.0, 24.0, "AVATAR Toyota"), (20.0, 80.0, 11.0, "Wavy quartz jumps over 12 lazy dogs."), (20.0, 120.0, 30.0, "Ky Wo")]; +/// A line set glyph by glyph, each 2 pt further on than its advance (as `Tc` or `TJ` set it). +const SPACED: (f32, f32, f32, &str) = (20.0, 160.0, 14.0, "Spaced out"); + +/// A page of [`LINES`] and [`SPACED`] in `font` (Source Serif 4 or a renamed copy), written as +/// writers write type: a subset of the font embedded as a CID-keyed TrueType font (Identity-H) with +/// a ToUnicode map. +fn page_pdf(font: Vec) -> Vec { + let mut pdf = krilla::Document::new(); + let mut page = pdf.start_page_with(PageSettings::from_wh(400.0, 200.0).unwrap()); + let mut s = page.surface(); + let kfont = Font::new(font.into(), 0).unwrap(); + for &(x, y, size, text) in LINES { + s.draw_text(KPoint::from_xy(x, y), kfont.clone(), size, text, false, TextDirection::Auto); + } + let face = FontDb::global().face("Source Serif 4", "Regular").unwrap(); + let (x, y, size, text) = SPACED; + let glyphs: Vec = text + .char_indices() + .map(|(i, c)| { + let g = face.glyph_for(c); + let advance = face.advance(g) / face.units_per_em() + 2.0 / f64::from(size); + KrillaGlyph::new(GlyphId::new(g), advance as f32, 0.0, 0.0, 0.0, i..i + c.len_utf8(), None) + }) + .collect(); + s.draw_glyphs(KPoint::from_xy(x, y), &glyphs, kfont, text, size, false); + s.finish(); + page.finish(); + pdf.finish().unwrap() +} + +fn import(bytes: &[u8]) -> ImportReport { + import_with_report(bytes, &ImportOptions::default()).unwrap() +} + +/// A drawn line: its text, and its glyphs' origins and ink boxes (document space). +type DrawnLine = (String, Vec<(Point, Option)>); + +/// Each line `db` lays the type of `d` out in ([`DrawnLine`]), sorted by text. +fn drawn(db: &FontDb, d: &Document) -> Vec { + let mut out = vec![]; + for t in texts(d) { + let lay = vectorcraft_text::layout(db, &t); + let plain = t.plain_text(); + for (i, line) in lay.lines.iter().enumerate() { + let glyphs = lay + .glyphs + .iter() + .filter(|g| g.line == i) + .map(|g| { + let ink = (!g.outline.elements().is_empty()).then(|| (t.xf * g.outline.clone()).bounding_box()); + (t.xf * g.origin, ink) + }) + .collect(); + out.push((plain[line.start..line.end].trim().to_string(), glyphs)); + } + } + out.sort_by(|a, b| a.0.cmp(&b.0)); + out +} + +/// The largest distance between the glyphs of `a` and `b`, line by line (their texts the same). +fn farthest(a: &[DrawnLine], b: &[DrawnLine]) -> f64 { + assert_eq!(a.iter().map(|l| &l.0).collect::>(), b.iter().map(|l| &l.0).collect::>(), "the same lines"); + let mut far: f64 = 0.0; + for ((text, ga), (_, gb)) in a.iter().zip(b) { + assert_eq!(ga.len(), gb.len(), "{text}"); + for ((pa, ia), (pb, ib)) in ga.iter().zip(gb) { + far = far.max((*pa - *pb).hypot()); + match (ia, ib) { + (Some(ia), Some(ib)) => { + far = far.max((ia.x0 - ib.x0).abs().max((ia.x1 - ib.x1).abs()).max((ia.y0 - ib.y0).abs()).max((ia.y1 - ib.y1).abs())) + } + (None, None) => {} + _ => panic!("{text}: ink on one side only"), + } + } + } + far +} + +fn text_of<'a>(d: &'a [TextObject], text: &str) -> &'a TextObject { + d.iter() + .find(|t| t.plain_text() == text) + .unwrap_or_else(|| panic!("no `{text}` among {:?}", d.iter().map(TextObject::plain_text).collect::>())) +} + +#[test] +fn type_in_a_font_the_file_carries_keeps_its_glyphs_and_places() { + let db = FontDb::global(); + let installed = import(&page_pdf(SOURCE_SERIF.to_vec())); + let carried = import(&page_pdf(uninstalled_serif())); + let t = texts(&carried.document); + assert_eq!(t.len(), LINES.len() + 1, "a line stays a line: {:?}", t.iter().map(TextObject::plain_text).collect::>()); + // Named by the file's font, which stays missing (Find Font and the Missing Fonts dialog list it). + let st = text_of(&t, "AVATAR Toyota").first_style(); + assert_eq!(st.font_family, "Source Serif 9"); + assert_eq!(db.resolve(&st.font_family, &st.font_style).map(|(_, m)| m), Some(FontMatch::Missing)); + // Drawn as the same file whose font is installed: the file's glyphs, where the file put them. + let far = farthest(&drawn(db, &carried.document), &drawn(db, &installed.document)); + assert!(far < 0.02, "glyphs {far} pt off the installed font's"); + // Every glyph from the font the file carries, which the document keeps. + for t in &t { + let lay = vectorcraft_text::layout(db, t); + assert!(lay.glyphs.iter().all(|g| db.is_file_font(g.font_id)), "{}", t.plain_text()); + let key = &t.file_fonts.as_ref().unwrap().fonts[0].key; + assert_eq!(carried.document.images[key].mime, FILE_FONT_MIME); + } + assert_eq!(carried.document.images.values().filter(|b| b.mime == FILE_FONT_MIME).count(), 1, "one font for the family and style"); + // Where the file put them: the ink is the file's own glyphs' (read as outlines). + let as_outlines = import_with_report(&page_pdf(uninstalled_serif()), &ImportOptions { text_as: TextAs::Outlines, ..Default::default() }).unwrap(); + let ink = drawn(db, &carried.document).iter().flat_map(|(_, g)| g.iter().filter_map(|(_, i)| *i)).reduce(|a, b| a.union(b)).unwrap(); + let file = outlines(&as_outlines.document).bounding_box(); + let off = (ink.x0 - file.x0).abs().max((ink.x1 - file.x1).abs()).max((ink.y0 - file.y0).abs()).max((ink.y1 - file.y1).abs()); + assert!(off < 0.05, "{ink:?} vs the file's {file:?}"); + // Spacing measured from the file's widths, as with the font installed (not a stand-in's, #3756). + let tracking = |d: &Document| text_of(&texts(d), "Spaced out").first_style().tracking; + assert!( + (tracking(&carried.document) - tracking(&installed.document)).abs() < 1.0, + "{} vs {}", + tracking(&carried.document), + tracking(&installed.document) + ); + assert!(carried.warnings.iter().any(|w| w.contains("Source Serif 9") && w.contains("until their text is edited")), "{:?}", carried.warnings); +} + +#[test] +fn edited_type_takes_the_substitute_and_unedited_type_keeps_the_files_font() { + let db = FontDb::global(); + let carried = import(&page_pdf(uninstalled_serif())); + let t = text_of(&texts(&carried.document), "AVATAR Toyota").clone(); + let from_file = |t: &TextObject| vectorcraft_text::layout(db, t).glyphs.iter().filter(|g| db.is_file_font(g.font_id)).count(); + assert_eq!(from_file(&t), vectorcraft_text::layout(db, &t).glyphs.len(), "every glyph"); + // Moved or resized, the text is the file's: still its font. + let mut moved = t.clone(); + moved.xf = kurbo::Affine::translate((40.0, 10.0)) * moved.xf; + for r in &mut moved.runs { + r.style.size *= 2.0; + } + assert!(from_file(&moved) > 0); + // Edited: the substitute (the run still names the missing font). + let mut edited = t.clone(); + edited.runs[0].text.insert(0, 'Z'); + assert!(edited.file_fonts_in_use().is_empty()); + assert_eq!(from_file(&edited), 0); + assert_eq!(edited.first_style().font_family, "Source Serif 9"); + // Undone, the file's again. + edited.runs[0].text.remove(0); + assert_eq!(from_file(&edited), from_file(&t)); +} + +#[test] +fn a_font_that_is_installed_keeps_drawing_its_type() { + // With the family installed nothing is kept: the type is set in the installed font as before. + let installed = import(&page_pdf(SOURCE_SERIF.to_vec())); + assert!(!installed.document.images.values().any(|b| b.mime == FILE_FONT_MIME)); + assert!(texts(&installed.document).iter().all(|t| t.file_fonts.is_none())); +} + +/// `ImportOptions::embedded_fonts` on (the default): type in an embedded font the machine lacks +/// carries the file's glyphs (a font blob kept with the document) and the text keeps naming the +/// file's font. +#[test] +fn embedded_fonts_on_keeps_the_files_glyphs() { + let r = import_with_report(&page_pdf(uninstalled_serif()), &ImportOptions { embedded_fonts: true, ..Default::default() }).unwrap(); + assert!(r.document.images.values().any(|b| b.mime == FILE_FONT_MIME), "a font kept with the document"); + assert!(texts(&r.document).iter().any(|t| t.file_fonts.is_some()), "its type draws in the file's font"); +} + +/// Off (Preferences › File Handling › Use fonts embedded in imported PDFs): import behaves as it +/// did without the feature: no font is kept, the type is set in the fallback font and the missing +/// font is warned about. +#[test] +fn embedded_fonts_off_sets_type_in_the_fallback_font_with_the_warning() { + let r = import_with_report(&page_pdf(uninstalled_serif()), &ImportOptions { embedded_fonts: false, ..Default::default() }).unwrap(); + assert!(!r.document.images.values().any(|b| b.mime == FILE_FONT_MIME), "no font kept"); + assert!(texts(&r.document).iter().all(|t| t.file_fonts.is_none()), "no type draws in a file font"); + assert!(r.warnings.iter().any(|w| w.contains("Source Serif 9")), "the missing font is named: {:?}", r.warnings); + let st = texts(&r.document)[0].first_style().clone(); + assert_eq!(st.font_family, "Source Serif 9", "the text still names the file's font"); +} + +/// A page with the glyph of `a`, then of `b`, then of `a` again, each on its own line and each +/// named `a` by the ToUnicode map: two different glyphs of the embedded font for one character. +fn two_glyphs_pdf() -> Vec { + let face = FontDb::global().face("Source Serif 4", "Regular").unwrap(); + let mut pdf = krilla::Document::new(); + let mut page = pdf.start_page_with(PageSettings::from_wh(400.0, 200.0).unwrap()); + let mut s = page.surface(); + let font = Font::new(uninstalled_serif().into(), 0).unwrap(); + // Glyph `from` standing for the character "a", on its own line at y. + let mut draw = |y: f32, from: char| { + let g = KrillaGlyph::new(GlyphId::new(face.glyph_for(from)), 0.5, 0.0, 0.0, 0.0, 0..1, None); + s.draw_glyphs(KPoint::from_xy(20.0, y), &[g], font.clone(), "a", 30.0, false); + }; + draw(40.0, 'a'); + draw(100.0, 'b'); + draw(160.0, 'a'); + s.finish(); + page.finish(); + pdf.finish().unwrap() +} + +/// The ink box of the glyph on each of the page's three lines (set at 40, 100 and 160 pt from the +/// top) as `d` draws it: type laid out by `db` and outline paths, which an import may merge into +/// one path for the page, so their subpaths are told apart by the line they lie on. +fn glyph_ink(db: &FontDb, d: &Document) -> Vec { + let mut lines: [Option; 3] = [None; 3]; + let mut add = |path: &kurbo::BezPath| { + let mut start = 0; + let els = path.elements(); + for end in (1..=els.len()).filter(|&e| e == els.len() || matches!(els[e], kurbo::PathEl::MoveTo(_))) { + let ink = kurbo::BezPath::from_vec(els[start..end].to_vec()).bounding_box(); + let line = usize::from(ink.center().y > 70.0) + usize::from(ink.center().y > 130.0); + lines[line] = Some(lines[line].map_or(ink, |l| l.union(ink))); + start = end; + } + }; + for t in texts(d) { + for g in vectorcraft_text::layout(db, &t).glyphs { + add(&(t.xf * g.outline.clone())); + } + } + d.walk(|n| { + if let vectorcraft_doc::NodeKind::Path { path, .. } = &n.kind { + add(&path.to_bezpath()); + } + }); + lines.into_iter().flatten().collect() +} + +/// Two different glyphs of the embedded font that map to one character (a normal and an alternate +/// `a`, here the glyphs of `a` and `b` both named `a` by the ToUnicode map) can't both go into the +/// font kept with the document, which has one glyph per character: the line with the other glyph is +/// kept as outlines. Each glyph is the one the file draws, where it draws it: the outlines of the same page +/// imported as outlines are the reference (the save and reopen half is `two_glyphs_for_one_character_survive_a_native_save_and_reopen` in the engine). +#[test] +fn two_glyphs_for_one_character_both_survive_import() { + let db = FontDb::global(); + let bytes = two_glyphs_pdf(); + let reference = glyph_ink(db, &import_with_report(&bytes, &ImportOptions { text_as: TextAs::Outlines, ..Default::default() }).unwrap().document); + assert_eq!(reference.len(), 3, "the file draws three glyphs: {reference:?}"); + assert!((reference[0].height() - reference[1].height()).abs() > 2.0, "the file's two glyphs differ in shape: {reference:?}"); + assert!((reference[0].height() - reference[2].height()).abs() < 0.01, "and the first and third are the same glyph: {reference:?}"); + + let imported = import(&bytes).document; + let text: Vec = texts(&imported).iter().map(|t| t.plain_text()).collect(); + assert!(text.iter().any(|t| t == "a"), "the glyphs the font keeps stay live type: {text:?}"); + assert!(text.len() < 3, "the line with the other glyph is not live type: {text:?}"); + + let close = |got: &[Rect], what: &str| { + assert_eq!(got.len(), reference.len(), "{what}: {got:?}"); + for (got, want) in got.iter().zip(&reference) { + let off = (got.x0 - want.x0).abs().max((got.x1 - want.x1).abs()).max((got.y0 - want.y0).abs()).max((got.y1 - want.y1).abs()); + assert!(off < 0.25, "{what}: {got:?} is {off} pt from the file's {want:?}"); + } + }; + close(&glyph_ink(db, &imported), "imported"); +} diff --git a/crates/pdf/src/tests/live_text.rs b/crates/pdf/src/tests/live_text.rs index bddeb758d2..c1c57fbf0f 100644 --- a/crates/pdf/src/tests/live_text.rs +++ b/crates/pdf/src/tests/live_text.rs @@ -10,7 +10,7 @@ use vectorcraft_doc::{Document, NodeKind, TextObject}; use crate::*; const SOURCE_SANS: &[u8] = include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf"); -const SOURCE_SERIF: &[u8] = include_bytes!("../../../../assets/fonts/SourceSerif4-Regular.ttf"); +pub(crate) const SOURCE_SERIF: &[u8] = include_bytes!("../../../../assets/fonts/SourceSerif4-Regular.ttf"); /// A 300 × 200 pt page with `lines` of (x, y from the top, size, text) in Source Sans 3, and the /// same rotated 90° when `rotated`. @@ -33,7 +33,7 @@ pub(crate) fn text_pdf(lines: &[(f32, f32, f32, &str)], rotated: bool) -> Vec Vec { +pub(crate) fn texts(d: &Document) -> Vec { let mut v = vec![]; d.walk(|n| { if let NodeKind::Text(t) = &n.kind { @@ -294,7 +294,7 @@ fn uninstalled_font() -> Vec { /// Source Serif 4 renamed `SourceSerif9-Regular`, family Source Serif 9: a serif font that isn't /// installed (the fallback font, Source Sans 3, is a sans). -fn uninstalled_serif() -> Vec { +pub(crate) fn uninstalled_serif() -> Vec { renamed(SOURCE_SERIF, &[("SourceSerif4", "SourceSerif9"), ("Source Serif 4", "Source Serif 9")]) } @@ -310,7 +310,7 @@ fn one_line_pdf(font: Vec, text: &str) -> Vec { } /// The outlines text imported as (`textAs: outlines`), as one path. -fn outlines(d: &Document) -> kurbo::BezPath { +pub(crate) fn outlines(d: &Document) -> kurbo::BezPath { let mut all = kurbo::BezPath::new(); d.walk(|n| { if let NodeKind::Path { path, .. } = &n.kind { diff --git a/crates/render/src/tests/colorize.rs b/crates/render/src/tests/colorize.rs index 38f3b6dca5..d1c5082c14 100644 --- a/crates/render/src/tests/colorize.rs +++ b/crates/render/src/tests/colorize.rs @@ -284,7 +284,7 @@ fn colorize_dims_with_the_grays() { fn a_colorized_missing_link_placeholder_draws_in_its_own_colors() { let proxy = |bytes: Vec| { let bytes = std::sync::Arc::new(bytes); - ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) } + ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() } }; let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); let sharp = RenderOptions { smooth_images: false, ..Default::default() }; diff --git a/crates/render/src/tests/fontchange.rs b/crates/render/src/tests/fontchange.rs index 9174696d20..24ac40271a 100644 --- a/crates/render/src/tests/fontchange.rs +++ b/crates/render/src/tests/fontchange.rs @@ -75,6 +75,55 @@ fn type_redraws_when_its_font_becomes_available() { assert_eq!(after, Renderer::new().render(&d, 300, 150, Affine::IDENTITY, &opts).pixels, "as a new renderer draws it"); } +/// Same serialized text and node ids are not the same glyph geometry when each document owns +/// different file-font bytes. Both fonts are bound before either render, so generation is steady. +#[test] +fn file_font_geometry_is_scoped_to_owned_resources_not_serialized_keys() { + use vectorcraft_doc::{FILE_FONT_MIME, FileFont, FileFonts, ImageBlob}; + use vectorcraft_text::{FileFontInfo, FileGlyph, FontDb, build_file_font}; + + let _adding = adding_fonts(); + let make = |width| { + const FAMILY: &str = "Rendered Owned File Font Regression"; + let info = FileFontInfo { family: FAMILY.into(), style: "Regular".into(), ..Default::default() }; + let g = FileGlyph { ch: 'x', outline: Rect::new(0.0, 0.0, width, 700.0).to_path(0.1), advance: width + 100.0 }; + let mut doc = Document::new(100.0, 100.0); + doc.images.insert("chosen".into(), ImageBlob::new(FILE_FONT_MIME, build_file_font(&info, &[g]).unwrap())); + let style = CharStyle { size: 60.0, font_family: FAMILY.into(), ..Default::default() }; + let mut t = TextObject::point(Point::new(10.0, 70.0), "x", style); + t.file_fonts = Some(Box::new(FileFonts::new(vec![FileFont { family: FAMILY.into(), style: "Regular".into(), key: "chosen".into() }], "x"))); + let id = doc.alloc_id(); + let layer = doc.layers[0].id; + doc.insert(Some(layer), 0, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap(); + assert!(FontDb::global().bind_document_file_fonts(&mut doc).is_empty()); + doc + }; + let (a, b) = (make(200.0), make(800.0)); + let renderer = with_fonts_unchanged(|| { + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let mut reused = Renderer::new(); + let first = reused.render(&a, 100, 100, Affine::IDENTITY, &opts).pixels; + let second = reused.render(&b, 100, 100, Affine::IDENTITY, &opts).pixels; + let fresh = Renderer::new().render(&b, 100, 100, Affine::IDENTITY, &opts).pixels; + assert_ne!(first, second, "B must draw its own wider glyph"); + assert_eq!(second, fresh, "a renderer must not reuse A's glyph geometry for B"); + reused + }); + let mut faces = vec![]; + for doc in [&a, &b] { + doc.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + faces.extend(FontDb::global().file_faces(t).into_iter().flatten().map(|face| Arc::downgrade(&face))); + } + }); + } + assert_eq!(faces.len(), 2); + drop(a); + drop(b); + assert!(!renderer.texts.is_empty(), "the idle renderer still holds its old text nodes"); + assert!(faces.iter().all(|face| face.upgrade().is_none()), "geometry-cache nodes must not pin document font allowance"); +} + /// Type with raster effects redraws in a font that becomes available: its drop shadow and its /// blurred content are made again. #[test] diff --git a/crates/render/src/text_geom.rs b/crates/render/src/text_geom.rs index eaa15a6841..4d56e94e52 100644 --- a/crates/render/src/text_geom.rs +++ b/crates/render/src/text_geom.rs @@ -166,18 +166,22 @@ pub(crate) fn text_geom_snapped(t: &TextObject, snap: Option) -> TextGeo _ => spans.push((run, start, end)), } }; - // Per run: is its family missing, and the face its glyphs should come from. + // Per run: is its family missing, and the face its glyphs should come from. A run drawn in a + // font its file carried isn't substituted: its glyphs come from that font. + let file = db.file_faces(t); let faces: Vec<(bool, Option)> = t .runs .iter() - .map(|r| match db.resolve(&r.style.font_family, &r.style.font_style) { + .enumerate() + .map(|(i, r)| match (file.get(i).and_then(Option::as_ref), db.resolve(&r.style.font_family, &r.style.font_style)) { + (Some(f), _) => (false, Some(f.id())), // The version the type names, when it's installed (see `FontDb::face_version`), at its // Variable Font settings (see `FontDb::style_face`). - Some((f, m)) => { + (None, Some((f, m))) => { let face = db.style_face(&r.style).unwrap_or(f); (m == vectorcraft_text::FontMatch::Missing, Some(face.id())) } - None => (true, None), + (None, None) => (true, None), }) .collect(); let (mut substituted_fonts, mut substituted_glyphs, mut alternate_candidates) = (BezPath::new(), BezPath::new(), vec![]); diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index 7cf350e5e1..19d719ccf3 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -795,7 +795,7 @@ impl Importer { let link = linked.map(|l| l.link.clone()); let key = self.image_key(source, bytes, link.as_ref().map(|l| l.path.as_str())); self.doc.images.entry(key.clone()).or_insert_with(|| { - let blob = ImageBlob { mime: mime.into(), bytes: bytes.clone(), proxy: missing.then(|| bytes.clone()) }; + let blob = ImageBlob { mime: mime.into(), bytes: bytes.clone(), proxy: missing.then(|| bytes.clone()), file_font: Default::default() }; if link.is_some() && !missing { blob.with_proxy() } else { blob } }); let xf = acc * Affine::scale_non_uniform(size.width() as f64 / pw as f64, size.height() as f64 / ph as f64); diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index 07695b034c..b667c5d9bb 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -39,9 +39,13 @@ unicode-normalization = "0.1.26" # Draws COLR colour glyphs whose paints documents have no form for (sweep gradients, compositing # modes) into images: the canvas's renderer, already in the build. vello_cpu = { workspace = true } -# Builds a small variable font for tests (`test_fonts`; no font file is committed). MIT OR -# Apache-2.0, already in the build through subsetter. -write-fonts = { version = "0.48", optional = true } +# Builds the fonts files carried for their type (`file_font`: a PDF's embedded fonts, from the +# glyphs it drew) and a small variable font for tests (`test_fonts`; no font file is committed). +# MIT OR Apache-2.0, already in the build through subsetter. +write-fonts = "0.48" + +[dev-dependencies] +serde_json = { workspace = true } [features] default = ["bundled-fonts"] @@ -52,10 +56,7 @@ default = ["bundled-fonts"] # vectorcraft-ui-egui and vectorcraft-mcp by default through the engine. bundled-fonts = [] # `vectorcraft_text::test_fonts` for other crates' tests (dev-dependencies only). -test-fonts = ["dep:write-fonts"] - -[dev-dependencies] -write-fonts = "0.48" +test-fonts = [] # Fonts registered with Windows outside its font folders ("install as shortcut", installers); # MIT OR Apache-2.0, a safe wrapper of the registry API from the windows-rs project. diff --git a/crates/text/src/file_font.rs b/crates/text/src/file_font.rs new file mode 100644 index 0000000000..21215aa5f5 --- /dev/null +++ b/crates/text/src/file_font.rs @@ -0,0 +1,462 @@ +//! Fonts files carried for type whose fonts aren't available here ([`vectorcraft_doc::FileFonts`]): +//! a TrueType font built from the glyphs a file drew, each with the outline and advance the file +//! gave it, for the character it shows. Built from outlines, it is the same whatever the file's +//! font program was (Type 1, CFF or TrueType, simple or CID-keyed): CFF's cubic curves become +//! quadratic ones within a quarter of a thousandth of an em. + +use kurbo::{BezPath, PathEl, Shape}; +use write_fonts::FontBuilder; +use write_fonts::tables::cmap::Cmap; +use write_fonts::tables::glyf::{Bbox, GlyfLocaBuilder, Glyph, SimpleGlyph}; +use write_fonts::tables::head::{Flags, Head, MacStyle}; +use write_fonts::tables::hhea::Hhea; +use write_fonts::tables::hmtx::{Hmtx, LongMetric}; +use write_fonts::tables::maxp::Maxp; +use write_fonts::tables::os2::{Os2, SelectionFlags}; +use write_fonts::tables::post::Post; +use write_fonts::types::{FWord, Fixed, GlyphId, Tag, UfWord, Version16Dot16}; + +/// Units per em of the fonts built: two per thousandth of an em, the unit of PDF glyph space, so +/// the widths a file gives in whole and half thousandths stay exact. +pub const FILE_FONT_UPEM: u16 = 2000; +/// Font units per thousandth of an em. +const SCALE: f64 = FILE_FONT_UPEM as f64 / 1000.0; +/// How far a quadratic curve may stray from the cubic it stands for (font units). +const ACCURACY: f64 = 0.5; +/// The most glyphs a font is built with: TrueType counts them in 16 bits, `.notdef` included. +pub const MAX_FILE_GLYPHS: usize = 65_534; +/// The furthest a point may lie from the glyph's origin (font units): further, the glyph is left +/// out (its character takes the substitute). +const MAX_COORD: f64 = 30_000.0; + +/// A glyph a file drew: the character it shows, its outline (thousandths of an em, y up, as PDF +/// glyph space measures) and its advance (thousandths of an em). +#[derive(Clone, Debug)] +pub struct FileGlyph { + pub ch: char, + pub outline: BezPath, + pub advance: f64, +} + +/// What a font built from a file's glyphs is called and how it is set. +#[derive(Clone, Debug, Default)] +pub struct FileFontInfo { + pub family: String, + pub style: String, + /// The PostScript name of the file's font (without a subset's tag). + pub postscript: String, + /// Ascent and descent (thousandths of an em, the descent below the baseline negative). + pub ascent: f64, + pub descent: f64, + /// The file's font's licence flags (OS/2 `fsType`) when it says; else 4, print and preview, + /// which lets an export embed it as the file did. + pub fs_type: Option, +} + +/// A TrueType font of `glyphs` (the first glyph of each character; at most [`MAX_FILE_GLYPHS`]) +/// named and set as `info` says. A glyph whose outline can't be written is left out: its character +/// takes the substitute. `None` when no glyph can be written. +pub fn build_file_font(info: &FileFontInfo, glyphs: &[FileGlyph]) -> Option> { + let mut seen = std::collections::HashSet::new(); + let mut made: Vec<(char, Glyph, u16)> = vec![]; + for g in glyphs { + if made.len() >= MAX_FILE_GLYPHS { + break; + } + if seen.contains(&g.ch) { + continue; + } + let Some(glyph) = glyph(&g.outline) else { continue }; + let advance = (g.advance * SCALE).round(); + let advance = if advance.is_finite() { advance.clamp(0.0, f64::from(u16::MAX)) as u16 } else { 0 }; + seen.insert(g.ch); + made.push((g.ch, glyph, advance)); + } + if made.is_empty() { + return None; + } + let notdef = (Glyph::Empty, FILE_FONT_UPEM / 2); + let all = std::iter::once((¬def.0, notdef.1)).chain(made.iter().map(|(_, g, a)| (g, *a))); + let mut glyf = GlyfLocaBuilder::new(); + let mut metrics = vec![]; + let mut bounds: Option = None; + let (mut max_points, mut max_contours) = (0usize, 0usize); + let (mut min_lsb, mut min_rsb, mut max_extent, mut max_advance) = (i16::MAX, i16::MAX, i16::MIN, 0u16); + for (g, advance) in all { + glyf.add_glyph(g).ok()?; + let b = match g { + Glyph::Simple(s) => { + max_points = max_points.max(s.contours.iter().map(|c| c.len()).sum()); + max_contours = max_contours.max(s.contours.len()); + Some(s.bbox) + } + _ => None, + }; + let lsb = b.map_or(0, |b| b.x_min); + if let Some(b) = b { + bounds = Some(bounds.map_or(b, |u| u.union(b))); + min_lsb = min_lsb.min(b.x_min); + min_rsb = min_rsb.min((i32::from(advance) - i32::from(b.x_max)).clamp(i16::MIN.into(), i16::MAX.into()) as i16); + max_extent = max_extent.max(b.x_max); + } + max_advance = max_advance.max(advance); + metrics.push(LongMetric::new(advance, lsb)); + } + let (glyf, loca, loca_format) = glyf.build(); + let count = u16::try_from(metrics.len()).ok()?; + let bounds = bounds.unwrap_or_default(); + let units = |v: f64| { + let v = (v * SCALE).round(); + if v.is_finite() { v.clamp(f64::from(i16::MIN), f64::from(i16::MAX)) as i16 } else { 0 } + }; + // A font without them stands on an em from 0.88 up to 0.12 down, as PDF's vertical metrics do. + let ascent = if info.ascent > 0.0 { units(info.ascent) } else { units(880.0) }; + let descent = if info.descent < 0.0 { units(info.descent) } else { units(-120.0) }; + let bold = info.style.to_ascii_lowercase().contains("bold"); + let italic = ["italic", "oblique"].iter().any(|s| info.style.to_ascii_lowercase().contains(s)); + let head = Head { + font_revision: Fixed::from_f64(1.0), + flags: Flags::from_bits_truncate(0b1011), + units_per_em: FILE_FONT_UPEM, + x_min: bounds.x_min, + y_min: bounds.y_min, + x_max: bounds.x_max, + y_max: bounds.y_max, + mac_style: MacStyle::from_bits_truncate(u16::from(bold) | (u16::from(italic) << 1)), + lowest_rec_ppem: 6, + index_to_loc_format: loca_format as i16, + ..Head::default() + }; + let hhea = Hhea { + ascender: FWord::new(ascent), + descender: FWord::new(descent), + line_gap: FWord::new(0), + advance_width_max: UfWord::new(max_advance), + min_left_side_bearing: FWord::new(if min_lsb == i16::MAX { 0 } else { min_lsb }), + min_right_side_bearing: FWord::new(if min_rsb == i16::MAX { 0 } else { min_rsb }), + x_max_extent: FWord::new(if max_extent == i16::MIN { 0 } else { max_extent }), + caret_slope_rise: 1, + caret_slope_run: 0, + caret_offset: 0, + number_of_h_metrics: count, + }; + let maxp = Maxp { + num_glyphs: count, + max_points: Some(u16::try_from(max_points).unwrap_or(u16::MAX)), + max_contours: Some(u16::try_from(max_contours).unwrap_or(u16::MAX)), + max_composite_points: Some(0), + max_composite_contours: Some(0), + max_zones: Some(1), + max_twilight_points: Some(0), + max_storage: Some(0), + max_function_defs: Some(0), + max_instruction_defs: Some(0), + max_stack_elements: Some(0), + max_size_of_instructions: Some(0), + max_component_elements: Some(0), + max_component_depth: Some(0), + }; + let chars: Vec = made.iter().map(|(c, ..)| u32::from(*c)).collect(); + let first = chars.iter().copied().min().unwrap_or(0).min(0xffff) as u16; + let last = chars.iter().copied().max().unwrap_or(0).min(0xffff) as u16; + let advances: Vec = metrics.iter().skip(1).map(|m| u32::from(m.advance)).filter(|a| *a > 0).collect(); + let avg = advances.iter().sum::().checked_div(advances.len() as u32).unwrap_or(0); + let selection = if bold || italic { + u16::from(italic) | (u16::from(bold) << 5) + } else { + // Regular, and the typographic ascent and descent are the line's. + 0x40 | 0x80 + }; + let os2 = Os2 { + x_avg_char_width: i16::try_from(avg).unwrap_or(i16::MAX), + us_weight_class: if bold { 700 } else { 400 }, + us_width_class: 5, + fs_type: info.fs_type.unwrap_or(4), + y_strikeout_size: units(50.0), + y_strikeout_position: units(250.0), + ach_vend_id: Tag::new(b"NONE"), + fs_selection: SelectionFlags::from_bits_truncate(selection), + us_first_char_index: first, + us_last_char_index: last, + s_typo_ascender: ascent, + s_typo_descender: descent, + s_typo_line_gap: 0, + us_win_ascent: u16::try_from(ascent.max(bounds.y_max)).unwrap_or(0), + us_win_descent: u16::try_from(-i32::from(descent.min(bounds.y_min))).unwrap_or(0), + ul_code_page_range_1: Some(0), + ul_code_page_range_2: Some(0), + sx_height: Some(0), + s_cap_height: Some(0), + us_default_char: Some(0), + us_break_char: Some(32), + us_max_context: Some(1), + ..Os2::default() + }; + let post = Post { + version: Version16Dot16::VERSION_3_0, + underline_position: FWord::new(units(-75.0)), + underline_thickness: FWord::new(units(50.0)), + ..Post::default() + }; + let cmap = Cmap::from_mappings(made.iter().enumerate().map(|(i, (c, ..))| (*c, GlyphId::new(i as u32 + 1)))).ok()?; + let hmtx = Hmtx::new(metrics, vec![]); + let full = if info.style.is_empty() { info.family.clone() } else { format!("{} {}", info.family, info.style) }; + let name = name_table(&[(1, &info.family), (2, &info.style), (4, &full), (5, "Version 1.0"), (6, &postscript_name(&info.postscript))])?; + let mut b = FontBuilder::new(); + b.add_table(&head).ok()?; + b.add_table(&hhea).ok()?; + b.add_table(&maxp).ok()?; + b.add_table(&os2).ok()?; + b.add_table(&hmtx).ok()?; + b.add_table(&cmap).ok()?; + b.add_table(&post).ok()?; + b.add_table(&glyf).ok()?; + b.add_table(&loca).ok()?; + b.add_raw(Tag::new(b"name"), name); + Some(b.build()) +} + +/// The largest coordinate of a glyph outline read from a file, in the file's units (thousandths of +/// an em). Far past any glyph; a curve control point beyond it leaves the glyph out. +const MAX_INPUT: f64 = 1e6; + +/// `outline` (thousandths of an em, y up) as a TrueType glyph in font units: its cubic curves as +/// quadratic ones, its contours that draw nothing (a lone point) left out. `Glyph::Empty` for a +/// glyph without ink (a space); `None` when it can't be written (points that aren't numbers or lie +/// too far out, a malformed path). +fn glyph(outline: &BezPath) -> Option { + let at = |p: kurbo::Point| kurbo::Point::new(p.x * SCALE, p.y * SCALE); + let mut out = BezPath::new(); + // The contour being read: its start, and its drawing commands (font units). + let mut contour: Option<(kurbo::Point, Vec)> = None; + let mut last = kurbo::Point::ZERO; + let flush = |c: Option<(kurbo::Point, Vec)>, out: &mut BezPath| { + if let Some((start, els)) = c.filter(|(_, els)| !els.is_empty()) { + out.move_to(start); + for e in els { + out.push(e); + } + out.close_path(); + } + }; + // A point that isn't a number can't be written (nor bounded: `min`/`max` skip NaN), and one + // far outside any glyph would make the curve subdivision below enormous. + let sane = |p: kurbo::Point| p.is_finite() && p.x.abs() <= MAX_INPUT && p.y.abs() <= MAX_INPUT; + let finite = |el: &PathEl| match *el { + PathEl::MoveTo(p) | PathEl::LineTo(p) => sane(p), + PathEl::QuadTo(a, p) => sane(a) && sane(p), + PathEl::CurveTo(a, b, p) => sane(a) && sane(b) && sane(p), + PathEl::ClosePath => true, + }; + if !outline.elements().iter().all(finite) { + return None; + } + for el in outline.elements() { + let p = match *el { + PathEl::MoveTo(p) => { + flush(contour.take(), &mut out); + last = at(p); + contour = Some((last, vec![])); + continue; + } + PathEl::ClosePath => { + if let Some((start, _)) = &contour { + last = *start; + } + flush(contour.take(), &mut out); + continue; + } + PathEl::LineTo(p) | PathEl::QuadTo(_, p) | PathEl::CurveTo(_, _, p) => at(p), + }; + // A drawing command without a move goes on from where the pen is. + let (_, els) = contour.get_or_insert((last, vec![])); + match *el { + PathEl::QuadTo(c, _) => els.push(PathEl::QuadTo(at(c), p)), + PathEl::CurveTo(c1, c2, _) => { + let cubic = kurbo::CubicBez::new(last, at(c1), at(c2), p); + els.extend(cubic.to_quads(ACCURACY).map(|(.., q)| PathEl::QuadTo(q.p1, q.p2))); + } + _ => els.push(PathEl::LineTo(p)), + } + last = p; + } + flush(contour.take(), &mut out); + if out.elements().is_empty() { + return Some(Glyph::Empty); + } + let b = out.bounding_box(); + if !(b.is_finite() && b.x0 > -MAX_COORD && b.y0 > -MAX_COORD && b.x1 < MAX_COORD && b.y1 < MAX_COORD) { + return None; + } + SimpleGlyph::from_bezpath(&out).ok().map(Glyph::Simple) +} + +/// `name` as a PostScript name: printable ASCII other than the characters PostScript reserves, at +/// most 63 of them ("Font" when none is left). +fn postscript_name(name: &str) -> String { + let s: String = name.chars().filter(|c| c.is_ascii_graphic() && !"[](){}<>/%".contains(*c)).take(63).collect(); + if s.is_empty() { "Font".to_string() } else { s } +} + +/// A `name` table of Windows English (US) records (name id, string). +pub(crate) fn name_table(records: &[(u16, &str)]) -> Option> { + let mut records = records.to_vec(); + records.sort_by_key(|r| r.0); + let n = u16::try_from(records.len()).ok()?; + let (mut head, mut strings) = (Vec::new(), Vec::new()); + for v in [0, n, 6 + 12 * n] { + head.extend_from_slice(&v.to_be_bytes()); + } + for (id, s) in records { + let bytes: Vec = s.encode_utf16().flat_map(u16::to_be_bytes).collect(); + for v in [3, 1, 0x0409, id, u16::try_from(bytes.len()).ok()?, u16::try_from(strings.len()).ok()?] { + head.extend_from_slice(&v.to_be_bytes()); + } + strings.extend(bytes); + } + head.extend(strings); + Some(head) +} + +#[cfg(test)] +mod tests { + use kurbo::{Affine, Rect}; + use skrifa::MetadataProvider; + + use super::*; + use crate::FontDb; + + /// Source Serif 4's glyphs of `text` as a PDF draws them (thousandths of an em, y up). + fn glyphs(text: &str) -> Vec { + let db = FontDb::global(); + let face = db.face("Source Serif 4", "Regular").unwrap(); + let k = 1000.0 / face.units_per_em(); + text.chars() + .map(|ch| { + let gid = face.glyph_for(ch); + // The database's outlines run y down. + let outline = Affine::scale_non_uniform(k, -k) * db.outline(&face, gid).as_ref().clone(); + FileGlyph { ch, outline, advance: face.advance(gid) * k } + }) + .collect() + } + + fn info() -> FileFontInfo { + FileFontInfo { family: "Kept Serif".into(), style: "Regular".into(), postscript: "KeptSerif-Regular".into(), ..Default::default() } + } + + fn near(a: Rect, b: Rect, tol: f64) -> bool { + (a.x0 - b.x0).abs() < tol && (a.x1 - b.x1).abs() < tol && (a.y0 - b.y0).abs() < tol && (a.y1 - b.y1).abs() < tol + } + + #[test] + fn a_font_built_from_a_files_glyphs_draws_them_with_their_widths() { + let from = glyphs("Hamburg é&Q "); + let bytes = build_file_font(&info(), &from).unwrap(); + let font = skrifa::FontRef::new(&bytes).unwrap(); + assert_eq!(font.metrics(skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::default()).units_per_em, FILE_FONT_UPEM); + let db = FontDb::with_font_dirs(vec![]); + let face = db.keep_file_font(&vectorcraft_doc::ImageBlob::new(vectorcraft_doc::FILE_FONT_MIME, bytes)).unwrap(); + assert_eq!((face.family.as_str(), face.style.as_str()), ("Kept Serif", "Regular")); + assert_eq!(face.postscript_name(), "KeptSerif-Regular"); + // Kept apart: no family name finds it. + assert!(!db.has_family("Kept Serif")); + let k = 1000.0 / face.units_per_em(); + for g in &from { + let gid = face.glyph_for(g.ch); + assert_ne!(gid, 0, "{}", g.ch); + assert!((face.advance(gid) * k - g.advance).abs() < 0.5, "{}: the file's width", g.ch); + let drawn = Affine::scale_non_uniform(k, -k) * db.outline(&face, gid).as_ref().clone(); + if g.outline.elements().is_empty() { + assert!(drawn.elements().is_empty()); + } else { + assert!( + near(drawn.bounding_box(), g.outline.bounding_box(), 0.6), + "{}: {:?} vs {:?}", + g.ch, + drawn.bounding_box(), + g.outline.bounding_box() + ); + } + } + } + + /// The file's font's licence flags travel with the font built from its glyphs, so an export + /// treats it as the file's font was treated (#4568): a restricted licence keeps its outlines + /// out of an SVG's `@font-face`, a missing one reads as print and preview, which may embed. + #[test] + fn a_file_fonts_licence_flags_carry_over_to_the_font_built_from_it() { + use crate::embed::Embedding; + let from = glyphs("Hamburg"); + for (fs_type, want) in [ + (Some(2), Embedding::Forbidden), + (Some(0x0200), Embedding::Forbidden), + (Some(4), Embedding::Subset), + (Some(0x0108), Embedding::Whole), + (None, Embedding::Subset), + ] { + let bytes = build_file_font(&FileFontInfo { fs_type, ..info() }, &from).unwrap(); + let db = FontDb::with_font_dirs(vec![]); + let face = db.keep_file_font(&vectorcraft_doc::ImageBlob::new(vectorcraft_doc::FILE_FONT_MIME, bytes)).unwrap(); + assert_eq!(face.embedding(), want, "fsType {fs_type:?}"); + } + } + + /// A curve whose control point is absurdly far out is left out before it is subdivided + /// (CodeRabbit, #4569); a glyph of ordinary size still builds. + #[test] + fn a_curve_with_an_absurd_control_point_is_left_out() { + let mut from = glyphs("a"); + let mut wild = BezPath::new(); + wild.move_to((0.0, 0.0)); + wild.curve_to((1e12, 0.0), (0.0, 1e12), (10.0, 10.0)); + wild.line_to((10.0, 0.0)); + wild.close_path(); + from.push(FileGlyph { ch: 'w', outline: wild, advance: 500.0 }); + let bytes = build_file_font(&info(), &from).unwrap(); + let db = FontDb::with_font_dirs(vec![]); + let face = db.keep_file_font(&vectorcraft_doc::ImageBlob::new(vectorcraft_doc::FILE_FONT_MIME, bytes)).unwrap(); + assert_ne!(face.glyph_for('a'), 0); + assert_eq!(face.glyph_for('w'), 0); + } + + #[test] + fn glyphs_that_cannot_be_written_are_left_out() { + let mut from = glyphs("ab"); + // A second glyph for `a`: the first is kept. + from.push(FileGlyph { ch: 'a', outline: glyphs("x").remove(0).outline, advance: 999.0 }); + let mut nan = BezPath::new(); + nan.move_to((0.0, 0.0)); + nan.line_to((f64::NAN, 10.0)); + nan.line_to((10.0, 10.0)); + from.push(FileGlyph { ch: 'c', outline: nan, advance: 500.0 }); + let mut far = BezPath::new(); + far.move_to((0.0, 0.0)); + far.line_to((1e9, 0.0)); + far.line_to((0.0, 10.0)); + from.push(FileGlyph { ch: 'd', outline: far, advance: 500.0 }); + // A lone point draws nothing; an advance that isn't a number is none. + let mut dot = BezPath::new(); + dot.move_to((5.0, 5.0)); + from.push(FileGlyph { ch: 'e', outline: dot, advance: f64::NAN }); + let db = FontDb::with_font_dirs(vec![]); + let blob = vectorcraft_doc::ImageBlob::new(vectorcraft_doc::FILE_FONT_MIME, build_file_font(&info(), &from).unwrap()); + let face = db.keep_file_font(&blob).unwrap(); + assert!(face.covers('a') && face.covers('b') && face.covers('e')); + assert!(!face.covers('c') && !face.covers('d')); + assert!((face.advance(face.glyph_for('a')) - from[0].advance * 2.0).abs() < 1.0, "the first glyph of a character"); + assert_eq!(face.advance(face.glyph_for('e')), 0.0); + assert!(db.outline(&face, face.glyph_for('e')).elements().is_empty()); + assert!(build_file_font(&info(), &[]).is_none()); + // Bytes that aren't a font are kept by no one. + assert!(db.keep_file_font(&vectorcraft_doc::ImageBlob::new(vectorcraft_doc::FILE_FONT_MIME, b"not a font".to_vec())).is_none()); + } + + #[test] + fn extreme_negative_descent_does_not_overflow() { + let mut i = info(); + i.descent = -100_000.0; + let bytes = build_file_font(&i, &glyphs("a")); + assert!(bytes.is_some()); + } +} diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index b7efa856c8..cf579a5724 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -79,6 +79,18 @@ pub use traits::{FontClass, FontLikeness, FontMatch, FontTraits, GENERIC_FAMILIE pub(crate) use traits::{alias_lists, face_styles, on_faces_published}; pub use wanted::{WantedFont, WantedFonts}; +/// Weak indexes of live file-font resources, by content hash (collisions checked by bytes) and id. +#[derive(Default)] +pub(super) struct FileFaces { + pub(super) by_key: HashMap>>, + pub(super) by_id: HashMap>, + /// Only each admitted face's own byte allocation, never an unbounded list of alias owners. + pub(super) by_blob: HashMap>, +} + +/// How many live fonts files carried the database admits at most (each shares its document's bytes). +pub const MAX_FILE_FACES: usize = 4096; + /// Process-wide font database. pub struct FontDb { faces: RwLock>>, @@ -87,6 +99,9 @@ pub struct FontDb { images: Mutex, colours: Mutex, catalog: RwLock, + /// Fonts files carried for their type ([`vectorcraft_doc::FileFonts`]): apart from the faces, + /// so no family name, font menu, fallback or PostScript name lookup finds them. + pub(super) file_faces: RwLock, /// The installed faces by PostScript name (documents name fonts so: PDF, EPS, .ai). postscript: RwLock, /// Where the system font scan looks. diff --git a/crates/text/src/fontdb/composite.rs b/crates/text/src/fontdb/composite.rs index bdcb84ae8c..f5b6cbc1f9 100644 --- a/crates/text/src/fontdb/composite.rs +++ b/crates/text/src/fontdb/composite.rs @@ -395,8 +395,11 @@ impl FontDb { if !self.lends() && self.composites.read().unwrap_or_else(|e| e.into_inner()).is_empty() { return None; } - let fonts: Vec>> = - t.runs.iter().map(|r| if r.inline.is_some() { None } else { self.composite_font(&r.style.font_family) }).collect(); + let fonts: Vec>> = t + .runs + .iter() + .map(|r| if r.inline.is_some() || r.style.file_font_id.is_some() { None } else { self.composite_font(&r.style.font_family) }) + .collect(); if fonts.iter().all(Option::is_none) { return None; } diff --git a/crates/text/src/fontdb/db.rs b/crates/text/src/fontdb/db.rs index 1b8d9cd04d..764562c206 100644 --- a/crates/text/src/fontdb/db.rs +++ b/crates/text/src/fontdb/db.rs @@ -56,6 +56,7 @@ impl FontDb { images: Mutex::new(GlyphCache::default()), colours: Mutex::new(GlyphCache::default()), catalog: RwLock::new(Catalog::new()), + file_faces: RwLock::new(super::FileFaces::default()), postscript: RwLock::new(PostScriptNames::new()), font_paths, aliases: RwLock::new(HashMap::new()), diff --git a/crates/text/src/fontdb/face.rs b/crates/text/src/fontdb/face.rs index d6e114a33f..c418d40308 100644 --- a/crates/text/src/fontdb/face.rs +++ b/crates/text/src/fontdb/face.rs @@ -212,6 +212,16 @@ pub struct FontFace { pub(super) named_chars: std::sync::OnceLock>, } +impl vectorcraft_doc::FileFontFace for FontFace { + fn id(&self) -> u32 { + self.id + } + + fn bytes(&self) -> &[u8] { + self.data() + } +} + /// Where the ideographic character face (ICF) lies inside the ideographic em box: its distance /// from each edge of the em box, in ems. `top` and `bottom` along a horizontal line, `right` and /// `left` across a vertical one. diff --git a/crates/text/src/fontdb/file_fonts_tests.rs b/crates/text/src/fontdb/file_fonts_tests.rs new file mode 100644 index 0000000000..54194f47b3 --- /dev/null +++ b/crates/text/src/fontdb/file_fonts_tests.rs @@ -0,0 +1,234 @@ +use super::*; +use crate::{FileFontInfo, FileGlyph, build_file_font, layout}; +use kurbo::{Point, Rect, Shape}; +use vectorcraft_doc::{CharStyle, Document, FILE_FONT_MIME, FileFont, FileFonts, ImageBlob, Node, NodeId, NodeKind, TextObject}; + +const FAMILY: &str = "Owned File Font Regression"; + +fn blob(width: f64) -> ImageBlob { + let glyph = FileGlyph { ch: 'x', outline: Rect::new(0.0, 0.0, width, 700.0).to_path(0.1), advance: width + 100.0 }; + let info = FileFontInfo { family: FAMILY.into(), style: "Regular".into(), ..Default::default() }; + ImageBlob::new(FILE_FONT_MIME, build_file_font(&info, &[glyph]).unwrap()) +} + +fn text(key: &str) -> TextObject { + let mut t = TextObject::point(Point::ZERO, "x", CharStyle { font_family: FAMILY.into(), size: 20.0, ..Default::default() }); + t.file_fonts = Some(Box::new(FileFonts::new(vec![FileFont { family: FAMILY.into(), style: "Regular".into(), key: key.into() }], "x"))); + t +} + +fn document(key: &str, blob: ImageBlob) -> Document { + let mut doc = Document::new(100.0, 100.0); + doc.images.insert(key.into(), blob); + doc.layers.push(Arc::new(Node::new(NodeId(100), NodeKind::Text(Box::new(text(key)))))); + doc +} + +fn first_text(doc: &Document) -> &TextObject { + let NodeKind::Text(t) = &doc.layers.last().unwrap().kind else { panic!("text") }; + t +} + +#[test] +fn chosen_keys_cannot_replace_another_documents_owned_font() { + for reverse in [false, true] { + let db = FontDb::with_font_dirs(vec![]); + let (a, b) = (blob(200.0), blob(800.0)); + // A chooses the exact key an honest B derives from its different bytes. + let key = b.content_key(); + let (mut da, mut dbb) = (document(&key, a.clone()), document(&key, b.clone())); + let (first, second) = if reverse { (&mut dbb, &mut da) } else { (&mut da, &mut dbb) }; + assert!(db.bind_document_file_fonts(first).is_empty()); + assert!(db.bind_document_file_fonts(second).is_empty()); + for (doc, owned) in [(&da, &a), (&dbb, &b)] { + let laid = layout(&db, first_text(doc)); + assert_eq!(laid.glyphs.len(), 1); + let face = db.face_by_id(laid.glyphs[0].font_id).unwrap(); + assert_eq!(face.file_data(), owned.bytes.as_slice()); + } + assert!(layout(&db, first_text(&dbb)).bounds.width() > layout(&db, first_text(&da)).bounds.width() * 2.0); + } +} + +#[test] +fn metadata_and_forged_internal_family_do_not_authorize_global_faces() { + let db = FontDb::with_font_dirs(vec![]); + let owned = blob(500.0); + let face = db.keep_file_font(&owned).unwrap(); + let id = face.id(); + let mut missing = text(&owned.content_key()); + assert!(!db.bind_file_fonts(&mut missing, |_| None)); + assert!(db.file_faces(&missing).is_empty()); + assert!(layout(&db, &missing).glyphs.iter().all(|g| g.font_id != id)); + + let mut json = serde_json::to_value(CharStyle::default()).unwrap(); + json["font_family"] = format!("\u{1}file font {id}").into(); + json["file_font_id"] = id.into(); + let forged: CharStyle = serde_json::from_value(json).unwrap(); + assert_eq!(forged.file_font_id, None); + assert!(db.style_face(&forged).is_none_or(|face| face.id() != id)); + let forged = TextObject::point(Point::ZERO, "x", forged); + assert!(layout(&db, &forged).glyphs.iter().all(|g| g.font_id != id)); + + let mut owned_text = text("chosen"); + assert!(db.bind_file_fonts(&mut owned_text, |_| Some(&owned))); + let serialized = serde_json::to_string(&owned_text).unwrap(); + let unowned: TextObject = serde_json::from_str(&serialized).unwrap(); + assert!(db.file_faces(&unowned).is_empty(), "runtime authorization never travels as metadata"); + let mut invalid = document("chosen", ImageBlob::new(FILE_FONT_MIME, b"not a font".to_vec())); + let warnings = db.bind_document_file_fonts(&mut invalid); + assert!(warnings.iter().any(|w| w.contains(FAMILY) && w.contains("substitute"))); + assert!(db.file_faces(first_text(&invalid)).is_empty()); +} + +#[test] +fn only_fonts_referenced_by_active_runs_consume_allowance() { + let db = FontDb::with_font_dirs(vec![]); + let mut doc = Document::new(100.0, 100.0); + for i in 0..32 { + doc.images.insert(format!("unused-{i}"), blob(100.0 + f64::from(i))); + } + let mut unused_reference = text("unused-0"); + unused_reference.runs[0].style.font_family = "Another Missing Family".into(); + doc.layers.push(Arc::new(Node::new(NodeId(100), NodeKind::Text(Box::new(unused_reference))))); + assert!(db.bind_document_file_fonts(&mut doc).is_empty()); + assert!(db.read_file_faces().by_id.is_empty()); + let wanted = blob(900.0); + let face = db.keep_file_font_up_to(&wanted, 1).unwrap(); + assert_eq!(face.file_data(), wanted.bytes.as_slice()); + assert_eq!(db.read_file_faces().by_id.len(), 1); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn removing_an_installed_exact_face_uses_the_owned_snapshot_fallback() { + let dir = std::env::temp_dir().join(format!("vc-file-font-{}-installed-fallback", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + let installed_path = dir.join("Installed.ttf"); + std::fs::write(&installed_path, blob(800.0).bytes.as_slice()).unwrap(); + let db = FontDb::with_font_dirs(vec![dir.clone()]); + db.set_system_fallback(false); + let installed_id = { + let (face, matched) = db.resolve(FAMILY, "Regular").unwrap(); + assert_eq!(matched, super::super::traits::FontMatch::Exact); + face.id() + }; + let mut doc = document("carried", blob(200.0)); + assert!(db.bind_document_file_fonts(&mut doc).is_empty()); + assert!(db.file_faces(first_text(&doc)).is_empty(), "the installed exact face still wins"); + assert_eq!(layout(&db, first_text(&doc)).glyphs[0].font_id, installed_id); + assert_eq!(db.read_file_faces().by_id.len(), 1, "the referenced carried resource is admitted while dormant"); + let (carried_id, weak) = { + let face = first_text(&doc).file_fonts.as_ref().unwrap().face("carried").unwrap(); + assert_ne!(face.id(), installed_id); + assert_eq!(face.bytes(), doc.images["carried"].bytes.as_slice()); + (face.id(), Arc::downgrade(&face)) + }; + let undo = doc.clone(); + let resource = doc.images["carried"].clone(); + let cached_text = first_text(&doc).clone(); + let replacement = blob(900.0); + assert!(db.keep_file_font_up_to(&replacement, 1).is_none(), "dormant owned resources count toward the live allowance"); + + std::fs::remove_file(&installed_path).unwrap(); + std::fs::remove_dir(&dir).unwrap(); + assert_eq!(db.load_system_fonts(), 0); + assert!(db.face_by_id(installed_id).is_none()); + for retained in [&doc, &undo] { + assert_eq!(layout(&db, first_text(retained)).glyphs[0].font_id, carried_id, "removal needs no reopen or rebind"); + } + + doc.images.clear(); + assert!(!db.bind_document_file_fonts(&mut doc).is_empty()); + assert!(db.file_faces(first_text(&doc)).is_empty()); + drop(doc); + assert_eq!(layout(&db, first_text(&undo)).glyphs[0].font_id, carried_id, "current-document rebinding cannot revoke Undo ownership"); + drop(undo); + assert_eq!(layout(&db, &cached_text).glyphs[0].font_id, carried_id, "a resource snapshot still owns the carried face"); + assert!(db.keep_file_font_up_to(&replacement, 1).is_none()); + drop(resource); + assert!(weak.upgrade().is_none()); + assert!(db.face_by_id(carried_id).is_none()); + assert!(db.file_faces(&cached_text).is_empty(), "text bindings alone do not own admission"); + assert!(db.keep_file_font_up_to(&replacement, 1).is_some(), "closing the last resource owner releases allowance"); +} + +#[test] +fn document_snapshots_and_inflight_faces_keep_only_live_allowance() { + let db = FontDb::with_font_dirs(vec![]); + let (a, b) = (blob(200.0), blob(800.0)); + let mut doc = document("k", a.clone()); + assert!(db.bind_document_file_fonts(&mut doc).is_empty()); + let original = layout(&db, first_text(&doc)); + let id = original.glyphs[0].font_id; + let inflight = db.face_by_id(id).unwrap(); + let weak = Arc::downgrade(&inflight); + let open_document = Arc::new(doc); + let undo_or_copy = open_document.clone(); + let resource_copy = (*open_document).clone(); + let cached_node = open_document.layers.last().unwrap().clone(); + let cached_text = first_text(&open_document).clone(); + let before_expiry = cached_text.clone(); + assert!(db.keep_file_font_up_to(&b, 1).is_none()); + // Identical content may share a live face even while the allowance is full. + assert_eq!(db.keep_file_font_up_to(&a, 1).unwrap().id(), id); + drop(open_document); + assert_eq!(layout(&db, first_text(&undo_or_copy)).glyphs[0].font_id, id); + assert!(db.keep_file_font_up_to(&b, 1).is_none()); + drop(undo_or_copy); + assert!(db.keep_file_font_up_to(&b, 1).is_none(), "a copied document owns its image resources too"); + drop(resource_copy); + drop(a); + assert!(db.keep_file_font_up_to(&b, 1).is_none(), "an in-flight font Arc still owns its slot"); + drop(inflight); + assert!(weak.upgrade().is_none()); + assert!(db.face_by_id(id).is_none()); + assert_eq!(cached_text, before_expiry, "weak expiry must not change cache identity"); + assert!(db.file_faces(&cached_text).is_empty()); + let NodeKind::Text(cached) = &cached_node.kind else { panic!("text") }; + assert!(db.file_faces(cached).is_empty(), "a cached node is not a resource owner"); + let recovered = db.keep_file_font_up_to(&b, 1).unwrap(); + assert_eq!(recovered.file_data(), b.bytes.as_slice()); + assert_eq!(db.read_file_faces().by_id.len(), 1, "dead slots were reaped, not accumulated"); + assert_eq!(db.read_file_faces().by_key.len(), 1); + assert_eq!(db.read_file_faces().by_blob.len(), 1); +} + +#[test] +fn cloned_and_mutated_blobs_cannot_reuse_an_old_runtime_face() { + let db = FontDb::with_font_dirs(vec![]); + let (a, b) = (blob(200.0), blob(800.0)); + let first = db.keep_file_font(&a).unwrap(); + let mut changed = a.clone(); + assert_eq!(changed, a, "runtime ownership does not change blob equality"); + changed.bytes = b.bytes.clone(); + // Cloning must not propagate a stale lease after public bytes were replaced. + let copied = changed.clone(); + assert!(copied.file_font.lock().unwrap().is_none()); + assert!(changed.file_font.lock().unwrap().is_none()); + let second = db.keep_file_font(&copied).unwrap(); + assert_ne!(first.id(), second.id()); + assert_eq!(second.file_data(), b.bytes.as_slice()); + assert_eq!(first.file_data(), a.bytes.as_slice()); + let mut invalid = copied.clone(); + invalid.bytes = Arc::new(b"invalid replacement".to_vec()); + assert!(db.keep_file_font(&invalid).is_none()); + assert!(invalid.file_font.lock().unwrap().is_none()); +} + +#[test] +fn file_font_height_references_measure_the_owned_face() { + use vectorcraft_doc::FontHeightReference; + let db = FontDb::with_font_dirs(vec![]); + let owned = ImageBlob::new(FILE_FONT_MIME, crate::test_fonts::height_font(true).expect("the fixture has explicit OS/2 heights")); + let mut t = text("k"); + assert!(db.bind_file_fonts(&mut t, |_| Some(&owned))); + let face = db.file_faces(&t)[0].clone().unwrap(); + let height = face.font_height(FontHeightReference::CapHeight, false).unwrap(); + t.runs[0].style.font_height_reference = FontHeightReference::CapHeight; + let mut em = t.clone(); + em.runs[0].style.font_height_reference = FontHeightReference::EmBox; + em.runs[0].style.size /= height; + assert!((layout(&db, &t).bounds.width() - layout(&db, &em).bounds.width()).abs() < 1e-6); + assert_eq!(t.runs[0].style.file_font_id, None, "internal layout ids never enter source runs"); +} diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index 2e6014fcf4..f6ffca1254 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -12,6 +12,12 @@ use super::scan::{enumerate_faces, font_files}; use super::traits::{Alias, FontMatch, FontTraits, regular_rank}; use super::{Arc, BezPath, CANONICAL_CACHE_MAX, Color, ColourContent, FontDb, GlyphImage, MetadataProvider, NEXT_ID, OUTLINE_CACHE_MAX, Ordering}; +fn has_file_fonts(n: &vectorcraft_doc::Node) -> bool { + matches!(&n.kind, vectorcraft_doc::NodeKind::Text(t) if t.file_fonts.is_some()) + || n.extras().mask.as_ref().is_some_and(|mask| has_file_fonts(&mask.art)) + || n.children().is_some_and(|children| children.iter().any(|child| has_file_fonts(child))) +} + /// The most faces [`FontDb::postscript_faces`] gives, and the most families it loads. const MAX_POSTSCRIPT_FACES: usize = 16; @@ -362,7 +368,7 @@ impl FontDb { /// instanced face ([`Self::instance`]) included. pub fn face_by_id(&self, id: u32) -> Option> { let loaded = self.read_faces().iter().find(|f| f.id == id).cloned(); - loaded.or_else(|| self.instance_by_id(id)) + loaded.or_else(|| self.instance_by_id(id)).or_else(|| self.read_file_faces().by_id.get(&id).and_then(std::sync::Weak::upgrade)) } /// The faces loaded so far (the bundled fonts and the installed ones type has used), in load @@ -374,6 +380,11 @@ impl FontDb { /// The face of character style `st`: [`Self::face_version`] of its font, instanced at its /// Variable Font settings ([`Self::instance`]). pub fn style_face(&self, st: &vectorcraft_doc::CharStyle) -> Option> { + if let Some(id) = st.file_font_id + && let Some(face) = self.read_file_faces().by_id.get(&id).and_then(std::sync::Weak::upgrade) + { + return Some(face); + } let face = self.face_version(&st.font_family, &st.font_style, st.font_version.as_deref())?; Some(self.instance(&face, &st.font_axes)) } @@ -729,8 +740,210 @@ impl FontDb { self.colours.lock().unwrap_or_else(std::sync::PoisonError::into_inner).keep(key, content.clone()); content } + + /// Admit a font resource, sharing its bytes. Its blob and returned face own the admission. + /// Invalid fonts and the live-face cap return `None`; document keys are never identities. + pub fn keep_file_font(&self, blob: &vectorcraft_doc::ImageBlob) -> Option> { + self.keep_file_font_up_to(blob, super::MAX_FILE_FACES) + } + + fn keep_file_font_up_to(&self, blob: &vectorcraft_doc::ImageBlob, limit: usize) -> Option> { + // Drop this short-lived resource lock before touching registry locks. + let cached = { + let mut owner = blob.file_font.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if blob.mime != vectorcraft_doc::FILE_FONT_MIME { + *owner = None; + return None; + } + if owner.as_ref().is_some_and(|face| !std::ptr::eq(face.bytes(), blob.bytes.as_slice()) && face.bytes() != blob.bytes.as_slice()) { + *owner = None; + } + owner.clone() + }; + if let Some(cached) = cached + && let Some(face) = self.read_file_faces().by_id.get(&cached.id()).and_then(std::sync::Weak::upgrade) + && std::ptr::eq::(face.as_ref(), cached.as_ref()) + { + return Some(face); + } + let face = self.admit_file_font(blob, limit)?; + // No registry lock is held here; only resource owners, never weak bindings, keep slots. + *blob.file_font.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(face.clone()); + Some(face) + } + + fn admit_file_font(&self, blob: &vectorcraft_doc::ImageBlob, limit: usize) -> Option> { + let allocation = Arc::as_ptr(&blob.bytes) as usize; + if let Some(face) = self.read_file_faces().by_blob.get(&allocation).and_then(std::sync::Weak::upgrade) { + return Some(face); + } + let key = blob.content_key(); + let mut faces = self.file_faces.write().unwrap_or_else(|e| e.into_inner()); + if let Some(face) = faces + .by_key + .get(&key) + .and_then(|bucket| bucket.iter().filter_map(std::sync::Weak::upgrade).find(|face| face.data() == blob.bytes.as_slice())) + { + return Some(face); + } + // Reap on admission, including dead hash buckets, so closed documents recover allowance. + faces.by_id.retain(|_, face| face.strong_count() != 0); + faces.by_blob.retain(|_, face| face.strong_count() != 0); + faces.by_key.retain(|_, bucket| { + bucket.retain(|face| face.strong_count() != 0); + !bucket.is_empty() + }); + if faces.by_id.len() >= limit { + return None; + } + let (i, spec) = super::scan::enumerate_faces(&blob.bytes).into_iter().next()?; + let face = Arc::new(super::build::make_face(super::face::FontBytes::Owned(blob.bytes.clone()), i, spec, None)?); + faces.by_id.insert(face.id, Arc::downgrade(&face)); + faces.by_blob.insert(allocation, Arc::downgrade(&face)); + faces.by_key.entry(key).or_default().push(Arc::downgrade(&face)); + self.generation.fetch_add(1, super::Ordering::Relaxed); + Some(face) + } + + /// Bind only references whose owning document actually carries the bytes. A serialized + /// reference without its blob cannot borrow a font another document loaded. + /// Keep owned fallbacks bound even while an installed exact face wins, in case it is removed. + /// The return value says whether every active reference was admitted. + pub fn bind_file_fonts<'a>(&self, t: &mut vectorcraft_doc::TextObject, image: impl Fn(&str) -> Option<&'a vectorcraft_doc::ImageBlob>) -> bool { + let mut resources: Vec<(String, Arc)> = vec![]; + let mut complete = true; + for font in t.file_fonts_in_use() { + if !t.runs.iter().any(|r| r.style.font_family == font.family && r.style.font_style == font.style) + || resources.iter().any(|(key, _)| *key == font.key) + { + continue; + } + let face = image(&font.key).and_then(|blob| self.keep_file_font(blob)); + if let Some(face) = face { + resources.push((font.key.clone(), face)); + } else { + complete = false; + } + } + if let Some(fonts) = t.file_fonts.as_mut() + && fonts.bind(resources) + { + t.cached_bounds = None; + t.cached_baselines.clear(); + self.generation.fetch_add(1, super::Ordering::Relaxed); + } + complete + } + + /// Bind text throughout a resource tree, including opacity masks, reporting rejected fonts. + pub fn bind_node_file_fonts<'a>( + &self, + n: &mut vectorcraft_doc::Node, + image: &impl Fn(&str) -> Option<&'a vectorcraft_doc::ImageBlob>, + ) -> Vec { + fn visit<'a>( + db: &FontDb, + n: &mut vectorcraft_doc::Node, + image: &impl Fn(&str) -> Option<&'a vectorcraft_doc::ImageBlob>, + warnings: &mut Vec, + ) { + if let vectorcraft_doc::NodeKind::Text(t) = &mut n.kind + && !db.bind_file_fonts(t, image) + { + for font in t.file_fonts_in_use() { + if t.runs.iter().any(|r| r.style.font_family == font.family && r.style.font_style == font.style) + && t.file_fonts.as_ref().is_none_or(|fonts| fonts.face(&font.key).is_none()) + && db.resolve(&font.family, &font.style).is_none_or(|(_, m)| m != super::traits::FontMatch::Exact) + { + let note = format!( + "the file font {} {} could not be used (missing, invalid or live-font limit reached); its text uses a substitute", + font.family, font.style + ); + if !warnings.contains(¬e) { + warnings.push(note); + } + } + } + } + if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_mut()) + && has_file_fonts(&mask.art) + { + visit(db, Arc::make_mut(&mut mask.art), image, warnings); + } + for child in n.children_mut().into_iter().flatten().filter(|n| has_file_fonts(n)) { + visit(db, Arc::make_mut(child), image, warnings); + } + } + let mut warnings = vec![]; + visit(self, n, image, &mut warnings); + warnings + } + + /// Establish document ownership before layout; unrelated blobs never enter the font cache. + pub fn bind_document_file_fonts(&self, doc: &mut vectorcraft_doc::Document) -> Vec { + let vectorcraft_doc::Document { layers, symbols, graph_designs, patterns, pattern_edit, images, .. } = doc; + let trees = layers.iter_mut().chain(symbols.iter_mut().map(|s| &mut s.art)).chain(graph_designs.iter_mut().map(|g| &mut g.art)); + let patterns = patterns.iter_mut().chain(pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut())); + let mut warnings = vec![]; + for root in trees.chain(patterns.flat_map(|p| &mut p.art)).filter(|n| has_file_fonts(n)) { + for note in self.bind_node_file_fonts(Arc::make_mut(root), &|key| images.get(key)) { + if !warnings.contains(¬e) { + warnings.push(note); + } + } + } + warnings + } + + /// Is `id` a live file-font resource? + pub fn is_file_font(&self, id: u32) -> bool { + self.read_file_faces().by_id.get(&id).is_some_and(|face| face.strong_count() != 0) + } + + pub(super) fn read_file_faces(&self) -> std::sync::RwLockReadGuard<'_, super::FileFaces> { + self.file_faces.read().unwrap_or_else(|e| e.into_inner()) + } + + /// For each run of `t`, the font a file carried that draws it ([`vectorcraft_doc::FileFonts`]): + /// while its text is the file's, the font the run names isn't available as named (missing, or + /// another style of its family stands in) and the font kept for that family and style is + /// bound to its owning blob. `None` for runs drawn in their named font or substitute; + /// empty when none is drawn in such a font. + pub fn file_faces(&self, t: &vectorcraft_doc::TextObject) -> Vec>> { + if t.file_fonts.is_none() { + return vec![]; + } + let fonts = t.file_fonts_in_use(); + if fonts.is_empty() { + return vec![]; + } + // Each family and style's answer once: a line has a run per character it spaces apart. + let mut known: Vec<(&str, &str, Option>)> = vec![]; + let mut out = Vec::with_capacity(t.runs.len()); + for r in &t.runs { + let (family, style) = (r.style.font_family.as_str(), r.style.font_style.as_str()); + let face = match known.iter().find(|(f, s, _)| *f == family && *s == style) { + Some((.., face)) => face.clone(), + None => { + let face = fonts + .iter() + .find(|f| f.family == family && f.style == style) + .filter(|_| self.resolve(family, style).is_none_or(|(_, m)| m != super::traits::FontMatch::Exact)) + .and_then(|f| t.file_fonts.as_ref()?.face(&f.key)) + .and_then(|face| self.read_file_faces().by_id.get(&face.id()).and_then(std::sync::Weak::upgrade)); + known.push((family, style, face.clone())); + face + } + }; + out.push(face); + } + if out.iter().all(Option::is_none) { vec![] } else { out } + } } +#[cfg(test)] +#[path = "file_fonts_tests.rs"] +mod file_fonts_tests; #[cfg(test)] mod shared_outline_tests { use super::super::glyph_pen::FlipPen; diff --git a/crates/text/src/harakat.rs b/crates/text/src/harakat.rs index 9ea14d0f08..e04d01917d 100644 --- a/crates/text/src/harakat.rs +++ b/crates/text/src/harakat.rs @@ -66,6 +66,7 @@ pub(crate) fn paint_only(a: &CharStyle, b: &CharStyle) -> bool { let CharStyle { font_family, font_style, + file_font_id, font_version, font_axes, size, @@ -127,6 +128,7 @@ pub(crate) fn paint_only(a: &CharStyle, b: &CharStyle) -> bool { original_paint == normalized_paint && font_family == &b.font_family && font_style == &b.font_style + && file_font_id == &b.file_font_id && font_version == &b.font_version && font_axes == &b.font_axes && size == &b.size diff --git a/crates/text/src/kept.rs b/crates/text/src/kept.rs index 8010642526..22653587c5 100644 --- a/crates/text/src/kept.rs +++ b/crates/text/src/kept.rs @@ -160,10 +160,11 @@ fn text_hash(t: &TextObject) -> u64 { } /// Does [`text_bytes`] and [`layout_bytes`] count everything `t` and `layout` hold? They do not count -/// a gradient's stops, or a glyph's bitmap or color art. +/// owned file-font resources, a gradient's stops, or a glyph's bitmap or color art. fn counts_its_memory(t: &TextObject, layout: &TextLayout) -> bool { let gradient = |p: &Paint| matches!(p, Paint::Gradient(_)); - !t.runs.iter().any(|r| gradient(&r.style.fill) || gradient(&r.style.stroke)) + t.file_fonts.is_none() + && !t.runs.iter().any(|r| gradient(&r.style.fill) || gradient(&r.style.stroke)) && !layout.glyphs.iter().chain(&layout.ruby).any(|g| g.image.is_some() || g.colour.is_some()) } diff --git a/crates/text/src/layout/driver.rs b/crates/text/src/layout/driver.rs index 59c6ac38bf..5813687d76 100644 --- a/crates/text/src/layout/driver.rs +++ b/crates/text/src/layout/driver.rs @@ -213,6 +213,9 @@ pub fn layout_with(db: &FontDb, t: &TextObject, opts: &LayoutOptions) -> TextLay // The sizes the fits step and limit are the ones the Character panel shows (`shown`), whatever // em size a font height reference sets them at. let shown = t; + // Keep the verified faces alive throughout fitting and resolve their height references too. + let file = in_file_fonts(db, t); + let t = file.as_ref().map_or(t, |(text, _)| text); let resolved = db.font_heights_resolved(t); let t = &*resolved; let first = layout_once(db, t, opts); @@ -375,6 +378,24 @@ pub fn scaled(t: &TextObject, f: f64) -> TextObject { s } +/// `t` with the runs a font its file carried draws ([`FontDb::file_faces`]) set in that font; +/// `None` when none is. +fn in_file_fonts(db: &FontDb, t: &TextObject) -> Option<(TextObject, Vec>>)> { + let faces = db.file_faces(t); + if faces.is_empty() { + return None; + } + let mut out = t.clone(); + for (r, face) in out.runs.iter_mut().zip(&faces) { + let Some(face) = face else { continue }; + r.style.file_font_id = Some(face.id()); + r.style.font_style = face.style.clone(); + r.style.font_version = None; + r.style.font_axes.clear(); + } + Some((out, faces)) +} + /// `t` in the styles its layout draws it in: [`scaled`] by the layout's /// [`TextLayout::fit_scale`] when Shrink Text to Fit (area type) or Dynamic Text (type on a path) /// scales it, `t` itself otherwise. Text with neither setting is not laid out. diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 7b70b9c5a2..f1cc911824 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -18,6 +18,7 @@ pub mod craft_fonts; pub mod edit; pub mod embed; mod features; +mod file_font; mod fontconfig; mod fontdb; mod harakat; @@ -41,9 +42,10 @@ pub use craft_fonts::{CRAFT_FONTS, CraftFont, WEB_FONTS, WebFont}; pub use features::{ EXTRA_FEATURES, LIGATURE_TRACKING_LIMITS, MAX_FEATURE_VALUE, MAX_STYLE_FEATURES, OtFeatures, explicit_ligatures, ligatures_suppressed_by, }; +pub use file_font::{FILE_FONT_UPEM, FileFontInfo, FileGlyph, MAX_FILE_GLYPHS, build_file_font}; pub use fontdb::{ CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GENERIC_FAMILIES, GlyphAlternate, - GlyphCategory, GlyphCategoryKind, GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, OutlineFormat, PlatformFontFiles, + GlyphCategory, GlyphCategoryKind, GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, MAX_FILE_FACES, OutlineFormat, PlatformFontFiles, RECENTLY_ADDED_WITHIN, RecentlyAdded, StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, is_font_file, is_generic_family, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs, diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index 9dfff9a0d6..8db9ae60b5 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -1158,6 +1158,7 @@ fn drawn_alike(a: &CharStyle, b: &CharStyle, vertical: bool) -> bool { let CharStyle { font_family, font_style, + file_font_id, font_version, font_axes, size, @@ -1226,6 +1227,7 @@ fn drawn_alike(a: &CharStyle, b: &CharStyle, vertical: bool) -> bool { && offsets == other_offsets && font_family == &b.font_family && font_style == &b.font_style + && file_font_id == &b.file_font_id && font_version == &b.font_version && font_axes == &b.font_axes && size == &b.size @@ -1292,6 +1294,7 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { let CharStyle { font_family, font_style, + file_font_id, font_version, font_axes, size, @@ -1355,6 +1358,7 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { *font_family == b.font_family && warichu_alike(a, b) && *font_style == b.font_style + && *file_font_id == b.file_font_id && *font_version == b.font_version && *font_axes == b.font_axes && *size == b.size diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index 3666fb156e..cc7b26baa2 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -398,22 +398,7 @@ pub fn two_axis_font() -> Option> { /// A `name` table of Windows English (US) records (name id, string). pub fn name_table(records: &[(u16, &str)]) -> Option> { - let mut records = records.to_vec(); - records.sort_by_key(|r| r.0); - let n = u16::try_from(records.len()).ok()?; - let (mut head, mut strings) = (Vec::new(), Vec::new()); - for v in [0, n, 6 + 12 * n] { - head.extend_from_slice(&v.to_be_bytes()); - } - for (id, s) in records { - let bytes: Vec = s.encode_utf16().flat_map(u16::to_be_bytes).collect(); - for v in [3, 1, 0x0409, id, u16::try_from(bytes.len()).ok()?, u16::try_from(strings.len()).ok()?] { - head.extend_from_slice(&v.to_be_bytes()); - } - strings.extend(bytes); - } - head.extend(strings); - Some(head) + crate::file_font::name_table(records) } /// The family of [`vertical_font`]. diff --git a/crates/text/src/tests/composite.rs b/crates/text/src/tests/composite.rs index b31b597ce7..98da675b3f 100644 --- a/crates/text/src/tests/composite.rs +++ b/crates/text/src/tests/composite.rs @@ -116,6 +116,38 @@ fn composite_type_draws_each_class_in_its_font() { assert!((l.glyphs[1].advance - alone.glyphs[0].advance).abs() < 1e-9); } +/// A file font and a composite font can share one text object without losing either face or the +/// original run indices when the composite run splits. +#[test] +fn file_fonts_and_composite_fonts_draw_together() { + use vectorcraft_doc::{FileFont, FileFonts}; + + let db = FontDb::with_font_dirs(vec![]); + db.set_composite_font(&mixed("Mixed")); + let info = FileFontInfo { family: "Carried Test".into(), style: "Regular".into(), ..Default::default() }; + let glyph = FileGlyph { ch: 'x', outline: Rect::new(0.0, 0.0, 500.0, 700.0).to_path(0.1), advance: 600.0 }; + let blob = vectorcraft_doc::ImageBlob::new(vectorcraft_doc::FILE_FONT_MIME, build_file_font(&info, &[glyph]).unwrap()); + let mut t = TextObject::point(Point::ZERO, "x", style("Carried Test", 12.0)); + t.runs.push(TextRun::new("A1", style("Mixed", 20.0))); + t.runs.push(TextRun::new("x", style("Carried Test", 12.0))); + t.file_fonts = Some(Box::new(FileFonts::new( + vec![FileFont { family: "Carried Test".into(), style: "Regular".into(), key: "carried-test".into() }], + &t.plain_text(), + ))); + assert!(db.bind_file_fonts(&mut t, |key| (key == "carried-test").then_some(&blob))); + let carried = db.file_faces(&t)[0].as_ref().unwrap().id(); + let l = layout(&db, &t); + let fonts: Vec<(usize, u32)> = l.glyphs.iter().map(|g| (g.run, g.font_id)).collect(); + assert_eq!(fonts, [(0, carried), (1, face_id(&db, "JetBrains Mono")), (1, face_id(&db, "Inter")), (2, carried)]); + assert_eq!(t.runs[0].style.font_family, "Carried Test", "layout does not rename the source runs"); + // Editing the text drops the file faces, but not the composite font's class-specific faces. + t.runs[0].text.push('x'); + let edited = layout(&db, &t); + assert!(edited.glyphs.iter().all(|g| !db.is_file_font(g.font_id))); + let composite: Vec = edited.glyphs.iter().filter(|g| g.run == 1).map(|g| g.font_id).collect(); + assert_eq!(composite, [face_id(&db, "JetBrains Mono"), face_id(&db, "Inter")]); +} + /// A ruby reading over type in a composite font is set in the parts its own characters fall in. #[test] fn ruby_over_composite_type_is_set_in_its_own_parts() { diff --git a/crates/text/src/tests/harakat.rs b/crates/text/src/tests/harakat.rs index 4281cf9a5d..b2c75f7254 100644 --- a/crates/text/src/tests/harakat.rs +++ b/crates/text/src/tests/harakat.rs @@ -749,7 +749,13 @@ fn duplicate_authored_glyphs_keep_occurrence_order() { let mut wrong = before.clone(); wrong.glyphs[0].run = 1; - assert!(std::panic::catch_unwind(|| assert_kashida_ownership(&text, &before, &wrong, &red(), "changed owner", false)).is_err()); + // This panic probe only reads snapshots; opaque carried-font handles need no unwind-safety bound. + assert!( + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + assert_kashida_ownership(&text, &before, &wrong, &red(), "changed owner", false) + })) + .is_err() + ); } /// Compare authored glyph run indices before/after Insert Kashidas (matched by byte and gid; diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..97c8f88766 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -4647,7 +4647,7 @@ fn a_documents_placed_key_moves_only_for_bitmaps_of_its_own_files() { assert_eq!(key(&mut keys, &session, plain, 10, &|_, _| files(&[file.as_str()])), 8, "no images: a file another document holds"); // The same document holding an image and showing no placed document. let mut raster = session.documents().iter().find(|d| d.uid == plain).unwrap().clone(); - let blob = vectorcraft_doc::ImageBlob { mime: "image/png".into(), bytes: Default::default(), proxy: None }; + let blob = vectorcraft_doc::ImageBlob { mime: "image/png".into(), bytes: Default::default(), proxy: None, file_font: Default::default() }; std::sync::Arc::make_mut(&mut raster.doc).images.insert("an image".into(), blob); assert_eq!(placed_key_at(&mut keys, &session, &raster, 11, |_, _| None), 8, "an image and no placed document: files no longer known"); assert_eq!(keys.len(), 2); diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index 5b4c8619ee..d3b6940f66 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -79,6 +79,7 @@ pub fn start_with(app: &mut VectorcraftApp, path: &str, bytes: Vec, params: // Update Links (Preferences › File Handling) applies there as it is set now. let update_links = app.session.prefs.update_links == "automatically"; let low_res_proxy_eps = app.session.prefs.low_res_proxy_eps; + let open_params = app.session.prefs.with_pdf_font_choice(¶ms); // The automation roots in force here are in force there. let scope = ScopeHandle::capture(); let opener = scope.clone(); @@ -90,7 +91,7 @@ pub fn start_with(app: &mut VectorcraftApp, path: &str, bytes: Vec, params: vectorcraft_engine::guard::catch_panic(|| { cancel::scope(&raised, None, || { // A profile question Edit › Color Settings asks waits for the UI thread. - fileio::read_for_open_asking(&name, &file, Some(name.clone()), ¶ms, update_links, low_res_proxy_eps, true) + fileio::read_for_open_asking(&name, &file, Some(name.clone()), &open_params, update_links, low_res_proxy_eps, true) .map_err(|e| e.to_string()) }) }) diff --git a/crates/ui-egui/src/prefs_dialog/descriptions.rs b/crates/ui-egui/src/prefs_dialog/descriptions.rs index ec8aea7063..aa53b3659f 100644 --- a/crates/ui-egui/src/prefs_dialog/descriptions.rs +++ b/crates/ui-egui/src/prefs_dialog/descriptions.rs @@ -332,6 +332,7 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ "lowResProxyEps", "When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links.", ), + ("pdfImportEmbeddedFonts", "Uses a PDF's embedded glyphs for imported text when its font is missing; off, it uses the fallback font."), ( "antiAliasedBitmaps", "In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed.", diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index c79ca22470..1c0e5a9650 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -2972,8 +2972,8 @@ fn the_description_line_keeps_the_fields_column_height() { } /// Each sentence describes a setting the dialog shows on this platform or, like System Title Bar, -/// on another one, and every complete catalog translates it into at most the three lines the -/// description line holds. +/// on another one. The actual translation, or English fallback for a new sentence, fits the three +/// lines the description line holds. #[test] fn every_description_names_a_setting_and_fits_in_every_language() { let ctx = egui::Context::default(); @@ -2986,13 +2986,14 @@ fn every_description_names_a_setting_and_fits_in_every_language() { } for lang in crate::i18n::Lang::all() { let text = crate::i18n::tr(lang, sentence); - if lang != crate::i18n::Lang::EN && text == *sentence { - bad.push(format!("{}: no row for {sentence:?}", lang.code())); + let translated = crate::i18n::has(lang, sentence); + if lang != crate::i18n::Lang::EN && translated && text == *sentence { + bad.push(format!("{}: the available translation for {sentence:?} was not used", lang.code())); } - let mut job = egui::text::LayoutJob::simple(text.to_string(), egui::FontId::proportional(11.5), egui::Color32::WHITE, 530.0); - job.wrap.max_rows = 3; - let galley = ui.painter().layout_job(job); - if galley.elided || galley.size().y > DESCRIPTION_HEIGHT { + if !translated && text != *sentence { + bad.push(format!("{}: missing {sentence:?} did not fall back to English", lang.code())); + } + if !description_fits(ui, text) { bad.push(format!("{}: {text:?} takes more than three lines", lang.code())); } } @@ -3001,3 +3002,29 @@ fn every_description_names_a_setting_and_fits_in_every_language() { out.textures_delta.clear(); assert!(bad.is_empty(), "{}", bad.join("\n")); } + +fn description_fits(ui: &egui::Ui, text: &str) -> bool { + let mut job = egui::text::LayoutJob::simple(text.to_string(), egui::FontId::proportional(11.5), egui::Color32::WHITE, 530.0); + job.wrap.max_rows = 3; + let galley = ui.painter().layout_job(job); + !galley.elided && galley.size().y <= DESCRIPTION_HEIGHT +} + +/// English fallback still has to fit: accepting a missing catalog row must not hide overflow. +#[test] +fn description_layout_rejects_overflow_even_for_english_fallback() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let short = "A new setting without a catalog row."; + let long = format!("{short} ").repeat(100); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + for lang in crate::i18n::Lang::all() { + assert!(!crate::i18n::has(lang, short) && !crate::i18n::has(lang, &long)); + assert_eq!(crate::i18n::tr(lang, short), short); + assert_eq!(crate::i18n::tr(lang, &long), long); + assert!(description_fits(ui, crate::i18n::tr(lang, short))); + assert!(!description_fits(ui, crate::i18n::tr(lang, &long)), "{}: overflowing fallback was accepted", lang.code()); + } + }); + out.textures_delta.clear(); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index da354bd345..932138e226 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -2,6 +2,8 @@ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (`.ai` import: a stroke's arrowheads, the symbols its style names, come in as custom arrowheads with their tip on, or past, the path's end, as the drawn art places it, and the line stopping where the symbol's sample of it ends, #8188; PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group instead of reading as nested clipping groups that clip nothing or stop the editing data from being read; previously: PDF import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF export writes the document language as the catalog's `/Lang`, #3644; PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) > +> **File-font integration status (2026-11-19, #4569):** 56 focused PDF/native-reopen, file-font, stroked-text and font-binding tests passed on the current-main integration candidate. Full workspace CI and hardening paths outside those suites remain pending. Scores and estimates unchanged. +> > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, @@ -9,6 +11,42 @@ Every format Illustrator opens, places, saves or exports, against VectorCraft's documentation (helpx "file formats" and Save/Export pages), not from its installed bundle: the clean-room rule forbids reading the install. Part of [target-app-parity.md](target-app-parity.md). +### File-font ownership hardening (#4569) + +The implementation binds editable PDF and native text to font bytes the owning document carries. +Serialized blob keys and forged internal font-family names cannot authorize another document's +face. Content keys index candidate faces; a byte comparison resolves collisions. Referenced fonts +enter a bounded live-face registry with weak indexes, so admission can reap released slots. +Runtime image-blob leases retain faces across document, Undo and clipboard resource copies; +weak text bindings keep cached geometry from retaining admission after those owners disappear. +Explicit in-flight face handles retain their admission until their final owner drops. +Unreferenced `font/ttf` blobs do not enter that registry. Referenced carried fonts retain an owned, +dormant binding while an installed exact face draws, so removing that face needs no reopen. +Place and Break Link transfer font resources and their runtime leases, including equal-byte reuse +and conflicting keys. Older-version placed-art saves prefix serialized and runtime font keys +together. Recovery restores the blobs before binding and reporting actual refusals. Invalid, +missing and cap-refused resources produce substitution warnings during native open, PDF import, +paste and recovery. + +Synthetic regressions cover chosen-key collisions in both opening orders, metadata-only references, +forged internal names, unused blobs, last-owner quota recovery, cross-document renderer reuse, and +native open/save, source-tab close, clipboard relinking, Undo/Redo and export. Placement, Break Link, +older-version save, recovery and installed-font-removal regressions cover resource-lifetime paths. +The serde round-trip regressions use a test-only `serde_json` dependency; the read-only harakat +panic probe asserts unwind safety locally without restricting production font interfaces. +The height-reference regression uses a fixture with explicit OS/2 cap-height metadata. +Native and recovery regression fixtures put artwork inside a layer, preserving the document +structure that placement, clipboard insertion and native reopening require. +SVG regression checks read the text response and require both owned faces to be embedded; the +existing warning for overlapping CSS font descriptions is distinct from font substitution. +Paragraph reconstruction binds the source lines' validated carried faces before measuring or +checking wrapping. The native-reopen regressions compare conflicting-glyph positions and wrapped +paragraph ink bounds with outline imports, including filled-and-stroked `TJ` text. The focused +engine PDF-fidelity, PDF file-font/stroked-text and text binding/shared-outline suites passed +56 tests on the canonical-main integration candidate. Full workspace CI and hardening paths +outside those suites remain pending. Existing PDF respacing and composite-font regressions +remain; no parity score or estimate changes. + **Fidelity** is estimated unless a test is named. Test sources: unit and property tests per crate (`crates/svg/tests`, `crates/pdf/tests`, `crates/format/tests/prop_format.rs`), import fuzzing (`crates/engine/tests/import_fuzz.rs`), the Affinity corpus (`cargo xtask corpus --affinity`, 51 pinned public @@ -386,6 +424,8 @@ Stop opacity on translated artboards remains outside this regression coverage. |---|---|---| | 2026-11-19 | minor | `.ai` import: a stroke's arrowheads were left out, so lines came in without their heads (#8188). A Stroke Style filter's stroke dictionary names each end's head as a symbol of the file (`/GObjRef : (name) /SymbolArt ; (BSArrowBeginSymbol)` or `(BSArrowEndSymbol)`), with its scale in percent (`BSArrowEndScale`, and `BSArrowBeginScale` read the same way; 100 without one). As the files have it, such a symbol's art (y down, as symbols are read) points right along a straight, level sample of the line: an open stroked path with no fill, which ends where the line stops under the head. The rest of the art that paints is the head, its tip its rightmost point, at one symbol unit a head weight (the stroke's weight at the scale). The head comes in as a custom arrowhead with that outline and that stop (a custom head now carries an optional stop, else its line ends halfway along it, as before). Its placement is the one of the two (tip on the end of the path, or Extend, the tip past it by the line's length under the head) that gives the object its drawn art's bounds; the user's file has every tip on its path's end. A stroke keeps its drawn look when neither placement gives those bounds (heads on other subpaths, say) or both do while a head moves 0.2 pt or more between them (a line whose end lies inside the bounds of its other segments), when its symbol isn't read whole or isn't read as a head (no sample or more than one, a sample that isn't 1 pt wide, as in art stored at a Large Canvas scale, art other than paths, compound paths and groups such as a clip group, a group with fills or strokes of its own, effects, brushes, partial opacity or an opacity mask), when its dictionary holds another `BSArrow` entry beside heads, when a scale is outside 1–1000 %, or when the head's weight would be under the 0.25 pt least one VectorCraft draws; a graphic style with such a stroke isn't read rather than read without its heads, and one with heads takes them on the end of the path, so an object whose heads are read past its ends isn't linked to its listed style. Measured on a user's file of ten arrows (used locally, never committed): every line gets its heads, and drawn at 4× its pixels match the file's own page but for 3 of 9,825 inked ones (0.24.1: 1,232 differ). Tests `a_strokes_arrowhead_symbols_are_its_arrowheads`, `a_strokes_start_arrowhead_points_back_and_keeps_its_side`, `a_stroke_takes_both_heads_at_their_own_scales`, `heads_drawn_past_the_path_extend_it`, `arrowheads_this_does_not_read_keep_the_drawn_look`, `an_arrowhead_entry_without_heads_leaves_the_stroke_read` in `crates/eps/src/import/ai/tests.rs`, `heads_whose_placement_the_drawn_bounds_leave_open_keep_the_drawn_look`, `a_head_that_stays_put_leaves_a_moving_heads_placement_open`, `a_style_library_reads_the_heads_of_symbols_defined_after_its_styles` in it, `a_symbol_entry_cut_short_leaves_the_next_style_read` and `a_comment_inside_a_symbol_entry_is_skipped` in `crates/eps/src/import/ai/style/tests.rs`, `partly_transparent_or_masked_art_makes_no_head` in `crates/eps/src/import/ai/arrowhead.rs`, fuzzed by `ai_arrowhead_strokes_never_panic`; scores unchanged | | 2026-11-19 | minor | PDF import (#8549 follow-up): type filled and stroked after a page of type filled only came in as a filled object and a stroked one: since #8549 lines filled only are kept for a stroke pass too, and the glyphs of the lines finished past the 64 kept were remembered until the next stroke, so `2 Tr (Title) Tj` after more than 64 lines of type filled only took its first stroke for the start of a stroke pass over them, always once more than 4,096 glyphs had been finished so. Those glyphs are now forgotten when anything else is drawn (a path, an image, a Type 3 glyph's art, a change of blend mode or soft mask: nothing is drawn between an operator's fill pass and its stroke pass), and past the first 4,096 glyphs none are remembered instead of every stroke matching. A `TJ` over more lines than are kept still comes in as a filled object and a stroked one for each part, also when it ends where it began, and when a glyph kept as an outline comes before that (the line it starts keeps the glyphs of the lines finished). Remaining: with nothing drawn between them, type filled and stroked at exactly the place, font, size and text of a glyph filled only on a line finished so still comes in as a filled object and a stroked one, as the device can't tell its stroke pass from the start of one over that glyph. Tests: `type_filled_and_stroked_after_a_dense_page_of_filled_type_is_filled_and_stroked`, `type_filled_and_stroked_over_a_finished_glyph_after_a_path_is_filled_and_stroked`, `an_outline_glyph_in_a_tj_over_more_lines_than_are_kept_leaves_fill_and_stroke_apart`; scores and estimates unchanged. | +| 2026-11-12 | minor | #4569: document-owned file-font bindings, exact-byte identity checks and reclaimable live-face allowance; preserve referenced fallback bindings through installed-font removal, transfer placement leases/resources, relink older-save font keys, and restore recovery blobs before binding/diagnostics. Regression sources cover native/clipboard/export, Place/Break Link/older saves/recovery and isolated text/renderer ownership. Format-only verification; compilation and runtime proof pending. Scores and estimates unchanged. | +| 2026-11-09 | minor | PDF embedded-font import and composite-font layout work together: retained file fonts keep their glyphs while composite runs split by character class, with glyphs still naming their original runs; editing switches only the file-font text to its substitute. Background opens keep explicit importer parameters and PDF options while applying the embedded-font preference only when no choice was supplied. Regression `tests::composite::file_fonts_and_composite_fonts_draw_together` and existing PDF fidelity and Open With tests; scores unchanged (#4568) | | 2026-11-18 | minor | PDF import (#8543): type filled and stroked (text rendering modes 2 and 6) by a `TJ` whose kerning starts a new line part way through came in as four type objects, each part filled only and each part stroked only over it: the reader fills every glyph of the operator before it strokes them, and the line the first part was gathered on was finished before the stroke pass came back to it. Lines an operator's fill pass finishes while a stroke may still be drawn over them are now kept (up to 64 besides the open line, so a `TJ` over up to 65 lines: one over more stays a filled object and a stroked one for each part, as before) until the stroke pass goes past them, and the pass's strokes are held (up to 4096: a longer pass is matched a part at a time, each part to glyphs filled one right after another, never to one an operator before it filled) until it ends, then matched to the glyphs filled last, in the order they were filled, so each stroke finds the glyph it was filled as, also where the `TJ` draws a glyph again where it drew one (`[(A) -3500 (B) 4834 (A)] TJ`). Each part comes in as one type object filled and stroked, in the order drawn; also a `TJ` that jumps back and one whose kerning starts two new lines. In an `ActualText` span (whose stroke was lost) the replacement text stays one type object on the first glyph's line and in its style, now filled and stroked, also where the `TJ` draws a glyph again: the span's strokes are matched the same way. A stroke over no filled glyph (stroked type of its own) and the start and end of an `ActualText` span end a stroke pass: no stroke after them goes over a glyph filled before them, so none is drawn under type drawn after it, and a later span keeps its own replacement text. Stroke rendering stays stroke only, and translucent type stays a filled object and a stroked one. Tests: `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`, `a_tj_that_draws_a_glyph_again_where_it_drew_one_strokes_each_copy`, `a_stroked_tj_whose_kerning_starts_a_new_line_stays_stroke_only`, `a_translucent_tj_whose_kerning_starts_a_new_line_stays_fill_and_stroke_apart`, `a_long_stroke_pass_strokes_its_own_glyphs_not_one_filled_before`, `a_stroke_after_stroked_type_of_its_own_does_not_join_a_glyph_filled_before`, `a_stroke_in_an_actual_text_span_does_not_take_an_earlier_spans_glyph`, `a_tj_that_draws_a_glyph_again_in_an_actual_text_span_strokes_the_replacement`, `a_tj_over_more_lines_than_are_kept_comes_in_as_fill_and_stroke_apart`, `a_tj_over_more_lines_than_are_kept_that_ends_where_it_began_stays_fill_and_stroke_apart`, `type_after_a_tj_over_more_lines_than_are_kept_is_filled_and_stroked`; scores and estimates unchanged. | | 2026-11-18 | minor | PDF export (#3644): the document language chosen in Document Setup is written as the catalog's `/Lang` (BCP 47, `en-US` by default) and as XMP `dc:language`; a language without a tag writes none. Scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. | @@ -460,6 +500,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | 2026-11-04 | minor | Raster/PSD export uses document resolution unless ppi or scale is supplied; CLI run/convert accept --ppi. Synthetic engine, CLI and MCP regressions cover dimensions and override precedence; scores and hours unchanged. | | 2026-11-01 | minor | Native format: a symbol's Symbol Type (`dynamic`) and a dynamic symbol instance's appearance changes to objects of its art (`symbol_overrides`) round-trip; both are left out when unset, so other documents save unchanged (#4938). `.ai` reading and writing of dynamic symbols remains. | | 2026-11-01 | minor | Exports draw each artboard's background color behind its art (#4937): PNG, JPEG, GIF, TIFF, WebP, BMP, Targa and PSD (a layer of its own; on a transparent background too), PDF, SVG and EPS pages, a `.ai` file's PDF pages and PostScript and PDF print; `includeArtboardFill: false` leaves it out. Files with editing data (Preserve Editing, `.ai`, EPS, native) keep it as the artboard's color and reopen without extra art. Not read from the reference app's own `.ai` data, nor written to it. DXF, EMF and WMF leave it out | +| 2026-11-01 | minor | PDF import: type in a font the file embeds and this machine lacks is drawn in a small TrueType font built from the glyphs the file draws, kept with the document (MIME `font/ttf`, one per family and style, at most 64 are used to draw one type object, however many the file lists; 200,000 glyphs per import, a per-font glyph cap and a cap on fonts kept in memory), not the file's own font program: that program draws nothing and builds nothing, and is read only for its licence flags and metrics. The file's licence flags (OS/2 `fsType`) are copied to it (4, print and preview, when the file's program has none), so an export honours them as for any font: a restricted one (`fsType` 2, or bitmaps only) keeps its outlines out of an SVG's embedded fonts, and Document Info lists the permission. The text keeps naming the file's fonts, so they stay listed as missing; editing it, or installing the font, returns it to the font it names or its substitute. A saved file carries these glyphs, which is third-party font software in a file that may be shared: whether that is allowed is for the user to check against the font's licence. Import itself does not leave out a font whose flags forbid editing or embedding: it keeps the glyphs the file drew and carries the flags, and a policy that goes further (refusing such fonts, or a licence note when saving) is for the project owner. Sources: [Acrobat Help, PDF fonts](https://helpx.adobe.com/acrobat/using/pdf-fonts.html) and [Edit text in PDFs](https://helpx.adobe.com/acrobat/using/edit-text-pdfs1.html) for embedded fonts and what editing text in a font that is not installed does; the OpenType [OS/2 `fsType`](https://learn.microsoft.com/en-us/typography/opentype/spec/os2#fstype) field for the licence flags. Two programs of one family and style share one built font, which takes the stricter of their flags. It is on by default and has an opt-out: Preferences › File Handling › Use fonts embedded in imported PDFs (`pdfImportEmbeddedFonts`) and the `embeddedFonts` param of `document.open` and `file.place`; off, import sets the type in the fallback font and warns, as before (owner decision 2026-11-03). Tests `embedded_fonts_on_keeps_the_files_glyphs`, `embedded_fonts_off_sets_type_in_the_fallback_font_with_the_warning` and `the_embedded_fonts_preference_reaches_the_import_options`. Scores unchanged. | | 2026-10-31 | minor | PDF import finds an installed font whose PDF name holds hyphens (`Noto-Sans-Bold` is Noto Sans, Bold: the longest part before a hyphen that names an installed family) and a composite font by its CIDFont's name rather than its base name, which ends in the CMap's (`Name-Identity-H`, [ISO 32000-1 §9.7.6.1](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf)); a missing font is split only before a style part (`Helvetica-BoldOblique`), so it is reported as `MS PGothic`, not `MS`; scores unchanged (estimated) | | 2026-10-31 | minor | DXF export (2000–2018): the LAYOUT objects wrote the paper image origin as a point at group codes 148 and 158, but PLOTSETTINGS defines 148 and 149 and no 158, so strict readers could reject the file (Autodesk Fusion reported "DXF File failed to insert", #3085). They now write 148/149, the shade plot mode, resolution and DPI (76–78, 2004 and later) and flag 1024 on the Model layout; the plot style ACDBPLACEHOLDER no longer carries a subclass marker. Test `r2000_and_later_files_have_the_structure_cad_apps_require` (required sections and table entries, handles and references, LAYOUT group codes); exports pass ezdxf's recover and audit; not tested in Fusion itself; scores unchanged | | 2026-10-31 | minor | `.ai`/EPS editing data: an envelope whose contents are being edited is written the other way round from one that isn't: its contents, a group on `%_` lines, then its dictionary, which holds the mesh that shapes them. Those contents were read as art, so the undistorted art drew over the distorted art the page draws. The group on `%_` lines before an envelope's dictionary is now left out whatever it holds (text in it stays as hidden text, as the dictionary's own does), as the envelope's mesh already was (#2405). Test `import::ai::tests::an_envelope_s_contents_being_edited_are_not_read_as_art`; checked locally against a user's file: it opens from its layers, 0.0% from its page (it was 9.7%, over the 5% limit); scores unchanged | diff --git a/docs/gaps.md b/docs/gaps.md index 549d74f46b..2554f85b7a 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -8,6 +8,8 @@ > Blend redraw update (#5179; previously: Keyboard Shortcuts: user-bindable Switch Selection Tools (#7645), with no default key; scores and estimates unchanged): renderer bounds include spine-placed keys and steps; both focused CPU regressions pass. Scores and estimates unchanged. +> **File-font hardening status (2026-11-12, #4569):** G8 implementation and synthetic regressions added; compilation and runtime proof pending. Scores and estimates unchanged. + ## Feature submission evidence Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. @@ -315,6 +317,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G8 Hardening at scale +- **Implementation awaiting runtime proof (#4569):** bind file-font references to owned document blobs, compare candidate face bytes, and reclaim dead live-face slots. Unused blobs do not consume admission; native/PDF/paste report refused resources. Synthetic text, renderer and native/clipboard regressions added; no gap closed before compilation and runtime checks. + - **Done:** PngSuite fetching verifies 175 original PNGs and redistribution notices against a pinned SHA-256/size manifest before publishing; file and total-size budgets, cache verification and no archive extraction (#1729). The real-world corpus and manual QA gaps below remain. - **Done:** bounded synthetic control-input expansion (#1709): click/drag counts and pending-event capacity are checked before mutation, and control-channel bursts yield between frames. The corpus and platform QA below remain pending. @@ -990,6 +994,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | 2026-11-19 | minor | G12: Brushes panel item right-click context menu offering Brush Options…, Duplicate Brush, and Delete Brush (disabled if the last remaining brush); right-clicking an unselected brush selects it first, and right-clicking within a multi-selection preserves it offering Duplicate Brushes / Delete Brushes; headless tests in `crates/ui-egui/src/panels/brushes/tests.rs`; scores and estimates unchanged. | | 2026-11-19 | minor | G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…); right-clicking an unselected link row selects it first, and right-clicking within a multi-selection preserves it; headless tests in `crates/ui-egui/src/panels/tests_links.rs`; scores and estimates unchanged. | | 2026-11-18 | minor | G12: Layers panel context menu on guide rows (Release Guide, Duplicate, Delete Guide, Lock/Unlock, Hide/Show); regression tests in `crates/ui-egui/src/panels/layers/tests.rs`; scores and estimates unchanged. | +| 2026-11-12 | minor | G8 / #4569: file-font ownership and reclaimable admission implementation; regression sources added, compilation and runtime proof pending. Scores and estimates unchanged. | | 2026-11-18 | minor | G4 type: Retype phase 1 (#4934), `type.retype` for outlined text that exactly matches an available font; near matches, the ranked font list and images remain. Scores and estimates unchanged | | 2026-11-18 | minor | Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged. See [production-preflight.md](production-preflight.md) for scope and limits. | | 2026-11-16 | minor | Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..0541cc2ebd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1563,6 +1563,7 @@ are compared with the first page only. An artboard, or the page of an EPS's edit a point of its page's is compared on an area of the page's size. A file whose editing data is for a page of another size opens the same way, and its warning gives both sizes in points, with the scale of the editing data's page to the file's page (1:10 for a tenth of its size) when their sides are in proportion. +Type in a font a PDF embeds and this machine lacks is drawn in glyphs built from the file's own, kept with the document (#4568); `embeddedFonts: false` (default `true`) sets it in the fallback font with the missing-font warning instead, as before. Preferences › File Handling › Use fonts embedded in imported PDFs (`pdfImportEmbeddedFonts`, on by default) is the choice `document.open` and `file.place` take when they give none; a call's own `embeddedFonts` wins. With `textAs: "outlines"` a `.ai` file whose type shows opens from its PDF content, which has the type's outlines. A PDF With `textAs: "outlines"` a `.ai` file whose type shows opens from its PDF content, which has the type's outlines. A PDF saved with Illustrator's editing data holds it in `AIPDFPrivateData` streams and opens from it as a `.ai` file does. diff --git a/docs/roadmap.md b/docs/roadmap.md index 27c4f78e25..b403e455e9 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -5,6 +5,8 @@ > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > +> **M4/M7 file-font hardening status (2026-11-12, #4569):** implementation and synthetic regressions added; compilation and runtime proof pending. Scores and estimates unchanged. +> > Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Cap/join follow-up (2026-11-12): hidden-fill and no-fill stroke hits must respect cap and join geometry; focused cap/join CPU regressions passed. Scores and estimates unchanged. > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). @@ -246,6 +248,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | 2026-11-19 | minor | M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688). Scores and estimates unchanged. | | 2026-11-19 | minor | M14/G12: Character Styles and Paragraph Styles panels item context menus (Options…, Duplicate, Delete, Redefine, Clear Overrides); regression tests in crates/ui-egui/src/panels/text_styles/tests.rs; scores and estimates unchanged. | | 2026-11-18 | minor | M10/G5: Media Controls joins Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons and Weather Icons as a seventh built-in symbol library (Play, Pause, Stop, Skip Next, Shuffle, Repeat; original procedural vector symbols generated in code, no default 9-slice); G5 estimate decremented to 2–12 h, milestone estimates unchanged | +| 2026-11-12 | minor | M4/M7 / #4569: document-owned file-font identity and reclaimable live-face allowance implementation, with text/renderer/native/clipboard/export regression sources. Format-only verification; compilation and runtime proof pending. Scores and estimates unchanged. | | 2026-11-18 | minor | M7/G4: Retype phase 1 (#4934): `type.retype` turns outlined text that exactly matches an available font back into point text. Scores and estimates unchanged | | 2026-11-18 | minor | M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538). Scores and estimates unchanged. | | 2026-11-18 | minor | Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged. See [production-preflight.md](production-preflight.md) for scope and limits. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..e84ce63592 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -8,6 +8,8 @@ > > Glyphs update (#5514): Alternates for Current Selection applies a variant's OpenType feature to that letter alone (`salt=2`) so an Arabic word stays joined; Entire Font lists unencoded glyphs. A positional variant no supported feature draws can be applied as a glyph choice (#6084). Entire Font uses the selection's font version and variable axes, and the default cell remains available after an unlisted choice even without GSUB alternates. Only Arabic presentation-form characters insert their joining base letter. Scores and estimates unchanged. > +> **File-font integration status (2026-11-19, #4569):** 56 focused integration tests passed, including wrapped carried-font paragraphs and conflicting glyphs through native reopen. Full workspace CI and other hardening paths remain pending. Type core and file-format scores and estimates unchanged. See [file-font ownership evidence](file-format-parity.md#file-font-ownership-hardening-4569). +> > Live Paint Bucket update (2026-11-12): one drag fills the faces crossed in the same group (#6373). > > Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Cap/join follow-up (2026-11-12): hidden-fill and no-fill stroke hits must respect cap and join geometry; focused cap/join CPU regressions passed. Scores and estimates unchanged. @@ -3183,6 +3185,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-11-19 | minor | Performance: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688). Evidence added; scores and estimates unchanged. | | 2026-11-19 | minor | Artboard tool: Shift held once a move or an Alt-drag copy of an artboard is under way keeps it to the level, upright or 45° line from General › Constrain Angle, and snaps slide it along that line; a Shift-press still draws an artboard inside another or marquee-selects (#2497), #8580. Scores and estimates unchanged. | | 2026-11-18 | minor | Layers panel: context menu on guide rows (Release Guide, Duplicate, Delete Guide, Lock/Unlock, Hide/Show) with one-step undo; regression tests in `crates/ui-egui/src/panels/layers/tests.rs`; scores and estimates unchanged. | +| 2026-11-12 | minor | #4569: file-font identity, ownership and quota hardening implementation with isolated text/renderer and native/clipboard/export regression sources; integration coverage includes Place, Break Link, older saves, recovery and installed-font removal. Format-only verification; runtime proof pending. Scores and estimates unchanged. | | 2026-11-18 | minor | Type advanced: Retype phase 1 (`type.retype`, #4934), exact matches of available fonts become point text again; evidence added; near matches, the ranked font list and images remain; score and hours unchanged | | 2026-11-18 | minor | Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538). Scores and estimates unchanged. | | 2026-11-18 | minor | Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged. See [production-preflight.md](production-preflight.md) for scope and limits. | diff --git a/docs/type-parity.md b/docs/type-parity.md index 94993affe1..769d7a3e58 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -2,7 +2,9 @@ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: modal Check Spelling dialog: Edit › Spelling › Check Spelling…, `ui.checkSpelling`, #4936; spell check complete; previously minor: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; `.ai` and EPS files do not carry the choice; scores and estimates unchanged; previously minor: kerning at the Type tool's caret at the start of a line sets the space before the character after it, #5111; previously minor: type's strokes in an envelope paint along its bent glyph outlines at their own weight, Distort Appearance on or off, as users' `.ai` files draw them, #6644; previously minor: a centred or right-aligned line of tracked type is aligned without the tracking after its last character, as the page of users' `.ai` files aligns it, #6610; previously minor: tracking and manual kerning in horizontally scaled type are thousandths of the em as the Horizontal Scale draws it, as the page of users' `.ai` files spaces such type; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: Direct Selection shows and drags the direction handles of type on a path's path, #3565; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas base-letter paint; scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: right-aligned area type sets the text after a line's last tab against the right edge; a soft return in justified type no longer keeps its line from being justified; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen) · **Target:** Adobe Illustrator 2026 (30.x) -Glyphs review (#6084): a positional variant no supported feature draws is accepted as a glyph choice. Entire Font respects the selection's variable axes and font version; the default cell can reset an unlisted choice without GSUB alternates. Contextual choices use the supplying face, including fallback. Feature-only boundaries preserve ligature clusters and Arabic mark attachment. Encoded characters insert unchanged except Arabic presentation forms with a joining base letter; normalization reports success only after insertion succeeds. Latest follow-up regressions await runtime verification. Scores and estimates unchanged. +> **File-font hardening status (2026-11-12, #4569):** implementation and synthetic regressions added; compilation and runtime checks pending. Scores and estimates unchanged. +> +> Glyphs review (#6084): a positional variant no supported feature draws is accepted as a glyph choice. Entire Font respects the selection's variable axes and font version; the default cell can reset an unlisted choice without GSUB alternates. Contextual choices use the supplying face, including fallback. Feature-only boundaries preserve ligature clusters and Arabic mark attachment. Encoded characters insert unchanged except Arabic presentation forms with a joining base letter; normalization reports success only after insertion succeeds. Latest follow-up regressions await runtime verification. Scores and estimates unchanged. Type is Illustrator's largest single area by use (weight 13 of 105 across "Type core" and "Type advanced" in [target-app-parity.md](target-app-parity.md)). This checklist lists the features one by one. Status is from the @@ -20,6 +22,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Feature | Status | Notes | |---|---|---| +| File-carried font ownership and admission | unverified implementation | #4569 binds referenced fonts to document-owned bytes, compares content-hash collisions by bytes, and reaps dead global face entries. Synthetic text, renderer and native/clipboard regressions added; runtime proof pending. | | Mouse wheel over the closed font-family field | done | #5253: Character, Properties and Control step selected text through the family list using saved font filters (excluding search text), one undo step per notch; the style is matched and the list stops at either end. Escape and leaving the field keep the change. The field takes the wheel only when the pointer was moved onto it after the field last moved or was covered by a window or overlay, and the wheel stream began there; a stream that began elsewhere stays there until 0.5 s pass with no wheel input. Order, bounds, Undo grouping, this rule and its 0.5 s are VectorCraft's choices; scores unchanged. | | Soft return (forced line break, Shift+Enter) | done | Shift+Enter inserts a soft return (U+2028), breaking the line without starting a new paragraph; paragraph spacing (space before/after) and first-line indents apply only at paragraph ends; continuation lines in lists do not repeat the marker; in justified text a line a soft return ends is justified as a wrapped line is, only the paragraph's last line keeping its alignment, as Illustrator's own layout in a user's `.ai` sets it (evidence: `tests::typo::soft_return_in_justified_text_spreads_like_a_wrapped_line`; first done the other way in #2754) | | Native font-family labels | partial | With Show Font Names in English off, localized legacy names are used when typographic names contain no native label (#2208); loaded-font and catalog-only regressions. Choosing among multiple native languages is unchanged. | @@ -89,6 +92,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| +| 2026-11-12 | minor | #4569: file-font identity, ownership and live-face allowance hardening; forged internal family names no longer select global file fonts. Preserve owned fallback bindings through installed-font removal, placement, older saves and recovery. Added synthetic regressions; format-only verification, runtime proof pending. Scores and estimates unchanged. | | 2026-11-18 | minor | Retype phase 1 (#4934): `type.retype` turns outlined glyphs that exactly match an available font back into point text (font, size, baseline, turn, paint), reporting the shapes it cannot match; the Retype row is now partial. Scores and estimates unchanged | | 2026-11-15 | minor | Check Spelling dialog (#4936): Edit › Spelling › Check Spelling… (`Cmd+I`, `ui.checkSpelling`) modal dialog with sentence context, suggestions, Ignore, Ignore All, Change, Change All, Add to Dictionary, Done/Cancel, keyboard navigation, and one-step Undo/Redo; spell check complete. Scores and estimates unchanged. | | 2026-11-14 | minor | Paragraph composers (#4935): `text.setFormat {composer}` and paragraph styles take `singleLine` and `everyLine` (the Middle Eastern & South Asian composers, what all type used and the default) and `standardSingleLine` and `standardEveryLine`, which break lines the same way and set a complex script (Indic, Arabic, Hebrew) glyph by glyph as the font maps its characters, with no conjuncts, reordering, marks placed or joining forms. The choice is per paragraph, saved in the native file only when it is not Every-line, and not written to `.ai`, EPS or PDF files, whose composer setting this app has no recorded format for. Scores and estimates unchanged. Tests `tests::composers`. | From 5022ba5593c9524ea13acca4b2e4b6155f42d8a9 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:21:18 +0100 Subject: [PATCH 17/32] ci: note the shared SonarCloud archive job cap The reusable workflow now defaults build-jobs to 2 so a cold instrumented archive stays within hosted-runner memory (craft-common-actions#333). --- .github/workflows/sonarcloud.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index e78fe1ea3b..90cf166ed7 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -17,5 +17,7 @@ concurrency: jobs: sonarcloud: # Tracked at @main so org-wide CI improvements propagate without PR churn. + # The reusable workflow defaults build-jobs to 2 so a cold instrumented + # archive stays within hosted-runner memory (craft-common-actions#333). uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main secrets: inherit From a3b0b3dec019eaeaa1de075472cf0f51fa7e2c87 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:59:59 +0100 Subject: [PATCH 18/32] deps: pin all craft-libs crates to 205042e (craft-libs#778) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rule 10: every storytold/craft-libs crate is at the same rev, now 205042e406b630cda653990649264a78fea6296b, the merge of #3136 on craft-libs main. That rev still skips a form already on the drawing stack (ISO 32000-2 §8.10.1) but no longer reports it as ContentTruncated, so a 200-shape knockout-mask PDF imports completely. Also moves the leftover per-crate pins of craft-font-catalog and craft-web-api onto the same rev. --- Cargo.lock | 231 ++++++++++---------------------- Cargo.toml | 70 +++++----- apps/vectorcraft-web/Cargo.toml | 2 +- crates/text/Cargo.toml | 2 +- 4 files changed, 109 insertions(+), 196 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5955c4c20f..df20282409 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1001,7 +1001,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "crc32fast", "flate2", @@ -1012,7 +1012,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=9b28b56bc7207ef7ce806f37df72cb94c0ad5c37#9b28b56bc7207ef7ce806f37df72cb94c0ad5c37" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "crc32fast", "flate2", @@ -1021,7 +1021,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "md-5", "rayon", @@ -1030,20 +1030,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" -dependencies = [ - "rayon", -] - -[[package]] -name = "craft-dds" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "rayon", ] @@ -1051,12 +1043,12 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "craft-codepage", "encoding_rs", @@ -1068,17 +1060,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=068e079c7be4b100a8a6b305b31ac881e069727e#068e079c7be4b100a8a6b305b31ac881e069727e" - -[[package]] -name = "craft-eps" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec#cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "harfrust 0.13.3", "kurbo 0.13.1", @@ -1092,12 +1079,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "gif", ] @@ -1105,7 +1092,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "flate2", ] @@ -1113,7 +1100,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1136,39 +1123,12 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ - "craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", - "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", - "crc32fast", - "exr", - "flate2", - "half", - "hayro-jpeg2000", - "image", - "image-webp", - "jpeg-encoder", - "png 0.18.1", - "rayon", - "serde_json", - "thiserror 2.0.21", - "tiff", - "zune-core", - "zune-jpeg", - "zune-jpegxl", -] - -[[package]] -name = "craft-image-codecs" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" -dependencies = [ - "craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", - "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", + "craft-dds", + "craft-jpeg", + "craft-metadata", + "craft-tiff", "crc32fast", "exr", "flate2", @@ -1190,15 +1150,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" -dependencies = [ - "thiserror 2.0.21", -] - -[[package]] -name = "craft-jpeg" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "thiserror 2.0.21", ] @@ -1206,7 +1158,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1217,7 +1169,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "egui", "serde", @@ -1227,23 +1179,11 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "brotli-decompressor 6.3.2", "chrono", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", - "quick-xml 0.41.0", - "serde", -] - -[[package]] -name = "craft-metadata" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" -dependencies = [ - "brotli-decompressor 6.3.2", - "chrono", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", + "craft-tiff", "quick-xml 0.41.0", "serde", ] @@ -1251,7 +1191,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8f6ad14b58ca2efee67aac5d0f5573bad6a5ca81#8f6ad14b58ca2efee67aac5d0f5573bad6a5ca81" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "encoding_rs", "image", @@ -1262,7 +1202,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "chrono", "craft-codepage", @@ -1272,7 +1212,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1283,7 +1223,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1292,7 +1232,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "craft-winprint-gdi", "log", @@ -1306,7 +1246,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1317,9 +1257,9 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec#cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ - "craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec)", + "craft-eps", "flate2", "kurbo 0.13.1", "miniz_oxide 0.8.9", @@ -1331,7 +1271,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "encoding_rs", "flate2", @@ -1342,7 +1282,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "fax", "hayro-ccitt", @@ -1353,10 +1293,10 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", + "craft-image-codecs", + "craft-xml", "data-url", "flate2", "gif", @@ -1374,34 +1314,17 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" -dependencies = [ - "serde", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-tiff" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" -dependencies = [ - "serde", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-tiff" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "serde", "thiserror 2.0.21", + "tiff", ] [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1422,7 +1345,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "chrono", "dunce", @@ -1449,7 +1372,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "flate2", "serde", @@ -1460,7 +1383,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "js-sys", "serde_json", @@ -1471,7 +1394,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "egui", "objc2 0.6.5", @@ -1490,17 +1413,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" -dependencies = [ - "quick-xml 0.41.0", - "serde", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-xml" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2607,7 +2520,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "brotli", "hayro-postscript", @@ -2616,7 +2529,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -2634,7 +2547,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -2652,12 +2565,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "flate2", "hayro-ccitt", @@ -3457,7 +3370,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "base64 0.22.1", "bumpalo", @@ -3566,7 +3479,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -6772,7 +6685,7 @@ name = "vectorcraft-affinity" version = "0.24.1" dependencies = [ "craft-affinity", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "crc32fast", "proptest", "vectorcraft-affinity", @@ -6802,7 +6715,7 @@ name = "vectorcraft-cad" version = "0.24.1" dependencies = [ "craft-dxf", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "craft-plotter", "image", "kurbo 0.13.1", @@ -6857,7 +6770,7 @@ name = "vectorcraft-doc" version = "0.24.1" dependencies = [ "chrono", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "craft-stream-codecs", "flate2", "image", @@ -6877,7 +6790,7 @@ dependencies = [ name = "vectorcraft-effects" version = "0.24.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "craft-svg", "image", "kurbo 0.13.1", @@ -6903,11 +6816,11 @@ dependencies = [ "craft-cdr", "craft-codepage", "craft-docpath", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "craft-jxl", "craft-proof", "craft-stream-codecs", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", + "craft-xml", "crc32fast", "encoding_rs", "flate2", @@ -6960,8 +6873,8 @@ dependencies = [ name = "vectorcraft-eps" version = "0.24.1" dependencies = [ - "craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=068e079c7be4b100a8a6b305b31ac881e069727e)", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-eps", + "craft-image-codecs", "craft-pdf", "craft-ps", "craft-stream-codecs", @@ -7041,7 +6954,7 @@ dependencies = [ name = "vectorcraft-mcp" version = "0.24.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "image", "log", "proptest", @@ -7061,7 +6974,7 @@ dependencies = [ name = "vectorcraft-metafile" version = "0.24.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "craft-metafile", "image", "kurbo 0.13.1", @@ -7102,10 +7015,10 @@ version = "0.24.1" dependencies = [ "aes", "chrono", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "craft-pdf", "craft-stream-codecs", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", + "craft-xml", "flate2", "getrandom 0.4.3", "image", @@ -7137,7 +7050,7 @@ dependencies = [ name = "vectorcraft-plugins" version = "0.24.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "craft-vectorcraft-format", "log", "rustix 1.1.6", @@ -7159,10 +7072,10 @@ name = "vectorcraft-render" version = "0.24.1" dependencies = [ "craft-gif", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "craft-psd", "craft-stream-codecs", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", + "craft-tiff", "flate2", "image", "jpeg-encoder", @@ -7198,10 +7111,10 @@ name = "vectorcraft-svg" version = "0.24.1" dependencies = [ "craft-docpath", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "craft-mime", "craft-svg", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", + "craft-xml", "data-url", "flate2", "image", @@ -7229,7 +7142,7 @@ dependencies = [ name = "vectorcraft-testkit" version = "0.24.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "fax", "kurbo 0.13.1", "proptest", @@ -7281,7 +7194,7 @@ dependencies = [ name = "vectorcraft-tools" version = "0.24.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "kurbo 0.13.1", "serde", "serde_json", @@ -7298,7 +7211,7 @@ dependencies = [ name = "vectorcraft-trace" version = "0.24.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "image", "kurbo 0.13.1", "serde", @@ -7313,7 +7226,7 @@ version = "0.24.1" dependencies = [ "bytemuck", "chrono", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-image-codecs", "craft-keymap", "craft-ui", "craft-update", diff --git a/Cargo.toml b/Cargo.toml index c3d1611ea3..9dd7f32154 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,44 +11,44 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", default-features = false, features = ["interpret", "write"] } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["serde"] } -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b", default-features = false, features = ["interpret", "write"] } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b", features = ["serde"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } # Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per # desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b", features = ["egui"] } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } # craft-update: app-specific pretend versions apply to startup and manual checks. # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "9b28b56bc7207ef7ce806f37df72cb94c0ad5c37" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "068e079c7be4b100a8a6b305b31ac881e069727e" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "8f6ad14b58ca2efee67aac5d0f5573bad6a5ca81" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["egui"] } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "205042e406b630cda653990649264a78fea6296b", features = ["egui"] } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -191,13 +191,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 9569d2b3f3..515793665c 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -17,7 +17,7 @@ path = "src/main.rs" vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] } vectorcraft-ui-egui = { workspace = true } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b", version = "0.1.0" } vectorcraft-format = { workspace = true } vectorcraft-text = { workspace = true } egui = { workspace = true } diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index b667c5d9bb..a3dcd9633b 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -10,7 +10,7 @@ workspace = true [dependencies] # The shared font catalog from craft-libs main (it has the outline, bidi and caret helpers used here). -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", default-features = false } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b", default-features = false } vectorcraft-geom = { workspace = true } vectorcraft-doc = { workspace = true } kurbo = { workspace = true } From c9c2d711d1dbc0c9d1995e0cad03127d8dc50800 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:26:33 +0100 Subject: [PATCH 19/32] xtask: keep pdf-deps aligned with the 205042e craft-libs pin (craft-libs#778) Shard 5 (Checks) failed because cargo xtask pdf-deps still expected craft-pdf and the hayro/krilla backends at d7c9632, and hayro-jbig2 at the leftover stream-codec pin. All of those crates now resolve at the shared 205042e revision. --- xtask/src/pdf_deps.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 53437300b7..2abbb0ebe1 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,15 +5,13 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "d7c9632bfb3040cf45db394e7500cc93c81c49e0"; -const STREAM_REV: &str = "d20a82481b1f7b1d32c818b19c620338af9755d3"; +const REV: &str = "205042e406b630cda653990649264a78fea6296b"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), ("hayro-syntax", "0.7.2", REV), ("hayro-interpret", "0.7.0", REV), - // Share the vendored JBIG2 package pulled in by craft-stream-codecs. - ("hayro-jbig2", "0.3.0", STREAM_REV), + ("hayro-jbig2", "0.3.0", REV), ("hayro-cmap", "0.1.0", REV), ("hayro-postscript", "0.1.0", REV), ]; From 71965b6a425e93ed26b415cda6ca3ef5015a253c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 23 Nov 2026 09:34:26 -0500 Subject: [PATCH 20/32] ci(release): forward ARTCRAFT_SERVICES_DISPATCH_TOKEN secret (#9172) --- .github/workflows/release.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 32043bf033..226830fc1b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -57,6 +57,7 @@ jobs: WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }} AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} + ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }} AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} From a149f933926a4a25a12cea344cd3c15ce68ec1ee Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 09:54:50 -0800 Subject: [PATCH 21/32] Script checker: code the check can't read keeps a Folder's length, hidden and readonly setters The check leaves out `length`, `hidden` and `readonly` set on `new Folder(...)`, a `Folder` place, or a variable holding one, but a script can give that name a File object in ways the check does not read. Such a setter now counts as a file write in a check whose files: - use `with`, or name `eval`, `Function`, `evalFile` or `constructor`, as a word or as a string literal in brackets (`this['eval'](s)`, `$['evalFile'](f)`, `(function () {}).constructor(s)`) - read, call or assign a property in brackets when the brackets hold anything but one string or number literal (`this[k](s)`, `this['ev' + 'al'](s)`, `this[('eval')](s)`, `this[0, 'eval'](s)`, `$[k](f)`, `g[k] = ...`), including a preprocessor line inside the brackets - assign a property in brackets whose name is a string literal longer than 256 characters, or properties of more than 1,000 names - assign or declare `Folder` A variable whose name a member assignment writes (`$.global.d = ...`, `this.d = ...`, `this['d'] = ...`) counts as one that may hold a File object. Array literals, `o['plain']` and `a[0]` leave the Folder alone. docs/mcp.md and the progress line in docs/target-app-parity.md state the rule. --- crates/scriptcheck/src/analyze.rs | 22 ++- crates/scriptcheck/src/analyze/declared.rs | 137 +++++++++++++++++-- crates/scriptcheck/src/analyze/features.rs | 7 +- crates/scriptcheck/src/tests.rs | 148 +++++++++++++++++++++ docs/mcp.md | 10 +- docs/target-app-parity.md | 2 +- 6 files changed, 305 insertions(+), 21 deletions(-) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 5d01cc8438..d718c88b30 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -53,19 +53,23 @@ pub(crate) struct Known { pub bound: HashMap, pub files: HashSet, pub folders: HashSet, + /// A file gives names values the analysis doesn't read ([`Declared::unsure`]): no object counts + /// as a Folder object whatever the path names. + pub unsure: bool, } impl Known { /// The names known, a name that may hold a File object counting twice: a Folder that becomes a /// possible File object ([`Known::add`]) changes it too. pub fn len(&self) -> usize { - self.bound.len() + self.files.len().saturating_mul(2).saturating_sub(self.folders.len()) + self.bound.len() + self.files.len().saturating_mul(2).saturating_sub(self.folders.len()) + usize::from(self.unsure) } /// What `other` adds, up to [`crate::Limits::entries`] names of each kind: a name already /// bound keeps its chain. A name that holds a File or Folder object on both sides holds a Folder /// object only when both sides say so; otherwise it may hold a File object. pub fn add(&mut self, other: Known, entries: usize) { + self.unsure |= other.unsure; for (name, chain) in other.bound { if self.bound.len() < entries || self.bound.contains_key(&name) { self.bound.entry(name).or_insert(chain); @@ -566,6 +570,9 @@ struct Analyzer<'s, 'a, 'l> { maybe_files: HashSet, /// `maybe_files` ran out of room: no variable counts as holding a Folder object. maybe_files_full: bool, + /// This file or what the scan started with gives names values the analysis doesn't read + /// ([`Declared::unsure`]): no object counts as a Folder object whatever the path names. + unsure: bool, /// The platform names ([`platform_name`]) the script declares or assigns a meaning of its own /// for: they no longer stand for the platform's objects. own_names: HashSet, @@ -635,8 +642,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { bound: known.bound.clone(), files: known.files.clone(), folders: known.folders.clone(), - maybe_files: known.files.difference(&known.folders).cloned().collect(), + // A variable of the same name as a property a member assignment writes may be that + // property of the global object. + maybe_files: known.files.difference(&known.folders).chain(declared.rebound.iter()).cloned().collect(), maybe_files_full: false, + unsure: known.unsure || declared.unsure, own_names: HashSet::new(), scopes: vec![], declared, @@ -865,10 +875,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } - /// `name` holds a Folder object whatever the path names, and no assignment the check read gave it - /// a value that may be a File object. + /// `name` holds a Folder object whatever the path names, no assignment the check read gave it a + /// value that may be a File object, and the file gives no name a value the analysis doesn't read. fn folder(&self, name: &str) -> bool { - !self.maybe_files_full && self.files.contains(name) && self.folders.contains(name) && !self.maybe_files.contains(name) + !self.maybe_files_full && !self.unsure && self.files.contains(name) && self.folders.contains(name) && !self.maybe_files.contains(name) } /// `t`, when it names a parameter of the function whose body's `{` is still to come: kept, up to @@ -1568,7 +1578,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } // A variable that any assignment gave a value that may be a File object leaves as one. let folders = self.folders.iter().filter(|name| self.folder(name)).cloned().collect(); - let known = Known { bound: std::mem::take(&mut self.bound), files: std::mem::take(&mut self.files), folders }; + let known = Known { bound: std::mem::take(&mut self.bound), files: std::mem::take(&mut self.files), folders, unsure: self.unsure }; (std::mem::take(&mut self.includes), module, known) } } diff --git a/crates/scriptcheck/src/analyze/declared.rs b/crates/scriptcheck/src/analyze/declared.rs index d0e55cbb1f..48f071d2ac 100644 --- a/crates/scriptcheck/src/analyze/declared.rs +++ b/crates/scriptcheck/src/analyze/declared.rs @@ -2,7 +2,21 @@ use std::collections::HashSet; -use super::{Acc, Brackets, Lexer, LineBreaks, Read, Sig, T, for_in, goes_on_after, goes_on_with, is, member_mark, word}; +use super::{Acc, Brackets, Lexer, LineBreaks, Read, Sig, T, catalog, for_in, goes_on_after, goes_on_with, is, member_mark, unquote, word}; + +/// The names that give variables values the analysis doesn't read: a `with` statement makes an +/// object's properties stand for names in its body (ECMA-262 3rd edition, section 12.10), and `eval`, +/// `Function` and `$.evalFile` run code given as text. A string literal in brackets that names one +/// reaches it too (`this['eval']`), and so does a function's `constructor` property, which is +/// `Function` (section 15.3.4.1). +const UNREAD_BINDINGS: &[&str] = &["with", "eval", "Function", catalog::DOLLAR_EVAL_FILE]; + +/// The property a function reaches `Function` through. +const CONSTRUCTOR: &str = "constructor"; + +/// The longest property name, in characters, that [`Declared::rebound`] keeps. A string literal in +/// brackets that spells a longer one sets [`Declared::unsure`]. +const PROPERTY_CHARS: usize = 256; /// The names a file's function bodies and its global code declare, read before the analysis. A /// function's `var` statements and the function declarations directly in its body make the names @@ -19,6 +33,17 @@ pub(crate) struct Declared<'s> { pub(super) bodies: Vec<(usize, Vec<&'s str>)>, /// The names the function declarations directly in the global code declare. pub(super) global: HashSet<&'s str>, + /// The property names a member assignment writes (`o.d = …`, `o['d'] = …`). The object may be + /// the global object, so a variable of that name may get a value the analysis doesn't read. + pub(super) rebound: HashSet, + /// The file gives names values the analysis doesn't read in other ways ([`UNREAD_BINDINGS`] or + /// a `constructor` property used, a property read, called or assigned whose name in brackets is + /// not one string or number literal, which may be a variable's name on the global object + /// (ECMA-262 3rd edition, section 10.1.3) or one of [`UNREAD_BINDINGS`] whatever object the + /// brackets follow, a property assigned whose name is a string literal longer than + /// [`PROPERTY_CHARS`], or `Folder` assigned or declared), or `rebound` ran out of room: no + /// object counts as a Folder object whatever the path names. + pub(super) unsure: bool, } /// A function body [`Declarations`] is reading: the bracket depth inside it, its entry in @@ -31,13 +56,23 @@ struct Body<'s> { var_depth: Option, } +/// A `[` [`Declarations`] is reading: the bracket depth inside it, whether a property's name in +/// brackets starts at it (it comes after a value, where no array literal starts), and the tokens read +/// inside it so far: how many, and the kind of the first. +struct Key { + depth: usize, + member: bool, + tokens: usize, + first: Option, +} + /// The pass that finds [`Declared`]. It follows brackets, function bodies and `var` statements by /// the rules [`Analyzer`] follows them by, so that both passes find the same function bodies. struct Declarations<'s, 'a, 'l> { acc: &'a mut Acc<'l>, brackets: Brackets, - /// The two significant tokens before this one, the latest first. - h: [Option>; 2], + /// The three significant tokens before this one, the latest first. + h: [Option>; 3], /// `function` was read at this bracket depth, and its body's `{` is still to come. function: Option, /// The bracket depth of the `var` statement being read. @@ -50,6 +85,8 @@ struct Declarations<'s, 'a, 'l> { /// The bracket depth inside the outermost function body past that limit being read. The names /// declared inside it are not kept. untracked: Option, + /// The `[` brackets being read, the innermost last, up to [`crate::Limits::nesting`]. + keys: Vec, out: Declared<'s>, } @@ -59,12 +96,13 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { let mut d = Declarations { acc, brackets: Brackets::default(), - h: [None; 2], + h: [None; 3], function: None, var_depth: None, assign: None, bodies: vec![], untracked: None, + keys: vec![], out: Declared::default(), }; let mut breaks = LineBreaks::default(); @@ -75,7 +113,8 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { Read::Token(sig) => d.token(sig), } } - let out = d.out; + let mut out = d.out; + out.unsure |= out.rebound.contains(catalog::FOLDER); acc.steps = acc.steps.saturating_add(lexer.steps); out } @@ -86,7 +125,14 @@ impl<'s> Declarations<'s, '_, '_> { } fn token(&mut self, t: Sig<'s>) { - let [h0, h1] = self.h; + let [h0, h1, _] = self.h; + self.unread_binding(&t); + if !t.is("]") + && let Some(key) = self.keys.last_mut() + { + key.tokens = key.tokens.saturating_add(1); + key.first = key.first.or(Some(t.kind)); + } // As in [`Analyzer::token`], a line break ends a `var` statement when it is outside the // statement's brackets, and the tokens on either side of it don't go on with the expression. if t.nl && self.var_depth == Some(self.depth()) && !goes_on_after(h0) && !goes_on_with(&t) { @@ -118,7 +164,51 @@ impl<'s> Declarations<'s, '_, '_> { if t.word("function") && !member_mark(h0) && !word(h0, "function") { self.function = Some(depth); } - self.h = [Some(t), h0]; + self.h = [Some(t), h0, h1]; + } + + /// `t`, a token before the brackets are followed past it: notes in [`Declared::rebound`] and + /// [`Declared::unsure`] the ways the file gives names values the analysis doesn't read. + fn unread_binding(&mut self, t: &Sig<'s>) { + let [h0, h1, h2] = self.h; + if t.kind == T::Ident && (UNREAD_BINDINGS.contains(&t.text) || t.text == CONSTRUCTOR) { + self.out.unsure = true; + } + // `this['eval']`, `$['evalFile']` and `o['constructor']`. + if t.kind == T::Str && is(h0, "[") { + let name = unquote(t.text, PROPERTY_CHARS.saturating_add(1)); + if UNREAD_BINDINGS.contains(&name.as_str()) || name == CONSTRUCTOR { + self.out.unsure = true; + } + } + // `var Folder`, `function Folder` and `Folder = …`: `Folder` may stop being the platform's. + if (t.word(catalog::FOLDER) && (word(h0, "var") || word(h0, "function") || (is(h0, ",") && self.var_depth.is_some()))) + || (t.is("=") && word(h0, catalog::FOLDER)) + { + self.out.unsure = true; + } + if t.is("=") { + let literal = |kind: T| h1.is_some_and(|s| s.kind == kind) && is(h2, "["); + let property = if h0.is_some_and(|s| s.kind == T::Ident) && member_mark(h1) { + h0.map(|s| s.text.to_string()) + } else if is(h0, "]") && literal(T::Str) { + // The value spells a longer name than is kept: it may be any variable's. + h1.map(|s| unquote(s.text, PROPERTY_CHARS.saturating_add(1))).filter(|name| name.chars().count() <= PROPERTY_CHARS) + } else { + None + }; + if let Some(name) = property { + if self.out.rebound.contains(&name) || self.acc.room(self.out.rebound.len()) { + self.out.rebound.insert(name); + } else { + self.out.unsure = true; + } + } else if is(h0, "]") && !literal(T::Number) { + // `o[k] = …` with a computed name, or a string literal too long to keep. A number + // names no variable. + self.out.unsure = true; + } + } } /// An open or close bracket, by the rules of [`Analyzer::bracket`]: the first `{` after @@ -128,6 +218,16 @@ impl<'s> Declarations<'s, '_, '_> { "(" | "[" | "{" => { let body = t.text == "{" && self.function.take() == Some(self.depth()); self.brackets.open(t, self.acc.limits.nesting); + if t.text == "[" { + // After a value, `[` starts a property's name in brackets (ECMA-262 3rd + // edition, section 11.2.1); elsewhere it starts an array literal. + let member = !t.expr; + if self.keys.len() < self.acc.limits.nesting { + self.keys.push(Key { depth: self.depth(), member, tokens: 0, first: None }); + } else if member { + self.out.unsure = true; + } + } if !body { return; } @@ -140,10 +240,22 @@ impl<'s> Declarations<'s, '_, '_> { } } ")" | "]" | "}" => { + let inside = self.depth(); if !self.brackets.close(t) { return; } let depth = self.depth(); + // `o[k]`, `this['ev' + 'al']` and `o[('eval')]`, read, called or assigned: a name + // in brackets that isn't one string or number literal may be any variable's on the + // global object, or `eval`, `Function`, `evalFile` or `constructor`. + if t.text == "]" + && let Some(key) = self.keys.pop_if(|k| k.depth == inside) + && key.member + && !(key.tokens == 1 && matches!(key.first, Some(T::Str | T::Number))) + { + self.out.unsure = true; + } + while self.keys.pop_if(|k| depth < k.depth).is_some() {} if self.var_depth.is_some_and(|d| depth < d) { self.var_depth = None; } @@ -163,7 +275,7 @@ impl<'s> Declarations<'s, '_, '_> { /// directly in it, and for the global code when the declaration is directly in the global code. /// Each body keeps up to [`crate::Limits::entries`] names, and so does the global code. fn declaration(&mut self, t: &Sig<'s>) { - let [h0, _] = self.h; + let [h0, ..] = self.h; let depth = self.depth(); let var = word(h0, "var") || (is(h0, ",") && self.var_depth == Some(depth)); let function = word(h0, "function") && h0.is_some_and(|f| f.stmt); @@ -182,9 +294,14 @@ impl<'s> Declarations<'s, '_, '_> { } } - /// A preprocessor line ends the statement before it, as in [`Analyzer::directive`]. + /// A preprocessor line ends the statement before it, as in [`Analyzer::directive`]. Inside a + /// property's name in brackets it hides the tokens before the name (`this[`, a line, `'eval']`), + /// so the name may be any. fn directive(&mut self) { - self.h = [None; 2]; + if self.keys.iter().any(|k| k.member) { + self.out.unsure = true; + } + self.h = [None; 3]; self.var_depth = None; self.assign = None; } diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 19806fb9ad..5599d5b691 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -334,12 +334,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } /// What [`Self::file_receiver`] finds: `Some(true)` for a Folder object whatever the path names - /// ([`Sig::folder`], [`Analyzer::folder`]), `Some(false)` for an object that may be a File object, - /// and `None` for anything else. + /// ([`Sig::folder`], [`Analyzer::folder`]), unless the file gives names values the analysis + /// doesn't read ([`Analyzer::unsure`]), `Some(false)` for an object that may be a File object, and + /// `None` for anything else. fn held_file(&self, receiver: Option>, before: Option>) -> Option { let r = receiver?; if r.file { - Some(r.folder) + Some(r.folder && !self.unsure) } else if r.kind == T::Ident && !member_mark(before) && self.alias(&r) { Some(self.folder(r.text)) } else { diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index b771cc6417..1f527349b4 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -653,6 +653,154 @@ fn a_variable_that_may_hold_a_file_counts_as_one() { assert!(r.outside.is_empty(), "{:?}", r.outside); } +/// A `with` statement, `eval`, `Function`, `$.evalFile`, a member assignment that may write the +/// global object's property of a variable's name, and a script's own `Folder` may give a name a +/// File object the check doesn't see, before or after the setter in the text, so the setter counts. +#[test] +fn a_folder_that_other_code_may_rebind_counts_as_a_file() { + let scripts: [(&str, usize); 11] = [ + ("var d = new Folder(p);\nwith (o) { d.length = 0; }\n", 2), + ("var d = new Folder(p);\nfunction w() { d.hidden = true; }\n$.global.d = new File(q);\n", 2), + ("var d = new Folder(p);\nfunction w() { d.hidden = true; }\nthis.d = new File(q);\n", 2), + ("var d = new Folder(p);\nfunction w() { d.hidden = true; }\nthis['d'] = new File(q);\n", 2), + ("var d = new Folder(p);\nfunction w() { d.hidden = true; }\n$.global[k] = new File(q);\n", 2), + ("eval(s);\nnew Folder(p).length = 0;\n", 2), + ("var d = new Folder(p);\nd.readonly = true;\n$.evalFile(f);\n", 2), + ("var d = new Folder(p);\nd.readonly = true;\nvar g = new Function(s);\n", 2), + ("$.global.Folder = File;\nnew Folder(p).length = 0;\n", 2), + ("function w() { new Folder(p).hidden = true; }\nFolder = File;\n", 1), + ("function w() { Folder.temp.hidden = true; }\nvar Folder = File;\n", 1), + ]; + let written = |r: &Report| r.outside.iter().find(|o| o.id == "filesWritten").map(|o| o.lines.clone()); + for (script, line) in scripts { + assert_eq!(written(&report(script)), Some(vec![line]), "{script}"); + } + // Another variable's name, or a number as the index, leaves the Folder alone. + let r = report("var d = new Folder(p);\no.e = new File(q);\na[0] = new File(q);\nd.length = 0;\n"); + assert_eq!(written(&r), None); + // A computed index may name the variable on any object that may be the global object. + let r = report("var d = new Folder(p);\na[k] = new File(q);\nd.length = 0;\n"); + assert_eq!(written(&r), Some(vec![3])); + // A `with` statement in an included file counts in the script too. + let mut m = mem(&[("lib.jsxinc", "with (o) { x = 1; }\n")]); + let r = check("main.jsx", b"#include 'lib.jsxinc'\nvar d = new Folder(p);\nd.length = 0;\n", Some(&mut m), &Limits::default()); + let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect(); + assert_eq!(outside, [("filesWritten", &[3][..])]); +} + +/// An assignment to a computed property of any object, a string literal in brackets that names +/// `eval`, `Function` or `$.evalFile`, and any `constructor` property may give a name a File object +/// the check doesn't see, so no object counts as a Folder object. +#[test] +fn a_folder_that_unnamed_code_may_rebind_counts_as_a_file() { + let scripts: [(&str, usize); 13] = [ + ("var d = new Folder(p);\nvar g = this;\ng[k] = new File(q);\nd.length = 0;\n", 4), + ("var d = new Folder(p);\nvar g = $.global;\ng[k] = File;\nd.length = 0;\n", 4), + ("var d = new Folder(p);\n$['global'][k] = new File(q);\nd.length = 0;\n", 3), + ("var d = new Folder(p);\n$[\"global\"][k] = new File(q);\nd.length = 0;\n", 3), + ("var d = new Folder(p);\no[f(k)] = new File(q);\nd.length = 0;\n", 3), + ("var d = new Folder(p);\nd.length = 0;\n$['evalFile'](f);\n", 2), + ("var d = new Folder(p);\nd.length = 0;\nthis['eval'](s);\n", 2), + ("var d = new Folder(p);\nd.length = 0;\nthis['\\u0065val'](s);\n", 2), + ("var d = new Folder(p);\nd.length = 0;\nvar g = $.global['Function'];\n", 2), + ("var d = new Folder(p);\nd.length = 0;\n(function () {}).constructor(s)();\n", 2), + ("var d = new Folder(p);\nd.length = 0;\nvar c = o['constructor'];\n", 2), + ("new Folder(p).hidden = true;\nvar c = o.constructor;\n", 1), + ("var d = new Folder(p);\nd.length = 0;\nvar c = constructor;\n", 2), + ]; + let written = |r: &Report| r.outside.iter().find(|o| o.id == "filesWritten").map(|o| o.lines.clone()); + for (script, line) in scripts { + assert_eq!(written(&report(script)), Some(vec![line]), "{script}"); + } +} + +/// A string literal in brackets names the property its value spells, escapes undone, as a name +/// written with escapes is read as the name it spells. A literal longer than the check reads may +/// name any variable, so no object counts as a Folder object. +#[test] +fn a_bracketed_name_is_read_whole_or_counts_as_any_name() { + let long = "a".repeat(300); + let scripts = [ + format!("var {long} = new Folder(p);\nfunction w() {{ {long}.length = 0; }}\nthis['{long}'] = new File(q);\n"), + format!("var d = new Folder(p);\nfunction w() {{ d.length = 0; }}\nthis['{long}'] = new File(q);\n"), + "var d = new Folder(p);\nfunction w() { d.hidden = true; }\nthis['\\u0064'] = new File(q);\n".to_string(), + "var \\u0064 = new Folder(p);\nfunction w() { d.hidden = true; }\nthis['d'] = new File(q);\n".to_string(), + "var d = new Folder(p);\nfunction w() { \\u0064.hidden = true; }\nthis['\\x64'] = new File(q);\n".to_string(), + ]; + let written = |r: &Report| r.outside.iter().find(|o| o.id == "filesWritten").map(|o| o.lines.clone()); + for script in &scripts { + assert_eq!(written(&report(script)), Some(vec![2]), "{script}"); + } + // A short literal that names another variable leaves the Folder alone. + let r = report(&format!("var d = new Folder(p);\nfunction w() {{ d.length = 0; }}\nthis['{}'] = new File(q);\n", "a".repeat(200))); + assert_eq!(written(&r), None); +} + +/// The lines of `filesWritten` in the report on `script`. +fn files_written(script: &str) -> Option> { + report(script).outside.iter().find(|o| o.id == "filesWritten").map(|o| o.lines.clone()) +} + +/// A name in brackets held in a variable may be `eval`, so no object counts as a Folder object. +#[test] +fn a_bracketed_variable_read_counts_as_any_name() { + let script = "var d = new Folder(p);\nd.length = 0;\nvar k = 'eval';\nthis[k]('d = new File(q)');\n"; + assert_eq!(files_written(script), Some(vec![2])); +} + +/// A name in brackets joined from strings may be `eval`, so no object counts as a Folder object. +#[test] +fn a_bracketed_joined_name_counts_as_any_name() { + let script = "var d = new Folder(p);\nd.length = 0;\nthis['ev' + 'al']('d = new File(q)');\n"; + assert_eq!(files_written(script), Some(vec![2])); +} + +/// A string literal in grouping parentheses inside brackets is read as a computed name. +#[test] +fn a_bracketed_name_in_parentheses_counts_as_any_name() { + let script = "var d = new Folder(p);\nd.length = 0;\nthis[('eval')]('d = new File(q)');\n"; + assert_eq!(files_written(script), Some(vec![2])); +} + +/// A comma expression in brackets names its last operand's value, which may be `eval`. +#[test] +fn a_bracketed_comma_expression_counts_as_any_name() { + let script = "var d = new Folder(p);\nd.length = 0;\nthis[0, 'eval']('d = new File(q)');\n"; + assert_eq!(files_written(script), Some(vec![2])); +} + +/// A name in brackets held in a variable may be `evalFile`, called on `$`. +#[test] +fn a_bracketed_variable_call_on_dollar_counts_as_any_name() { + let script = "var d = new Folder(p);\nd.length = 0;\nvar k = 'evalFile';\n$[k](f);\n"; + assert_eq!(files_written(script), Some(vec![2])); +} + +/// A name in brackets held in a variable may be `constructor`, which reaches `Function`. +#[test] +fn a_bracketed_variable_constructor_counts_as_any_name() { + let script = "var d = new Folder(p);\nd.length = 0;\nvar k = 'constructor';\n(function () {})[k](s)();\n"; + assert_eq!(files_written(script), Some(vec![2])); +} + +/// One string or number literal in brackets names one property, and an array literal names none, +/// also with brackets inside brackets, so the Folder is left alone. A computed name inside another +/// name in brackets still counts as any name. +#[test] +fn a_literal_name_in_brackets_leaves_the_folder_alone() { + let script = "var d = new Folder(p);\nvar x = o['plain'];\nvar y = a[0][1];\na[0] = 1;\nvar z = [k, o['x'], a[0]];\nd.length = 0;\n"; + assert_eq!(files_written(script), None); + assert_eq!(files_written("var d = new Folder(p);\nd.length = 0;\nvar x = o[a[0]];\n"), Some(vec![2])); +} + +/// A preprocessor line inside a name in brackets hides the `[` before the name, so the name may be +/// `eval` and no object counts as a Folder object. +#[test] +fn a_directive_in_a_bracketed_name_counts_as_any_name() { + let script = "var d = new Folder(p);\nd.length = 0;\nthis[\n#target illustrator\n'eval']('d = new File(q)');\n"; + assert_eq!(files_written(script), Some(vec![2])); +} + #[test] fn a_function_after_a_line_that_ends_a_statement_is_a_declaration() { let r = report("var n = 1\nfunction File() {}\nFile('x');\nvar m = 2 /* a\n */ function Socket() {}\nnew Socket();\n"); diff --git a/docs/mcp.md b/docs/mcp.md index 0541cc2ebd..949d1c3952 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2566,7 +2566,15 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, whose argument isn't a string literal. - `outside` lists what the script does outside the document: `filesWritten` (with the open modes used; setting a File object's `length`, `hidden` or `readonly` counts too, on any object that may be a File object; only - `new Folder(…)` and the `Folder` places such as `Folder.temp`, other than `Folder.current`, are left out), `filesOpened` (files opened in other apps), `network`, + `new Folder(…)` and the `Folder` places such as `Folder.temp`, other than `Folder.current`, are left out, and + nothing is left out in a check whose files use `with`, name `eval`, `Function`, `evalFile` or `constructor` as a + word or as a string literal in brackets, read, call or assign a property in brackets (a `[` after a value, not an + array literal) when the brackets hold anything but one number or string literal (`o[k]`, `this['ev' + 'al'](s)`, + `this[('eval')](s)`, `this[0, 'eval'](s)`, `o[a[0]]`, or a preprocessor line inside the brackets) or the `[` opens + while 4,096 other `[` are open, assign a property in brackets whose name is a string literal of more than 256 + characters, assign properties of more than 1,000 different names on members (`o.d = …`, `o['d'] = …`), or + assign or declare `Folder`; a variable whose name a member assignment writes counts as one that may hold a File + object), `filesOpened` (files opened in other apps), `network`, `nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`, `new Function` and `$.evalFile`) and `preferences` (the reference app's preferences changed). - `problems` lists what would stop the script loading as written (strings, comments, regular expressions, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e84ce63592..2b9293c9fb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1077,7 +1077,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Headless CLI (`vectorcraft-cli run`, `convert`, `info`, `bench`, `perf`, `mcp`). A `run` step, like a `command_batch` step over MCP, can use an earlier step's result (`"$1.id"`, #785); `run --commands FILE` (or `-` for standard input) reads the steps from a JSON array or JSON Lines, past the Windows command-line limit (#3147, `apps/vectorcraft-cli/tests/it/cli.rs` `run_reads_*`, `run_refuses_malformed_commands_naming_the_step`). - File › Scripts › Check Script… reads a script written for Illustrator (`.jsx`, `.jsxinc` or a compiled `.jsxbin`) without running any of it and reports what it needs (the document model, files, dialogs, menu commands, features only Illustrator has), what it would do outside the document, the menu commands and document-model members it uses, its directives and included files, and the problems that would stop it loading (`script.check`, which also reads `.js` files); File › Open and drag-and-drop show the report for `.jsx`, `.jsxinc` and `.jsxbin` files. - Check Script reads names by the same identifier rule as `vectorcraft-js`: Unicode 17.0 `ID_Start` characters, `$` and `_` start a name, and `ID_Continue` characters and `$` continue it (https://www.unicode.org/reports/tr31/, https://tc39.es/ecma262/#sec-names-and-keywords). U+2118, U+203F, U+00B7 and the zero width non-joiner and joiner are name characters, and U+00B2 and U+2E2F are not. Of the characters Unicode 17.0 assigned, U+088F starts a name and U+1ACF may follow its first character. A `\uXXXX` escape is read as its character only where a name may hold it, so `\u0030abc` does not become a name that starts with a digit; a `\u{…}` escape takes any number of hexadecimal digits up to U+10FFFF, and one that is empty, unclosed, out of range or a surrogate is not part of a name. Each `\u{…}` escape read in a name is reported as syntax newer than ES3, which has only the four-digit form (https://ecma-international.org/wp-content/uploads/ECMA-262_3rd_edition_december_1999.pdf, section 7.6). A private name may start with an escape (`this.#\u{61}pp` is the private name `#app`), and a private name at the start of a line inside braces is not read as a directive unless its name is a directive's. Tests: `crates/scriptcheck/src/tests.rs` (`names_are_made_of_the_unicode_identifier_characters`, `an_escape_stands_for_a_character_only_where_a_name_may_hold_it`, `braced_escapes_in_names_are_read_by_their_value`, `braced_name_escape_reports_later_syntax_and_member`, `private_names_with_escaped_starts_are_single_tokens`, `private_name_at_line_start_is_not_a_directive`), `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs` (`both_lexers_take_the_same_characters_into_names`). - - Check Script reports `file.write` and `filesWritten` when a script sets a File object's `length`, `hidden` or `readonly` (https://extendscript.docsforadobe.dev/file-system-access/file-object/), by plain or compound assignment, `++` or `--`, or the name as a string literal in brackets. It leaves out only objects that are always Folder objects, `new Folder(…)` and the `Folder` places such as `Folder.temp` other than `Folder.current`, which a script can assign; `Folder(…)` gives a File object when the path names a file and `Folder.selectDialog()` gives a File or Folder object (https://extendscript.docsforadobe.dev/file-system-access/folder-object/), so setting those counts, as it does on a variable that any assignment, in any branch or included file, gives such an object (`setting_a_folders_length_or_flags_does_not_write`, `a_variable_that_may_hold_a_file_counts_as_one`, `a_file_in_a_local_variable_leaves_an_outer_folder_alone`). A test lists every global and member the script host adds to the JavaScript engine, except VectorCraft's own `vc` and its members, and fails when one has no row; for each one that reaches outside the document it checks that `script.check` reports the expected `outside` id, and it checks that the checker lists every directive the host reads. Tests: `crates/scriptcheck/src/tests.rs` (`setting_a_files_length_or_flags_writes_it`), `crates/engine/tests/it/script_host_vs_scriptcheck.rs` (`every_name_the_host_adds_has_a_row`, `every_name_that_reaches_outside_has_its_checker_id`, `the_checker_lists_every_directive_the_host_reads`). + - Check Script reports `file.write` and `filesWritten` when a script sets a File object's `length`, `hidden` or `readonly` (https://extendscript.docsforadobe.dev/file-system-access/file-object/), by plain or compound assignment, `++` or `--`, or the name as a string literal in brackets. It leaves out only objects that are always Folder objects, `new Folder(…)` and the `Folder` places such as `Folder.temp` other than `Folder.current`, which a script can assign; `Folder(…)` gives a File object when the path names a file and `Folder.selectDialog()` gives a File or Folder object (https://extendscript.docsforadobe.dev/file-system-access/folder-object/), so setting those counts, as it does on a variable that any assignment, in any branch or included file, gives such an object. Nothing counts as a Folder object in a check whose files use `with`, name `eval`, `Function`, `evalFile` or `constructor` as a word or as a string literal in brackets (`this['eval'](s)`, `(function () {}).constructor(s)`), read, call or assign a property in brackets on any object (a `[` after a value, not an array literal) when the brackets hold anything but one number or string literal (`g[k] = …`, `$['global'][k] = …`, `this[k](s)`, `this['ev' + 'al'](s)`, `this[('eval')](s)`, `this[0, 'eval'](s)`, `$[k](f)`, `(function () {})[k](s)`, or a preprocessor line inside the brackets) or the `[` opens while 4,096 other `[` are open, assign a property in brackets whose name is a string literal of more than 256 characters, assign properties of more than 1,000 different names on members, or assign or declare `Folder`, and a variable whose name a member assignment writes (`$.global.d = …`, `this.d = …`, `this['d'] = …`, with the string's escapes undone) counts as one that may hold a File object (`setting_a_folders_length_or_flags_does_not_write`, `a_variable_that_may_hold_a_file_counts_as_one`, `a_file_in_a_local_variable_leaves_an_outer_folder_alone`, `a_folder_that_other_code_may_rebind_counts_as_a_file`, `a_folder_that_unnamed_code_may_rebind_counts_as_a_file`, `a_bracketed_name_is_read_whole_or_counts_as_any_name`, `a_bracketed_variable_read_counts_as_any_name`, `a_bracketed_joined_name_counts_as_any_name`, `a_bracketed_name_in_parentheses_counts_as_any_name`, `a_bracketed_comma_expression_counts_as_any_name`, `a_bracketed_variable_call_on_dollar_counts_as_any_name`, `a_bracketed_variable_constructor_counts_as_any_name`, `a_literal_name_in_brackets_leaves_the_folder_alone`, `a_directive_in_a_bracketed_name_counts_as_any_name`). A test lists every global and member the script host adds to the JavaScript engine, except VectorCraft's own `vc` and its members, and fails when one has no row; for each one that reaches outside the document it checks that `script.check` reports the expected `outside` id, and it checks that the checker lists every directive the host reads. Tests: `crates/scriptcheck/src/tests.rs` (`setting_a_files_length_or_flags_writes_it`), `crates/engine/tests/it/script_host_vs_scriptcheck.rs` (`every_name_the_host_adds_has_a_row`, `every_name_that_reaches_outside_has_its_checker_id`, `the_checker_lists_every_directive_the_host_reads`). - `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans; it reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`. - `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`). - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. From 93bc8da6d7b3034b8e5c99547f3301a113c77514 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 23 Nov 2026 13:17:42 -0500 Subject: [PATCH 22/32] ci(release): publish scheduled nightly prereleases (#9181) --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 226830fc1b..f462c00374 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -39,7 +39,7 @@ jobs: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: - dry-run: ${{ github.event_name == 'schedule' }} + nightly: ${{ github.event_name == 'schedule' }} app-name: vectorcraft app-title: VectorCraft craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 From 3465b06c38099ba45d5871d96d649f4c0e6d7e66 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 23 Nov 2026 14:45:47 -0500 Subject: [PATCH 23/32] revert: restore scheduled release.yml dry-run on main (#9184) --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f462c00374..226830fc1b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -39,7 +39,7 @@ jobs: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: - nightly: ${{ github.event_name == 'schedule' }} + dry-run: ${{ github.event_name == 'schedule' }} app-name: vectorcraft app-title: VectorCraft craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 From ce5af98dd56141e310851494917b20444aa8f320 Mon Sep 17 00:00:00 2001 From: mohamedwithai Date: Tue, 24 Nov 2026 04:52:04 +0530 Subject: [PATCH 24/32] Fix #6929: NHM Writer's legacy Tamil keymaps (symbol fonts) type their characters on Windows (#6930) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Type: NHM Writer's legacy Tamil keymaps (symbol fonts) type their characters on Windows NHM Writer's legacy Tamil keymaps (e.g. "Tamil Phonetic StmzhRgb" for SR-Tamil fonts) post each byte as a WM_CHAR of U+F000 + byte, Windows' symbol-font convention. egui-winit's is_printable_char rejects the Private Use Area, so the Type tool got nothing (only the tool's Backspace presses arrived). windows_symbol_chars notes U+F020..=U+F0FF characters in winit's message hook, in order with Backspace presses, and hands them to the frame as Event::Text, unchanged (symbol fonts map exactly these code points), each before the Backspace press that followed it. Unchanged matters: as Latin-1, byte 0xAD (SR-Tamil's ஷ) would become U+00AD, a soft hyphen the text engine never draws. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SY4wMcmnVnfGn5yC3dDic2 * Contributors: add my display name (HASAN CGI) * Type: symbol-font characters keep their order among all typed text and keys; no new unsafe Review of #6930: windows_symbol_chars now notes every character and key press the window gets, not only Backspace, and places each symbol-font character before the text or key press that followed it (a symbol then an ordinary character, or a symbol then a navigation key, no longer swap). It no longer has a message hook of its own: windows_alt_codes's existing msg_hook, which already reads each MSG, hands it the message, so the module has no unsafe code. Tests cover symbol/ordinary-text and symbol/navigation sequences. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SY4wMcmnVnfGn5yC3dDic2 * Revert "Contributors: add my display name (HASAN CGI)" This reverts commit 78ff9cbb2a7e18118c9c3b58dcf799ad008d8f5e. * Type: rustfmt order for mod windows_symbol_chars --------- Co-authored-by: Claude Opus 5.5 --- apps/vectorcraft/src/app.rs | 3 + apps/vectorcraft/src/main.rs | 1 + apps/vectorcraft/src/windows_alt_codes.rs | 6 +- apps/vectorcraft/src/windows_symbol_chars.rs | 312 +++++++++++++++++++ 4 files changed, 320 insertions(+), 2 deletions(-) create mode 100644 apps/vectorcraft/src/windows_symbol_chars.rs diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index a40eb0c92f..9b71404f5c 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -70,6 +70,9 @@ impl eframe::App for App { // The characters Alt + keypad codes typed (#5108). #[cfg(windows)] super::windows_alt_codes::raw_input_hook(raw); + // Symbol-font characters a keyboard tool typed (NHM Writer legacy Tamil). + #[cfg(windows)] + super::windows_symbol_chars::raw_input_hook(raw); file_access::unconfined(|| self.app.raw_input_hook(ctx, raw)); // A mouse-up that never reached the window (#4326) is delivered once AppKit reports // that no mouse button is down. diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 29cb56bdfa..a7454d896b 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -79,6 +79,7 @@ mod windows_alt_codes; mod windows_cores; mod windows_screen_color; mod windows_stylus; +mod windows_symbol_chars; mod xwayland; use vectorcraft_engine::Session; diff --git a/apps/vectorcraft/src/windows_alt_codes.rs b/apps/vectorcraft/src/windows_alt_codes.rs index b370bf214e..0abf65ddc9 100644 --- a/apps/vectorcraft/src/windows_alt_codes.rs +++ b/apps/vectorcraft/src/windows_alt_codes.rs @@ -160,8 +160,8 @@ impl AltCodes { } } -/// winit's message hook for the keyboard: notes Alt + keypad codes and the characters they type. -/// It never consumes the message. +/// winit's message hook for the keyboard: notes Alt + keypad codes and the characters they type, +/// and hands each message to `windows_symbol_chars`. It never consumes the message. #[cfg(windows)] #[allow(unsafe_code)] pub fn msg_hook(msg: *const std::ffi::c_void) { @@ -171,6 +171,8 @@ pub fn msg_hook(msg: *const std::ffi::c_void) { let Some(msg) = (unsafe { msg.cast::().as_ref() }) else { return; }; + // Symbol-font characters (NHM Writer legacy Tamil), which egui-winit drops. + crate::windows_symbol_chars::message(msg.message, msg.wParam.0); if (WM_KEYDOWN..=WM_SYSCHAR).contains(&msg.message) { CODES.with(|c| { if let Ok(mut c) = c.try_borrow_mut() { diff --git a/apps/vectorcraft/src/windows_symbol_chars.rs b/apps/vectorcraft/src/windows_symbol_chars.rs new file mode 100644 index 0000000000..c8b9418052 --- /dev/null +++ b/apps/vectorcraft/src/windows_symbol_chars.rs @@ -0,0 +1,312 @@ +//! Characters a keyboard tool types in a symbol font's encoding on Windows, such as NHM Writer's +//! legacy Tamil keymaps for SR-Tamil fonts. +//! +//! Such a tool posts each byte of the font's 8-bit encoding as a `WM_CHAR` holding U+F000 plus the +//! byte, Windows' convention for symbol fonts. Those are Private Use Area characters, which +//! egui-winit drops as unprintable (`is_printable_char`), so the Type tool gets nothing (the tool's +//! Backspace presses, which it sends to rewrite a syllable, still arrive). [`message`] notes the +//! characters in order with the other characters and key presses the window gets (it is fed by +//! `windows_alt_codes::msg_hook`, which already reads each `MSG`), and [`raw_input_hook`] hands +//! them to the frame unchanged, each in its place among the frame's text and key events. A symbol +//! font maps exactly these code points (its Windows cmap is (3,0) at U+F020..=U+F0FF), so they draw +//! as typed; turning them into the bytes' Latin-1 characters instead would make byte 0xAD +//! (SR-Tamil's ஷ) a soft hyphen, which the text engine never draws, and bytes 0x80..=0x9F control +//! characters. + +#![cfg_attr(not(windows), allow(dead_code))] + +use std::cell::RefCell; +use std::collections::VecDeque; + +use egui::Event; + +const WM_KEYDOWN: u32 = 0x0100; +const WM_CHAR: u32 = 0x0102; +const WM_SYSKEYDOWN: u32 = 0x0104; +/// `VK_PACKET` (`winuser.h`): the key press a keyboard tool's injected character comes with, which +/// egui reports as no key. +const VK_PACKET: usize = 0xE7; +/// U+F020..=U+F0FF: a symbol font's bytes 0x20..=0xFF. +const SYMBOL_FIRST: u32 = 0xF020; +const SYMBOL_LAST: u32 = 0xF0FF; + +thread_local! { + /// The UI thread's sequence: [`message`] and [`raw_input_hook`] both run on it. + static TYPED: RefCell = RefCell::new(SymbolChars::default()); +} + +/// A keyboard message that becomes an egui event, in the order the window got it. +#[derive(Debug, PartialEq)] +enum Typed { + /// A symbol-font character (U+F020..=U+F0FF), which egui drops. + Symbol(char), + /// Another character, which egui reports as text. + Char(char), + /// A key press, which egui reports as a key event. + Key, +} + +#[derive(Default)] +struct SymbolChars { + typed: VecDeque, + /// A high surrogate waiting for its low half. + high: Option, +} + +/// The symbol-font character `unit` is, or `None` for any other code point. +fn symbol_char(unit: u32) -> Option { + (SYMBOL_FIRST..=SYMBOL_LAST).contains(&unit).then(|| char::from_u32(unit)).flatten() +} + +fn is_symbol(c: char) -> bool { + (SYMBOL_FIRST..=SYMBOL_LAST).contains(&u32::from(c)) +} + +/// A character egui reports as text: not a control character and not in a Private Use Area. +fn is_text(c: char) -> bool { + let private = matches!(c, '\u{E000}'..='\u{F8FF}' | '\u{F0000}'..='\u{FFFFD}' | '\u{100000}'..='\u{10FFFD}'); + !private && !c.is_control() +} + +/// Take `typed` up to and including the first entry `is_match` accepts, and return the symbols +/// before it. When no entry matches, nothing is taken. +fn symbols_before(typed: &mut VecDeque, is_match: impl Fn(&Typed) -> bool) -> String { + let Some(i) = typed.iter().position(is_match) else { + return String::new(); + }; + typed + .drain(..=i) + .filter_map(|t| match t { + Typed::Symbol(c) => Some(c), + _ => None, + }) + .collect() +} + +impl SymbolChars { + /// Note a keyboard message `message` with `wparam` (the virtual-key code, or a UTF-16 unit). + fn message(&mut self, message: u32, wparam: usize) { + match message { + WM_KEYDOWN | WM_SYSKEYDOWN if wparam != VK_PACKET => self.typed.push_back(Typed::Key), + WM_CHAR => { + let unit = u16::try_from(wparam & 0xffff).unwrap_or_default(); + if (0xd800..0xdc00).contains(&unit) { + self.high = Some(unit); + return; + } + let units: Vec = self.high.take().into_iter().chain([unit]).collect(); + for c in char::decode_utf16(units).filter_map(Result::ok) { + if let Some(s) = symbol_char(u32::from(c)) { + self.typed.push_back(Typed::Symbol(s)); + } else if is_text(c) { + self.typed.push_back(Typed::Char(c)); + } + } + } + _ => {} + } + } + + /// Hand the frame `events` the symbol-font characters typed since the last frame, as typed + /// text, each before the text or key press that followed it. + fn drain(&mut self, events: &mut Vec) { + let mut typed = std::mem::take(&mut self.typed); + if !typed.iter().any(|t| matches!(t, Typed::Symbol(_))) { + return; + } + // Should egui ever pass these characters on itself, leave them to it. + if events.iter().any(|e| matches!(e, Event::Text(t) if t.chars().any(is_symbol))) { + return; + } + let mut out = Vec::with_capacity(events.len() + 1); + for e in events.drain(..) { + match e { + Event::Key { pressed: true, .. } => { + let symbols = symbols_before(&mut typed, |t| *t == Typed::Key); + if !symbols.is_empty() { + out.push(Event::Text(symbols)); + } + out.push(e); + } + Event::Text(text) => { + // Each character of the text was typed on its own: the symbols typed before + // it go first, splitting the text where they fall. + let mut run = String::new(); + for c in text.chars() { + let symbols = symbols_before(&mut typed, |t| *t == Typed::Char(c)); + if !symbols.is_empty() { + if !run.is_empty() { + out.push(Event::Text(std::mem::take(&mut run))); + } + out.push(Event::Text(symbols)); + } + run.push(c); + } + if !run.is_empty() { + out.push(Event::Text(run)); + } + } + e => out.push(e), + } + } + let rest: String = typed + .into_iter() + .filter_map(|t| match t { + Typed::Symbol(c) => Some(c), + _ => None, + }) + .collect(); + if !rest.is_empty() { + out.push(Event::Text(rest)); + } + *events = out; + } +} + +/// Note a keyboard message of the UI thread's queue. `windows_alt_codes::msg_hook` calls this for +/// each message winit's message hook gets. +pub fn message(message: u32, wparam: usize) { + TYPED.with(|t| { + if let Ok(mut t) = t.try_borrow_mut() { + t.message(message, wparam); + } + }); +} + +/// Before egui reads the main window's frame: the symbol-font characters typed, as text. +pub fn raw_input_hook(raw: &mut egui::RawInput) { + TYPED.with(|t| { + if let Ok(mut t) = t.try_borrow_mut() { + t.drain(&mut raw.events); + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use egui::Key; + + const VK_BACK: usize = 0x08; + const VK_LEFT: usize = 0x25; + const VK_A: usize = 0x41; + + /// A character a keyboard tool injects. + fn injected(c: &mut SymbolChars, unit: u32) { + c.message(WM_KEYDOWN, VK_PACKET); + c.message(WM_CHAR, unit as usize); + } + + fn key(key: Key, pressed: bool) -> Event { + Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers: egui::Modifiers::default() } + } + + fn text(s: &str) -> Event { + Event::Text(s.into()) + } + + #[test] + fn a_symbol_font_character_is_typed_as_it_came() { + let mut c = SymbolChars::default(); + injected(&mut c, 0xF0E3); + injected(&mut c, 0xF05B); + let mut events = vec![]; + c.drain(&mut events); + assert_eq!(events, vec![text("\u{F0E3}\u{F05B}")]); + let mut events = vec![]; + c.drain(&mut events); + assert!(events.is_empty(), "nothing carries over to a later frame"); + } + + #[test] + fn characters_keep_their_place_around_backspace() { + // What NHM Writer sends while rewriting a syllable (from a real log). + let mut c = SymbolChars::default(); + injected(&mut c, 0xF0E3); + c.message(WM_KEYDOWN, VK_BACK); + injected(&mut c, 0xF0C7); + injected(&mut c, 0xF0DF); + c.message(WM_KEYDOWN, VK_BACK); + injected(&mut c, 0xF0C4); + let mut events = vec![key(Key::Backspace, true), key(Key::Backspace, false), key(Key::Backspace, true), key(Key::Backspace, false)]; + c.drain(&mut events); + assert_eq!( + events, + vec![ + text("\u{F0E3}"), + key(Key::Backspace, true), + key(Key::Backspace, false), + text("\u{F0C7}\u{F0DF}"), + key(Key::Backspace, true), + key(Key::Backspace, false), + text("\u{F0C4}"), + ] + ); + } + + #[test] + fn a_symbol_goes_before_ordinary_text_typed_after_it() { + // Two injected characters in one frame: egui reports only the second. + let mut c = SymbolChars::default(); + injected(&mut c, 0xF0E3); + injected(&mut c, u32::from('a')); + let mut events = vec![text("a")]; + c.drain(&mut events); + assert_eq!(events, vec![text("\u{F0E3}"), text("a")]); + // A key typed after the symbol: its press and character both come after it. + injected(&mut c, 0xF0E3); + c.message(WM_KEYDOWN, VK_A); + c.message(WM_CHAR, usize::from(b'a')); + let mut events = vec![key(Key::A, true), text("a"), key(Key::A, false)]; + c.drain(&mut events); + assert_eq!(events, vec![text("\u{F0E3}"), key(Key::A, true), text("a"), key(Key::A, false)]); + } + + #[test] + fn a_symbol_goes_before_a_navigation_key_pressed_after_it() { + let mut c = SymbolChars::default(); + c.message(WM_KEYDOWN, VK_LEFT); + injected(&mut c, 0xF0E3); + c.message(WM_KEYDOWN, VK_LEFT); + let mut events = vec![key(Key::ArrowLeft, true), key(Key::ArrowLeft, false), key(Key::ArrowLeft, true), key(Key::ArrowLeft, false)]; + c.drain(&mut events); + assert_eq!( + events, + vec![key(Key::ArrowLeft, true), key(Key::ArrowLeft, false), text("\u{F0E3}"), key(Key::ArrowLeft, true), key(Key::ArrowLeft, false)] + ); + } + + #[test] + fn a_symbol_between_ordinary_characters_splits_their_text() { + let mut c = SymbolChars::default(); + injected(&mut c, u32::from('x')); + injected(&mut c, 0xF0AD); + injected(&mut c, u32::from('y')); + let mut events = vec![text("xy")]; + c.drain(&mut events); + assert_eq!(events, vec![text("x"), text("\u{F0AD}"), text("y")]); + } + + #[test] + fn only_the_symbol_range_counts_and_stays_as_it_is() { + // 0xAD is SR-Tamil's ஷ: as U+00AD it would be a soft hyphen, which never draws. + assert_eq!(symbol_char(0xF0AD), Some('\u{F0AD}')); + assert_eq!(symbol_char(0xF092), Some('\u{F092}')); + assert_eq!(symbol_char(0xF020), Some('\u{F020}')); + assert_eq!(symbol_char(0xF0FF), Some('\u{F0FF}')); + assert_eq!(symbol_char(0xF01F), None); + assert_eq!(symbol_char(0xF100), None); + } + + #[test] + fn other_characters_are_left_to_winit() { + let mut c = SymbolChars::default(); + c.message(WM_KEYDOWN, VK_A); + c.message(WM_CHAR, usize::from(b'a')); + injected(&mut c, 0x0B85); + c.message(WM_KEYDOWN, VK_BACK); + let mut events = vec![key(Key::A, true), text("aஅ"), key(Key::Backspace, true)]; + c.drain(&mut events); + assert_eq!(events, vec![key(Key::A, true), text("aஅ"), key(Key::Backspace, true)]); + } +} From 6f37bd839ccbe7f0553072af549383cf6d6d6273 Mon Sep 17 00:00:00 2001 From: BFlat Date: Tue, 24 Nov 2026 08:25:24 +0700 Subject: [PATCH 25/32] VectorCraft on the craft UI framework (#8800) VectorCraft's UI moves onto the shared craft UI framework in storytold/craft-libs (`next`; the framework side is storytold/craft-libs#2809), as PhotoCraft's did. The app keeps its engine, document model, file formats, commands and automation; its windows, panels, bars, dialogs and canvas are now built and driven by the framework: shell, docking and panels, hosted dialogs, keyboard, focus, IME and pointer routing, and theme tokens. About 264,000 lines of VectorCraft's own egui UI code are removed and about 154,000 added. craft-libs is pinned at bf62d509f (in `next`), the egui fork at f5025284. Tests that drove the old UI were rewritten against the port where only their premise changed, with their assertions kept. The UI tests still failing at merge, and their follow-ups, are listed in the pull request. --- .github/workflows/print.yml | 8 +- AGENTS.md | 2 +- ASSETS.md | 23 +- Cargo.lock | 1757 ++- Cargo.toml | 104 +- apps/vectorcraft-cli/src/main.rs | 10 +- apps/vectorcraft-web/Cargo.toml | 8 +- apps/vectorcraft-web/src/api.rs | 10 +- apps/vectorcraft-web/src/demand.rs | 139 - apps/vectorcraft-web/src/fonts.rs | 63 +- apps/vectorcraft-web/src/keys.rs | 102 +- apps/vectorcraft-web/src/locks.rs | 8 +- apps/vectorcraft-web/src/main.rs | 5 +- apps/vectorcraft-web/src/pencil.rs | 56 +- apps/vectorcraft-web/src/web.rs | 177 +- apps/vectorcraft/Cargo.toml | 45 +- apps/vectorcraft/src/app.rs | 101 +- apps/vectorcraft/src/automation_args.rs | 133 +- apps/vectorcraft/src/caps_lock.rs | 216 - apps/vectorcraft/src/clipboard.rs | 369 +- apps/vectorcraft/src/control_server.rs | 320 - apps/vectorcraft/src/control_server/tests.rs | 411 - apps/vectorcraft/src/cursor_theme.rs | 91 - apps/vectorcraft/src/display_profile.rs | 2 +- apps/vectorcraft/src/hang_watch.rs | 8 +- apps/vectorcraft/src/host_services.rs | 533 +- apps/vectorcraft/src/linux_screen_color.rs | 41 - .../src/linux_screen_color/portal.rs | 291 - apps/vectorcraft/src/mac_cursor.rs | 238 - apps/vectorcraft/src/mac_cursor/tests.rs | 227 - apps/vectorcraft/src/mac_menu.rs | 503 - apps/vectorcraft/src/mac_save_format.rs | 293 - apps/vectorcraft/src/mac_screen_color.rs | 69 - apps/vectorcraft/src/mac_tablet.rs | 166 +- apps/vectorcraft/src/main.rs | 367 +- apps/vectorcraft/src/portal_request.rs | 231 - apps/vectorcraft/src/portal_save.rs | 658 - apps/vectorcraft/src/prefs.rs | 615 +- apps/vectorcraft/src/prefs_dir.rs | 22 +- apps/vectorcraft/src/printing.rs | 31 +- apps/vectorcraft/src/printing/direct_pdf.rs | 2 +- apps/vectorcraft/src/profile.rs | 66 +- apps/vectorcraft/src/quit_windows.rs | 8 +- apps/vectorcraft/src/single_instance.rs | 5 +- apps/vectorcraft/src/tablet.rs | 209 +- apps/vectorcraft/src/tests.rs | 374 +- apps/vectorcraft/src/titlebar.rs | 228 - apps/vectorcraft/src/window.rs | 603 - apps/vectorcraft/src/windows_screen_color.rs | 655 - apps/vectorcraft/src/windows_stylus.rs | 391 +- apps/vectorcraft/tests/it/automation_args.rs | 21 +- assets/cursors/cursor-anchor-point.svg | 1 + .../cursors/cursor-direct-anchor-selected.svg | 1 + assets/cursors/cursor-direct-anchor.svg | 1 + assets/cursors/cursor-loaded-text-link.svg | 1 + assets/cursors/cursor-loaded-text.svg | 1 + assets/cursors/cursor-mark-bracket.svg | 1 + assets/cursors/cursor-mark-edge.svg | 1 + assets/cursors/cursor-mark-line-level.svg | 1 + assets/cursors/cursor-mark-line-rising.svg | 1 + assets/cursors/cursor-mark-ring.svg | 1 + assets/cursors/cursor-mark-square.svg | 1 + assets/cursors/cursor-mark-star.svg | 1 + assets/cursors/cursor-pen-convert.svg | 1 + assets/cursors/cursor-pen-curvature.svg | 1 + assets/cursors/cursor-pen-join.svg | 1 + assets/cursors/cursor-pen-new.svg | 1 + assets/cursors/cursor-reshape-segment.svg | 1 + assets/icons/circle-off.svg | 17 + assets/icons/dc-blend-align-page.svg | 1 + assets/icons/dc-blend-align-path.svg | 1 + assets/icons/dc-free-distort.svg | 7 + crates/color/Cargo.toml | 3 + crates/color/src/cms.rs | 3 +- crates/color/src/cms/display.rs | 327 - crates/color/src/gradient.rs | 15 - crates/color/src/gradient/tests.rs | 10 - crates/color/src/harmony.rs | 452 +- crates/color/src/libraries.rs | 7 +- crates/engine/src/cmd.rs | 1 + crates/engine/src/cmd/buildcmds/trace.rs | 2 +- crates/engine/src/cmd/colorcmds.rs | 8 +- crates/engine/src/cmd/colormgmt/proof_file.rs | 1 + crates/engine/src/cmd/colortheme.rs | 8 +- crates/engine/src/cmd/compositefonts.rs | 29 +- crates/engine/src/cmd/fileio/pdf.rs | 33 +- crates/engine/src/cmd/fileio/tests_pdf.rs | 9 +- crates/engine/src/cmd/layerpanel.rs | 2 +- crates/engine/src/cmd/pdfcmds.rs | 14 +- crates/engine/src/cmd/printadvanced.rs | 2 +- crates/engine/src/cmd/retype_tests.rs | 2 +- crates/engine/src/cmd/style.rs | 15 +- crates/engine/src/cmd/swatchlib.rs | 8 +- crates/engine/src/doc_state.rs | 103 +- crates/engine/src/interaction.rs | 3 + crates/engine/src/lib.rs | 2 +- crates/engine/src/session/documents.rs | 9 +- crates/engine/src/session/edit.rs | 20 + crates/engine/src/session/execute.rs | 24 + crates/engine/src/store.rs | 4 +- crates/engine/src/tests/colorguide.rs | 6 +- crates/engine/src/tests/colorthemes.rs | 4 +- crates/engine/src/tests/docsetup.rs | 10 - crates/engine/src/tests/draw2.rs | 6 +- crates/engine/src/tests/emptytype.rs | 16 - crates/engine/src/tests/layers.rs | 56 +- crates/engine/src/tests/pattern.rs | 40 +- crates/engine/src/tests/pdfpresets.rs | 9 +- crates/engine/src/tests/prefs.rs | 61 +- crates/engine/src/tests/shaper.rs | 10 +- crates/engine/src/tests/symbol_nine_slice.rs | 20 +- crates/engine/src/tooling.rs | 60 +- crates/geom/Cargo.toml | 1 - crates/mcp/Cargo.toml | 1 + crates/mcp/src/backend.rs | 205 +- crates/mcp/src/lib.rs | 2 +- crates/mcp/src/tests.rs | 179 +- crates/mcp/src/tests/concurrency.rs | 11 +- crates/mcp/src/tests/fileio.rs | 9 +- crates/mcp/src/tools/definitions.rs | 2 +- crates/mcp/src/ui_catalog.rs | 23 +- crates/pdf/Cargo.toml | 2 +- crates/pdf/src/editing.rs | 8 +- crates/pdf/src/encrypt.rs | 133 +- crates/pdf/src/export.rs | 4 +- crates/pdf/src/export/entry.rs | 13 +- crates/pdf/src/file_info.rs | 4 +- crates/pdf/src/forms.rs | 2 +- crates/pdf/src/images.rs | 2 +- crates/pdf/src/import.rs | 12 +- crates/pdf/src/import/actual_text.rs | 2 +- crates/pdf/src/import/builder.rs | 38 +- crates/pdf/src/import/cid.rs | 24 +- crates/pdf/src/import/device.rs | 20 +- crates/pdf/src/import/entry.rs | 18 +- crates/pdf/src/import/state.rs | 10 +- crates/pdf/src/import_color.rs | 16 +- crates/pdf/src/import_image.rs | 6 +- crates/pdf/src/import_scan.rs | 20 +- crates/pdf/src/import_shading.rs | 4 +- crates/pdf/src/lib.rs | 18 +- crates/pdf/src/marks.rs | 58 +- crates/pdf/src/output.rs | 50 +- crates/pdf/src/pages.rs | 40 +- crates/pdf/src/pdfx.rs | 70 +- crates/pdf/src/presets.rs | 111 - crates/pdf/src/print.rs | 4 +- crates/pdf/src/print/layout.rs | 4 +- crates/pdf/src/settings.rs | 534 +- crates/pdf/src/streams.rs | 6 +- crates/pdf/src/surface.rs | 2 +- crates/pdf/src/tests.rs | 7 +- crates/pdf/src/tests/cmykimages.rs | 13 +- crates/pdf/src/tests/colorize.rs | 4 +- crates/pdf/src/tests/compression.rs | 12 +- crates/pdf/src/tests/editing.rs | 7 - crates/pdf/src/tests/encrypt.rs | 50 +- crates/pdf/src/tests/file_fonts.rs | 2 +- crates/pdf/src/tests/import_color.rs | 8 +- crates/pdf/src/tests/import_fidelity.rs | 8 +- crates/pdf/src/tests/layers.rs | 14 +- crates/pdf/src/tests/links.rs | 6 +- crates/pdf/src/tests/live_text.rs | 2 +- crates/pdf/src/tests/marks.rs | 26 +- crates/pdf/src/tests/output.rs | 11 +- crates/pdf/src/tests/pdf13.rs | 16 - crates/pdf/src/tests/pdfx.rs | 29 +- crates/pdf/src/tests/presets.rs | 24 - crates/pdf/src/tests/printadvanced.rs | 2 +- crates/pdf/src/tests/realtext.rs | 6 +- crates/pdf/src/tests/settings.rs | 110 +- crates/pdf/src/tests/text_placement.rs | 4 +- crates/text/Cargo.toml | 17 +- crates/text/build.rs | 113 +- crates/text/src/craft_fonts.rs | 165 +- crates/text/src/fontconfig.rs | 253 - crates/text/src/fontdb.rs | 101 +- crates/text/src/fontdb/added.rs | 23 +- crates/text/src/fontdb/cache.rs | 38 +- crates/text/src/fontdb/composite.rs | 2 +- crates/text/src/fontdb/db.rs | 272 +- crates/text/src/fontdb/dirs.rs | 163 +- crates/text/src/fontdb/glyph_pen.rs | 2 +- crates/text/src/fontdb/lookup.rs | 196 +- crates/text/src/layout.rs | 2 +- crates/text/src/layout/bidi.rs | 4 +- crates/text/src/layout/breaking.rs | 2 +- crates/text/src/lib.rs | 5 +- crates/text/src/shape.rs | 10 +- crates/text/src/tests.rs | 4 +- crates/text/src/tests/sysfonts.rs | 92 +- crates/tools/src/extra.rs | 6 - crates/tools/src/lib.rs | 38 - crates/tools/src/mirror.rs | 53 +- crates/tools/src/nineslice.rs | 95 +- crates/tools/src/repeat_grid.rs | 33 +- crates/tools/src/repeat_radial.rs | 35 +- crates/tools/src/select.rs | 267 +- crates/tools/src/shaperwidget.rs | 23 +- crates/tools/src/text.rs | 13 +- crates/tools/src/text/plain.rs | 106 +- crates/tools/src/text/tests.rs | 115 - crates/tools/src/text/tool.rs | 95 +- crates/tools/src/trace_split.rs | 26 +- crates/ui-egui/Cargo.toml | 41 +- crates/ui-egui/src/addons.rs | 60 +- crates/ui-egui/src/addons/arrange.rs | 390 +- crates/ui-egui/src/addons/arrange/tests.rs | 162 +- crates/ui-egui/src/addons/cleanup.rs | 280 +- crates/ui-egui/src/addons/cleanup/tests.rs | 172 +- crates/ui-egui/src/addons/color.rs | 143 +- crates/ui-egui/src/addons/color/legend.rs | 122 +- .../ui-egui/src/addons/color/legend/tests.rs | 77 +- crates/ui-egui/src/addons/color/nearest.rs | 293 +- crates/ui-egui/src/addons/color/tests.rs | 162 +- crates/ui-egui/src/addons/compounds.rs | 17 +- crates/ui-egui/src/addons/contour.rs | 7 +- crates/ui-egui/src/addons/cutting.rs | 13 +- crates/ui-egui/src/addons/cutting/tests.rs | 597 +- crates/ui-egui/src/addons/dialogs.rs | 132 + crates/ui-egui/src/addons/dialogs/tests.rs | 263 + crates/ui-egui/src/addons/document.rs | 88 +- crates/ui-egui/src/addons/document/tests.rs | 68 +- crates/ui-egui/src/addons/enclosing_lasso.rs | 7 +- crates/ui-egui/src/addons/image.rs | 13 +- crates/ui-egui/src/addons/image/tests.rs | 176 +- crates/ui-egui/src/addons/packaging.rs | 246 +- .../ui-egui/src/addons/packaging/preview.rs | 781 +- .../src/addons/packaging/preview/tests.rs | 559 +- crates/ui-egui/src/addons/packaging/tests.rs | 219 +- crates/ui-egui/src/addons/pathtools.rs | 367 +- crates/ui-egui/src/addons/pathtools/bridge.rs | 165 +- crates/ui-egui/src/addons/pathtools/corner.rs | 53 +- crates/ui-egui/src/addons/pathtools/dashes.rs | 111 +- .../src/addons/pathtools/set_corners.rs | 176 +- crates/ui-egui/src/addons/pathtools/shape.rs | 158 +- .../src/addons/pathtools/shared_edge.rs | 43 +- .../src/addons/pathtools/tangent_circle.rs | 185 +- crates/ui-egui/src/addons/pathtools/tests.rs | 507 +- crates/ui-egui/src/addons/pen.rs | 53 +- crates/ui-egui/src/addons/pen/tests.rs | 57 - crates/ui-egui/src/addons/polygonal_lasso.rs | 7 +- crates/ui-egui/src/addons/select.rs | 324 +- .../ui-egui/src/addons/select/link_status.rs | 331 +- .../src/addons/select/link_status/tests.rs | 129 +- crates/ui-egui/src/addons/select/tests.rs | 174 +- crates/ui-egui/src/addons/shapes.rs | 428 +- crates/ui-egui/src/addons/typetools.rs | 125 +- crates/ui-egui/src/addons/typetools/tests.rs | 132 +- crates/ui-egui/src/addons/units.rs | 150 +- crates/ui-egui/src/addons/units/tests.rs | 173 +- crates/ui-egui/src/app.rs | 773 +- crates/ui-egui/src/app/clipboard.rs | 13 - crates/ui-egui/src/app/commands.rs | 39 +- crates/ui-egui/src/app/control.rs | 211 +- crates/ui-egui/src/app/files.rs | 39 +- crates/ui-egui/src/app/fonts.rs | 72 +- crates/ui-egui/src/app/frame.rs | 62 +- crates/ui-egui/src/app/ime.rs | 24 - crates/ui-egui/src/app/input.rs | 302 +- crates/ui-egui/src/app/links.rs | 23 +- crates/ui-egui/src/app/screenshot.rs | 181 - crates/ui-egui/src/app/tests.rs | 80 + crates/ui-egui/src/app/view.rs | 90 +- crates/ui-egui/src/background.rs | 213 +- crates/ui-egui/src/brand.rs | 92 +- crates/ui-egui/src/caches.rs | 160 +- crates/ui-egui/src/canvas.rs | 1887 +-- crates/ui-egui/src/canvas/alternates_bar.rs | 205 +- .../src/canvas/alternates_bar/tests.rs | 206 +- crates/ui-egui/src/canvas/artboards.rs | 340 +- crates/ui-egui/src/canvas/artboards/tests.rs | 180 + crates/ui-egui/src/canvas/bar_place.rs | 27 + crates/ui-egui/src/canvas/context.rs | 186 - crates/ui-egui/src/canvas/context_menu.rs | 71 + crates/ui-egui/src/canvas/contour_bar.rs | 121 +- crates/ui-egui/src/canvas/cursor.rs | 130 +- crates/ui-egui/src/canvas/drag.rs | 474 - crates/ui-egui/src/canvas/drops.rs | 412 + crates/ui-egui/src/canvas/drops/tests.rs | 259 + crates/ui-egui/src/canvas/fill.rs | 23 +- crates/ui-egui/src/canvas/grid.rs | 515 +- crates/ui-egui/src/canvas/guides.rs | 90 + crates/ui-egui/src/canvas/guides/tests.rs | 113 + crates/ui-egui/src/canvas/home.rs | 232 +- crates/ui-egui/src/canvas/input.rs | 818 -- crates/ui-egui/src/canvas/marks.rs | 796 ++ crates/ui-egui/src/canvas/marks/tests.rs | 228 + crates/ui-egui/src/canvas/outline.rs | 48 +- crates/ui-egui/src/canvas/overlays.rs | 943 +- crates/ui-egui/src/canvas/overlays/tests.rs | 63 + crates/ui-egui/src/canvas/panes.rs | 677 +- crates/ui-egui/src/canvas/panes/tests.rs | 1036 +- crates/ui-egui/src/canvas/quick_pen_bar.rs | 337 +- crates/ui-egui/src/canvas/raster.rs | 595 +- crates/ui-egui/src/canvas/rulers.rs | 320 + crates/ui-egui/src/canvas/rulers/tests.rs | 262 + crates/ui-egui/src/canvas/selection.rs | 504 + crates/ui-egui/src/canvas/selection/tests.rs | 403 + crates/ui-egui/src/canvas/selection_marks.rs | 941 -- .../src/canvas/selection_marks/tests.rs | 629 - .../ui-egui/src/canvas/selection_widgets.rs | 569 + .../src/canvas/selection_widgets/tests.rs | 356 + crates/ui-egui/src/canvas/task_bar.rs | 769 +- crates/ui-egui/src/canvas/tests.rs | 11297 +--------------- .../ui-egui/src/canvas/tests_edge_scroll.rs | 154 +- crates/ui-egui/src/canvas/tests_ui_scaling.rs | 171 +- crates/ui-egui/src/canvas/tool_adapter.rs | 736 + .../ui-egui/src/canvas/tool_adapter/tests.rs | 69 + crates/ui-egui/src/canvas/tool_overlays.rs | 773 -- crates/ui-egui/src/canvas/view.rs | 655 - crates/ui-egui/src/canvas/widgets.rs | 383 + crates/ui-egui/src/canvas/widgets/tests.rs | 417 + crates/ui-egui/src/chrome.rs | 680 +- crates/ui-egui/src/chrome/control_bar.rs | 1378 +- crates/ui-egui/src/chrome/hints.rs | 90 +- crates/ui-egui/src/chrome/status_bar.rs | 467 +- crates/ui-egui/src/chrome/tabs.rs | 683 +- crates/ui-egui/src/chrome/tests.rs | 5211 ++----- crates/ui-egui/src/clipboard_probe.rs | 113 - crates/ui-egui/src/clock.rs | 25 - crates/ui-egui/src/community.rs | 149 +- crates/ui-egui/src/control.rs | 942 +- crates/ui-egui/src/control/tests.rs | 485 +- crates/ui-egui/src/credits.rs | 780 +- crates/ui-egui/src/cursors.rs | 1003 +- crates/ui-egui/src/cursors/native_request.rs | 136 - .../src/cursors/native_request/tests.rs | 98 - crates/ui-egui/src/cursors/tests.rs | 612 +- crates/ui-egui/src/custom_toolbars.rs | 2895 +--- crates/ui-egui/src/dialogs.rs | 986 +- crates/ui-egui/src/dialogs/about.rs | 76 - crates/ui-egui/src/dialogs/action_batch.rs | 678 +- .../src/dialogs/action_insert_menu_item.rs | 472 +- crates/ui-egui/src/dialogs/action_new.rs | 245 +- crates/ui-egui/src/dialogs/action_playback.rs | 138 +- .../src/dialogs/action_select_object.rs | 135 +- .../ui-egui/src/dialogs/action_set_options.rs | 267 +- crates/ui-egui/src/dialogs/action_stop.rs | 187 +- crates/ui-egui/src/dialogs/actions.rs | 404 + .../ui-egui/src/dialogs/artboard_options.rs | 1238 +- .../src/dialogs/attributes_panel_options.rs | 130 +- crates/ui-egui/src/dialogs/blend_options.rs | 320 +- .../ui-egui/src/dialogs/brush_art_options.rs | 1042 +- crates/ui-egui/src/dialogs/brush_delete.rs | 127 +- .../ui-egui/src/dialogs/brush_delete/tests.rs | 94 +- crates/ui-egui/src/dialogs/brush_options.rs | 404 +- .../src/dialogs/brush_options/tests.rs | 1036 +- .../ui-egui/src/dialogs/brush_replace_art.rs | 99 +- .../src/dialogs/brush_replace_art/tests.rs | 104 +- .../ui-egui/src/dialogs/bullets_numbering.rs | 908 +- .../ui-egui/src/dialogs/char_style_options.rs | 2587 +--- .../src/dialogs/char_style_options/tests.rs | 829 ++ crates/ui-egui/src/dialogs/check_spelling.rs | 1187 +- crates/ui-egui/src/dialogs/circle_options.rs | 163 +- crates/ui-egui/src/dialogs/color_balance.rs | 290 +- .../src/dialogs/color_group_options.rs | 167 +- .../src/dialogs/color_guide_options.rs | 145 +- crates/ui-egui/src/dialogs/color_picker.rs | 1003 +- .../ui-egui/src/dialogs/color_picker/tests.rs | 883 +- crates/ui-egui/src/dialogs/command.rs | 1127 +- crates/ui-egui/src/dialogs/composite_fonts.rs | 1265 +- .../src/dialogs/composite_fonts/sample.rs | 222 +- .../src/dialogs/composite_fonts/tests.rs | 408 +- crates/ui-egui/src/dialogs/confirm.rs | 411 +- crates/ui-egui/src/dialogs/corners.rs | 223 +- .../ui-egui/src/dialogs/custom_dictionary.rs | 424 +- crates/ui-egui/src/dialogs/dimension.rs | 1118 +- crates/ui-egui/src/dialogs/document_setup.rs | 1478 +- crates/ui-egui/src/dialogs/duotone.rs | 208 +- crates/ui-egui/src/dialogs/dxf_import.rs | 557 +- crates/ui-egui/src/dialogs/dxf_options.rs | 285 +- crates/ui-egui/src/dialogs/edit_selection.rs | 184 +- crates/ui-egui/src/dialogs/edit_views.rs | 169 +- crates/ui-egui/src/dialogs/effect.rs | 2068 +-- crates/ui-egui/src/dialogs/effect_adjust.rs | 190 + crates/ui-egui/src/dialogs/effect_gallery.rs | 1160 +- crates/ui-egui/src/dialogs/effect_params.rs | 293 + crates/ui-egui/src/dialogs/effect_rows.rs | 305 + crates/ui-egui/src/dialogs/envelope.rs | 561 +- crates/ui-egui/src/dialogs/eps_options.rs | 296 +- crates/ui-egui/src/dialogs/expand.rs | 524 +- crates/ui-egui/src/dialogs/export_as.rs | 271 +- .../ui-egui/src/dialogs/export_for_screens.rs | 1661 +-- crates/ui-egui/src/dialogs/export_host.rs | 222 + crates/ui-egui/src/dialogs/eyedropper.rs | 152 +- crates/ui-egui/src/dialogs/file_info.rs | 1014 +- crates/ui-egui/src/dialogs/find_links.rs | 561 +- .../ui-egui/src/dialogs/find_links/tests.rs | 239 +- crates/ui-egui/src/dialogs/find_replace.rs | 393 +- .../ui-egui/src/dialogs/find_replace/tests.rs | 597 +- crates/ui-egui/src/dialogs/flare_options.rs | 537 +- crates/ui-egui/src/dialogs/flatten.rs | 699 +- .../ui-egui/src/dialogs/flattener_presets.rs | 359 +- crates/ui-egui/src/dialogs/form.rs | 1390 +- crates/ui-egui/src/dialogs/free_distort.rs | 245 +- crates/ui-egui/src/dialogs/freehand.rs | 547 +- crates/ui-egui/src/dialogs/freehand/tests.rs | 429 +- crates/ui-egui/src/dialogs/gradient_stop.rs | 732 +- crates/ui-egui/src/dialogs/graph_data.rs | 1387 +- crates/ui-egui/src/dialogs/graph_design.rs | 1169 +- crates/ui-egui/src/dialogs/graph_type.rs | 1598 +-- .../src/dialogs/graphic_style_options.rs | 141 +- crates/ui-egui/src/dialogs/halftone.rs | 160 +- crates/ui-egui/src/dialogs/host.rs | 241 + crates/ui-egui/src/dialogs/hpgl_options.rs | 340 +- crates/ui-egui/src/dialogs/hyphenation.rs | 215 +- crates/ui-egui/src/dialogs/import_pdf.rs | 857 +- crates/ui-egui/src/dialogs/indexed_color.rs | 143 +- .../ui-egui/src/dialogs/javascript_files.rs | 401 +- crates/ui-egui/src/dialogs/justification.rs | 426 +- crates/ui-egui/src/dialogs/kinsoku_sets.rs | 747 +- .../ui-egui/src/dialogs/kinsoku_sets/tests.rs | 269 +- crates/ui-egui/src/dialogs/layer_color.rs | 57 + crates/ui-egui/src/dialogs/layer_options.rs | 933 +- .../src/dialogs/layers_panel_options.rs | 188 +- crates/ui-egui/src/dialogs/liquify.rs | 230 +- .../ui-egui/src/dialogs/live_paint_bucket.rs | 178 +- crates/ui-egui/src/dialogs/live_paint_gaps.rs | 385 +- .../src/dialogs/live_paint_selection.rs | 159 +- crates/ui-egui/src/dialogs/missing_fonts.rs | 753 +- .../src/dialogs/missing_fonts/tests.rs | 283 +- crates/ui-egui/src/dialogs/missing_links.rs | 677 +- crates/ui-egui/src/dialogs/modal.rs | 569 - .../src/dialogs/navigator_panel_options.rs | 228 +- crates/ui-egui/src/dialogs/new_brush.rs | 180 +- crates/ui-egui/src/dialogs/new_color_group.rs | 93 +- crates/ui-egui/src/dialogs/new_document.rs | 2435 ++-- crates/ui-egui/src/dialogs/new_swatch.rs | 150 +- crates/ui-egui/src/dialogs/new_text_style.rs | 171 +- crates/ui-egui/src/dialogs/object_dialogs.rs | 89 + crates/ui-egui/src/dialogs/object_mosaic.rs | 1270 +- .../src/dialogs/objects_on_path_options.rs | 150 +- crates/ui-egui/src/dialogs/office_export.rs | 123 +- crates/ui-egui/src/dialogs/option_form.rs | 575 + crates/ui-egui/src/dialogs/package.rs | 129 +- .../ui-egui/src/dialogs/para_style_options.rs | 927 +- .../src/dialogs/para_style_options/tests.rs | 628 +- crates/ui-egui/src/dialogs/path_ops.rs | 648 +- .../ui-egui/src/dialogs/pathfinder_options.rs | 82 +- crates/ui-egui/src/dialogs/pdf_presets.rs | 428 +- .../ui-egui/src/dialogs/perspective_grid.rs | 756 +- .../src/dialogs/perspective_options.rs | 66 +- .../ui-egui/src/dialogs/perspective_plane.rs | 153 +- .../src/dialogs/perspective_presets.rs | 329 +- .../ui-egui/src/dialogs/pixel_snap_options.rs | 59 +- crates/ui-egui/src/dialogs/place.rs | 191 +- .../ui-egui/src/dialogs/placement_options.rs | 93 +- crates/ui-egui/src/dialogs/plugin.rs | 766 +- crates/ui-egui/src/dialogs/png_options.rs | 439 +- crates/ui-egui/src/dialogs/preset_manager.rs | 505 + crates/ui-egui/src/dialogs/preview.rs | 168 + crates/ui-egui/src/dialogs/preview_folders.rs | 186 + crates/ui-egui/src/dialogs/print.rs | 1661 ++- crates/ui-egui/src/dialogs/print_presets.rs | 202 +- .../ui-egui/src/dialogs/profile_mismatch.rs | 478 +- .../src/dialogs/profile_mismatch/tests.rs | 271 +- crates/ui-egui/src/dialogs/proof_setup.rs | 1127 +- crates/ui-egui/src/dialogs/psd_import.rs | 362 +- crates/ui-egui/src/dialogs/psd_options.rs | 46 +- crates/ui-egui/src/dialogs/raster_effects.rs | 350 +- .../src/dialogs/rearrange_artboards.rs | 463 +- crates/ui-egui/src/dialogs/recolor.rs | 4713 +++---- .../ui-egui/src/dialogs/recolor/edit_tab.rs | 616 + crates/ui-egui/src/dialogs/recolor/fixture.rs | 211 + .../ui-egui/src/dialogs/recolor/prominent.rs | 280 + crates/ui-egui/src/dialogs/recovery.rs | 37 - crates/ui-egui/src/dialogs/relink.rs | 421 +- .../ui-egui/src/dialogs/rename_artboards.rs | 120 +- crates/ui-egui/src/dialogs/revolve.rs | 1344 +- crates/ui-egui/src/dialogs/revolve/tests.rs | 1181 +- crates/ui-egui/src/dialogs/revolve_gizmo.rs | 904 +- crates/ui-egui/src/dialogs/revolve_lights.rs | 478 +- crates/ui-egui/src/dialogs/safe_mode.rs | 225 +- crates/ui-egui/src/dialogs/saturate.rs | 63 +- .../ui-egui/src/dialogs/save_brush_library.rs | 36 +- crates/ui-egui/src/dialogs/save_changes.rs | 19 - crates/ui-egui/src/dialogs/save_for_web.rs | 1964 +-- .../src/dialogs/save_for_web/color_table.rs | 210 + .../ui-egui/src/dialogs/save_for_web/tests.rs | 796 ++ .../src/dialogs/save_for_web/tests_table.rs | 231 + crates/ui-egui/src/dialogs/save_library.rs | 107 + crates/ui-egui/src/dialogs/save_options.rs | 833 +- .../ui-egui/src/dialogs/save_options/tests.rs | 615 +- crates/ui-egui/src/dialogs/save_pdf.rs | 1719 +-- crates/ui-egui/src/dialogs/save_pdf/tests.rs | 1545 +-- .../ui-egui/src/dialogs/save_style_library.rs | 37 +- .../src/dialogs/save_swatch_library.rs | 143 +- .../src/dialogs/save_symbol_library.rs | 37 +- crates/ui-egui/src/dialogs/saved_names.rs | 359 + crates/ui-egui/src/dialogs/screen_formats.rs | 561 + crates/ui-egui/src/dialogs/script_check.rs | 305 +- crates/ui-egui/src/dialogs/script_run.rs | 1035 +- .../src/dialogs/shape_builder_options.rs | 293 +- crates/ui-egui/src/dialogs/shapes.rs | 1672 +-- crates/ui-egui/src/dialogs/shortcut_import.rs | 1046 +- crates/ui-egui/src/dialogs/simplify_slider.rs | 367 +- crates/ui-egui/src/dialogs/slices.rs | 343 +- .../ui-egui/src/dialogs/smart_punctuation.rs | 177 +- crates/ui-egui/src/dialogs/smooth_slider.rs | 43 +- crates/ui-egui/src/dialogs/spot_colors.rs | 89 +- crates/ui-egui/src/dialogs/svg_filter.rs | 834 +- crates/ui-egui/src/dialogs/svg_options.rs | 779 +- crates/ui-egui/src/dialogs/swatch_conflict.rs | 350 +- crates/ui-egui/src/dialogs/swatch_options.rs | 832 +- crates/ui-egui/src/dialogs/symbol_delete.rs | 150 +- crates/ui-egui/src/dialogs/symbol_options.rs | 256 +- .../ui-egui/src/dialogs/symbolism_options.rs | 488 +- crates/ui-egui/src/dialogs/tate_chu_yoko.rs | 179 +- crates/ui-egui/src/dialogs/tests.rs | 3927 +----- .../src/dialogs/tests_accessibility.rs | 183 +- crates/ui-egui/src/dialogs/tests_dxf.rs | 139 +- crates/ui-egui/src/dialogs/tests_eps.rs | 255 +- crates/ui-egui/src/dialogs/tests_export.rs | 752 +- .../src/dialogs/tests_export_selection.rs | 140 +- crates/ui-egui/src/dialogs/tests_hpgl.rs | 237 +- .../ui-egui/src/dialogs/tests_import_pdf.rs | 159 +- crates/ui-egui/src/dialogs/tests_messages.rs | 83 + crates/ui-egui/src/dialogs/tests_metafile.rs | 16 +- crates/ui-egui/src/dialogs/tests_modal.rs | 776 +- crates/ui-egui/src/dialogs/tests_package.rs | 268 +- .../ui-egui/src/dialogs/tests_perspective.rs | 216 +- .../src/dialogs/tests_plugin_export.rs | 76 +- .../src/dialogs/tests_plugin_fields.rs | 194 +- .../src/dialogs/tests_plugin_import.rs | 128 +- crates/ui-egui/src/dialogs/tests_print.rs | 526 +- .../src/dialogs/tests_print_advanced.rs | 69 +- .../src/dialogs/tests_print_presets.rs | 136 +- crates/ui-egui/src/dialogs/tests_psd.rs | 64 +- .../src/dialogs/tests_raster_formats.rs | 201 +- .../dialogs/tests_raster_supplied_options.rs | 48 +- .../src/dialogs/tests_rectangular_grid.rs | 371 +- .../src/dialogs/tests_revolve_gizmo.rs | 628 +- .../ui-egui/src/dialogs/tests_save_for_web.rs | 1238 -- crates/ui-egui/src/dialogs/tests_scale.rs | 42 - .../src/dialogs/tests_screen_assets.rs | 124 +- crates/ui-egui/src/dialogs/tests_screens.rs | 1131 +- crates/ui-egui/src/dialogs/tests_scroll.rs | 484 - .../src/dialogs/tests_shortcut_import.rs | 687 +- .../src/dialogs/tests_svg_options_range.rs | 147 - .../ui-egui/src/dialogs/tests_tiff_bmp_tga.rs | 76 +- .../ui-egui/src/dialogs/tests_track_cube.rs | 97 +- crates/ui-egui/src/dialogs/tests_warp.rs | 579 +- crates/ui-egui/src/dialogs/text_export.rs | 70 +- crates/ui-egui/src/dialogs/text_import.rs | 318 +- crates/ui-egui/src/dialogs/three_d.rs | 306 + .../src/dialogs/three_d/tests_support.rs | 130 + crates/ui-egui/src/dialogs/three_d_classic.rs | 1330 +- .../ui-egui/src/dialogs/three_d_materials.rs | 227 +- .../src/dialogs/three_point_arc_options.rs | 85 +- crates/ui-egui/src/dialogs/tiff_bmp_tga.rs | 146 +- crates/ui-egui/src/dialogs/tile_edge_color.rs | 122 +- crates/ui-egui/src/dialogs/tool_options.rs | 52 + crates/ui-egui/src/dialogs/tools.rs | 200 +- crates/ui-egui/src/dialogs/trace_presets.rs | 71 - crates/ui-egui/src/dialogs/tracing_presets.rs | 701 +- .../src/dialogs/tracing_presets/tests.rs | 397 +- crates/ui-egui/src/dialogs/track_cube.rs | 452 + crates/ui-egui/src/dialogs/transform.rs | 922 +- crates/ui-egui/src/dialogs/transform_each.rs | 1051 +- crates/ui-egui/src/dialogs/variables.rs | 663 +- crates/ui-egui/src/dialogs/variation.rs | 84 + crates/ui-egui/src/dialogs/warichu.rs | 329 +- crates/ui-egui/src/dialogs/warp_effect.rs | 202 +- crates/ui-egui/src/dialogs/width_point.rs | 988 +- .../ui-egui/src/dialogs/width_point/tests.rs | 705 +- crates/ui-egui/src/display_profile.rs | 125 +- crates/ui-egui/src/doc_windows.rs | 467 +- crates/ui-egui/src/doc_windows/tests.rs | 449 +- crates/ui-egui/src/dock.rs | 138 +- crates/ui-egui/src/document_drag.rs | 326 - crates/ui-egui/src/edit_toolbar.rs | 512 +- crates/ui-egui/src/edit_toolbar/tests.rs | 696 +- crates/ui-egui/src/edits.rs | 189 + crates/ui-egui/src/export_progress.rs | 391 +- crates/ui-egui/src/fields.rs | 187 + crates/ui-egui/src/file_asks.rs | 322 + crates/ui-egui/src/find_font.rs | 1286 +- crates/ui-egui/src/font_menu.rs | 2483 +--- crates/ui-egui/src/font_menu/tests.rs | 1700 +-- crates/ui-egui/src/free_transform.rs | 242 +- crates/ui-egui/src/graphics.rs | 65 +- crates/ui-egui/src/hang_beacon.rs | 94 +- crates/ui-egui/src/i18n.rs | 839 +- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 9 +- crates/ui-egui/src/i18n/ca.tsv | 3 +- crates/ui-egui/src/i18n/catalog.rs | 354 - crates/ui-egui/src/i18n/cs.tsv | 9 +- crates/ui-egui/src/i18n/da.tsv | 3 +- crates/ui-egui/src/i18n/de.tsv | 3 +- crates/ui-egui/src/i18n/el.tsv | 3 +- crates/ui-egui/src/i18n/es.tsv | 3 +- crates/ui-egui/src/i18n/fi.tsv | 3 +- crates/ui-egui/src/i18n/fr.tsv | 9 +- crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 11 +- crates/ui-egui/src/i18n/hu.tsv | 215 +- crates/ui-egui/src/i18n/id.tsv | 3 +- crates/ui-egui/src/i18n/it.tsv | 11 +- crates/ui-egui/src/i18n/ja.tsv | 3 +- crates/ui-egui/src/i18n/ka.tsv | 209 +- crates/ui-egui/src/i18n/ko.tsv | 45 +- crates/ui-egui/src/i18n/nl.tsv | 3 +- crates/ui-egui/src/i18n/pl.tsv | 11 +- crates/ui-egui/src/i18n/pt-br.tsv | 7 +- crates/ui-egui/src/i18n/ru.tsv | 11 +- crates/ui-egui/src/i18n/sv.tsv | 3 +- crates/ui-egui/src/i18n/tests.rs | 5851 +------- crates/ui-egui/src/i18n/tr.tsv | 209 +- crates/ui-egui/src/i18n/uk.tsv | 11 +- crates/ui-egui/src/i18n/vi.tsv | 3 +- crates/ui-egui/src/i18n/zh-hans.tsv | 9 +- crates/ui-egui/src/i18n/zh-hant.tsv | 9 +- crates/ui-egui/src/icon_data.rs | 46 +- crates/ui-egui/src/icons.rs | 142 +- crates/ui-egui/src/ime.rs | 855 -- crates/ui-egui/src/io.rs | 121 +- crates/ui-egui/src/io/export.rs | 152 +- crates/ui-egui/src/io/open.rs | 181 +- crates/ui-egui/src/io/read_only_save.rs | 52 +- crates/ui-egui/src/io/save.rs | 591 +- crates/ui-egui/src/io/tests_read_only_save.rs | 164 +- crates/ui-egui/src/keymap.rs | 726 +- crates/ui-egui/src/layout_migration.rs | 627 +- crates/ui-egui/src/layout_migration/tests.rs | 246 +- crates/ui-egui/src/lib.rs | 354 +- crates/ui-egui/src/menus.rs | 96 +- crates/ui-egui/src/menus/bar.rs | 301 - crates/ui-egui/src/menus/context.rs | 87 +- crates/ui-egui/src/menus/entries.rs | 176 +- crates/ui-egui/src/menus/invoke.rs | 136 +- crates/ui-egui/src/menus/keyboard.rs | 940 -- crates/ui-egui/src/menus/labels.rs | 93 +- crates/ui-egui/src/menus/model.rs | 447 + crates/ui-egui/src/menus/native.rs | 92 + crates/ui-egui/src/menus/run.rs | 250 +- crates/ui-egui/src/menus/state.rs | 100 +- crates/ui-egui/src/menus/submenus.rs | 59 +- crates/ui-egui/src/menus/tests.rs | 790 +- crates/ui-egui/src/menus/tree.rs | 133 +- crates/ui-egui/src/menus/ui_commands.rs | 23 +- crates/ui-egui/src/native_menu.rs | 631 - crates/ui-egui/src/opening.rs | 168 +- crates/ui-egui/src/opening/tests.rs | 130 +- crates/ui-egui/src/original_editor.rs | 351 +- crates/ui-egui/src/page_glyphs.rs | 60 + crates/ui-egui/src/paint_preview.rs | 377 + crates/ui-egui/src/palette.rs | 5623 ++------ crates/ui-egui/src/palette/search.rs | 1986 --- crates/ui-egui/src/palette/words.rs | 158 - crates/ui-egui/src/panel_docking.rs | 2285 ++-- .../ui-egui/src/panel_docking/native_tests.rs | 1495 +- crates/ui-egui/src/panel_docking/peek.rs | 266 +- crates/ui-egui/src/panel_docking/sizes.rs | 77 +- crates/ui-egui/src/panel_docking/tests.rs | 2288 +--- crates/ui-egui/src/panel_drag.rs | 69 + crates/ui-egui/src/panels.rs | 874 +- crates/ui-egui/src/panels/actions.rs | 9497 +------------ crates/ui-egui/src/panels/actions/edits.rs | 1084 ++ crates/ui-egui/src/panels/actions/files.rs | 322 +- crates/ui-egui/src/panels/actions/keys.rs | 79 + crates/ui-egui/src/panels/actions/menu.rs | 270 + crates/ui-egui/src/panels/actions/model.rs | 432 + crates/ui-egui/src/panels/actions/playback.rs | 703 + .../ui-egui/src/panels/actions/recording.rs | 309 + .../ui-egui/src/panels/actions/tests_edits.rs | 1319 ++ .../ui-egui/src/panels/actions/tests_files.rs | 930 ++ .../ui-egui/src/panels/actions/tests_keys.rs | 340 + .../src/panels/actions/tests_limits.rs | 882 ++ .../ui-egui/src/panels/actions/tests_menu.rs | 117 + .../src/panels/actions/tests_playback.rs | 773 ++ .../src/panels/actions/tests_recording.rs | 207 + .../ui-egui/src/panels/actions/tests_stops.rs | 311 + .../src/panels/actions/tests_support.rs | 350 + crates/ui-egui/src/panels/align.rs | 362 +- crates/ui-egui/src/panels/align/tests.rs | 658 +- crates/ui-egui/src/panels/appearance.rs | 2972 ++-- crates/ui-egui/src/panels/appearance/tests.rs | 1292 +- crates/ui-egui/src/panels/artboards.rs | 678 +- crates/ui-egui/src/panels/artboards/tests.rs | 1448 +- crates/ui-egui/src/panels/asset_export.rs | 998 +- crates/ui-egui/src/panels/attributes.rs | 304 +- crates/ui-egui/src/panels/blend.rs | 199 +- crates/ui-egui/src/panels/brushes.rs | 1116 +- crates/ui-egui/src/panels/brushes/tests.rs | 1260 +- crates/ui-egui/src/panels/character.rs | 1540 +-- crates/ui-egui/src/panels/character/tests.rs | 1577 +-- crates/ui-egui/src/panels/color.rs | 1010 +- crates/ui-egui/src/panels/color/tests.rs | 1055 +- crates/ui-egui/src/panels/color_guide.rs | 1051 +- crates/ui-egui/src/panels/color_themes.rs | 1436 +- crates/ui-egui/src/panels/color_wheel.rs | 1188 +- crates/ui-egui/src/panels/css_properties.rs | 334 +- crates/ui-egui/src/panels/discover.rs | 295 +- crates/ui-egui/src/panels/doc_info.rs | 336 +- .../ui-egui/src/panels/flattener_preview.rs | 412 +- crates/ui-egui/src/panels/glyphs.rs | 3023 +---- crates/ui-egui/src/panels/glyphs/tests.rs | 1104 ++ crates/ui-egui/src/panels/gradient.rs | 1222 +- crates/ui-egui/src/panels/gradient/tests.rs | 928 +- crates/ui-egui/src/panels/graphic_styles.rs | 2089 +-- crates/ui-egui/src/panels/history.rs | 320 +- crates/ui-egui/src/panels/image_trace.rs | 824 +- crates/ui-egui/src/panels/image_trace/rows.rs | 331 + .../ui-egui/src/panels/image_trace/tests.rs | 2021 +-- crates/ui-egui/src/panels/info.rs | 248 +- crates/ui-egui/src/panels/layers.rs | 668 +- crates/ui-egui/src/panels/layers/cells.rs | 396 + crates/ui-egui/src/panels/layers/controls.rs | 696 +- crates/ui-egui/src/panels/layers/model.rs | 790 +- crates/ui-egui/src/panels/layers/rows.rs | 1192 +- crates/ui-egui/src/panels/layers/tests.rs | 3991 +----- .../ui-egui/src/panels/layers/tests_reveal.rs | 886 ++ crates/ui-egui/src/panels/layers/thumbs.rs | 756 +- crates/ui-egui/src/panels/learn.rs | 451 +- crates/ui-egui/src/panels/learn/locate.rs | 209 +- crates/ui-egui/src/panels/learn/tests.rs | 323 +- .../ui-egui/src/panels/learn/tests_locate.rs | 121 + crates/ui-egui/src/panels/libraries.rs | 1559 ++- crates/ui-egui/src/panels/libraries/tests.rs | 788 +- crates/ui-egui/src/panels/library_panel.rs | 657 +- .../ui-egui/src/panels/library_panel/tests.rs | 310 +- crates/ui-egui/src/panels/links.rs | 1127 +- crates/ui-egui/src/panels/magic_wand.rs | 133 +- crates/ui-egui/src/panels/navigator.rs | 758 +- crates/ui-egui/src/panels/opentype.rs | 473 +- crates/ui-egui/src/panels/paragraph.rs | 949 +- crates/ui-egui/src/panels/paragraph/tests.rs | 548 +- crates/ui-egui/src/panels/pathfinder.rs | 787 +- crates/ui-egui/src/panels/pattern_options.rs | 407 +- crates/ui-egui/src/panels/preflight.rs | 340 +- crates/ui-egui/src/panels/preflight/tests.rs | 196 +- crates/ui-egui/src/panels/properties.rs | 1187 +- .../panels/properties/appearance_section.rs | 221 + .../panels/properties/artboard_sections.rs | 241 + .../panels/properties/document_sections.rs | 99 + .../src/panels/properties/dynamic_text.rs | 33 +- crates/ui-egui/src/panels/properties/graph.rs | 48 +- .../src/panels/properties/object_sections.rs | 156 + crates/ui-egui/src/panels/properties/tests.rs | 2474 ++-- .../panels/properties/transform_section.rs | 111 + .../src/panels/properties/type_sections.rs | 43 + .../src/panels/properties/vertical_align.rs | 10 +- crates/ui-egui/src/panels/retype.rs | 143 +- crates/ui-egui/src/panels/retype/tests.rs | 28 +- crates/ui-egui/src/panels/script_console.rs | 218 +- crates/ui-egui/src/panels/separations.rs | 540 +- crates/ui-egui/src/panels/stroke.rs | 1202 +- .../ui-egui/src/panels/svg_interactivity.rs | 256 +- crates/ui-egui/src/panels/swatches.rs | 885 +- crates/ui-egui/src/panels/swatches/actions.rs | 372 +- crates/ui-egui/src/panels/swatches/body.rs | 236 - crates/ui-egui/src/panels/swatches/dnd.rs | 368 +- .../ui-egui/src/panels/swatches/libraries.rs | 149 +- crates/ui-egui/src/panels/swatches/tests.rs | 1886 +-- .../src/panels/swatches/tests/context_menu.rs | 225 +- crates/ui-egui/src/panels/swatches/tiles.rs | 220 - crates/ui-egui/src/panels/symbols.rs | 3705 +---- crates/ui-egui/src/panels/symbols/tests.rs | 1609 +++ crates/ui-egui/src/panels/tabs.rs | 936 +- crates/ui-egui/src/panels/tabs/tests.rs | 1340 +- crates/ui-egui/src/panels/tests_appearance.rs | 2123 +-- .../ui-egui/src/panels/tests_asset_export.rs | 1131 +- crates/ui-egui/src/panels/tests_blend.rs | 492 +- .../src/panels/tests_brush_libraries.rs | 150 +- .../ui-egui/src/panels/tests_color_wheel.rs | 1193 +- .../src/panels/tests_color_wheel_box.rs | 288 +- .../tests_color_wheel_document_colors.rs | 356 +- .../src/panels/tests_color_wheel_gamut.rs | 203 +- .../src/panels/tests_color_wheel_harmony.rs | 281 +- .../src/panels/tests_color_wheel_vision.rs | 201 +- crates/ui-egui/src/panels/tests_constrain.rs | 408 +- .../src/panels/tests_css_properties.rs | 84 +- crates/ui-egui/src/panels/tests_effectedit.rs | 282 +- crates/ui-egui/src/panels/tests_fontsize.rs | 147 - crates/ui-egui/src/panels/tests_freeform.rs | 101 +- crates/ui-egui/src/panels/tests_links.rs | 536 +- .../ui-egui/src/panels/tests_long_popups.rs | 490 - crates/ui-egui/src/panels/tests_maskview.rs | 178 +- .../src/panels/tests_script_console.rs | 112 +- crates/ui-egui/src/panels/tests_stroke.rs | 23 +- .../ui-egui/src/panels/tests_strokedepth.rs | 364 +- crates/ui-egui/src/panels/tests_strokeux.rs | 280 +- .../src/panels/tests_style_libraries.rs | 123 +- .../src/panels/tests_symbol_libraries.rs | 110 +- crates/ui-egui/src/panels/tests_three_d.rs | 1059 +- crates/ui-egui/src/panels/tests_units.rs | 370 +- crates/ui-egui/src/panels/text_styles.rs | 581 +- .../ui-egui/src/panels/text_styles/tests.rs | 1410 +- crates/ui-egui/src/panels/three_d.rs | 596 +- crates/ui-egui/src/panels/three_d/handles.rs | 298 + crates/ui-egui/src/panels/transform.rs | 1052 +- crates/ui-egui/src/panels/transform/shape.rs | 202 + crates/ui-egui/src/panels/transform/tests.rs | 1200 +- crates/ui-egui/src/panels/transparency.rs | 796 +- crates/ui-egui/src/panels/variables.rs | 1286 +- crates/ui-egui/src/picks.rs | 565 - crates/ui-egui/src/place.rs | 693 +- crates/ui-egui/src/placing.rs | 304 +- crates/ui-egui/src/placing/tests.rs | 360 +- crates/ui-egui/src/plugin_runs.rs | 78 +- crates/ui-egui/src/prefs_dialog.rs | 1105 +- crates/ui-egui/src/prefs_dialog/model.rs | 428 + crates/ui-egui/src/prefs_dialog/runtime.rs | 83 + crates/ui-egui/src/prefs_dialog/tests.rs | 2940 +--- crates/ui-egui/src/print.rs | 27 +- crates/ui-egui/src/recovery.rs | 153 +- crates/ui-egui/src/render_worker.rs | 9 +- crates/ui-egui/src/screen_color.rs | 206 +- crates/ui-egui/src/screen_color/tests.rs | 258 +- crates/ui-egui/src/script_runs.rs | 32 +- crates/ui-egui/src/scripts_menu.rs | 316 +- crates/ui-egui/src/scrub.rs | 261 - crates/ui-egui/src/services.rs | 149 +- crates/ui-egui/src/settings.rs | 63 + crates/ui-egui/src/shortcut_editor.rs | 3368 ++--- crates/ui-egui/src/shortcuts.rs | 1517 +-- crates/ui-egui/src/shortcuts/alt_tap.rs | 114 - crates/ui-egui/src/shortcuts/held_tool.rs | 131 +- .../ui-egui/src/shortcuts/held_tool/tests.rs | 226 +- crates/ui-egui/src/shortcuts/hold_keys.rs | 426 - .../ui-egui/src/shortcuts/hold_keys/tests.rs | 757 -- crates/ui-egui/src/shortcuts/labels.rs | 127 +- crates/ui-egui/src/shortcuts/paste.rs | 72 - crates/ui-egui/src/shortcuts/presentation.rs | 57 +- crates/ui-egui/src/shortcuts/tests.rs | 4557 ++----- crates/ui-egui/src/shortcuts/typing.rs | 484 - crates/ui-egui/src/state.rs | 1147 +- crates/ui-egui/src/stylus.rs | 477 +- crates/ui-egui/src/sysclip.rs | 441 +- crates/ui-egui/src/testing.rs | 102 + crates/ui-egui/src/tests.rs | 10 +- crates/ui-egui/src/tests/adjust.rs | 150 +- crates/ui-egui/src/tests/aisave.rs | 42 +- crates/ui-egui/src/tests/automation.rs | 873 +- crates/ui-egui/src/tests/background.rs | 79 +- crates/ui-egui/src/tests/clipboard.rs | 221 +- crates/ui-egui/src/tests/contextmenu.rs | 649 +- crates/ui-egui/src/tests/cut.rs | 32 +- crates/ui-egui/src/tests/distortkeys.rs | 42 +- crates/ui-egui/src/tests/docsetup.rs | 261 - crates/ui-egui/src/tests/document_drag.rs | 290 +- crates/ui-egui/src/tests/folder.rs | 24 +- crates/ui-egui/src/tests/font_menu.rs | 1257 +- crates/ui-egui/src/tests/fonts.rs | 9 - crates/ui-egui/src/tests/guide_escape.rs | 19 +- crates/ui-egui/src/tests/home.rs | 411 +- crates/ui-egui/src/tests/labels.rs | 70 +- crates/ui-egui/src/tests/lifecycle.rs | 1546 +-- crates/ui-egui/src/tests/nativemenu.rs | 556 +- crates/ui-egui/src/tests/nativeoptions.rs | 178 +- crates/ui-egui/src/tests/numfields.rs | 1787 +-- crates/ui-egui/src/tests/overprint.rs | 34 +- crates/ui-egui/src/tests/paintchips.rs | 374 +- crates/ui-egui/src/tests/panel_harness.rs | 330 + crates/ui-egui/src/tests/pastechords.rs | 97 +- crates/ui-egui/src/tests/pathtype.rs | 200 +- crates/ui-egui/src/tests/pdfoutput.rs | 44 +- crates/ui-egui/src/tests/picks.rs | 1448 +- crates/ui-egui/src/tests/place.rs | 1003 +- crates/ui-egui/src/tests/plugin_runs.rs | 292 +- crates/ui-egui/src/tests/plugins.rs | 641 +- crates/ui-egui/src/tests/printps.rs | 25 +- crates/ui-egui/src/tests/printtiling.rs | 32 +- crates/ui-egui/src/tests/puppetwarp.rs | 35 - crates/ui-egui/src/tests/quickpenbar.rs | 455 +- crates/ui-egui/src/tests/recolor.rs | 2197 ++- crates/ui-egui/src/tests/recovery.rs | 154 +- crates/ui-egui/src/tests/removeanchors.rs | 78 +- crates/ui-egui/src/tests/rotateview.rs | 259 +- crates/ui-egui/src/tests/ruler_origin.rs | 135 +- crates/ui-egui/src/tests/save.rs | 141 +- crates/ui-egui/src/tests/saveext.rs | 614 +- crates/ui-egui/src/tests/screenmode.rs | 649 +- crates/ui-egui/src/tests/screenshots.rs | 400 - crates/ui-egui/src/tests/script_check.rs | 160 +- crates/ui-egui/src/tests/script_dialogs.rs | 245 +- crates/ui-egui/src/tests/script_run.rs | 493 +- crates/ui-egui/src/tests/scripts_menu.rs | 370 +- crates/ui-egui/src/tests/scrub.rs | 350 +- crates/ui-egui/src/tests/selectall.rs | 253 +- crates/ui-egui/src/tests/selectescape.rs | 9 +- crates/ui-egui/src/tests/slices.rs | 18 +- crates/ui-egui/src/tests/svg.rs | 50 +- crates/ui-egui/src/tests/svgsave.rs | 10 +- crates/ui-egui/src/tests/synthetic.rs | 285 +- crates/ui-egui/src/tests/sysclip.rs | 304 +- crates/ui-egui/src/tests/sysclip_emf.rs | 2 +- crates/ui-egui/src/tests/sysclip_guides.rs | 33 +- crates/ui-egui/src/tests/sysclip_probe.rs | 300 - crates/ui-egui/src/tests/tab_overflow.rs | 251 - crates/ui-egui/src/tests/tab_reorder.rs | 95 +- crates/ui-egui/src/tests/taskbar.rs | 2615 ++-- crates/ui-egui/src/tests/toolescape.rs | 9 +- crates/ui-egui/src/tests/trace_runs.rs | 16 +- crates/ui-egui/src/tests/transparencygrid.rs | 42 - crates/ui-egui/src/tests/widthtool.rs | 29 - crates/ui-egui/src/theme.rs | 723 +- crates/ui-egui/src/thumb_worker.rs | 10 +- crates/ui-egui/src/titlebar.rs | 517 - crates/ui-egui/src/toasts.rs | 356 - crates/ui-egui/src/toolbar.rs | 1510 +-- crates/ui-egui/src/toolbar/card.rs | 237 +- crates/ui-egui/src/toolbar/tests.rs | 1888 +-- crates/ui-egui/src/tools_float.rs | 303 - crates/ui-egui/src/touch.rs | 129 +- crates/ui-egui/src/trace_runs.rs | 72 +- crates/ui-egui/src/type_editing.rs | 516 + crates/ui-egui/src/ui_fonts.rs | 599 +- crates/ui-egui/src/unsaved.rs | 479 +- crates/ui-egui/src/updates_ui.rs | 437 +- crates/ui-egui/src/widgets.rs | 1065 -- crates/ui-egui/src/widgets/blend.rs | 229 - crates/ui-egui/src/widgets/buttons.rs | 242 - crates/ui-egui/src/widgets/chips.rs | 307 - crates/ui-egui/src/widgets/color.rs | 1394 -- crates/ui-egui/src/widgets/drag.rs | 324 - crates/ui-egui/src/widgets/dropdowns.rs | 858 -- crates/ui-egui/src/widgets/labels.rs | 201 - crates/ui-egui/src/widgets/look_tests.rs | 1349 -- crates/ui-egui/src/widgets/numeric.rs | 1458 -- crates/ui-egui/src/widgets/panel_chrome.rs | 296 - crates/ui-egui/src/widgets/text.rs | 431 - crates/ui-egui/src/widgets/toggles.rs | 116 - crates/ui-egui/src/widgets/wheel_stream.rs | 66 - crates/ui-egui/src/workspaces.rs | 1296 +- .../ui-egui/tests/actions_automatic_align.rs | 105 +- .../tests/brush_keycolor_modal_repro.rs | 348 +- .../ui-egui/tests/color_working_components.rs | 342 +- crates/ui-egui/tests/control_bar_corners.rs | 93 +- .../tests/dimension_extension_properties.rs | 677 +- .../fixtures/ui-production-toolbars.json | 62 + crates/ui-egui/tests/font_wheel.rs | 196 - .../tests/image_trace_ignore_sampler.rs | 254 +- crates/ui-egui/tests/install_fonts.rs | 97 +- crates/ui-egui/tests/menu_access_keys.rs | 1327 +- crates/ui-egui/tests/pattern_only_nudge.rs | 24 +- crates/ui-egui/tests/safe_mode.rs | 192 +- .../ui-egui/tests/selection_tools_toggle.rs | 49 +- crates/ui-egui/tests/toolbar_compact.rs | 334 +- docs/development.md | 43 +- docs/mcp.md | 8 +- docs/target-app-parity.md | 4 +- docs/type-parity.md | 2 +- xtask/src/pdf_deps.rs | 2 +- xtask/src/ui_commands.rs | 15 +- 947 files changed, 152318 insertions(+), 262736 deletions(-) delete mode 100644 apps/vectorcraft-web/src/demand.rs delete mode 100644 apps/vectorcraft/src/caps_lock.rs delete mode 100644 apps/vectorcraft/src/control_server.rs delete mode 100644 apps/vectorcraft/src/control_server/tests.rs delete mode 100644 apps/vectorcraft/src/linux_screen_color.rs delete mode 100644 apps/vectorcraft/src/linux_screen_color/portal.rs delete mode 100644 apps/vectorcraft/src/mac_cursor.rs delete mode 100644 apps/vectorcraft/src/mac_cursor/tests.rs delete mode 100644 apps/vectorcraft/src/mac_menu.rs delete mode 100644 apps/vectorcraft/src/mac_save_format.rs delete mode 100644 apps/vectorcraft/src/mac_screen_color.rs delete mode 100644 apps/vectorcraft/src/portal_request.rs delete mode 100644 apps/vectorcraft/src/portal_save.rs delete mode 100644 apps/vectorcraft/src/titlebar.rs delete mode 100644 apps/vectorcraft/src/window.rs delete mode 100644 apps/vectorcraft/src/windows_screen_color.rs create mode 100644 assets/cursors/cursor-anchor-point.svg create mode 100644 assets/cursors/cursor-direct-anchor-selected.svg create mode 100644 assets/cursors/cursor-direct-anchor.svg create mode 100644 assets/cursors/cursor-loaded-text-link.svg create mode 100644 assets/cursors/cursor-loaded-text.svg create mode 100644 assets/cursors/cursor-mark-bracket.svg create mode 100644 assets/cursors/cursor-mark-edge.svg create mode 100644 assets/cursors/cursor-mark-line-level.svg create mode 100644 assets/cursors/cursor-mark-line-rising.svg create mode 100644 assets/cursors/cursor-mark-ring.svg create mode 100644 assets/cursors/cursor-mark-square.svg create mode 100644 assets/cursors/cursor-mark-star.svg create mode 100644 assets/cursors/cursor-pen-convert.svg create mode 100644 assets/cursors/cursor-pen-curvature.svg create mode 100644 assets/cursors/cursor-pen-join.svg create mode 100644 assets/cursors/cursor-pen-new.svg create mode 100644 assets/cursors/cursor-reshape-segment.svg create mode 100644 assets/icons/circle-off.svg create mode 100644 assets/icons/dc-blend-align-page.svg create mode 100644 assets/icons/dc-blend-align-path.svg create mode 100644 assets/icons/dc-free-distort.svg delete mode 100644 crates/color/src/cms/display.rs delete mode 100644 crates/pdf/src/presets.rs delete mode 100644 crates/pdf/src/tests/presets.rs delete mode 100644 crates/text/src/fontconfig.rs create mode 100644 crates/ui-egui/src/addons/dialogs.rs create mode 100644 crates/ui-egui/src/addons/dialogs/tests.rs delete mode 100644 crates/ui-egui/src/addons/pen/tests.rs delete mode 100644 crates/ui-egui/src/app/clipboard.rs delete mode 100644 crates/ui-egui/src/app/ime.rs delete mode 100644 crates/ui-egui/src/app/screenshot.rs create mode 100644 crates/ui-egui/src/app/tests.rs create mode 100644 crates/ui-egui/src/canvas/artboards/tests.rs create mode 100644 crates/ui-egui/src/canvas/bar_place.rs delete mode 100644 crates/ui-egui/src/canvas/context.rs create mode 100644 crates/ui-egui/src/canvas/context_menu.rs delete mode 100644 crates/ui-egui/src/canvas/drag.rs create mode 100644 crates/ui-egui/src/canvas/drops.rs create mode 100644 crates/ui-egui/src/canvas/drops/tests.rs create mode 100644 crates/ui-egui/src/canvas/guides.rs create mode 100644 crates/ui-egui/src/canvas/guides/tests.rs delete mode 100644 crates/ui-egui/src/canvas/input.rs create mode 100644 crates/ui-egui/src/canvas/marks.rs create mode 100644 crates/ui-egui/src/canvas/marks/tests.rs create mode 100644 crates/ui-egui/src/canvas/overlays/tests.rs create mode 100644 crates/ui-egui/src/canvas/rulers.rs create mode 100644 crates/ui-egui/src/canvas/rulers/tests.rs create mode 100644 crates/ui-egui/src/canvas/selection.rs create mode 100644 crates/ui-egui/src/canvas/selection/tests.rs delete mode 100644 crates/ui-egui/src/canvas/selection_marks.rs delete mode 100644 crates/ui-egui/src/canvas/selection_marks/tests.rs create mode 100644 crates/ui-egui/src/canvas/selection_widgets.rs create mode 100644 crates/ui-egui/src/canvas/selection_widgets/tests.rs create mode 100644 crates/ui-egui/src/canvas/tool_adapter.rs create mode 100644 crates/ui-egui/src/canvas/tool_adapter/tests.rs delete mode 100644 crates/ui-egui/src/canvas/tool_overlays.rs delete mode 100644 crates/ui-egui/src/canvas/view.rs create mode 100644 crates/ui-egui/src/canvas/widgets.rs create mode 100644 crates/ui-egui/src/canvas/widgets/tests.rs delete mode 100644 crates/ui-egui/src/clipboard_probe.rs delete mode 100644 crates/ui-egui/src/clock.rs delete mode 100644 crates/ui-egui/src/cursors/native_request.rs delete mode 100644 crates/ui-egui/src/cursors/native_request/tests.rs delete mode 100644 crates/ui-egui/src/dialogs/about.rs create mode 100644 crates/ui-egui/src/dialogs/actions.rs create mode 100644 crates/ui-egui/src/dialogs/char_style_options/tests.rs create mode 100644 crates/ui-egui/src/dialogs/effect_adjust.rs create mode 100644 crates/ui-egui/src/dialogs/effect_params.rs create mode 100644 crates/ui-egui/src/dialogs/effect_rows.rs create mode 100644 crates/ui-egui/src/dialogs/export_host.rs create mode 100644 crates/ui-egui/src/dialogs/host.rs create mode 100644 crates/ui-egui/src/dialogs/layer_color.rs delete mode 100644 crates/ui-egui/src/dialogs/modal.rs create mode 100644 crates/ui-egui/src/dialogs/object_dialogs.rs create mode 100644 crates/ui-egui/src/dialogs/option_form.rs create mode 100644 crates/ui-egui/src/dialogs/preset_manager.rs create mode 100644 crates/ui-egui/src/dialogs/preview.rs create mode 100644 crates/ui-egui/src/dialogs/preview_folders.rs create mode 100644 crates/ui-egui/src/dialogs/recolor/edit_tab.rs create mode 100644 crates/ui-egui/src/dialogs/recolor/fixture.rs create mode 100644 crates/ui-egui/src/dialogs/recolor/prominent.rs delete mode 100644 crates/ui-egui/src/dialogs/recovery.rs delete mode 100644 crates/ui-egui/src/dialogs/save_changes.rs create mode 100644 crates/ui-egui/src/dialogs/save_for_web/color_table.rs create mode 100644 crates/ui-egui/src/dialogs/save_for_web/tests.rs create mode 100644 crates/ui-egui/src/dialogs/save_for_web/tests_table.rs create mode 100644 crates/ui-egui/src/dialogs/save_library.rs create mode 100644 crates/ui-egui/src/dialogs/saved_names.rs create mode 100644 crates/ui-egui/src/dialogs/screen_formats.rs create mode 100644 crates/ui-egui/src/dialogs/tests_messages.rs delete mode 100644 crates/ui-egui/src/dialogs/tests_save_for_web.rs delete mode 100644 crates/ui-egui/src/dialogs/tests_scale.rs delete mode 100644 crates/ui-egui/src/dialogs/tests_scroll.rs delete mode 100644 crates/ui-egui/src/dialogs/tests_svg_options_range.rs create mode 100644 crates/ui-egui/src/dialogs/three_d.rs create mode 100644 crates/ui-egui/src/dialogs/three_d/tests_support.rs create mode 100644 crates/ui-egui/src/dialogs/tool_options.rs delete mode 100644 crates/ui-egui/src/dialogs/trace_presets.rs create mode 100644 crates/ui-egui/src/dialogs/track_cube.rs create mode 100644 crates/ui-egui/src/dialogs/variation.rs delete mode 100644 crates/ui-egui/src/document_drag.rs create mode 100644 crates/ui-egui/src/edits.rs create mode 100644 crates/ui-egui/src/fields.rs create mode 100644 crates/ui-egui/src/file_asks.rs delete mode 100644 crates/ui-egui/src/i18n/catalog.rs delete mode 100644 crates/ui-egui/src/ime.rs delete mode 100644 crates/ui-egui/src/menus/bar.rs delete mode 100644 crates/ui-egui/src/menus/keyboard.rs create mode 100644 crates/ui-egui/src/menus/model.rs create mode 100644 crates/ui-egui/src/menus/native.rs delete mode 100644 crates/ui-egui/src/native_menu.rs create mode 100644 crates/ui-egui/src/page_glyphs.rs create mode 100644 crates/ui-egui/src/paint_preview.rs delete mode 100644 crates/ui-egui/src/palette/search.rs delete mode 100644 crates/ui-egui/src/palette/words.rs create mode 100644 crates/ui-egui/src/panel_drag.rs create mode 100644 crates/ui-egui/src/panels/actions/edits.rs create mode 100644 crates/ui-egui/src/panels/actions/keys.rs create mode 100644 crates/ui-egui/src/panels/actions/menu.rs create mode 100644 crates/ui-egui/src/panels/actions/model.rs create mode 100644 crates/ui-egui/src/panels/actions/playback.rs create mode 100644 crates/ui-egui/src/panels/actions/recording.rs create mode 100644 crates/ui-egui/src/panels/actions/tests_edits.rs create mode 100644 crates/ui-egui/src/panels/actions/tests_files.rs create mode 100644 crates/ui-egui/src/panels/actions/tests_keys.rs create mode 100644 crates/ui-egui/src/panels/actions/tests_limits.rs create mode 100644 crates/ui-egui/src/panels/actions/tests_menu.rs create mode 100644 crates/ui-egui/src/panels/actions/tests_playback.rs create mode 100644 crates/ui-egui/src/panels/actions/tests_recording.rs create mode 100644 crates/ui-egui/src/panels/actions/tests_stops.rs create mode 100644 crates/ui-egui/src/panels/actions/tests_support.rs create mode 100644 crates/ui-egui/src/panels/glyphs/tests.rs create mode 100644 crates/ui-egui/src/panels/image_trace/rows.rs create mode 100644 crates/ui-egui/src/panels/layers/cells.rs create mode 100644 crates/ui-egui/src/panels/layers/tests_reveal.rs create mode 100644 crates/ui-egui/src/panels/learn/tests_locate.rs create mode 100644 crates/ui-egui/src/panels/properties/appearance_section.rs create mode 100644 crates/ui-egui/src/panels/properties/artboard_sections.rs create mode 100644 crates/ui-egui/src/panels/properties/document_sections.rs create mode 100644 crates/ui-egui/src/panels/properties/object_sections.rs create mode 100644 crates/ui-egui/src/panels/properties/transform_section.rs create mode 100644 crates/ui-egui/src/panels/properties/type_sections.rs delete mode 100644 crates/ui-egui/src/panels/swatches/body.rs delete mode 100644 crates/ui-egui/src/panels/swatches/tiles.rs create mode 100644 crates/ui-egui/src/panels/symbols/tests.rs delete mode 100644 crates/ui-egui/src/panels/tests_fontsize.rs delete mode 100644 crates/ui-egui/src/panels/tests_long_popups.rs create mode 100644 crates/ui-egui/src/panels/three_d/handles.rs create mode 100644 crates/ui-egui/src/panels/transform/shape.rs delete mode 100644 crates/ui-egui/src/picks.rs create mode 100644 crates/ui-egui/src/prefs_dialog/model.rs create mode 100644 crates/ui-egui/src/prefs_dialog/runtime.rs delete mode 100644 crates/ui-egui/src/scrub.rs create mode 100644 crates/ui-egui/src/settings.rs delete mode 100644 crates/ui-egui/src/shortcuts/alt_tap.rs delete mode 100644 crates/ui-egui/src/shortcuts/hold_keys.rs delete mode 100644 crates/ui-egui/src/shortcuts/hold_keys/tests.rs delete mode 100644 crates/ui-egui/src/shortcuts/paste.rs delete mode 100644 crates/ui-egui/src/shortcuts/typing.rs create mode 100644 crates/ui-egui/src/testing.rs delete mode 100644 crates/ui-egui/src/tests/docsetup.rs create mode 100644 crates/ui-egui/src/tests/panel_harness.rs delete mode 100644 crates/ui-egui/src/tests/puppetwarp.rs delete mode 100644 crates/ui-egui/src/tests/screenshots.rs delete mode 100644 crates/ui-egui/src/tests/sysclip_probe.rs delete mode 100644 crates/ui-egui/src/tests/tab_overflow.rs delete mode 100644 crates/ui-egui/src/tests/transparencygrid.rs delete mode 100644 crates/ui-egui/src/tests/widthtool.rs delete mode 100644 crates/ui-egui/src/titlebar.rs delete mode 100644 crates/ui-egui/src/toasts.rs delete mode 100644 crates/ui-egui/src/tools_float.rs create mode 100644 crates/ui-egui/src/type_editing.rs delete mode 100644 crates/ui-egui/src/widgets.rs delete mode 100644 crates/ui-egui/src/widgets/blend.rs delete mode 100644 crates/ui-egui/src/widgets/buttons.rs delete mode 100644 crates/ui-egui/src/widgets/chips.rs delete mode 100644 crates/ui-egui/src/widgets/color.rs delete mode 100644 crates/ui-egui/src/widgets/drag.rs delete mode 100644 crates/ui-egui/src/widgets/dropdowns.rs delete mode 100644 crates/ui-egui/src/widgets/labels.rs delete mode 100644 crates/ui-egui/src/widgets/look_tests.rs delete mode 100644 crates/ui-egui/src/widgets/numeric.rs delete mode 100644 crates/ui-egui/src/widgets/panel_chrome.rs delete mode 100644 crates/ui-egui/src/widgets/text.rs delete mode 100644 crates/ui-egui/src/widgets/toggles.rs delete mode 100644 crates/ui-egui/src/widgets/wheel_stream.rs create mode 100644 crates/ui-egui/tests/fixtures/ui-production-toolbars.json delete mode 100644 crates/ui-egui/tests/font_wheel.rs diff --git a/.github/workflows/print.yml b/.github/workflows/print.yml index 058705ce29..8cdaf0cb28 100644 --- a/.github/workflows/print.yml +++ b/.github/workflows/print.yml @@ -25,7 +25,13 @@ jobs: uses: storytold/craft-common-actions/.github/workflows/gate.yml@main with: os: '["windows-2022"]' - timeout-minutes: 90 + # A change to Cargo.lock finds no cache (only main saves one) and builds everything cold: + # about 55 minutes for `-p vectorcraft` alone, then the UI crate's tests. + timeout-minutes: 150 + # As in ci.yml: test binaries without debug info or symbols, and workspace crates without + # line tables. A panic still names its file and line. + dev-strip: true + dev-debug: "0" # As before: printing builds and tests without craft-fonts, nextest or the wasm target. craft-fonts-ref: "" tools: "" diff --git a/AGENTS.md b/AGENTS.md index 11a86058f0..a8f8b84f7e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -77,7 +77,7 @@ For the crates you changed: `cargo fmt`, `cargo clippy -p --all-targets` ### Paths and conventions - `unsafe`: the workspace denies it. The desktop app's platform modules in `apps/vectorcraft/src/` call OS APIs that have no safe binding and allow it with a scoped `#[allow(unsafe_code)]`: the `mac_*.rs` and `windows_*.rs` files, `caps_lock.rs`, `clipboard.rs`, `cursor_theme.rs`, `display_profile.rs`, `host_services.rs`, `open_documents.rs`, `portal_save.rs` and `system_fonts.rs`. -- Attribution file: [`ASSETS.md`](ASSETS.md) (a row for every asset); licence texts next to the assets, summarised in `NOTICE`. Code-drawn defaults are preferred for swatches, brushes, cursors. +- Attribution file: [`ASSETS.md`](ASSETS.md) (a row for every asset); licence texts next to the assets, summarised in `NOTICE`. Code-drawn defaults are preferred for swatches, brushes, symbols and patterns. - Fonts: [storytold/craft-fonts](https://github.com/storytold/craft-fonts) through the optional `CRAFT_FONTS_DIR` build option, read by `crates/text/build.rs`; everything builds with it empty. - Crash handling: `vectorcraft_engine::guard` wraps every entry point. Hostile-input tests: `crates/engine/tests/{import_fuzz,command_sweep}.rs`, `crates/format/tests/prop_format.rs`, `crates/mcp/tests/protocol_props.rs`. - Large corpora: [storytold/photocraft-corpus](https://github.com/storytold/photocraft-corpus), fetched pinned and sha256-verified. diff --git a/ASSETS.md b/ASSETS.md index 2812067e00..c14753a7d9 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -20,7 +20,7 @@ Every non-code asset in this repository (icons, images, fonts, example art, colo **Policy (mandatory):** VectorCraft contains **no Adobe iconography, images, artwork, presets, swatch/brush/symbol/pattern libraries or ICC profiles**. Every asset is either original work by VectorCraft contributors, or third-party material under an open licence (OSI open source, public domain / CC0, or Creative Commons that allows redistribution), and it is attributed below. Screenshots of Adobe software are never committed. The one exception is the ArtCraft name, wordmark and logos in `docs/brand/`: ArtCraft trademarks, not open source, usable only under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt). -Generated-in-code art is original and has no file to list. This covers the default swatches, brushes, symbols, patterns, graphic styles, image-trace presets, the vector tool cursors (`crates/ui-egui/src/cursors.rs`) and the Learn panel's practice samples (`crates/ui-egui/src/panels/learn/samples.rs`). +Generated-in-code art is original and has no file to list. This covers the default swatches, brushes, symbols, patterns, graphic styles, image-trace presets and the Learn panel's practice samples (`crates/ui-egui/src/panels/learn/samples.rs`). **Font files are never committed here.** Fonts shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts). The small Latin UI/document fonts below predate that rule and stay. @@ -58,6 +58,23 @@ Generated-in-code art is original and has no file to list. This covers the defau | `packaging/macos/dmg/background.svg` | Xus Badia (contributed in #493) | Original artwork for VectorCraft's DMG window; links the app icon `assets/app-icon/vectorcraft-small.svg` | MIT OR Apache-2.0 (licensed by the contributor under the project licence) | DMG background source. Text in Inter and JetBrains Mono (OFL-1.1, `assets/fonts`), not embedded; paper grain generated by an SVG `feTurbulence` filter | | `packaging/macos/dmg/background.tiff` | Xus Badia (contributed in #493) | Rendered from `packaging/macos/dmg/background.svg` by `packaging/macos/dmg/generate.py` | MIT OR Apache-2.0 | 1x + 2x DMG background; includes the app icon (see its rows), text rendered from OFL-1.1 fonts and LittleCMS's built-in sRGB profile ("No copyright, use freely") | | `packaging/macos/dmg/DS_Store` | Xus Badia (layout, #493) | Written by `packaging/macos/dmg/generate.py` | MIT OR Apache-2.0 | Finder view settings for the DMG (window, icon size and positions, background alias); no machine data | +| `assets/cursors/cursor-anchor-point.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-direct-anchor-selected.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-direct-anchor.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-loaded-text-link.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-loaded-text.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-mark-bracket.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-mark-edge.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-mark-line-level.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-mark-line-rising.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-mark-ring.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-mark-square.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-mark-star.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-pen-convert.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-pen-curvature.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-pen-join.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-pen-new.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-reshape-segment.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/fonts/Inter-Medium.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface, not product iconography or artwork | | `assets/fonts/Inter-Regular.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface, not product iconography or artwork | | `assets/fonts/Inter-SemiBold.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface, not product iconography or artwork | @@ -95,6 +112,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/chevrons-left.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC; derived from Feather, also MIT (`assets/icons/LICENSE-lucide.txt`) | | | `assets/icons/chevrons-right.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC; derived from Feather, also MIT (`assets/icons/LICENSE-lucide.txt`) | | | `assets/icons/circle.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC; derived from Feather, also MIT (`assets/icons/LICENSE-lucide.txt`) | | +| `assets/icons/circle-off.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | | | `assets/icons/clipboard-paste.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | | | `assets/icons/cloud.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | | | `assets/icons/combine.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | | @@ -124,6 +142,8 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-artboard-options.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-artboards.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-blend.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-blend-align-page.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-blend-align-path.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-bloat.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-cap-butt.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-cap-round.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | @@ -160,6 +180,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-filter.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-flare.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-folder.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-free-distort.svg` | VectorCraft contributors | Original work, drawn for VectorCraft: a quadrilateral with a handle on each corner | MIT OR Apache-2.0 | | | `assets/icons/dc-free-transform.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-fx.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-gamut.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | diff --git a/Cargo.lock b/Cargo.lock index df20282409..2db5a4112b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -140,6 +140,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "alloc-no-stdlib" version = "2.0.4" @@ -176,6 +185,12 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" +[[package]] +name = "ambient-authority" +version = "0.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b" + [[package]] name = "android-activity" version = "0.6.1" @@ -210,6 +225,22 @@ dependencies = [ "libc", ] +[[package]] +name = "annotate-snippets" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710e8eae58854cdc1790fcb56cca04d712a17be849eeb81da2a724bf4bae2bc4" +dependencies = [ + "anstyle", + "unicode-width", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + [[package]] name = "anyhow" version = "1.0.104" @@ -489,6 +520,25 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "bindgen" +version = "0.72.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +dependencies = [ + "annotate-snippets", + "bitflags 2.13.2", + "cexpr", + "clang-sys", + "itertools 0.13.0", + "proc-macro2", + "quote", + "regex", + "rustc-hash 2.1.3", + "shlex 1.3.0", + "syn 2.0.119", +] + [[package]] name = "bit-set" version = "0.10.0" @@ -541,6 +591,12 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "block" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" + [[package]] name = "block-buffer" version = "0.10.4" @@ -674,6 +730,16 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "calendrical_calculations" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5abbd6eeda6885048d357edc66748eea6e0268e3dd11f326fff5bd248d779c26" +dependencies = [ + "core_maths", + "displaydoc", +] + [[package]] name = "calloop" version = "0.13.0" @@ -724,6 +790,24 @@ dependencies = [ "wayland-client", ] +[[package]] +name = "cap-primitives" +version = "4.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b5f74729fd2f44701d1a8eb47e906cdb3ccd9ec0f02baad85a744b791940b18" +dependencies = [ + "ambient-authority", + "fs-set-times", + "io-extras", + "io-lifetimes 3.0.1", + "ipnet", + "maybe-owned", + "rustix 1.1.6", + "rustix-linux-procfs", + "windows-sys 0.61.2", + "winx", +] + [[package]] name = "cc" version = "1.9.0" @@ -733,7 +817,16 @@ dependencies = [ "find-msvc-tools", "jobserver", "libc", - "shlex", + "shlex 2.0.1", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom 7.1.3", ] [[package]] @@ -747,6 +840,16 @@ dependencies = [ "web-time", ] +[[package]] +name = "cfg-expr" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd44d82755fb9210fb10d9daf8dd7e522da0efe1d5f263cffc5db07725663ff" +dependencies = [ + "smallvec", + "target-lexicon", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -803,6 +906,17 @@ dependencies = [ "inout", ] +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + [[package]] name = "clipboard-win" version = "5.4.3" @@ -915,6 +1029,12 @@ version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +[[package]] +name = "cookie-factory" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9885fa71e26b8ab7855e2ec7cae6e9b380edff76cd052e07c683a0319d51b3a2" + [[package]] name = "core-foundation" version = "0.9.4" @@ -965,6 +1085,19 @@ dependencies = [ "libc", ] +[[package]] +name = "core-graphics2" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b65858d95344d2711161cd92196732f67d6c5fea238cf12f994584828731a5c" +dependencies = [ + "bitflags 2.13.2", + "block", + "cfg-if", + "core-foundation 0.10.1", + "libc", +] + [[package]] name = "core_detect" version = "1.0.0" @@ -998,10 +1131,51 @@ dependencies = [ "libc", ] +[[package]] +name = "craft" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "craft-automation", + "craft-behavior", + "craft-browse", + "craft-cms", + "craft-color-ui", + "craft-dialogs", + "craft-draw", + "craft-font-catalog", + "craft-font-manager", + "craft-host", + "craft-i18n", + "craft-imaging", + "craft-keymap", + "craft-layers", + "craft-menu", + "craft-pages", + "craft-pdf", + "craft-platform", + "craft-print", + "craft-quit", + "craft-review", + "craft-settings", + "craft-table", + "craft-text", + "craft-theme", + "craft-theme-store", + "craft-timeline", + "craft-tracked", + "craft-ui", + "craft-update", + "craft-wayland", + "craft-window", + "egui", + "toml", +] + [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "crc32fast", "flate2", @@ -1009,19 +1183,105 @@ dependencies = [ "ruzstd", ] +[[package]] +name = "craft-appkit" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "block2 0.6.2", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "craft-atomic" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "rustix 1.1.6", +] + +[[package]] +name = "craft-automation" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "base64 0.22.1", + "craft-behavior", + "craft-control", + "craft-keymap", + "craft-platform", + "craft-theme", + "craft-ui", + "egui", + "getrandom 0.3.4", + "hmac", + "log", + "png 0.17.16", + "serde", + "serde_json", + "sha2", + "thiserror 2.0.21", + "web-time", +] + +[[package]] +name = "craft-behavior" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "accesskit", + "bitflags 2.13.2", + "craft-host", + "craft-keymap", + "craft-theme", + "craft-tracked", + "craft-ui-macros", + "emath", + "kurbo 0.13.1", + "serde", + "smallvec", +] + +[[package]] +name = "craft-browse" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "craft-behavior", + "craft-docpath", + "craft-host", + "craft-i18n", + "craft-platform", + "craft-settings", + "craft-theme", + "craft-ui", + "egui", + "kurbo 0.13.1", + "serde", +] + [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "crc32fast", "flate2", ] +[[package]] +name = "craft-cloud-ui" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "egui", +] + [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "md-5", "rayon", @@ -1030,25 +1290,102 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" + +[[package]] +name = "craft-color-ui" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "craft-behavior", + "craft-cms", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-platform", + "craft-settings", + "craft-theme", + "craft-ui", + "craft-window", + "egui", + "serde", + "serde_json", +] + +[[package]] +name = "craft-control" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "getrandom 0.3.4", + "serde", + "serde_json", +] [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "rayon", ] +[[package]] +name = "craft-dialogs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "block2 0.6.2", + "craft-atomic", + "craft-behavior", + "craft-browse", + "craft-host", + "craft-i18n", + "craft-platform", + "craft-ui", + "egui", + "futures-lite", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "raw-window-handle", + "rfd", + "serde_json", + "zbus", +] + [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "serde", +] + +[[package]] +name = "craft-draw" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "craft-behavior", + "craft-color-ui", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-settings", + "craft-theme", + "craft-ui", + "egui", + "kurbo 0.13.1", + "serde", + "serde_json", +] [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "craft-codepage", "encoding_rs", @@ -1060,13 +1397,14 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ + "fontique", "harfrust 0.13.3", "kurbo 0.13.1", "skrifa 0.47.0", @@ -1076,15 +1414,55 @@ dependencies = [ "windows-registry", ] +[[package]] +name = "craft-font-manager" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "craft-behavior", + "craft-font-catalog", + "craft-font-store", + "craft-fonts-build", + "craft-host", + "craft-i18n", + "craft-theme", + "craft-ui", + "egui", + "log", + "serde", + "skrifa 0.44.0", +] + +[[package]] +name = "craft-font-store" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "cap-primitives", + "craft-atomic", + "craft-font-catalog", + "flate2", + "log", + "ruzstd", + "serde", + "serde_json", + "sha2", + "skrifa 0.47.0", + "tar", + "thiserror 2.0.21", + "toml", + "ureq", +] + [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "gif", ] @@ -1092,17 +1470,34 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "flate2", ] +[[package]] +name = "craft-host" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "bitflags 2.13.2", + "craft-i18n", + "egui", + "serde", + "toml", + "web-time", +] + [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ + "chrono", "fixed_decimal", + "icu_calendar", + "icu_collator", + "icu_datetime", "icu_decimal", "icu_locale_core", "icu_locale_fallback", @@ -1112,6 +1507,7 @@ dependencies = [ "icu_provider", "icu_provider_adapters", "icu_provider_blob", + "icu_time", "log", "objc2-foundation 0.3.2", "sys-locale", @@ -1123,7 +1519,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "craft-dds", "craft-jpeg", @@ -1147,10 +1543,28 @@ dependencies = [ "zune-jpegxl", ] +[[package]] +name = "craft-imaging" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "craft-behavior", + "craft-color-ui", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-theme", + "craft-ui", + "egui", + "kurbo 0.13.1", + "serde", + "serde_json", +] + [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "thiserror 2.0.21", ] @@ -1158,7 +1572,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1169,8 +1583,45 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ + "craft-host", + "craft-i18n", + "craft-tracked", + "craft-ui-macros", + "craft-xml", + "egui", + "serde", + "serde_json", +] + +[[package]] +name = "craft-layers" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "craft-behavior", + "craft-i18n", + "craft-keymap", + "craft-theme", + "craft-ui", + "egui", + "serde", +] + +[[package]] +name = "craft-menu" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-quit", + "craft-theme", + "craft-ui", + "craft-window", "egui", "serde", "serde_json", @@ -1179,7 +1630,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1191,7 +1642,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "encoding_rs", "image", @@ -1202,28 +1653,74 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "chrono", "craft-codepage", "encoding_rs", ] +[[package]] +name = "craft-pages" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "craft-behavior", + "craft-keymap", + "craft-text", + "craft-theme", + "craft-ui", + "egui", + "kurbo 0.13.1", + "serde", +] + [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "hayro-interpret", "hayro-syntax", "krilla", + "serde", "thiserror 2.0.21", ] +[[package]] +name = "craft-platform" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "async-channel", + "async-io", + "async-process", + "core-graphics2", + "craft-atomic", + "craft-docpath", + "craft-host", + "craft-theme", + "futures-lite", + "js-sys", + "log", + "objc2-app-kit 0.3.2", + "rfd", + "serde", + "serde_json", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "web-time", + "windows", + "x11rb", + "xcap", + "zbus", +] + [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1232,13 +1729,22 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ + "craft-behavior", + "craft-host", + "craft-ui", "craft-winprint-gdi", + "egui", + "js-sys", "log", "miniz_oxide 0.9.1", "roxmltree 0.21.2", + "serde", + "serde_json", "tempfile", + "wasm-bindgen", + "web-sys", "winprint", "winsafe", ] @@ -1246,7 +1752,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1257,7 +1763,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "craft-eps", "flate2", @@ -1271,7 +1777,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "encoding_rs", "flate2", @@ -1279,10 +1785,56 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-quit" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "dispatch2", + "egui", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", +] + +[[package]] +name = "craft-review" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-pages", + "craft-theme", + "craft-ui", + "egui", + "image", + "kurbo 0.13.1", + "serde", +] + +[[package]] +name = "craft-settings" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "craft-atomic", + "craft-host", + "dirs", + "log", + "serde", + "serde_json", + "toml", + "toml_edit", + "web-sys", + "web-time", +] + [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "fax", "hayro-ccitt", @@ -1293,7 +1845,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "craft-image-codecs", "craft-xml", @@ -1311,47 +1863,279 @@ dependencies = [ "vectorcraft-pathops 0.18.0", ] +[[package]] +name = "craft-table" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "craft-behavior", + "craft-keymap", + "craft-theme", + "craft-ui", + "egui", +] + +[[package]] +name = "craft-text" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "craft-behavior", + "craft-font-manager", + "craft-host", + "craft-keymap", + "craft-theme", + "craft-ui", + "egui", + "hypher", + "miniz_oxide 0.8.9", + "regex", + "regex-syntax", + "serde", + "serde_json", + "unicode-bidi", + "unicode-bidi-mirroring", + "unicode-general-category", + "unicode-linebreak", + "unicode-segmentation", +] + +[[package]] +name = "craft-theme" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "bitflags 2.13.2", + "craft-tracked", + "craft-ui-macros", + "ecolor", + "log", + "serde", + "serde_json", + "smallvec", +] + +[[package]] +name = "craft-theme-store" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "craft-atomic", + "craft-behavior", + "craft-theme", + "craft-ui", + "dirs", + "egui", + "serde", + "serde_json", +] + [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "serde", "thiserror 2.0.21", "tiff", ] +[[package]] +name = "craft-time" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-timeline" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "craft-behavior", + "craft-keymap", + "craft-theme", + "craft-time", + "craft-ui", + "egui", + "serde", + "web-time", +] + +[[package]] +name = "craft-tracked" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" + [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ - "craft-fonts-build", + "craft-cloud-ui", + "craft-ui-canvas", + "craft-ui-contract", + "craft-ui-panels", + "craft-ui-patterns", + "craft-ui-shell", + "craft-ui-widgets", +] + +[[package]] +name = "craft-ui-canvas" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "craft-behavior", "craft-i18n", + "craft-keymap", + "craft-theme", + "craft-ui-macros", + "craft-ui-panels", "egui", - "epaint", - "js-sys", - "log", - "objc2 0.6.5", - "objc2-app-kit 0.3.2", - "objc2-foundation 0.3.2", "serde", + "serde_json", +] + +[[package]] +name = "craft-ui-contract" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "accesskit", + "craft-behavior", + "craft-codepage", + "craft-font-catalog", + "craft-fonts-build", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-platform", + "craft-quit", + "craft-settings", + "craft-svg", + "craft-theme", + "craft-tracked", + "craft-ui-macros", + "craft-window", + "egui", + "epaint_default_fonts", + "flate2", + "inventory", + "log", + "scoped-tls", + "serde", + "serde_json", + "siphasher", "skrifa 0.44.0", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", + "smallvec", + "toml", + "typeid", + "web-time", +] + +[[package]] +name = "craft-ui-macros" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "craft-ui-panels" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-quit", + "craft-theme", + "craft-ui-macros", + "craft-ui-widgets", + "egui", + "serde", + "serde_json", +] + +[[package]] +name = "craft-ui-patterns" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-pdf", + "craft-theme", + "craft-ui-macros", + "craft-ui-panels", + "egui", + "serde", + "serde_json", + "toml", + "toml_edit", + "zeroize", +] + +[[package]] +name = "craft-ui-shell" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-platform", + "craft-svg", + "craft-theme", + "craft-ui-macros", + "craft-ui-panels", + "craft-window", + "eframe", + "egui", + "raw-window-handle", + "serde", + "web-time", +] + +[[package]] +name = "craft-ui-widgets" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-theme", + "craft-ui-contract", + "craft-ui-macros", + "egui", + "serde", + "smallvec", ] [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "chrono", + "craft-host", + "craft-theme", + "craft-ui", "dunce", "egui", "flate2", - "getrandom 0.3.4", "image", "log", "plist", @@ -1372,7 +2156,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "flate2", "serde", @@ -1380,10 +2164,20 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-wayland" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "raw-window-handle", + "wayland-backend", + "wayland-client", +] + [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "js-sys", "serde_json", @@ -1391,15 +2185,36 @@ dependencies = [ "wasm-bindgen-futures", ] +[[package]] +name = "craft-win32" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" +dependencies = [ + "winsafe", +] + [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ + "craft-appkit", + "craft-atomic", + "craft-behavior", + "craft-host", + "craft-settings", + "craft-win32", "egui", + "muda", "objc2 0.6.5", "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "raw-window-handle", + "serde", + "serde_json", "wayland-client", + "winsafe", + "x11rb", ] [[package]] @@ -1413,7 +2228,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "quick-xml 0.41.0", "serde", @@ -1554,6 +2369,28 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", + "subtle", +] + +[[package]] +name = "dirs" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.59.0", ] [[package]] @@ -1615,6 +2452,61 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +[[package]] +name = "drm" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bc8c5c6c2941f70a55c15f8d9f00f9710ebda3ffda98075f996a0e6c92756f" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "drm-ffi", + "drm-fourcc", + "libc", + "rustix 0.38.44", +] + +[[package]] +name = "drm" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a41816e58f47f49acfd956651055ddcf137c4882c2098c30c448817af21183a" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "bytemuck_derive", + "drm-ffi", + "drm-fourcc", + "libc", + "rustix 1.1.6", +] + +[[package]] +name = "drm-ffi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51a91c9b32ac4e8105dec255e849e0d66e27d7c34d184364fb93e469db08f690" +dependencies = [ + "drm-sys", + "rustix 1.1.6", +] + +[[package]] +name = "drm-fourcc" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0aafbcdb8afc29c1a7ee5fbe53b5d62f4565b35a042a662ca9fecd0b54dae6f4" + +[[package]] +name = "drm-sys" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8e1361066d91f5ffccff060a3c3be9c3ecde15be2959c1937595f7a82a9f8" +dependencies = [ + "libc", + "linux-raw-sys 0.9.4", +] + [[package]] name = "dunce" version = "1.0.5" @@ -1624,7 +2516,7 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "bytemuck", "emath", @@ -1633,7 +2525,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "ahash", "bytemuck", @@ -1668,14 +2560,14 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "accesskit", "ahash", "bitflags 2.13.2", "emath", "epaint", - "itertools", + "itertools 0.15.0", "log", "nohash-hasher", "profiling", @@ -1687,7 +2579,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "ahash", "bytemuck", @@ -1706,7 +2598,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "accesskit_winit", "arboard", @@ -1731,12 +2623,12 @@ dependencies = [ [[package]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "ahash", "egui", "enum-map", - "itertools", + "itertools 0.15.0", "log", "profiling", "resvg 0.45.1", @@ -1745,7 +2637,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "bytemuck", "egui", @@ -1758,7 +2650,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "dify", "eframe", @@ -1784,11 +2676,23 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "bytemuck", ] +[[package]] +name = "embedded-io" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced" + +[[package]] +name = "embedded-io" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" + [[package]] name = "encoding_rs" version = "0.8.42" @@ -1853,7 +2757,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "ahash", "bytemuck", @@ -1879,7 +2783,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" [[package]] name = "equivalent" @@ -2103,6 +3007,28 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "fontique" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6688bc1294fe7117d788937b6c53480169b29c566954af490830d4c09da9516a" +dependencies = [ + "hashbrown 0.17.1", + "linebender_resource_handle", + "memmap2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-text", + "objc2-foundation 0.3.2", + "parlance", + "read-fonts 0.41.0", + "roxmltree 0.21.2", + "smallvec", + "windows", + "windows-core", + "yeslogic-fontconfig-sys", +] + [[package]] name = "foreign-types" version = "0.5.0" @@ -2139,6 +3065,17 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs-set-times" +version = "0.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a" +dependencies = [ + "io-lifetimes 2.0.4", + "rustix 1.1.6", + "windows-sys 0.52.0", +] + [[package]] name = "fs_extra" version = "1.3.0" @@ -2219,6 +3156,30 @@ dependencies = [ "slab", ] +[[package]] +name = "gbm" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce852e998d3ca5e4a97014fb31c940dc5ef344ec7d364984525fd11e8a547e6a" +dependencies = [ + "bitflags 2.13.2", + "drm 0.14.1", + "drm-fourcc", + "gbm-sys", + "libc", + "wayland-backend", + "wayland-server", +] + +[[package]] +name = "gbm-sys" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c13a5f2acc785d8fb6bf6b7ab6bfb0ef5dad4f4d97e8e70bb8e470722312f76f" +dependencies = [ + "libc", +] + [[package]] name = "generic-array" version = "0.14.7" @@ -2297,6 +3258,15 @@ dependencies = [ "weezl 0.1.12", ] +[[package]] +name = "gl" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a94edab108827d67608095e269cf862e60d920f144a5026d3dbcfd8b877fb404" +dependencies = [ + "gl_generator", +] + [[package]] name = "gl_generator" version = "0.14.0" @@ -2325,6 +3295,12 @@ dependencies = [ "vello_common", ] +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + [[package]] name = "glow" version = "0.17.0" @@ -2520,7 +3496,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "brotli", "hayro-postscript", @@ -2529,7 +3505,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -2547,7 +3523,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -2565,12 +3541,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "flate2", "hayro-ccitt", @@ -2610,6 +3586,15 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + [[package]] name = "http" version = "1.5.0" @@ -2711,6 +3696,12 @@ dependencies = [ "windows-registry", ] +[[package]] +name = "hypher" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45f2b4f6b5da34d400d4c112eadcc14512cc5d04307a8eee182586d9bebd7ce6" + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -2735,6 +3726,39 @@ dependencies = [ "cc", ] +[[package]] +name = "icu_calendar" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58655df2f728e46e4eee80bddebefacf52ec3e77cdb925014b47c5a5905eb55c" +dependencies = [ + "calendrical_calculations", + "displaydoc", + "icu_locale_core", + "icu_provider", + "serde", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_collator" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08984ed58ac439ebf3e13d2cf26b0c46a60afcd21721c1d14087c0b240344dda" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_normalizer", + "icu_properties", + "icu_provider", + "serde", + "smallvec", + "utf16_iter", + "utf8_iter", + "zerovec", +] + [[package]] name = "icu_collections" version = "2.3.0" @@ -2743,12 +3767,37 @@ checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" dependencies = [ "displaydoc", "potential_utf", + "serde", "utf8_iter", "yoke", "zerofrom", "zerovec", ] +[[package]] +name = "icu_datetime" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c44df99c4c5297b05653d1a1629f13bdc9fd4044acfbbaf30b15194a1eed4cd6" +dependencies = [ + "displaydoc", + "fixed_decimal", + "icu_calendar", + "icu_decimal", + "icu_locale_core", + "icu_pattern", + "icu_plurals", + "icu_provider", + "icu_time", + "potential_utf", + "serde", + "smallvec", + "tinystr", + "writeable", + "zerotrie", + "zerovec", +] + [[package]] name = "icu_decimal" version = "2.3.0" @@ -2810,6 +3859,7 @@ dependencies = [ "icu_normalizer_data", "icu_properties", "icu_provider", + "serde", "smallvec", "utf16_iter", "utf8_iter", @@ -2860,6 +3910,7 @@ dependencies = [ "icu_locale_core", "icu_properties_data", "icu_provider", + "serde", "zerotrie", "zerovec", ] @@ -2935,6 +3986,22 @@ version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae293c039020f9ec10710af98d29ce6aa2051486638b49c9a6409f3b4a9e98ad" +[[package]] +name = "icu_time" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af37e1c3b9f3ab564b619fdf4b22de169f6381eb0f7048e3ca454290c438126b" +dependencies = [ + "calendrical_calculations", + "displaydoc", + "icu_calendar", + "icu_locale_core", + "icu_provider", + "serde", + "zerotrie", + "zerovec", +] + [[package]] name = "idna" version = "1.1.0" @@ -3023,6 +4090,37 @@ dependencies = [ "generic-array", ] +[[package]] +name = "inventory" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6928282826c822ad91bf1c9a1cb90a30ba1c26770749929b4656cd6be829cd7c" +dependencies = [ + "rustversion", +] + +[[package]] +name = "io-extras" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f" +dependencies = [ + "io-lifetimes 3.0.1", + "windows-sys 0.52.0", +] + +[[package]] +name = "io-lifetimes" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983" + +[[package]] +name = "io-lifetimes" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96" + [[package]] name = "ipnet" version = "2.12.2" @@ -3048,6 +4146,15 @@ dependencies = [ "once_cell", ] +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + [[package]] name = "itertools" version = "0.15.0" @@ -3370,7 +4477,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "base64 0.22.1", "bumpalo", @@ -3470,6 +4577,54 @@ dependencies = [ "redox_syscall 0.9.5", ] +[[package]] +name = "libspa" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "882f7427e7989dcc9d388b7f05c4630390a1d7696f9ffa469cd4a7a48f0b4c40" +dependencies = [ + "bitflags 2.13.2", + "cc", + "cookie-factory", + "libc", + "libspa-sys", + "nom 8.0.0", + "rustix 1.1.6", + "system-deps", +] + +[[package]] +name = "libspa-sys" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b6e17bdaf63ed0d5e4144022624032b41fd9733112e8c74ac26fc9bf1291924" +dependencies = [ + "bindgen", + "cc", + "system-deps", +] + +[[package]] +name = "libwayshot-xcap" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea8a46e4d016ef464e386e4970f5415fe0939c2d63abe0c2f539c05ef88c5fe5" +dependencies = [ + "drm 0.15.0", + "gbm", + "gl", + "image", + "khronos-egl", + "memmap2", + "rustix 1.1.6", + "thiserror 2.0.21", + "tracing", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", +] + [[package]] name = "linebender_resource_handle" version = "0.1.1" @@ -3479,7 +4634,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=205042e406b630cda653990649264a78fea6296b#205042e406b630cda653990649264a78fea6296b" +source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -3494,6 +4649,12 @@ version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" +[[package]] +name = "linux-raw-sys" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -3536,6 +4697,12 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" +[[package]] +name = "maybe-owned" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4" + [[package]] name = "md-5" version = "0.10.6" @@ -3576,6 +4743,12 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -3749,6 +4922,16 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + [[package]] name = "nom" version = "8.0.0" @@ -3831,8 +5014,8 @@ dependencies = [ "block2 0.5.1", "libc", "objc2 0.5.3", - "objc2-core-data", - "objc2-core-image", + "objc2-core-data 0.2.2", + "objc2-core-image 0.2.2", "objc2-foundation 0.2.2", "objc2-quartz-core 0.2.2", ] @@ -3845,13 +5028,51 @@ checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" dependencies = [ "bitflags 2.13.2", "block2 0.6.2", + "libc", "objc2 0.6.5", + "objc2-cloud-kit 0.3.2", + "objc2-core-data 0.3.2", "objc2-core-foundation", "objc2-core-graphics", + "objc2-core-image 0.3.2", + "objc2-core-text", + "objc2-core-video", "objc2-foundation 0.3.2", "objc2-quartz-core 0.3.2", ] +[[package]] +name = "objc2-av-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "478ae33fcac9df0a18db8302387c666b8ef08a3e2d62b510ca4fc278a384b6c0" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "dispatch2", + "objc2 0.6.5", + "objc2-avf-audio", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-image 0.3.2", + "objc2-core-video", + "objc2-foundation 0.3.2", + "objc2-image-io", + "objc2-media-toolbox", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "objc2-avf-audio" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13a380031deed8e99db00065c45937da434ca987c034e13b87e4441f9e4090be" +dependencies = [ + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-cloud-kit" version = "0.2.2" @@ -3865,6 +5086,17 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-cloud-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-contacts" version = "0.2.2" @@ -3876,6 +5108,28 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-core-audio" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2" +dependencies = [ + "dispatch2", + "objc2 0.6.5", + "objc2-core-audio-types", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-core-audio-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", +] + [[package]] name = "objc2-core-data" version = "0.2.2" @@ -3888,6 +5142,17 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-core-data" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-core-foundation" version = "0.3.2" @@ -3895,7 +5160,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ "bitflags 2.13.2", + "block2 0.6.2", "dispatch2", + "libc", "objc2 0.6.5", ] @@ -3906,10 +5173,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" dependencies = [ "bitflags 2.13.2", + "block2 0.6.2", "dispatch2", + "libc", "objc2 0.6.5", "objc2-core-foundation", "objc2-io-surface", + "objc2-metal 0.3.2", ] [[package]] @@ -3924,6 +5194,16 @@ dependencies = [ "objc2-metal 0.2.2", ] +[[package]] +name = "objc2-core-image" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006" +dependencies = [ + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-core-location" version = "0.2.2" @@ -3936,13 +5216,47 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-core-media" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05ec576860167a15dd9fce7fbee7512beb4e31f532159d3482d1f9c6caedf31d" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "dispatch2", + "objc2 0.6.5", + "objc2-core-audio", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-core-video", +] + [[package]] name = "objc2-core-text" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", "objc2-core-foundation", + "objc2-core-graphics", +] + +[[package]] +name = "objc2-core-video" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-io-surface", + "objc2-metal 0.3.2", ] [[package]] @@ -3972,10 +5286,22 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ "bitflags 2.13.2", "block2 0.6.2", + "libc", "objc2 0.6.5", "objc2-core-foundation", ] +[[package]] +name = "objc2-image-io" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32b0446e98cf4a784cc7a0177715ff317eeaa8463841c616cfc78aa4f953c4ea" +dependencies = [ + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", +] + [[package]] name = "objc2-io-surface" version = "0.3.2" @@ -3999,6 +5325,18 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-media-toolbox" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd9fdde720df3da7046bb9097811000c1e7ab5cd579fa89d96b27d56781fb30" +dependencies = [ + "objc2 0.6.5", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-core-media", +] + [[package]] name = "objc2-metal" version = "0.2.2" @@ -4069,9 +5407,9 @@ dependencies = [ "bitflags 2.13.2", "block2 0.5.1", "objc2 0.5.3", - "objc2-cloud-kit", - "objc2-core-data", - "objc2-core-image", + "objc2-cloud-kit 0.2.2", + "objc2-core-data 0.2.2", + "objc2-core-image 0.2.2", "objc2-core-location", "objc2-foundation 0.2.2", "objc2-link-presentation", @@ -4139,6 +5477,12 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + [[package]] name = "orbclient" version = "0.3.55" @@ -4216,6 +5560,12 @@ dependencies = [ "windows-link", ] +[[package]] +name = "parlance" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73072a9470554c8e794778acece2312661218aaabb635600957d952cf01c716e" + [[package]] name = "pdf-writer" version = "0.15.0" @@ -4405,6 +5755,31 @@ dependencies = [ "futures-io", ] +[[package]] +name = "pipewire" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bde71084c4e25959d68f1ea54daa75e5ecdb338e5caf0b5510143b79baa32d5c" +dependencies = [ + "bitflags 2.13.2", + "libc", + "libspa", + "libspa-sys", + "pipewire-sys", + "rustix 1.1.6", +] + +[[package]] +name = "pipewire-sys" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce653f53e63e5b93853218092ee9a8906a5d082c92f3f1db26316955dd63ce0" +dependencies = [ + "bindgen", + "libspa-sys", + "system-deps", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -4513,6 +5888,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24" dependencies = [ "cobs", + "embedded-io 0.4.0", + "embedded-io 0.6.1", "serde", ] @@ -4885,6 +6262,39 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror 2.0.21", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + [[package]] name = "regex-syntax" version = "0.8.11" @@ -4992,9 +6402,6 @@ dependencies = [ "raw-window-handle", "wasm-bindgen", "wasm-bindgen-futures", - "wayland-backend", - "wayland-client", - "wayland-protocols", "web-sys", "windows-sys 0.61.2", ] @@ -5084,6 +6491,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustix-linux-procfs" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056" +dependencies = [ + "once_cell", + "rustix 1.1.6", +] + [[package]] name = "rustls" version = "0.23.46" @@ -5409,6 +6826,12 @@ dependencies = [ "digest", ] +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + [[package]] name = "shlex" version = "2.0.1" @@ -5978,6 +7401,19 @@ dependencies = [ "libc", ] +[[package]] +name = "system-deps" +version = "7.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7" +dependencies = [ + "cfg-expr", + "heck", + "pkg-config", + "toml", + "version-compare", +] + [[package]] name = "tar" version = "0.4.46" @@ -5995,6 +7431,12 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5" +[[package]] +name = "target-lexicon" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + [[package]] name = "tempfile" version = "3.27.0" @@ -6269,8 +7711,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" dependencies = [ "indexmap", + "serde_core", + "serde_spanned", "toml_datetime", "toml_parser", + "toml_writer", "winnow", ] @@ -6373,7 +7818,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" dependencies = [ "memchr", - "nom", + "nom 8.0.0", "petgraph", ] @@ -6407,6 +7852,12 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + [[package]] name = "typenum" version = "1.20.1" @@ -6460,6 +7911,12 @@ version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "unicode-linebreak" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" + [[package]] name = "unicode-normalization" version = "0.1.26" @@ -6526,6 +7983,7 @@ dependencies = [ "rustls-platform-verifier", "ureq-proto", "utf8-zero", + "webpki-roots", ] [[package]] @@ -6639,15 +8097,12 @@ dependencies = [ "block2 0.6.2", "chrono", "clipboard-win", - "craft-print", - "craft-update", - "craft-window", + "craft", "eframe", "egui", - "futures-lite", + "egui_extras", "image", "log", - "muda", "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-core-foundation", @@ -6657,7 +8112,6 @@ dependencies = [ "objc2-quartz-core 0.3.2", "pollster 1.0.1", "raw-window-handle", - "rfd", "rustix 1.1.6", "serde_json", "socket2", @@ -6669,7 +8123,6 @@ dependencies = [ "wayland-backend", "wayland-client", "wayland-protocols", - "webbrowser", "windows", "winit", "winreg", @@ -6757,6 +8210,8 @@ name = "vectorcraft-color" version = "0.24.1" dependencies = [ "craft-cms", + "craft-color-ui", + "craft-theme", "kurbo 0.13.1", "moxcms", "proptest", @@ -6936,7 +8391,6 @@ dependencies = [ "proptest", "serde", "serde_json", - "thiserror 2.0.21", "vectorcraft-testkit", ] @@ -6954,6 +8408,7 @@ dependencies = [ name = "vectorcraft-mcp" version = "0.24.1" dependencies = [ + "craft", "craft-image-codecs", "image", "log", @@ -7015,8 +8470,8 @@ version = "0.24.1" dependencies = [ "aes", "chrono", + "craft", "craft-image-codecs", - "craft-pdf", "craft-stream-codecs", "craft-xml", "flate2", @@ -7160,7 +8615,8 @@ dependencies = [ name = "vectorcraft-text" version = "0.24.1" dependencies = [ - "craft-font-catalog", + "craft", + "craft-fonts-build", "craft-proof", "harfrust 0.13.3", "icu_segmenter", @@ -7177,7 +8633,6 @@ dependencies = [ "vectorcraft-doc", "vectorcraft-geom 0.24.1", "vello_cpu", - "windows-registry", "write-fonts", ] @@ -7226,10 +8681,8 @@ version = "0.24.1" dependencies = [ "bytemuck", "chrono", + "craft", "craft-image-codecs", - "craft-keymap", - "craft-ui", - "craft-update", "egui", "egui_extras", "egui_kittest", @@ -7265,12 +8718,13 @@ dependencies = [ name = "vectorcraft-web" version = "0.24.1" dependencies = [ + "craft", "craft-web-api", "eframe", "egui", + "egui_extras", "js-sys", "log", - "rfd", "serde_json", "vectorcraft-engine", "vectorcraft-format", @@ -7324,6 +8778,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "version-compare" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" + [[package]] name = "version_check" version = "0.9.5" @@ -7645,6 +9105,19 @@ dependencies = [ "quote", ] +[[package]] +name = "wayland-server" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dde9c29be0f723a573977de51ee455bf3dfa03652730a74f9dd3b337e374d75" +dependencies = [ + "bitflags 2.13.2", + "downcast-rs", + "rustix 1.1.6", + "wayland-backend", + "wayland-scanner", +] + [[package]] name = "wayland-sys" version = "0.31.11" @@ -7652,7 +9125,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" dependencies = [ "dlib", + "libc", "log", + "memoffset", "once_cell", "pkg-config", ] @@ -7677,22 +9152,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "webbrowser" -version = "1.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2c8ddfbbf66e501434657400268cefe51b95140a0266236415cda7627732df7" -dependencies = [ - "jni", - "log", - "ndk-context", - "objc2 0.6.5", - "objc2-app-kit 0.3.2", - "objc2-foundation 0.3.2", - "url", - "web-sys", -] - [[package]] name = "webpki-root-certs" version = "1.0.11" @@ -7702,6 +9161,15 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "weezl" version = "0.1.12" @@ -7897,6 +9365,12 @@ dependencies = [ "web-sys", ] +[[package]] +name = "widestring" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471" + [[package]] name = "winapi-util" version = "0.1.11" @@ -8226,6 +9700,16 @@ version = "0.0.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ef0ffc427f045c0cc9ebffd6f4f91153dcd2a1547b5c3c29ee3f541e16e95c6" +[[package]] +name = "winx" +version = "0.36.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d" +dependencies = [ + "bitflags 2.13.2", + "windows-sys 0.52.0", +] + [[package]] name = "wit-bindgen" version = "0.57.1" @@ -8345,6 +9829,48 @@ dependencies = [ "rustix 1.1.6", ] +[[package]] +name = "xcap" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da270fd7c8581d43d731cb690bcc791fc0a7b3bc96e131a4b6552d0379640a9e" +dependencies = [ + "dispatch2", + "image", + "libwayshot-xcap", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-av-foundation", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-media", + "objc2-core-video", + "objc2-foundation 0.3.2", + "percent-encoding", + "pipewire", + "rand", + "scopeguard", + "serde", + "thiserror 2.0.21", + "url", + "widestring", + "windows", + "xcb", + "zbus", +] + +[[package]] +name = "xcb" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6c2ad15e0e922856ee89afe862b8992334bbe7953adad56cd1199358cb30566" +dependencies = [ + "bitflags 2.13.2", + "libc", + "quick-xml 0.41.0", +] + [[package]] name = "xcursor" version = "0.3.11" @@ -8401,6 +9927,17 @@ dependencies = [ "serde_json", ] +[[package]] +name = "yeslogic-fontconfig-sys" +version = "6.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d8b8abf912b9a29ff112e1671c97c33636903d13a69712037190e6805af4f76" +dependencies = [ + "dlib", + "once_cell", + "pkg-config", +] + [[package]] name = "yoke" version = "0.8.3" @@ -8733,14 +10270,14 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" diff --git a/Cargo.toml b/Cargo.toml index 9dd7f32154..bbc2a8bc2d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,44 +11,44 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b", default-features = false, features = ["interpret", "write"] } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b", features = ["serde"] } -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } -# Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per -# desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b", features = ["egui"] } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } -# craft-update: app-specific pretend versions apply to startup and manual checks. +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "205042e406b630cda653990649264a78fea6296b", features = ["egui"] } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } +# The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names +# the members it imports. +craft = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } +# Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui +# without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes. +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -191,25 +191,25 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +emath = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 533074b9b5..6b4e0b8344 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -321,11 +321,13 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> { Box::new(accepting_grants(with_stores(Headless::with_document()), allow_grants)) } else if let Some(addr) = connect { // Explicit address: fail loudly if the app isn't there. - Box::new(Remote::connect(&addr).map_err(|e| format!("cannot connect to {addr}: {e}"))?) + let token = vectorcraft_mcp::control_token()?; + Box::new(Remote::connect(&addr, &token).map_err(|e| format!("cannot connect to {addr}: {e}"))?) } else { - match Remote::connect(DEFAULT_ADDR) { - Ok(r) => Box::new(r), - Err(_) => Box::new(with_stores(Headless::with_document())), + // No token or no app listening: the headless session answers instead. + match vectorcraft_mcp::control_token().ok().and_then(|token| Remote::connect(DEFAULT_ADDR, &token).ok()) { + Some(r) => Box::new(r), + None => Box::new(with_stores(Headless::with_document())), } }; eprintln!("vectorcraft-cli: MCP server on stdio ({})", backend.describe()); diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 515793665c..780259f957 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -16,17 +16,19 @@ path = "src/main.rs" [dependencies] vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] } vectorcraft-ui-egui = { workspace = true } -# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "205042e406b630cda653990649264a78fea6296b", version = "0.1.0" } vectorcraft-format = { workspace = true } vectorcraft-text = { workspace = true } +craft = { workspace = true, features = ["ui", "keymap", "automation", "platform"] } egui = { workspace = true } +egui_extras = { workspace = true } log = { workspace = true } [target.'cfg(target_arch = "wasm32")'.dependencies] # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } -rfd = { workspace = true, features = ["file-handle-inner"] } +# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0", version = "0.1.0" } + wasm-bindgen = "0.2" serde_json = { workspace = true } wasm-bindgen-futures = "0.4" diff --git a/apps/vectorcraft-web/src/api.rs b/apps/vectorcraft-web/src/api.rs index 1be921baf3..933de308cf 100644 --- a/apps/vectorcraft-web/src/api.rs +++ b/apps/vectorcraft-web/src/api.rs @@ -26,10 +26,10 @@ use std::pin::Pin; use std::rc::Rc; use std::sync::mpsc::{Receiver, Sender, TryRecvError}; +use craft::automation::{ControlRequest, Dispatch}; use craft_web_api::methods::Methods; use craft_web_api::page::{PageApi, Request}; use serde_json::{Value, json}; -use vectorcraft_ui_egui::{ControlRequest, ControlTicket as Ticket}; use wasm_bindgen::prelude::*; use wasm_bindgen_futures::{JsFuture, future_to_promise}; @@ -92,7 +92,7 @@ const POLL_MS: i32 = 16; /// timeout fired) gives the request up if the app has not started it, so the app never runs it late. struct Waiting { reply: Receiver, - ticket: Ticket, + dispatch: Dispatch, answered: bool, } @@ -116,7 +116,7 @@ impl Waiting { impl Drop for Waiting { fn drop(&mut self) { if !self.answered { - self.ticket.give_up(); + self.dispatch.give_up(); } } } @@ -125,13 +125,13 @@ impl Drop for Waiting { /// `{ok: false, error}` object. fn send(method: &str, params: Value) -> Pin>> { let (req, rx) = ControlRequest::new(method, params); - let ticket = req.ticket(); + let dispatch = req.dispatch.clone(); let sent = TX.with(|t| t.borrow().as_ref().is_some_and(|tx| tx.send(req).is_ok())); if !sent { return Box::pin(async { json!({"ok": false, "error": "VectorCraft is not running yet"}) }); } repaint(); - let mut waiting = Waiting { reply: rx, ticket, answered: false }; + let mut waiting = Waiting { reply: rx, dispatch, answered: false }; Box::pin(async move { loop { if let Some(reply) = waiting.poll() { diff --git a/apps/vectorcraft-web/src/demand.rs b/apps/vectorcraft-web/src/demand.rs deleted file mode 100644 index 7583248701..0000000000 --- a/apps/vectorcraft-web/src/demand.rs +++ /dev/null @@ -1,139 +0,0 @@ -//! Which `demand` web faces (`crates/text/web-fonts.txt`) to fetch: each face is fetched at most -//! once at a time and never again once it loaded. A face whose fetch failed is fetched again after -//! a wait that doubles with each failure, and not after [`MAX_TRIES`] failures. - -/// The wait after a face's first failed fetch before it is fetched again (ms). -const RETRY_MS: i32 = 30_000; -/// Failed fetches of a face after which it is not fetched again this session. -pub(crate) const MAX_TRIES: u32 = 5; - -#[derive(Clone, Copy, Debug, PartialEq)] -enum State { - Idle, - /// Being fetched, after `tries` failed fetches. - Loading { - tries: u32, - }, - Loaded, - /// `tries` fetches failed, the last at `failed_at` (ms); the next may start at `retry_at`, or - /// at once when the clock reads earlier than `failed_at`. - Failed { - tries: u32, - failed_at: f64, - retry_at: f64, - }, -} - -/// The fetch state of each face of a web font list, by index. -#[derive(Debug, Default)] -pub(crate) struct Demand { - states: Vec, -} - -impl Demand { - /// Of the faces `wanted` (indexes into the list), the ones to fetch at time `now` (ms): not - /// loaded, not being fetched, and not waiting to be fetched again. They are marked as being - /// fetched. - pub(crate) fn start(&mut self, wanted: &[usize], now: f64) -> Vec { - let mut out = Vec::new(); - for &i in wanted { - if self.states.len() <= i { - self.states.resize(i + 1, State::Idle); - } - let Some(state) = self.states.get_mut(i) else { continue }; - let tries = match *state { - State::Idle => Some(0), - State::Loading { .. } | State::Loaded => None, - State::Failed { tries, failed_at, retry_at } => (tries < MAX_TRIES && (now >= retry_at || now < failed_at)).then_some(tries), - }; - if let Some(tries) = tries { - *state = State::Loading { tries }; - out.push(i); - } - } - out - } - - /// The fetch of face `i` started by [`Demand::start`] ended at `now` (ms): loaded when `ok`. - /// Returns the wait (ms) after which a failed face may be fetched again, or `None` when it - /// loaded or has failed [`MAX_TRIES`] times. - pub(crate) fn finished(&mut self, i: usize, ok: bool, now: f64) -> Option { - let state = self.states.get_mut(i)?; - let State::Loading { tries } = *state else { return None }; - if ok { - *state = State::Loaded; - return None; - } - let tries = tries + 1; - let wait = RETRY_MS << (tries - 1).min(4); - *state = State::Failed { tries, failed_at: now, retry_at: now + f64::from(wait) }; - (tries < MAX_TRIES).then_some(wait) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_face_is_fetched_once_and_kept() { - let mut d = Demand::default(); - assert_eq!(d.start(&[2], 0.0), [2]); - assert!(d.start(&[2], 1.0).is_empty(), "already being fetched"); - assert_eq!(d.finished(2, true, 2.0), None, "loaded: no retry"); - assert!(d.start(&[2], 1e9).is_empty(), "loaded: never fetched again"); - assert_eq!(d.start(&[0, 2, 1], 3.0), [0, 1], "other faces start on their own"); - assert_eq!(d.finished(7, false, 4.0), None, "a face never started"); - } - - #[test] - fn a_failed_face_waits_longer_after_each_failure_and_then_stops() { - let mut d = Demand::default(); - let mut now = 0.0; - // The wait after the 1st, 2nd, ... failure: doubling, up to 16 times the first. - for wait in [1, 2, 4, 8].map(|k| k * RETRY_MS) { - assert_eq!(d.start(&[0], now), [0], "at {now}"); - assert_eq!(d.finished(0, false, now), Some(wait), "the wait after the failure at {now}"); - assert!(d.start(&[0], now + f64::from(wait) - 1.0).is_empty(), "waits {wait} ms after the failure at {now}"); - now += f64::from(wait); - } - // The fifth fetch, and after it fails, none. - assert_eq!(d.start(&[0], now), [0]); - assert_eq!(d.finished(0, false, now), None, "no retry after {MAX_TRIES} failures"); - assert!(d.start(&[0], now + 1e12).is_empty(), "no fetch after {MAX_TRIES} failures"); - // A later success after failures keeps the face. - let mut d = Demand::default(); - d.start(&[1], 0.0); - assert_eq!(d.finished(1, false, 0.0), Some(RETRY_MS)); - assert_eq!(d.start(&[1], f64::from(RETRY_MS)), [1]); - assert_eq!(d.finished(1, true, f64::from(RETRY_MS)), None); - assert!(d.start(&[1], 1e12).is_empty()); - } - - /// While a face is fetched again after a failure, neither the interface asking for its script - /// again nor the retry timer starts a second fetch of it. - #[test] - fn a_face_being_fetched_again_is_not_fetched_twice_at_once() { - let mut d = Demand::default(); - d.start(&[0], 0.0); - assert_eq!(d.finished(0, false, 0.0), Some(RETRY_MS)); - let retry = f64::from(RETRY_MS); - assert_eq!(d.start(&[0, 0], retry), [0], "one fetch for a face wanted twice"); - assert!(d.start(&[0], retry + 1.0).is_empty(), "the interface asking again"); - assert!(d.start(&[0], retry + 1_000.0).is_empty(), "the retry timer"); - assert_eq!(d.finished(0, true, retry + 2_000.0), None); - assert!(d.start(&[0], 1e12).is_empty(), "loaded"); - } - - /// A clock that reads earlier than the failure (one set back meanwhile) does not hold the - /// retry back: the timer that asks for it has waited already. - #[test] - fn a_clock_set_back_after_a_failure_does_not_stop_the_retry() { - let mut d = Demand::default(); - let failed_at = 1e12; - d.start(&[0], failed_at); - assert_eq!(d.finished(0, false, failed_at), Some(RETRY_MS)); - assert!(d.start(&[0], failed_at + 1.0).is_empty(), "still waiting"); - assert_eq!(d.start(&[0], failed_at - 3_600_000.0), [0], "the clock went back an hour"); - } -} diff --git a/apps/vectorcraft-web/src/fonts.rs b/apps/vectorcraft-web/src/fonts.rs index 873474f6c3..c752a09286 100644 --- a/apps/vectorcraft-web/src/fonts.rs +++ b/apps/vectorcraft-web/src/fonts.rs @@ -1,22 +1,20 @@ //! Craft-fonts faces served beside the wasm (`fonts//…`, copied by //! `cargo xtask web-fonts`) instead of embedded: [`load_startup_fonts`] fetches the `startup` -//! ones before the app starts, [`spawn_background_fonts`] the `background` ones once it runs, and -//! [`want_chars`] a `demand` face (Korean, Devanagari) when the interface language or the -//! interface's own text needs its script. The browser checks each file against its SHA-256 -//! (Subresource Integrity). A face that fails is logged and skipped: the app runs without it. With -//! `WEB_FONTS` empty (built without craft-fonts) these do nothing. +//! ones before the app starts and [`spawn_background_fonts`] the `background` ones once it runs, +//! both into the document font database. The interface's own faces are fetched by the font stack +//! through [`BrowserFetcher`]. The browser checks each file against its SHA-256 (Subresource +//! Integrity). A face that fails is logged and skipped: the app runs without it. With `WEB_FONTS` +//! empty (built without craft-fonts) these do nothing. -use std::cell::{Cell, RefCell}; +use std::cell::Cell; use std::rc::Rc; -use vectorcraft_text::craft_fonts::demand_fonts; +use craft::ui::fonts::{FetchDone, FetchWake, FontFetcher}; use vectorcraft_text::{FontDb, WEB_FONTS, WebFont}; use wasm_bindgen::JsCast as _; use wasm_bindgen::closure::Closure; use wasm_bindgen_futures::JsFuture; -use crate::demand::Demand; - /// Per startup face: the page shows its loading text meanwhile. const STARTUP_TIMEOUT_MS: i32 = 20_000; /// Per background face. @@ -27,41 +25,25 @@ const BACKGROUND_PARALLEL: usize = 4; thread_local! { /// The background fetch runs once per page, though a graphics restart creates the app again. static BACKGROUND_STARTED: Cell = const { Cell::new(false) }; - /// The `demand` faces' fetches. - static DEMAND: RefCell = RefCell::new(Demand::default()); - /// The running app's context, asked for a frame when a `demand` face arrives (none before the - /// app starts: its first frame looks through the faces loaded by then). - static REPAINT: RefCell> = const { RefCell::new(None) }; } -/// Fetch, in the background, the `demand` faces for the scripts of `chars` that are not loaded or -/// being fetched. Each one that arrives asks the app for a frame, and the interface draws those -/// characters with it from then on. Set as the interface's missing-glyph handler -/// (`vectorcraft_ui_egui::on_missing_glyphs`), and called with the interface language's name -/// before the app starts. -pub fn want_chars(chars: &[char]) { - let wanted = demand_fonts(WEB_FONTS, chars.iter().copied()); - if !wanted.is_empty() { - fetch_demand(&wanted); +/// Fetches the interface font stack's served faces with the browser's `fetch`, and keeps its time. +pub struct BrowserFetcher; + +impl FontFetcher for BrowserFetcher { + fn fetch(&self, url: &'static str, integrity: &'static str, done: FetchDone) { + wasm_bindgen_futures::spawn_local(async move { done(fetch(url, integrity, BACKGROUND_TIMEOUT_MS).await) }); } -} -/// Fetch the `demand` faces `wanted` (indexes into `WEB_FONTS`) that [`Demand::start`] lets start. -/// A face whose fetch fails is fetched again after the wait [`Demand::finished`] gives. -fn fetch_demand(wanted: &[usize]) { - for i in DEMAND.with(|d| d.borrow_mut().start(wanted, vectorcraft_ui_egui::now_ms())) { - let Some(f) = WEB_FONTS.get(i) else { continue }; + fn now(&self) -> f64 { + craft::platform::clock::monotonic_ms() / 1000.0 + } + + fn after(&self, seconds: f64, wake: FetchWake) { + let ms = (seconds * 1000.0).ceil().clamp(0.0, f64::from(i32::MAX)) as i32; wasm_bindgen_futures::spawn_local(async move { - let ok = load(f, BACKGROUND_TIMEOUT_MS).await; - let retry = DEMAND.with(|d| d.borrow_mut().finished(i, ok, vectorcraft_ui_egui::now_ms())); - if ok && let Some(ctx) = REPAINT.with(|r| r.borrow().clone()) { - ctx.request_repaint(); - } - if let Some(wait) = retry { - // A second longer, so a clock the browser coarsens still reads the wait as over. - crate::api::sleep(wait.saturating_add(1_000)).await; - fetch_demand(&[i]); - } + crate::api::sleep(ms).await; + wake(); }); } } @@ -79,9 +61,8 @@ pub async fn load_startup_fonts() -> usize { /// Fetch and register the `background` faces, [`BACKGROUND_PARALLEL`] at a time, asking `ctx` for /// a frame after each so the font menus and the canvas pick it up. Only the first call fetches -/// anything; each call makes `ctx` the context a `demand` face asks for a frame. +/// anything. pub fn spawn_background_fonts(ctx: egui::Context) { - REPAINT.with(|r| *r.borrow_mut() = Some(ctx.clone())); if BACKGROUND_STARTED.with(|s| s.replace(true)) { return; } diff --git a/apps/vectorcraft-web/src/keys.rs b/apps/vectorcraft-web/src/keys.rs index e2f3ea0b48..3d388d1720 100644 --- a/apps/vectorcraft-web/src/keys.rs +++ b/apps/vectorcraft-web/src/keys.rs @@ -7,39 +7,43 @@ //! command (or a text field its own undo). A few chords never reach a page at all (Safari's //! `Cmd+L`, Chrome's `Cmd+T`, `Cmd+W` and `Cmd+N`): the browser keeps those. +use craft::keymap::Chord; +// PLAN: assumed path `craft::ui::runtime::commands` for the ui contract's `commands` module. +#[cfg(target_arch = "wasm32")] +use craft::ui::runtime::commands; use egui::{Key, Modifiers}; -/// Whether the browser's own action for a key press is cancelled. `key` is the event's `key` (the -/// character typed), `code` its `code` (the key's position), `modifiers` as eframe reports them, -/// and `alt_graph` whether AltGr is held. +/// The chord of a key press the browser's own action may be cancelled for. `key` is the event's +/// `key` (the character typed), `code` its `code` (the key's position), `modifiers` as eframe +/// reports them, and `alt_graph` whether AltGr is held. /// /// Only Cmd and Ctrl presses: a plain or Shift press types (cancelling it would drop the /// character it types), and so does AltGr, which Windows reports as Ctrl and Alt held. Cut, Copy /// and Paste (with any other modifiers) are left to the browser, whose clipboard events carry /// their text, and Reload too, as eframe leaves them. -pub(crate) fn kept_from_browser(key: &str, code: &str, modifiers: Modifiers, alt_graph: bool) -> bool { +pub(crate) fn browser_chord(key: &str, code: &str, modifiers: Modifiers, alt_graph: bool) -> Option { if !(modifiers.ctrl || modifiers.mac_cmd) || alt_graph { - return false; + return None; } - if matches!(Key::from_name(key).or(Key::from_name(code)), Some(Key::C | Key::V | Key::X | Key::R)) { - return false; + let key = Key::from_name(key).or(Key::from_name(code))?; + if matches!(key, Key::C | Key::V | Key::X | Key::R) { + return None; } - vectorcraft_ui_egui::shortcuts::runs_a_shortcut(key, code, modifiers) + vectorcraft_ui_egui::keymap::chord_of_press(key, modifiers, vectorcraft_ui_egui::keymap::platform()) } -/// Leave a paste to its Paste event (#5555). eframe's web runner reports a Cmd+V press both as the -/// key press and, with the clipboard's text, as a Paste event (the browser's `paste` comes in the -/// same task as the `keydown`, so both are in one frame's input); the app pastes on each, as egui's -/// window integration sends only the Paste. With a Paste in `events`, the paste key's press is -/// dropped; its release stays, so the paste chord is still followed (`PasteChord`). A Cmd+V without -/// a Paste (a clipboard with no text) keeps its press. -pub(crate) fn drop_paste_key_presses(events: &mut Vec) { - if !events.iter().any(|e| matches!(e, egui::Event::Paste(_))) { - return; - } - events.retain(|e| !matches!(e, egui::Event::Key { key: Key::V, pressed: true, modifiers, .. } if modifiers.command)); +/// Whether the browser's own action for a key press is cancelled: the keymap in effect, the +/// user's shortcuts included, binds its chord. Before the first frame nothing is bound. +#[cfg(target_arch = "wasm32")] +pub(crate) fn kept_from_browser(ctx: &egui::Context, key: &str, code: &str, modifiers: Modifiers, alt_graph: bool) -> bool { + browser_chord(key, code, modifiers, alt_graph).is_some_and(|chord| commands::holder(ctx, &chord).is_some()) } +/// The egui context of the running app; empty until the first start fills it, and filled again by +/// every restart after the graphics were lost. +#[cfg(target_arch = "wasm32")] +pub(crate) type ContextSlot = std::rc::Rc>>; + /// The modifiers of a key event as eframe reports them to egui (its `modifiers_from_kb_event`). #[cfg(target_arch = "wasm32")] fn modifiers(e: &web_sys::KeyboardEvent) -> Modifiers { @@ -63,17 +67,19 @@ fn to_the_app(e: &web_sys::KeyboardEvent) -> bool { } /// Cancel the page's default action for [`kept_from_browser`] presses, before eframe's listener -/// sees the event (it doesn't stop it). +/// sees the event (it doesn't stop it). The framework cancels no browser default itself, so this +/// listener stays; it reads the context from `ctx` because it is installed before the first frame. #[cfg(target_arch = "wasm32")] -pub(crate) fn keep_app_keys() { +pub(crate) fn keep_app_keys(ctx: ContextSlot) { use wasm_bindgen::JsCast as _; let Some(window) = web_sys::window() else { return }; - let on_key = wasm_bindgen::closure::Closure::::new(|e: web_sys::KeyboardEvent| { + let on_key = wasm_bindgen::closure::Closure::::new(move |e: web_sys::KeyboardEvent| { // An IME's keys are its own until it commits. if e.is_composing() || !to_the_app(&e) { return; } - if kept_from_browser(&e.key(), &e.code(), modifiers(&e), e.get_modifier_state("AltGraph")) { + let Some(ctx) = ctx.borrow().clone() else { return }; + if kept_from_browser(&ctx, &e.key(), &e.code(), modifiers(&e), e.get_modifier_state("AltGraph")) { e.prevent_default(); } }); @@ -87,6 +93,7 @@ pub(crate) fn keep_app_keys() { #[cfg(test)] mod tests { use super::*; + use craft::keymap::{Key as ChordKey, Mods}; /// Cmd as egui reports it on this platform: the Command key on macOS, Ctrl elsewhere. fn cmd() -> Modifiers { @@ -95,15 +102,15 @@ mod tests { #[test] fn the_keymaps_chords_are_kept_from_the_browser() { - for (key, code, mods) in [ - ("=", "Equal", cmd()), - ("-", "Minus", cmd()), - ("0", "Digit0", cmd()), - ("z", "KeyZ", cmd()), - ("Z", "KeyZ", cmd() | Modifiers::SHIFT), - ("[", "BracketLeft", cmd()), + for (key, code, mods, want) in [ + ("=", "Equal", cmd(), Chord::new(Mods::CMD, ChordKey::Equals)), + ("-", "Minus", cmd(), Chord::parse("Cmd+-").unwrap()), + ("0", "Digit0", cmd(), Chord::parse("Cmd+0").unwrap()), + ("z", "KeyZ", cmd(), Chord::parse("Cmd+Z").unwrap()), + ("Z", "KeyZ", cmd() | Modifiers::SHIFT, Chord::parse("Cmd+Shift+Z").unwrap()), + ("[", "BracketLeft", cmd(), Chord::parse("Cmd+[").unwrap()), ] { - assert!(kept_from_browser(key, code, mods, false), "{key} ({code}) {mods:?}"); + assert_eq!(browser_chord(key, code, mods, false), Some(want), "{key} ({code}) {mods:?}"); } } @@ -121,38 +128,11 @@ mod tests { ("V", "KeyV", cmd() | Modifiers::SHIFT), ("r", "KeyR", cmd()), ] { - assert!(!kept_from_browser(key, code, mods, false), "{key} ({code}) {mods:?}"); + assert!(browser_chord(key, code, mods, false).is_none(), "{key} ({code}) {mods:?}"); } // AltGr+Z types ż on a Polish layout, reported as Ctrl and Alt held on Windows. let ctrl_alt = Modifiers::CTRL | Modifiers::COMMAND | Modifiers::ALT; - assert!(!kept_from_browser("ż", "KeyZ", ctrl_alt, true)); - assert!(!kept_from_browser("}", "Digit0", ctrl_alt, true)); - } - - fn key(key: Key, pressed: bool, modifiers: Modifiers) -> egui::Event { - egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers } - } - - #[test] - fn a_paste_chord_pastes_once() { - // Cmd+V and Cmd+Shift+V (Paste in Place): the press goes, the Paste and the release stay. - for mods in [cmd(), cmd() | Modifiers::SHIFT] { - let mut events = vec![key(Key::V, true, mods), egui::Event::Paste("".into()), key(Key::V, false, mods)]; - drop_paste_key_presses(&mut events); - assert_eq!(events, vec![egui::Event::Paste("".into()), key(Key::V, false, mods)], "{mods:?}"); - } - } - - #[test] - fn keys_without_a_paste_stay() { - // No text on the clipboard: no Paste event, so the press is the paste chord's only report. - let mut events = vec![key(Key::V, true, cmd()), key(Key::V, false, cmd())]; - drop_paste_key_presses(&mut events); - assert_eq!(events.len(), 2); - // Typing V, and other chords, beside a paste. - let typed = vec![key(Key::V, true, Modifiers::NONE), key(Key::C, true, cmd()), egui::Event::Paste("a".into())]; - let mut events = typed.clone(); - drop_paste_key_presses(&mut events); - assert_eq!(events, typed); + assert!(browser_chord("ż", "KeyZ", ctrl_alt, true).is_none()); + assert!(browser_chord("}", "Digit0", ctrl_alt, true).is_none()); } } diff --git a/apps/vectorcraft-web/src/locks.rs b/apps/vectorcraft-web/src/locks.rs index dffd87868a..4740b38d51 100644 --- a/apps/vectorcraft-web/src/locks.rs +++ b/apps/vectorcraft-web/src/locks.rs @@ -35,7 +35,7 @@ const REFRESH_MS: i32 = 10_000; const FRESH_MS: f64 = 60_000.0; /// Whether a snapshot asked for at `asked` can still be trusted at `now`, both in ms on -/// [`vectorcraft_ui_egui::now_ms`]'s clock: it is at most [`FRESH_MS`] old, and not stamped later +/// [`craft::platform::clock::monotonic_ms`]'s clock: it is at most [`FRESH_MS`] old, and not stamped later /// than `now`. fn trusted(asked: f64, now: f64) -> bool { (0.0..=FRESH_MS).contains(&(now - asked)) @@ -54,7 +54,7 @@ thread_local! { pub struct WebLocks { prefix: &'static str, /// The areas whose locks were held at the last snapshot, and when it was asked for (ms on - /// [`vectorcraft_ui_egui::now_ms`]'s monotonic clock, which a change to the system clock does + /// [`craft::platform::clock::monotonic_ms`]'s monotonic clock, which a change to the system clock does /// not move). `navigator.locks.query()` is asynchronous, so the snapshot is refreshed every /// [`REFRESH_MS`] and read from here. seen: Arc)>>, @@ -97,7 +97,7 @@ impl WebLocks { /// Take a new snapshot of the locks held. async fn refresh(&self) -> Option<()> { let m = manager()?; - let asked = vectorcraft_ui_egui::now_ms(); + let asked = craft::platform::clock::monotonic_ms(); let query: Promise = method(&m, "query")?.call0(&m).ok()?.dyn_into().ok()?; let snapshot = wasm_bindgen_futures::JsFuture::from(query).await.ok()?; let held = js_sys::Array::from(&Reflect::get(&snapshot, &"held".into()).ok()?); @@ -113,7 +113,7 @@ impl WebLocks { /// Does a tab hold `area`'s lock? Yes when the last snapshot is too old to tell. pub fn held(&self, area: &str) -> bool { let seen = self.seen.lock().unwrap_or_else(|e| e.into_inner()); - !trusted(seen.0, vectorcraft_ui_egui::now_ms()) || seen.1.contains(area) + !trusted(seen.0, craft::platform::clock::monotonic_ms()) || seen.1.contains(area) } /// Hold `area`'s lock until the returned hold is dropped (or the page goes). diff --git a/apps/vectorcraft-web/src/main.rs b/apps/vectorcraft-web/src/main.rs index b71b51b566..737b561e70 100644 --- a/apps/vectorcraft-web/src/main.rs +++ b/apps/vectorcraft-web/src/main.rs @@ -6,8 +6,7 @@ //! //! Differences from the desktop app: //! - no TCP control server (browsers can't listen on sockets); -//! - File → Open uses the browser file picker; bytes arrive asynchronously through -//! `Services::picked_inbox`; +//! - File → Open uses the browser file picker, through the host's file service (`BrowserFiles`); //! - Save / Export trigger a browser download; //! - dropped files are read asynchronously by `web::WebShell` and delivered through the inbox; //! - pen and finger input is read from Pointer Events by `pencil` (Apple Pencil pressure and @@ -21,8 +20,6 @@ #[cfg(target_arch = "wasm32")] mod api; -#[cfg(any(target_arch = "wasm32", test))] -mod demand; #[cfg(target_arch = "wasm32")] mod fonts; #[cfg(any(target_arch = "wasm32", test))] diff --git a/apps/vectorcraft-web/src/pencil.rs b/apps/vectorcraft-web/src/pencil.rs index 88b85e9d50..5b5cec5a69 100644 --- a/apps/vectorcraft-web/src/pencil.rs +++ b/apps/vectorcraft-web/src/pencil.rs @@ -6,7 +6,7 @@ //! canvas reads it), so holding it still opens the context menu (egui's long touch). It hovers //! where the pen can (Apple Pencil hover). //! - A press of the pen's eraser end (the eraser button, `button` 5 in Pointer Events) presses -//! like the tip, and the pen's samples go into a [`StylusFeed`] with that end, so the canvas +//! like the tip, and the pen's samples go into a [`PenSource`] with that end, so the canvas //! selects the Eraser tool for the press. A press of the tip turns the pen back. //! - Fingers are touch contacts: two pinch and pan the canvas, and tap to undo or redo. The first //! finger also drives the pointer, so it taps the panels and menus; on the canvas it navigates @@ -22,8 +22,9 @@ use std::cell::RefCell; #[cfg(target_arch = "wasm32")] use std::rc::Rc; +use craft::behavior::PointerSample; +use craft::ui::runtime::pen::PenSource; use egui::{Event, PointerButton, Pos2, TouchDeviceId, TouchId, TouchPhase}; -use vectorcraft_ui_egui::stylus::{PenPose, PenSample, StylusFeed}; use vectorcraft_ui_egui::touch::{self, Source}; #[cfg(target_arch = "wasm32")] use wasm_bindgen::JsCast as _; @@ -37,6 +38,7 @@ const FINGER_DEVICE: TouchDeviceId = TouchDeviceId(2); const ERASER_BUTTON: i16 = 5; /// The pen and finger contacts followed, and the egui events they made since the last frame. +#[derive(Default)] pub struct Pointers { events: Vec, /// The pen pressing, by pointer id. @@ -48,14 +50,9 @@ pub struct Pointers { button: Option, /// The pen last pressed with its eraser end. eraser: bool, - /// The pen's pressure and end for the canvas (`Services::stylus`). - stylus: StylusFeed, -} - -impl Default for Pointers { - fn default() -> Self { - Self { events: vec![], pen: None, fingers: vec![], primary: None, button: None, eraser: false, stylus: StylusFeed::on_ui_thread() } - } + /// The pen's pressure and end for the canvas, the source the install reads. + // PLAN: named `source`, not `pen`: `pen` is the pressing pen's pointer id above. + source: PenSource, } #[cfg(target_arch = "wasm32")] @@ -88,14 +85,16 @@ impl Pointers { std::mem::take(&mut self.events) } - /// The feed the pen's samples go into, for `Services::stylus`. - pub fn stylus(&self) -> StylusFeed { - self.stylus.clone() + /// The source the pen's samples go into, for the runtime install. + pub fn pen(&self) -> PenSource { + self.source.clone() } /// A pen moved or pressed with `pressure`, with the end it last pressed with. fn pen_sample(&self, pressure: f32) { - self.stylus.set_sample(Some(PenSample { pressure, eraser: self.eraser, pose: PenPose::default() })); + let mut sample = PointerSample::new(pressure); + sample.eraser = self.eraser; + self.source.set(Some(sample)); } fn touch(&mut self, device: TouchDeviceId, id: i32, phase: TouchPhase, pos: Pos2, force: Option) { @@ -140,7 +139,7 @@ impl Pointers { if e.pointer_type != "pen" && self.pen.is_none() && matches!(kind, "pointerdown" | "pointermove") { // Another pointer moved while no pen presses (a palm under a pen pressing is // rejected): the canvas takes no pen pressure or pen end for it. - self.stylus.set(None); + self.source.set(None); } match e.pointer_type { "pen" => { @@ -440,7 +439,12 @@ mod tests { assert!(!p.feed("pointerdown", &input("pen", 6), Pos2::ZERO, &[], true)); assert!(p.take().is_empty()); assert!(!touch::pen_seen()); - assert_eq!(p.stylus().eraser(), None); + assert_eq!(p.pen().current(), None); + } + + /// The end of the pen the source holds, `None` without a pen. + fn end(pen: &PenSource) -> Option { + pen.current().map(|s| s.eraser) } fn presses(p: &mut Pointers) -> Vec<(PointerButton, bool)> { @@ -459,27 +463,27 @@ mod tests { fn the_eraser_button_presses_with_the_eraser_end() { reset(); let mut p = Pointers::default(); - let feed = p.stylus(); + let feed = p.pen(); let pos = Pos2::new(30.0, 40.0); let eraser = input("pen", ERASER_BUTTON); assert!(p.feed("pointerdown", &eraser, pos, &[], true)); assert_eq!(presses(&mut p), [(PointerButton::Primary, true)]); assert!(touch::pen_seen()); - assert_eq!((feed.eraser(), feed.held()), (Some(true), Some(0.6))); + assert_eq!((end(&feed), feed.current().map(|s| s.pressure)), (Some(true), Some(0.6))); assert!(p.feed("pointermove", &input("pen", -1), pos, &[], true)); - assert_eq!(feed.eraser(), Some(true)); + assert_eq!(end(&feed), Some(true)); assert!(p.feed("pointerup", &eraser, pos, &[], true)); assert_eq!(presses(&mut p), [(PointerButton::Primary, false)]); let mut hover = input("pen", -1); hover.pressure = 0.0; assert!(p.feed("pointermove", &hover, pos, &[], true)); - assert_eq!(feed.eraser(), Some(true), "a hovering pen keeps the end it pressed with"); + assert_eq!(end(&feed), Some(true), "a hovering pen keeps the end it pressed with"); // The barrel button leaves the end as it was. assert!(p.feed("pointerdown", &input("pen", 2), pos, &[], true)); assert!(p.feed("pointerup", &input("pen", 2), pos, &[], true)); - assert_eq!(feed.eraser(), Some(true)); + assert_eq!(end(&feed), Some(true)); assert!(p.feed("pointerdown", &input("pen", 0), pos, &[], true)); - assert_eq!(feed.eraser(), Some(false), "the tip"); + assert_eq!(end(&feed), Some(false), "the tip"); reset(); } @@ -490,13 +494,13 @@ mod tests { for (pointer_type, kind) in [("mouse", "pointermove"), ("mouse", "pointerdown"), ("touch", "pointerdown"), ("touch", "pointermove")] { reset(); let mut p = Pointers::default(); - let feed = p.stylus(); + let feed = p.pen(); assert!(p.feed("pointerdown", &input("pen", ERASER_BUTTON), Pos2::ZERO, &[], true)); assert!(p.feed("pointerup", &input("pen", ERASER_BUTTON), Pos2::ZERO, &[], true)); let mut other = input(pointer_type, 0); other.id = 10; p.feed(kind, &other, Pos2::ZERO, &[], true); - assert_eq!((feed.eraser(), feed.held()), (None, None), "{pointer_type} {kind}"); + assert_eq!(feed.current(), None, "{pointer_type} {kind}"); } reset(); } @@ -507,14 +511,14 @@ mod tests { fn a_rejected_palm_keeps_the_pen_end() { reset(); let mut p = Pointers::default(); - let feed = p.stylus(); + let feed = p.pen(); assert!(p.feed("pointerdown", &input("pen", ERASER_BUTTON), Pos2::ZERO, &[], true)); let mut palm = input("touch", 0); palm.id = 10; for (pointer_type, kind) in [("touch", "pointerdown"), ("touch", "pointermove"), ("mouse", "pointermove")] { palm.pointer_type = pointer_type; p.feed(kind, &palm, Pos2::ZERO, &[], true); - assert_eq!(feed.eraser(), Some(true), "{pointer_type} {kind}"); + assert_eq!(end(&feed), Some(true), "{pointer_type} {kind}"); } reset(); } diff --git a/apps/vectorcraft-web/src/web.rs b/apps/vectorcraft-web/src/web.rs index 6d9e0cadd5..8a319ea351 100644 --- a/apps/vectorcraft-web/src/web.rs +++ b/apps/vectorcraft-web/src/web.rs @@ -5,19 +5,21 @@ use std::cell::{Cell, RefCell}; use std::rc::Rc; use std::sync::{Arc, Mutex}; +use craft::host::target::ShellInfo; +use craft::host::{AppInfo, InlineJobs}; +use craft::platform::browser_files::BrowserFiles; +use craft::ui::InstallSpec; +use craft::ui::shell::embed; +use craft::window::system::SystemWindows; use vectorcraft_engine::Session; use vectorcraft_engine::cmd::clipboard::{FILE_HEAD, Flavour, PASTE_ORDER, file_flavour, is_address}; use vectorcraft_engine::cmd::fileio; use vectorcraft_engine::cmd::recovery::{self, Hold, RecoveryStore}; -use vectorcraft_engine::cmd::scripts::RUN_EXTS; -use vectorcraft_engine::script::MAX_SOURCE_BYTES; -use vectorcraft_ui_egui::dialogs::script_run::ScriptInbox; use vectorcraft_ui_egui::graphics::GraphicsLoss; use vectorcraft_ui_egui::i18n; use vectorcraft_ui_egui::place::{DropTarget, PlaceArrival, PlaceInbox}; use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer}; -use vectorcraft_ui_egui::stylus::StylusFeed; -use vectorcraft_ui_egui::{PickedInbox, Services, VectorcraftApp}; +use vectorcraft_ui_egui::{Services, VectorcraftApp}; use wasm_bindgen::JsCast as _; use crate::locks::WebLocks; @@ -25,14 +27,12 @@ use crate::pencil::SharedPointers; pub(crate) type Inbox = Arc)>>>; -/// The files waiting to open, by where they came from (`Services::inbox`, `picked_inbox` and -/// `page_inbox`). +/// The files waiting to open, by where they came from (`Services::inbox` and `page_inbox`). The +/// browser's file chooser answers through the host's file service ([`BrowserFiles`]), not here. #[derive(Clone, Default)] struct OpenInboxes { /// Dropped on the page. dropped: Inbox, - /// The open picker's answers. - picked: PickedInbox, /// Handed over by the page's script (`window.vectorcraft.openFile`). page: Inbox, } @@ -62,11 +62,13 @@ struct Host { runner: eframe::WebRunner, inbox: OpenInboxes, place_inbox: PlaceInbox, - script_inbox: ScriptInbox, drag: DragPos, pasted: Rc>, /// Pen and finger input read from the page's Pointer Events (`crate::pencil`). pointers: SharedPointers, + /// The running app's context, for the page's key listener (`crate::keys`), which is installed + /// before the first frame; every start after lost graphics fills it again. + ctx: crate::keys::ContextSlot, /// The page's Web Locks for Data Recovery, started once before the first frame: a graphics /// restart keeps them, so the tab stays the owner of its recovery area. locks: Option, @@ -81,11 +83,6 @@ pub fn start() { return; }; detect_language(); - // The face for a Korean or Hindi browser language (or `?lang=`) starts loading now, beside the - // startup fonts, without holding up the start. Text in those scripts painted later (a saved - // interface language, another one chosen, a layer or file name) has its face fetched then. - vectorcraft_ui_egui::on_missing_glyphs(crate::fonts::want_chars); - crate::fonts::want_chars(&i18n::system_lang().name().chars().collect::>()); wasm_bindgen_futures::spawn_local(async move { // Before the first frame, which looks for copies a crash left behind. let locks = WebLocks::start(RECOVERY_PREFIX).await; @@ -96,15 +93,15 @@ pub fn start() { runner: eframe::WebRunner::new(), inbox: OpenInboxes::default(), place_inbox: Arc::default(), - script_inbox: Arc::default(), drag: DragPos::default(), pasted: Rc::default(), pointers: SharedPointers::default(), + ctx: crate::keys::ContextSlot::default(), locks, restarts: 0, }; track_paste(&host.pasted); - crate::keys::keep_app_keys(); + crate::keys::keep_app_keys(host.ctx.clone()); run(host, canvas, None).await; }); } @@ -130,7 +127,6 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option PenSource` (shell-w13's `pencil.rs`), in place of `stylus()`. + let pen = host.pointers.borrow().pen(); + let spec = InstallSpec::new(ShellInfo::current(), Arc::new(SystemWindows)).pen(pen); + // The interface faces the page serves are fetched by the stack as text needs them. + let fonts = vectorcraft_ui_egui::ui_fonts().fetcher(Arc::new(crate::fonts::BrowserFetcher)); + embed::install(ctx, spec, &fonts).map_err(|e| e.to_string())?; + egui_extras::install_image_loaders(ctx); + let files = { + let ctx = ctx.clone(); + BrowserFiles::new(move || ctx.request_repaint()) + }; + // The web saves no preferences: the host keeps its default in-memory sections. + craft::host::Host::builder(AppInfo { id: "vectorcraft", name: "VectorCraft", version: env!("CARGO_PKG_VERSION") }) + // PLAN: assumed `vectorcraft_ui_egui::i18n::shared() -> Arc` + .i18n(i18n::shared()) + .jobs(Arc::new(InlineJobs)) + .files(Arc::new(files)) + .install(ctx); + let services = services(host.inbox.clone(), host.place_inbox.clone(), host.locks.clone()); + let mut app = match taken.borrow_mut().take() { Some(mut app) => { // The old services asked the old context for frames. app.services = services; @@ -162,6 +175,7 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option { match target { DropTarget::Place(d) => { - place_inbox.lock().unwrap_or_else(|e| e.into_inner()).push(PlaceArrival { name, bytes, drop: Some(d) }) + place_inbox.lock().unwrap_or_else(|e| e.into_inner()).push(PlaceArrival { name, bytes, drop: d }) } DropTarget::Open => inbox.lock().unwrap_or_else(|e| e.into_inner()).push((name, bytes)), } @@ -448,123 +461,21 @@ impl eframe::App for WebShell { } } -fn services( - inbox: OpenInboxes, - place_inbox: PlaceInbox, - script_inbox: ScriptInbox, - ctx: egui::Context, - locks: Option, - stylus: StylusFeed, -) -> Services { - let open_inbox = inbox.picked.clone(); - let picked = place_inbox.clone(); - let place_ctx = ctx.clone(); - let screen_color = eye_dropper(ctx.clone()); - let (script_picked, script_ctx) = (script_inbox.clone(), ctx.clone()); +fn services(inbox: OpenInboxes, place_inbox: PlaceInbox, locks: Option) -> Services { Services { - // File › Scripts › Other Script…: the picked file goes to the warning before it runs. - script_async: Some(Box::new(move || { - let inbox = script_picked.clone(); - let ctx = script_ctx.clone(); - wasm_bindgen_futures::spawn_local(async move { - let filter = vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", "Scripts"); - let Some(file) = rfd::AsyncFileDialog::new().add_filter(filter, RUN_EXTS).pick_file().await else { - return; - }; - let bytes = if file.inner().size() > MAX_SOURCE_BYTES as f64 { None } else { Some(file.read().await) }; - inbox.lock().unwrap_or_else(|e| e.into_inner()).push((file.file_name(), bytes)); - ctx.request_repaint(); - }); - })), - script_inbox: Some(script_inbox), - // File → Place…: the picked files go to the Place dialog. - place_async: Some(Box::new(move || { - let inbox = picked.clone(); - let ctx = place_ctx.clone(); - wasm_bindgen_futures::spawn_local(async move { - let dialog = - fileio::place_filters().fold(rfd::AsyncFileDialog::new().set_title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| { - d.add_filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), exts) - }); - let Some(files) = dialog.pick_files().await else { - return; - }; - let mut arrived = vec![]; - for f in files { - arrived.push(PlaceArrival { name: f.file_name(), bytes: f.read().await, drop: None }); - } - inbox.lock().unwrap_or_else(|e| e.into_inner()).extend(arrived); - ctx.request_repaint(); - }); - })), - place_inbox: Some(place_inbox), - open_async: Some(Box::new(move || { - let inbox = open_inbox.clone(); - let ctx = ctx.clone(); - wasm_bindgen_futures::spawn_local(async move { - let dialog = fileio::open_filters().fold(rfd::AsyncFileDialog::new(), |d, (name, exts)| { - d.add_filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), exts) - }); - // A canceled pick answers `None`. - let answer = match dialog.pick_file().await { - Some(file) => Some((file.file_name(), file.read().await)), - None => None, - }; - inbox.lock().unwrap_or_else(|e| e.into_inner()).push(answer); - ctx.request_repaint(); - }); - })), - // Sample Color from Screen: the browser's EyeDropper, where it has one. - screen_color, // A download that couldn't be started fails the save or export it is for (#1693). download: Some(Box::new(|name: &str, bytes: &[u8]| download(name, bytes).inspect_err(|e| log::error!("download of {name} failed: {e}")))), inbox: Some(inbox.dropped), - picked_inbox: Some(inbox.picked), page_inbox: Some(inbox.page), + // Files dropped on the canvas to place. + place_inbox: Some(place_inbox), recovery_store: Some(Arc::new(BrowserStore { locks })), // File → Print: the browser's print dialog. print: Some(Box::new(BrowserPrint)), - // The pen's end, from the page's Pointer Events (`crate::pencil`). - stylus: Some(stylus), ..Default::default() } } -/// Sample Color from Screen in the browser: the EyeDropper API -/// (), which only some browsers have, -/// on secure (HTTPS) pages; `None` without it, and the command is then gray. `open()` needs a -/// transient user activation (otherwise it fails with a `NotAllowedError`) and resolves with the -/// picked color's `sRGBHex`; Escape rejects it with an `AbortError`. -fn eye_dropper(ctx: egui::Context) -> Option { - use js_sys::{Function, Promise, Reflect}; - use wasm_bindgen::JsValue; - let window = web_sys::window()?; - let constructor = Reflect::get(&window, &JsValue::from_str("EyeDropper")).ok()?.dyn_into::().ok()?; - Some(Box::new(move || { - let eye = Reflect::construct(&constructor, &js_sys::Array::new()).map_err(js_err)?; - let open = Reflect::get(&eye, &JsValue::from_str("open")).map_err(js_err)?.dyn_into::().map_err(js_err)?; - let promise = open.call0(&eye).map_err(js_err)?.dyn_into::().map_err(js_err)?; - let (tx, rx) = std::sync::mpsc::channel(); - let ctx = ctx.clone(); - wasm_bindgen_futures::spawn_local(async move { - let answer = match wasm_bindgen_futures::JsFuture::from(promise).await { - Ok(result) => Reflect::get(&result, &JsValue::from_str("sRGBHex")) - .ok() - .and_then(|hex| hex.as_string()) - .and_then(|hex| vectorcraft_ui_egui::screen_color::srgb_from_hex(&hex)) - .map(Some) - .ok_or_else(|| "the browser's EyeDropper answered no color".to_string()), - Err(e) if Reflect::get(&e, &JsValue::from_str("name")).ok().and_then(|n| n.as_string()).as_deref() == Some("AbortError") => Ok(None), - Err(e) => Err(js_err(e)), - }; - // The UI may be gone (the page closing): nothing waits for the color then. - let _ = tx.send(answer); - ctx.request_repaint(); - }); - Ok(rx) - })) -} - /// Data Recovery's store on the web: the browser's local storage (kept across visits and shared by /// the site's tabs), each entry as base64 under [`RECOVERY_PREFIX`]`/`. It has no /// locks: each tab holds its area with a heartbeat, judged by the browser's clock, and with a Web diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index 0fe5804a16..81dba266e0 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -18,27 +18,25 @@ accessibility = ["eframe/accesskit"] vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] } vectorcraft-ui-egui = { workspace = true } vectorcraft-text = { workspace = true } -# Shared across the Craft suite: decides who draws the window frame per desktop (compositor vs app) -# so VectorCraft matches the rest on Linux. `egui` adds `craft_window::decorate`. See #217. -craft-window = { workspace = true } +# Shared across the Craft suite: the UI runtime and its eframe hooks, settings, control server, file dialogs, the window +# frame policy and placement store (so VectorCraft matches the rest on Linux, see #217), printing and +# the update client. +craft = { workspace = true, features = ["ui", "ui-app", "settings", "automation", "platform", "window", "dialogs", "print", "update"] } eframe = { workspace = true, features = ["clipboard", "default_fonts", "wayland", "x11"] } egui = { workspace = true } +egui_extras = { workspace = true } serde_json = { workspace = true } log = { workspace = true } chrono = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -rfd = { workspace = true } # wayland-data-control: native Wayland clipboard (Linux; X11 through XWayland only sees what X11 apps copied). arboard = { workspace = true, features = ["image-data", "wayland-data-control"] } image = { workspace = true } -webbrowser = { workspace = true } # The window's monitors, size and position (the same winit eframe runs on). winit = { version = "0.30", default-features = false } -craft-print = { workspace = true } [target.'cfg(windows)'.dependencies] -craft-update = { workspace = true } clipboard-win = { workspace = true } # Reads a print queue's Standard TCP/IP RAW port for the direct-PDF transport (src/direct_pdf.rs). # MIT, already in the build through the update client. @@ -46,8 +44,7 @@ winreg = "0.55" # Which GPU drives which display (EnumDisplayDevices, src/gpu.rs), so the window is drawn on the # GPU that shows it: drawing on a GPU without a monitor reset the display driver. Safe wrappers over # Win32 (MIT); the `user` feature is User32.dll only. Only the wgpu renderer chooses an adapter. -# It also lists each monitor's work area for floating panels (src/window.rs), so a build without -# the `wgpu` feature keeps the panels to the monitors' whole rects. + winsafe = { version = "0.0.29", default-features = false, features = ["user"], optional = true } # Waits for Direct3D 12's adapter list before the window starts (src/gpu.rs, #4150). MIT OR # Apache-2.0, already in the build through eframe. @@ -60,8 +57,7 @@ pollster = "1" # read a pen's barrel button from its pointer messages. Win32_UI_Input_Pointer has # `GetPointerPenInfo`, which it uses to read the pen's pressure and which end of the pen is down. # Win32_System_Threading has `GetProcessAffinityMask`, which src/windows_cores.rs uses to count the -# cores the process may run on. Win32_UI_Input_KeyboardAndMouse has `GetKeyState`, which -# src/caps_lock.rs uses to read whether Caps Lock is on. Win32_System_Registry has `RegGetValueW`, +# cores the process may run on. Win32_System_Registry has `RegGetValueW`, # which src/host_services.rs uses to read the path PhotoCraft registers under App Paths. # Win32_Devices_Display has `QueryDisplayConfig`, Win32_UI_ColorSystem the display's ICC profile and # Win32_System_LibraryLoader `GetProcAddress`, which src/display_profile.rs uses to read the @@ -71,12 +67,9 @@ windows = { version = "0.62", features = ["Win32_Devices_Display", "Win32_Founda vectorcraft-render = { workspace = true } [target.'cfg(target_os = "macos")'.dependencies] -# The macOS menu bar (src/mac_menu.rs): Tauri's menu crate, AppKit menus behind a safe API (no GTK -# with default features off). Pinned exactly: review the diff before bumping. -muda = { version = "=0.21.2", default-features = false } objc2 = "0.6" -objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSampler", "NSColorSpace", "NSControl", "NSMenu", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSScreen", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] } -# Files opened from Finder and the Dock (src/open_documents.rs), pasted bitmaps (src/clipboard.rs) and the control channel's App Nap activity (src/control_server.rs); both already come with winit, muda and rfd. +objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSpace", "NSControl", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSScreen", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] } +# Files opened from Finder and the Dock (src/open_documents.rs) and pasted bitmaps (src/clipboard.rs); both already come with winit. objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSData", "NSGeometry", "NSNotification", "NSOperation", "NSProcessInfo", "NSString", "NSURL"] } block2 = "0.6" # The window's AppKit view, to centre its buttons on the app bar (src/mac_window.rs). MIT OR @@ -100,9 +93,10 @@ pollster = "1" winit = { version = "0.30", default-features = false, features = ["wayland-csd-adwaita-notitle"] } # A drawing tablet's pen pressure under X11 and XWayland (src/tablet.rs): XInput2 raw events on a # second X connection, x11rb's pure-Rust `RustConnection`. MIT OR Apache-2.0, already in the build -# through winit with the `xinput` feature. XKB reads Caps Lock's locked modifier state (src/caps_lock.rs). +# through winit with the `xinput` feature. # RandR reads a display's `_ICC_PROFILE` for the canvas (src/display_profile.rs). -x11rb = { version = "0.13", default-features = false, features = ["randr", "xinput", "xkb"] } +x11rb = { version = "0.13", default-features = false, features = ["randr", "xinput"] } +craft = { workspace = true, features = ["wayland"] } # Asks the Wayland compositor which GPU it draws with (linux-dmabuf feedback, src/compositor_gpu.rs), # so Automatic draws on that one, and copies and pastes text, SVG and PNG through the compositor's @@ -111,24 +105,17 @@ x11rb = { version = "0.13", default-features = false, features = ["randr", "xinp # through winit. wayland-client = "0.31" wayland-protocols = { version = "0.32", features = ["client", "unstable"] } -# The save dialog's parent window on Wayland (src/portal_save.rs): an xdg-foreign handle (in -# wayland-protocols' `unstable` set) made on the window's own connection. MIT, already in the build -# through winit and rfd. +# The window's own Wayland connection (src/clipboard.rs). MIT, already in the build through winit. wayland-backend = { version = "0.3", features = ["client_system"] } # The Wayland clipboard's pipes (src/clipboard.rs): `poll` and the nonblocking flag give up a read # or send when the other app moves no data for a while. Apache-2.0 WITH LLVM-exception OR # Apache-2.0 OR MIT, already in the build through the workspace. rustix = { workspace = true, features = ["std", "event", "fs"] } -# The save dialog's file type (src/portal_save.rs, #2679): the desktop portal over D-Bus, on the -# systems where rfd shows the portal's dialog. MIT, already in the build through accesskit. Pinned -# exactly: review the diff before bumping. +# The display's color profile over D-Bus (src/display_profile.rs). MIT, already in the build through +# accesskit. Pinned exactly: review the diff before bumping. [target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))'.dependencies] zbus = "=5.19.0" -# Waits for a portal answer (the save dialog's and the screen color sampler's) and for the portal -# leaving the bus at the same time (src/portal_request.rs). Apache-2.0 OR MIT, already in the build -# through zbus. -futures-lite = "2" # Tells whether arboard reads through the compositor's data-control protocol or through X11, the # same check arboard makes (src/clipboard.rs). MIT OR Apache-2.0, already in the build through # arboard. @@ -142,5 +129,3 @@ winresource = "0.1" tempfile = "3" # Bound socket buffers in real loopback transport deadline regressions. socket2 = { workspace = true } -# src/portal_save.rs's tests build and read the portal's D-Bus values on every system. -zbus = "=5.19.0" diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index 9b71404f5c..980df2bea5 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -1,43 +1,26 @@ #[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))] use super::gpu; -use super::prefs::{save_prefs, save_prefs_soon}; +use super::prefs::{flush, save_tick}; #[cfg(not(target_os = "macos"))] use super::single_instance; -#[cfg(all(windows, not(target_vendor = "win7")))] -use super::windows_stylus; -use super::{App, VectorcraftApp, file_access, window}; +use super::{App, VectorcraftApp, file_access}; #[cfg(target_os = "macos")] -use super::{mac_menu, mac_window, open_documents}; +use super::{mac_window, open_documents}; +use craft::ui::runtime::env::WindowKey; +use craft::ui::shell::{WindowDialogs, embed}; use vectorcraft_ui_egui::dialogs::safe_mode; use vectorcraft_ui_egui::hang_beacon::{self, BEACON, FrameTime, Stage}; -/// The parts of [`App::raw_input_hook`] that every window needs, for the OS windows of floating -/// panels: a click or Escape that closes the macOS menu bar's open menu, and the pen barrel -/// button's secondary click on Windows. The control channel's input and the native menu's keys -/// go to the main window only. -#[cfg(target_os = "macos")] -pub(crate) fn native_input_hook(app: &VectorcraftApp) -> Option { - app.services.native_menu.is_some().then(|| std::sync::Arc::new(mac_menu::raw_input_hook) as vectorcraft_ui_egui::NativeInputHook) -} - -#[cfg(windows)] -pub(crate) fn native_input_hook(_: &VectorcraftApp) -> Option { - Some(std::sync::Arc::new(windows_stylus::raw_input_hook)) -} - -#[cfg(not(any(target_os = "macos", windows)))] -pub(crate) fn native_input_hook(_: &VectorcraftApp) -> Option { - None -} - impl eframe::App for App { // Each frame runs unconfined: it is the person at the keyboard's. The app confines what the // control channel asks for, and the frames carrying input it injected, to the automation roots // (`VectorcraftApp::with_automation_roots`), which are in force elsewhere in the process. fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { let _timed = BEACON.enter_timed(Stage::Logic); - file_access::unconfined(|| self.logic_frame(ctx, frame)); - self.app.finish_ime_logic(ctx); + file_access::unconfined(|| { + self.logic_frame(ctx, frame); + embed::logic(ctx, || self.app.close_decision()); + }); BEACON.enter(Stage::Idle); } /// Restore the borderless caption, apply platform menu and pen input, and hand the frame to the @@ -60,28 +43,19 @@ impl eframe::App for App { if let Some(window_frame) = self.window_frame.as_mut() { window_frame(); } - #[cfg(target_os = "macos")] - if self.app.services.native_menu.is_some() { - mac_menu::raw_input_hook(raw); - } - // A pen contact with the barrel button held presses the secondary button (Windows Ink). - #[cfg(windows)] - windows_stylus::raw_input_hook(raw); // The characters Alt + keypad codes typed (#5108). #[cfg(windows)] super::windows_alt_codes::raw_input_hook(raw); // Symbol-font characters a keyboard tool typed (NHM Writer legacy Tamil). #[cfg(windows)] super::windows_symbol_chars::raw_input_hook(raw); - file_access::unconfined(|| self.app.raw_input_hook(ctx, raw)); - // A mouse-up that never reached the window (#4326) is delivered once AppKit reports - // that no mouse button is down. - #[cfg(target_os = "macos")] - self.app.release_lost_buttons(ctx, raw, objc2_app_kit::NSEvent::pressedMouseButtons() != 0); + self.app.raw_input(ctx, raw); + file_access::unconfined(|| embed::before_input(ctx, |out| self.app.frame_input(out))); BEACON.enter(Stage::Idle); } fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { let _timed = BEACON.enter_timed(Stage::Interface); + embed::before_ui(ui.ctx(), frame); #[cfg(target_os = "macos")] { let bar = vectorcraft_ui_egui::chrome::APP_BAR_HEIGHT; @@ -91,22 +65,24 @@ impl eframe::App for App { // macOS converts the frame from sRGB to the display's profile (#2249). #[cfg(all(target_os = "macos", feature = "wgpu"))] super::mac_color_space::tag(ui); - if let Some(on) = self.host_caps_lock.read_transition() { - self.app.set_caps_lock(on); - } file_access::unconfined(|| self.app.ui(ui)); // Preferences are written when confirmed, not only at exit: a session ended any other way // (the system shutting down, the process ended or crashing) used to lose them (#1747). - if self.app.take_prefs_changed() { - file_access::unconfined(|| save_prefs(&self.app)); - } else { - // The workspace, panels and other UI settings change without the dialog (#4625). - file_access::unconfined(|| save_prefs_soon(&self.app)); + file_access::unconfined(|| save_tick(&mut self.app, &self.settings, std::time::Instant::now())); + // The native dialogs the app asked for in this frame show now, over the window, in the + // interface language. + let lang = vectorcraft_ui_egui::i18n::current(); + if self.replace_lang != Some(lang) { + self.replace_lang = Some(lang); + self.file_panels.set_replace_words(vectorcraft_ui_egui::i18n::replace_words()); } - // Not while a file dialog's sheet has the keyboard: its name field's composition would go. - #[cfg(target_os = "macos")] - if !self.app.file_dialog_open() && self.app.take_ime_discard() { - discard_marked_text(); + WindowDialogs::of(ui.ctx(), &WindowKey::main()).with(|dialogs| self.file_panels.pump_with(dialogs, Some(&*frame))); + // The folders the picks chose are saved with the UI state; one the file can't hold (not + // UTF-8) is left out. + let mut folders = self.files.last_folders(); + folders.retain(|_, folder| folder.to_str().is_some()); + if folders != self.app.ui.last_folders { + self.app.ui.last_folders = folders; } self.end_frame(ui.ctx(), frame); } @@ -115,12 +91,10 @@ impl eframe::App for App { // of a stall the interface came back from is removed. let log_dir = super::prefs::log_dir().filter(|_| super::prefs::prefs_enabled()); super::hang_watch::closing(log_dir.as_deref(), &super::hang_watch::CLOSING, &BEACON); - file_access::unconfined(|| save_prefs(&self.app)); + file_access::unconfined(|| flush(&self.app, &self.settings)); // A ready update installs once the process has exited. The macOS exit below skips // dropping the app, so the helper is started here. self.app.start_pending_update(); - #[cfg(target_os = "macos")] - super::mac_cursor::release(); // Dropping the app can wait for the clipboard handles to let go: the windows leave the // screen first (`quit_windows`). #[cfg(not(any(target_os = "macos", windows)))] @@ -160,10 +134,6 @@ impl App { } fn logic_frame(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { - #[cfg(target_os = "macos")] - if self.winit_window.as_ref().is_some_and(|w| !w.has_focus() || w.is_visible() == Some(false) || w.is_minimized() == Some(true)) { - super::mac_cursor::release(); - } self.frames = ctx.cumulative_frame_nr(); if let Some(why) = self.graphics_loss.take() { // eframe can't give a window a new device: the user saves and starts again. @@ -202,26 +172,11 @@ impl App { open_files(&mut self.app, held); open_files(&mut self.app, files); } - let (now, zoom) = (ctx.input(|i| i.time), ctx.zoom_factor()); - if let Some(w) = &self.winit_window - && window::monitors_due(self.monitors_listed, now, zoom) - { - self.app.services.dock_monitors = window::dock_monitors(w, zoom); - self.monitors_listed = Some((now, zoom)); - } + let now = ctx.input(|i| i.time); if let Some(w) = &self.winit_window { self.display_profile.tick(w, now, self.app.session.prefs.monitor_profile_display, &self.app.display_profile, ctx); } self.app.tick(ctx); - if self.pending_maximize { - if let Some(w) = &self.winit_window { - self.pending_maximize = window::apply_pending_maximize(w, true, &mut self.maximize_tries); - } else { - self.pending_maximize = false; - } - } - let host_maximized = self.winit_window.as_ref().map(|w| w.is_maximized()); - window::track(ctx, &mut self.app.ui.window, host_maximized); if self.app.ui.status == "quit" { ctx.send_viewport_cmd(egui::ViewportCommand::Close); } diff --git a/apps/vectorcraft/src/automation_args.rs b/apps/vectorcraft/src/automation_args.rs index 979f42e7bd..58782fc5e8 100644 --- a/apps/vectorcraft/src/automation_args.rs +++ b/apps/vectorcraft/src/automation_args.rs @@ -1,10 +1,11 @@ -//! Parse the control port and automation roots before starting any desktop services. A malformed +//! Parse the control flags and automation roots before starting any desktop services. A malformed //! flag must not silently remove a root and leave the control channel unconfined, or leave the app //! running without the control channel that was asked for. -use std::ffi::OsString; use std::path::PathBuf; +use craft::automation::args::{ControlOptions, OptionsError, Source, control_port}; + pub struct AutomationArgs { pub read_roots: Vec, pub write_roots: Vec, @@ -50,50 +51,61 @@ impl AutomationArgs { } } -/// `--control ` or `--control=`, given at most once. +/// `--control `, `--control-token ` and `--control-token-file `, each in either +/// spelling (`--control=`) and given at most once. #[derive(Default)] pub struct ControlArg { - pub port: Option, + options: ControlOptions, } impl ControlArg { - /// Returns whether this argument is `--control`. The next argument is its port whatever it - /// is, so `--control --automation-read-root` reports the flag rather than reading it as a root. + /// What the command line gave, each value marked as a flag's, for + /// [`ControlOptions::resolve`] to put over the environment. + pub fn options(&self) -> ControlOptions { + self.options.clone() + } + + /// Returns whether this argument is one of the control flags. The next argument is the value + /// whatever it is, so `--control --automation-read-root` reports the flag rather than reading + /// it as a root. pub fn consume(&mut self, arg: &str, args: &mut impl Iterator) -> Result { - let value = match arg.strip_prefix("--control") { - Some("") => args.next(), - Some(rest) => match rest.strip_prefix('=') { - Some(value) => Some(value.to_owned()), - None => return Ok(false), - }, - None => return Ok(false), + let (flag, inline) = arg.split_once('=').map_or((arg, None), |(flag, value)| (flag, Some(value))); + let given = match flag { + "--control" => self.options.port.is_some(), + "--control-token" => self.options.token.is_some(), + "--control-token-file" => self.options.token_file.is_some(), + _ => return Ok(false), }; - if self.port.is_some() { - return Err("--control given twice".into()); + let value = match inline { + Some(value) => value.to_owned(), + None => args.next().ok_or_else(|| format!("a value is required for '{flag}' but none was supplied"))?, + }; + if given { + return Err(format!("the argument '{flag}' cannot be used multiple times")); + } + let options = &mut self.options; + let from_flag = Some(Source::Flag); + match flag { + "--control" => { + let not_a_port = || OptionsError::NotAPort { value: value.clone(), shown: "--control ".into() }.to_string(); + options.port = Some(control_port(&value).map_err(|_| not_a_port())?); + options.sources.port = from_flag; + } + // A blank token or path would leave the channel open to anyone or name no file. + _ if value.trim().is_empty() => return Err(format!("a value is required for '{flag}' but none was supplied")), + "--control-token" => { + options.token = Some(value); + options.sources.token = from_flag; + } + _ => { + options.token_file = Some(PathBuf::from(value)); + options.sources.token_file = from_flag; + } } - self.port = Some(port("--control", value.as_deref())?); Ok(true) } } -/// `VECTORCRAFT_CONTROL_PORT`, for when `--control` isn't given: unset or empty is no control -/// channel, anything else must be a port. -pub fn env_control_port(value: Option) -> Result, String> { - match value { - Some(v) if !v.is_empty() => port("VECTORCRAFT_CONTROL_PORT", Some(&v.to_string_lossy())).map(Some), - _ => Ok(None), - } -} - -/// A port from 1 to 65535 (the server would listen on 0's random port without saying which). -fn port(name: &str, value: Option<&str>) -> Result { - let need = format!("{name} needs a port number from 1 to 65535"); - match value { - None => Err(need), - Some(v) => v.parse().ok().filter(|&p| p != 0).ok_or(format!("{need}, not `{v}`")), - } -} - #[cfg(test)] mod tests { use super::*; @@ -147,27 +159,38 @@ mod tests { assert_eq!(roots.write_roots, [PathBuf::from("./-folder")]); } - fn control(args: &[&str]) -> Result, String> { + fn control(args: &[&str]) -> Result { let mut control = ControlArg::default(); let mut args = args.iter().map(|a| a.to_string()); while let Some(a) = args.next() { assert!(control.consume(&a, &mut args)?, "{a}"); } - Ok(control.port) + Ok(control.options()) } #[test] - fn control_needs_a_port_from_1_to_65535() { - let need = "--control needs a port number from 1 to 65535"; - assert_eq!(control(&["--control"]), Err(need.into())); - assert_eq!(control(&["--control", "--automation-read-root"]), Err(format!("{need}, not `--automation-read-root`"))); - for bad in ["abc", "0", "70000", "-1", ""] { - assert_eq!(control(&["--control", bad]), Err(format!("{need}, not `{bad}`"))); - assert_eq!(control(&[&format!("--control={bad}")]), Err(format!("{need}, not `{bad}`"))); + fn a_control_flag_takes_the_next_argument_whatever_it_is() { + assert!(control(&["--control"]).is_err(), "a flag with no value"); + let err = control(&["--control", "--automation-read-root"]).unwrap_err(); + assert!(err.contains("--automation-read-root"), "the next argument is the port, not a root flag: {err}"); + for bad in ["abc", "70000", "-1", ""] { + assert!(control(&["--control", bad]).is_err(), "{bad}"); + assert!(control(&[&format!("--control={bad}")]).is_err(), "{bad}"); } - assert_eq!(control(&["--control", "7979"]), Ok(Some(7979))); - assert_eq!(control(&["--control=65535"]), Ok(Some(65535))); - assert_eq!(control(&["--control", "7979", "--control=7980"]), Err("--control given twice".into())); + for twice in [ + ["--control", "7979", "--control=7980"], + ["--control-token", "a", "--control-token=b"], + ["--control-token-file", "a", "--control-token-file=b"], + ] { + assert!(control(&twice).is_err(), "{twice:?}"); + } + assert!(control(&["--control-token="]).is_err(), "an empty token"); + let port = control(&["--control", "7979"]).unwrap(); + assert_eq!(port, control(&["--control=7979"]).unwrap(), "both spellings agree"); + assert_eq!((port.port, port.sources.port), (Some(7979), Some(Source::Flag))); + assert_eq!(control(&["--control=0"]).unwrap().port, Some(0), "port 0 picks a free port"); + let secret = control(&["--control-token", "--odd", "--control-token-file=key.txt"]).unwrap(); + assert_eq!((secret.token.as_deref(), secret.token_file), (Some("--odd"), Some(PathBuf::from("key.txt")))); } #[test] @@ -178,21 +201,9 @@ mod tests { assert!(!control.consume(other, &mut args).unwrap(), "{other}"); } assert_eq!(args.next().as_deref(), Some("7979")); - assert_eq!(control.port, None); - } - - #[test] - fn control_port_variable_is_a_port_or_unset() { - assert_eq!(env_control_port(None), Ok(None)); - assert_eq!(env_control_port(Some("".into())), Ok(None)); - assert_eq!(env_control_port(Some("7979".into())), Ok(Some(7979))); - let need = "VECTORCRAFT_CONTROL_PORT needs a port number from 1 to 65535"; - assert_eq!(env_control_port(Some("abc".into())), Err(format!("{need}, not `abc`"))); - assert_eq!(env_control_port(Some("0".into())), Err(format!("{need}, not `0`"))); - #[cfg(unix)] - { - use std::os::unix::ffi::OsStringExt; - assert_eq!(env_control_port(Some(OsString::from_vec(vec![0x39, 0xff]))), Err(format!("{need}, not `9\u{fffd}`"))); + assert_eq!(control.options(), ControlOptions::default()); + for token_flag in ["--control-token", "--control-token-file"] { + assert!(ControlArg::default().consume(token_flag, &mut ["x".to_owned()].into_iter()).unwrap(), "{token_flag}"); } } } diff --git a/apps/vectorcraft/src/caps_lock.rs b/apps/vectorcraft/src/caps_lock.rs deleted file mode 100644 index 231a37e037..0000000000 --- a/apps/vectorcraft/src/caps_lock.rs +++ /dev/null @@ -1,216 +0,0 @@ -//! Read the host's Caps Lock state, which gives the drawing tools the precise crosshair while it is on. - -/// Only host transitions replace a value set by a script through `view.capsLock`. -#[derive(Default)] -pub struct HostCapsLock { - previous: Option, - #[cfg(target_os = "linux")] - x11: Option, -} - -#[cfg(target_os = "linux")] -struct X11CapsLock { - connection: x11rb::rust_connection::RustConnection, - locked: bool, - initial_sequence: u16, -} - -impl HostCapsLock { - pub fn new(window: Option<&winit::window::Window>) -> Self { - #[cfg(target_os = "linux")] - let x11 = window.and_then(x11_connection); - #[cfg(not(target_os = "linux"))] - let _ = window; - Self { - previous: None, - #[cfg(target_os = "linux")] - x11, - } - } - - pub fn read_transition(&mut self) -> Option { - #[cfg(target_os = "linux")] - let current = match self.x11.as_mut() { - Some(state) => match state.poll() { - Some(locked) => Some(locked), - None => { - self.x11 = None; - None - } - }, - None => { - // Native Wayland does not expose the seat's XKB lock bit through winit or egui. - None - } - }; - #[cfg(any(target_os = "macos", windows))] - let current = Some(read()); - // This platform has no lock-state reader. - #[cfg(not(any(target_os = "macos", windows, target_os = "linux")))] - let current = None; - self.transition(current) - } - - fn transition(&mut self, reading: Option) -> Option { - reading.and_then(|current| self.observe(current)) - } - - fn observe(&mut self, current: bool) -> Option { - if self.previous.replace(current) == Some(current) { None } else { Some(current) } - } -} - -#[cfg(target_os = "linux")] -fn x11_connection(window: &winit::window::Window) -> Option { - use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle}; - use x11rb::protocol::xkb; - if !matches!(window.window_handle().ok()?.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)) { - return None; - } - let (connection, _) = x11rb::connect(None).ok()?; - let supported = x11rb::protocol::xkb::use_extension(&connection, 1, 0).ok()?.reply().ok()?.supported; - if !supported { - return None; - } - // Subscribe before the initial read so changes during setup remain queued. - xkb::select_events( - &connection, - xkb::ID::USE_CORE_KBD.into(), - xkb::EventType::default(), - xkb::EventType::default(), - xkb::MapPart::default(), - xkb::MapPart::default(), - &xkb::SelectEventsAux { - state_notify: Some(xkb::SelectEventsAuxStateNotify { - affect_state: xkb::StatePart::MODIFIER_LOCK, - state_details: xkb::StatePart::MODIFIER_LOCK, - }), - ..Default::default() - }, - ) - .ok()? - .check() - .ok()?; - let (locked, initial_sequence) = read_x11(&connection)?; - Some(X11CapsLock { connection, locked, initial_sequence }) -} - -#[cfg(target_os = "linux")] -impl X11CapsLock { - fn poll(&mut self) -> Option { - use x11rb::connection::Connection as _; - use x11rb::protocol::Event; - while let Some(event) = self.connection.poll_for_event().ok()? { - if let Event::XkbStateNotify(state) = event - // Events queued before the initial GetState reply must not replace that newer snapshot. - && state.sequence.wrapping_sub(self.initial_sequence) < 0x8000 - { - self.locked = lock_modifier_is_set(state.locked_mods); - } - } - Some(self.locked) - } -} - -#[cfg(target_os = "linux")] -fn read_x11(connection: &x11rb::rust_connection::RustConnection) -> Option<(bool, u16)> { - use x11rb::protocol::xkb; - let state = xkb::get_state(connection, xkb::ID::USE_CORE_KBD.into()).ok()?.reply().ok()?; - Some((lock_modifier_is_set(state.locked_mods), state.sequence)) -} - -#[cfg(target_os = "linux")] -fn lock_modifier_is_set(modifiers: x11rb::protocol::xproto::ModMask) -> bool { - use x11rb::protocol::xproto::ModMask; - u16::from(modifiers) & u16::from(ModMask::LOCK) != 0 -} - -#[cfg(target_os = "macos")] -const MAC_CAPS_LOCK: usize = 1 << 16; - -#[cfg(target_os = "macos")] -fn mac_flags_have_caps_lock(flags: usize) -> bool { - flags & MAC_CAPS_LOCK != 0 -} - -#[cfg(target_os = "macos")] -pub fn read() -> bool { - mac_flags_have_caps_lock(objc2_app_kit::NSEvent::modifierFlags_class().bits()) -} - -#[cfg(windows)] -fn windows_state_has_caps_lock(state: i16) -> bool { - state & 1 != 0 -} - -#[cfg(windows)] -#[allow(unsafe_code)] -pub fn read() -> bool { - // GetKeyState reports the toggle bit for the calling UI thread's keyboard state. - use windows::Win32::UI::Input::KeyboardAndMouse::{GetKeyState, VK_CAPITAL}; - // SAFETY: `GetKeyState` takes a virtual-key code by value and reads no caller memory. - windows_state_has_caps_lock(unsafe { GetKeyState(i32::from(VK_CAPITAL.0)) }) -} - -// Querying XWayland for a native Wayland window would read a different keyboard. - -#[cfg(test)] -mod tests { - #[test] - fn no_host_reader_preserves_scripted_value_and_next_reading_transitions() { - let mut host = super::HostCapsLock::default(); - let mut session = vectorcraft_engine::Session::new(); - session.execute("view.capsLock", &serde_json::json!({"on": true})).unwrap(); - if let Some(on) = host.transition(None) { - session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap(); - } - assert!(session.caps_lock); - assert_eq!(host.transition(Some(false)), Some(false)); - } - - #[cfg(target_os = "linux")] - #[test] - fn no_x11_reader_has_no_transition() { - assert_eq!(super::HostCapsLock::default().read_transition(), None); - } - - #[test] - fn scripted_value_survives_unchanged_host_until_transition() { - let mut host = super::HostCapsLock::default(); - let mut session = vectorcraft_engine::Session::new(); - if let Some(on) = host.observe(false) { - session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap(); - } - session.execute("view.capsLock", &serde_json::json!({"on": true})).unwrap(); - if let Some(on) = host.observe(false) { - session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap(); - } - assert!(session.caps_lock); - session.execute("view.capsLock", &serde_json::json!({"on": false})).unwrap(); - if let Some(on) = host.observe(true) { - session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap(); - } - assert!(session.caps_lock); - if let Some(on) = host.observe(false) { - session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap(); - } - assert!(!session.caps_lock); - } - - #[cfg(target_os = "macos")] - #[test] - fn mac_modifier_flags_map_caps_lock() { - assert!(!super::mac_flags_have_caps_lock(0)); - assert!(!super::mac_flags_have_caps_lock(1 << 17)); - assert!(super::mac_flags_have_caps_lock(1 << 16)); - assert!(super::mac_flags_have_caps_lock((1 << 16) | (1 << 17))); - } - - #[cfg(windows)] - #[test] - fn windows_key_state_maps_toggle_bit() { - assert!(!super::windows_state_has_caps_lock(0)); - assert!(!super::windows_state_has_caps_lock(i16::MIN)); - assert!(super::windows_state_has_caps_lock(1)); - } -} diff --git a/apps/vectorcraft/src/clipboard.rs b/apps/vectorcraft/src/clipboard.rs index 3568b4683e..5830bc90dd 100644 --- a/apps/vectorcraft/src/clipboard.rs +++ b/apps/vectorcraft/src/clipboard.rs @@ -1,5 +1,5 @@ //! The system clipboard with every format Copy offers and Paste reads -//! (`Services::system_clipboard`). +//! (`Services::clipboard`). //! //! - Windows: text, SVG, PDF, PNG and an opaque bitmap (for apps that don't read PNG) in one go; //! Paste reads each of them and EPS, a bitmap as PNG, else as the device-independent bitmap that @@ -23,12 +23,12 @@ use std::io::{Cursor, Read}; use std::path::PathBuf; -use vectorcraft_engine::cmd::clipboard::{BITMAP, EPS, FILE_HEAD, Flavour, PDF, PNG, SVG, TEXT, file_flavour}; -use vectorcraft_ui_egui::{ClipboardRead, SystemClipboard}; +use craft::platform::clipboard::{ClipboardBackend, ClipboardError, ClipboardImage, Flavor}; +use vectorcraft_engine::cmd::clipboard::{BITMAP, EMF, EPS, FILE_HEAD, Flavour, PDF, PNG, SVG, TEXT, file_flavour}; /// This platform's system clipboard. On Linux, `window`'s Wayland connection carries text, SVG and /// PNG where arboard can't open (GNOME has no data-control protocol, a Flatpak there no X11). -pub fn system_clipboard(window: Option>) -> Box { +pub fn system_clipboard(window: Option>) -> Box { #[cfg(windows)] let cb = { let _ = window; @@ -39,6 +39,76 @@ pub fn system_clipboard(window: Option>) - cb } +/// What a read of the clipboard gave: the flavour, or the work that makes it from the bytes already +/// copied off the clipboard (a bitmap decoded and encoded as PNG, an owner's data waited for), which +/// a paste runs off the UI thread ([`ClipboardBackend::read_later`]). +pub(crate) enum ClipboardRead { + /// The flavour. + Now(Flavour), + /// The work that makes the flavour. + Later(MakeFlavour), +} + +/// Makes a flavour from bytes read off the clipboard, on any thread; `None` when it can't be made. +pub(crate) type MakeFlavour = Box Option + Send>; + +/// The platform's form of [`MakeFlavour`]. +type LaterFlavor = Box Option + Send>; + +impl ClipboardRead { + /// The flavour, made at once when it is work. + pub(crate) fn flavour(self) -> Option { + match self { + Self::Now(f) => Some(f), + Self::Later(make) => make(), + } + } +} + +/// The engine's name for `mime`: the platform's are not `'static`. `None` for a type the engine has +/// no name for. +fn engine_mime(mime: &str) -> Option<&'static str> { + [TEXT, SVG, PDF, EPS, EMF, PNG, BITMAP].into_iter().find(|known| *known == mime) +} + +/// The engine's names for `mimes`; a type the engine has no name for is dropped. +fn engine_mimes(mimes: &[&str]) -> Vec<&'static str> { + mimes.iter().filter_map(|m| engine_mime(m)).collect() +} + +/// `flavour` as the platform's, unless it is more than `limit` bytes. +fn bounded(flavour: Flavour, limit: u64) -> Result { + if flavour.data.len() as u64 > limit { + return Err(ClipboardError::TooLarge { limit }); + } + // A bitmap comes back already encoded (PNG, or the TIFF the macOS pasteboard holds), which the + // app and `Clipboard` take as it is. + Ok(Flavor::new(flavour.mime, flavour.data)) +} + +/// The first of `mimes` as `read` reads it, at most `limit` bytes of it. +fn read_flavor(mimes: &[&str], limit: u64, read: impl FnOnce(&[&'static str]) -> Option) -> Result, ClipboardError> { + read(&engine_mimes(mimes)).and_then(ClipboardRead::flavour).map(|f| bounded(f, limit)).transpose() +} + +/// [`read_flavor`] with the slow part of the read left in the work that comes back. +fn read_later_flavor( + mimes: &[&str], + limit: u64, + read: impl FnOnce(&[&'static str]) -> Option, +) -> Result, ClipboardError> { + Ok(read(&engine_mimes(mimes)).map(|read| -> LaterFlavor { Box::new(move || read.flavour().and_then(|f| bounded(f, limit).ok())) })) +} + +/// The clipboard's bitmap as RGBA8, at most `limit` bytes of it before it is decoded. Only a PNG is +/// decoded here: the app takes any other bitmap through [`read_flavor`]. +fn read_image_flavor(limit: u64, read: impl FnOnce(&[&'static str]) -> Option) -> Result, ClipboardError> { + let Some(flavor) = read_flavor(&[BITMAP], limit, read)? else { return Ok(None) }; + let Some(img) = decode_png(&flavor.data) else { return Ok(None) }; + let (width, height) = (img.width(), img.height()); + Ok(Some(ClipboardImage { width, height, rgba: img.into_raw() })) +} + /// The registered Windows clipboard formats a flavour is written under (and read from, first held /// first). #[cfg_attr(not(windows), allow(dead_code))] @@ -67,11 +137,6 @@ fn pasteboard_types(mime: &str) -> &'static [(&'static str, &'static str)] { } } -/// The text flavour among `flavours`. -fn text_of(flavours: &[Flavour]) -> Option { - flavours.iter().find(|f| f.mime == TEXT).map(|f| String::from_utf8_lossy(&f.data).into_owned()) -} - /// Most pixels a side of a bitmap another app put on the clipboard (untrusted data). const MAX_SIDE: u32 = 32_768; @@ -339,9 +404,12 @@ mod win { use clipboard_win::{formats, options::NoClear, raw}; + use std::path::PathBuf; + use super::{ - BITMAP, ClipboardRead, Cursor, Flavour, MAX_BYTES, MAX_URIS, PNG, SVG, SystemClipboard, TEXT, copied_file, copy_within, decode_png, - dib_image, drop_files_within, png_flavour, utf8_most, windows_formats, + BITMAP, ClipboardBackend, ClipboardError, ClipboardImage, ClipboardRead, Cursor, Flavor, Flavour, LaterFlavor, MAX_BYTES, MAX_URIS, PNG, SVG, + TEXT, copied_file, copy_within, decode_png, dib_image, drop_files_within, png_flavour, read_flavor, read_image_flavor, read_later_flavor, + utf8_most, windows_formats, }; /// The device-independent bitmaps, the one that carries alpha first. Each is there whenever the @@ -352,8 +420,8 @@ mod win { windows_formats(mime).iter().filter_map(|n| raw::register_format(n)).map(NonZeroU32::get) } - fn err(e: impl std::fmt::Display) -> String { - format!("{e}") + fn err(e: impl std::fmt::Display) -> ClipboardError { + ClipboardError::Other(e.to_string()) } /// `png` over white, as a BMP file (what the bitmap format takes). @@ -371,30 +439,45 @@ mod win { Some(bmp) } + /// Windows' clipboard, opened afresh by each call. #[derive(Default)] - pub struct Clipboard { - /// The clipboard's sequence number right after our last write. - seq: Option, + pub struct Clipboard; + + impl Clipboard { + /// A device-independent bitmap is copied off the clipboard here and decoded and encoded + /// as PNG by the work that comes back. + fn read_deferred(&mut self, mimes: &[&'static str]) -> Option { + let files = file_paths()?; + // The files are read with the clipboard closed again, not keeping other apps waiting. + copied_file(files, mimes).map(ClipboardRead::Now).or_else(|| { + let _open = clipboard_win::Clipboard::new_attempts(10).ok()?; + mimes.iter().find_map(|m| read_one(m)) + }) + } } - impl SystemClipboard for Clipboard { - /// Writes every flavour it can; the first failure is reported. - fn write(&mut self, flavours: &[Flavour]) -> Result<(), String> { + impl ClipboardBackend for Clipboard { + /// Writes every flavour it can; the first failure is reported. The index answered is the + /// first flavour that was written. + fn write(&mut self, flavors: &[Flavor]) -> Result { let mut result = Ok(()); + let mut first = None; { let _open = clipboard_win::Clipboard::new_attempts(10).map_err(err)?; raw::empty().map_err(err)?; - let mut set = |r: clipboard_win::SysResult<()>| { - if result.is_ok() { - result = r.map_err(err); - } - }; - for f in flavours { + for (i, f) in flavors.iter().enumerate() { + let mut set = |r: clipboard_win::SysResult<()>| match r { + Ok(()) => { + first.get_or_insert(i); + } + Err(e) if result.is_ok() => result = Err(err(e)), + Err(_) => {} + }; if f.mime == TEXT { set(raw::set_string_with(&String::from_utf8_lossy(&f.data), NoClear)); continue; } - for id in formats_of(f.mime) { + for id in formats_of(&f.mime) { set(raw::set_without_clear(id, &f.data)); } if f.mime == PNG @@ -404,44 +487,26 @@ mod win { } } } - self.seq = raw::seq_num(); - result + result.map(|()| first.unwrap_or(0)) } - fn holds_ours(&mut self) -> bool { - // The same text copied later by another app is a different clipboard entry. A - // clipboard manager that republishes our data is also a new entry. - self.seq.is_some() && raw::seq_num() == self.seq + fn read(&mut self, mimes: &[&str], limit: u64) -> Result, ClipboardError> { + read_flavor(mimes, limit, |m| self.read_deferred(m)) } - fn change_count(&mut self) -> Option { - raw::seq_num().map(|n| u64::from(n.get())) + fn read_later(&mut self, mimes: &[&str], limit: u64) -> Result, ClipboardError> { + read_later_flavor(mimes, limit, |m| self.read_deferred(m)) } - fn read(&mut self, mimes: &[&'static str]) -> Option { - self.read_deferred(mimes)?.flavour() + fn read_image(&mut self, limit: u64) -> Result, ClipboardError> { + read_image_flavor(limit, |m| self.read_deferred(m)) } - /// A device-independent bitmap is copied off the clipboard here and decoded and encoded - /// as PNG by the work that comes back. - fn read_deferred(&mut self, mimes: &[&'static str]) -> Option { - let mut files = vec![]; - { - let _open = clipboard_win::Clipboard::new_attempts(10).ok()?; - // None copied when the clipboard holds no file list, or one of more than MAX_BYTES - // or MAX_URIS files: the list is counted before its names are copied. - if copy_registered(formats::CF_HDROP, MAX_BYTES).is_some_and(|block| drop_files_within(&block, MAX_URIS)) { - let _ = raw::get_file_list_path(&mut files); - } - } - // The files are read with the clipboard closed again, not keeping other apps waiting. - copied_file(files, mimes).map(ClipboardRead::Now).or_else(|| { - let _open = clipboard_win::Clipboard::new_attempts(10).ok()?; - mimes.iter().find_map(|m| read_one(m)) - }) + fn read_files(&mut self, _limit: usize) -> Result>, ClipboardError> { + Ok(file_paths().filter(|files| !files.is_empty())) } - fn has(&mut self, mimes: &[&'static str]) -> bool { + fn has(&mut self, mimes: &[&str]) -> bool { raw::is_format_avail(formats::CF_HDROP) || mimes.iter().any(|m| match *m { TEXT => raw::is_format_avail(formats::CF_UNICODETEXT), @@ -451,6 +516,18 @@ mod win { } } + /// The files copied in a file manager, listed with the clipboard open only that long; `None` + /// when it can't be opened. Empty when it holds no file list, or one of more than MAX_BYTES or + /// MAX_URIS files: the list is counted before its names are copied. + fn file_paths() -> Option> { + let _open = clipboard_win::Clipboard::new_attempts(10).ok()?; + let mut files = vec![]; + if copy_registered(formats::CF_HDROP, MAX_BYTES).is_some_and(|block| drop_files_within(&block, MAX_URIS)) { + let _ = raw::get_file_list_path(&mut files); + } + Some(files) + } + /// The size the clipboard reports for format `id`, while it is open. fn size_of(id: u32) -> Option { raw::size(id).map(NonZeroUsize::get) @@ -808,17 +885,18 @@ mod portable { use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; - use super::{BITMAP, ClipboardRead, Flavour, PNG, SystemClipboard, TEXT, copied_file, decode_png, png_flavour, takes_files, text_of}; + use super::{ + BITMAP, ClipboardBackend, ClipboardError, ClipboardImage, ClipboardRead, Flavor, Flavour, LaterFlavor, PNG, TEXT, copied_file, decode_png, + engine_mimes, png_flavour, read_flavor, read_image_flavor, read_later_flavor, takes_files, + }; - /// What our last write put on the clipboard. + /// What our last write put on the clipboard, for a read answered late ([`Unanswered::paste`]): a + /// paste does not take what this app copied. Whether the clipboard still holds a copy is + /// [`Clipboard::owns`](ClipboardBackend::owns). #[derive(Clone)] enum Ours { Text(String), Image(usize, usize), - /// A Copy through the Wayland core protocol, whose data source tells whether the - /// clipboard still holds it. - #[cfg(target_os = "linux")] - Source, } /// A read of arboard's clipboard. @@ -1216,16 +1294,6 @@ mod portable { } } - /// Whether the clipboard holds the core protocol's last Copy made here (never for arboard, - /// whose writes are checked by what they wrote). - #[cfg(target_os = "linux")] - fn holds_source(&mut self) -> bool { - match self { - Self::Arboard(_) => false, - Self::Wayland(cb) => cb.holds_ours(), - } - } - /// The bitmap, for a check on the UI thread: on Linux and the BSDs it waits /// [`LOAD_WAIT`](super::loads::LOAD_WAIT) at most, as text does. fn image_now(&mut self) -> Result, String> { @@ -1462,61 +1530,7 @@ mod portable { } } - impl SystemClipboard for Clipboard { - /// arboard takes the text, else the PNG as a bitmap; the Wayland core protocol offers the - /// SVG, PNG and text together ([`DataClipboard::copy`](super::wayland::DataClipboard::copy)). - fn write(&mut self, flavours: &[Flavour]) -> Result<(), String> { - let cb = self.cb(Asker::User)?; - #[cfg(target_os = "linux")] - if let Backend::Wayland(wl) = cb { - wl.copy(flavours)?; - // What a read got late was on the clipboard before this write. - wl.forget_unanswered(); - self.ours = wl.holds_ours().then_some(Ours::Source); - return Ok(()); - } - let text = text_of(flavours); - let image = match &text { - Some(_) => None, - None => flavours.iter().find(|f| f.mime == PNG).and_then(|f| decode_png(&f.data)), - }; - let ours = match (text, image) { - (Some(t), _) => { - cb.set_text(t.as_str())?; - Some(Ours::Text(t)) - } - (None, Some(img)) => { - let (width, height) = (img.width() as usize, img.height() as usize); - cb.set_image(arboard::ImageData { width, height, bytes: Cow::Owned(img.into_raw()) })?; - Some(Ours::Image(width, height)) - } - (None, None) => { - cb.clear()?; - None - } - }; - // What a read got late was on the clipboard before this write. - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] - cb.forget_unanswered(); - self.ours = ours; - Ok(()) - } - - fn holds_ours(&mut self) -> bool { - let Some(cb) = self.cb.opened() else { return false }; - match &self.ours { - Some(Ours::Text(t)) => cb.get_text().is_ok_and(|now| now == *t), - Some(Ours::Image(w, h)) => cb.image_now().is_ok_and(|now| (now.width, now.height) == (*w, *h)), - #[cfg(target_os = "linux")] - Some(Ours::Source) => cb.holds_source(), - None => false, - } - } - - fn read(&mut self, mimes: &[&'static str]) -> Option { - self.read_now_or_later(mimes)?.flavour() - } - + impl Clipboard { /// arboard's image is read here and encoded as PNG by the work that comes back. On Linux and /// the BSDs, after a read that got no answer in its wait (such as the check whether the /// clipboard still holds what was copied here, or one of the reads here), the work waits for @@ -1534,23 +1548,105 @@ mod portable { } read } + } + + impl ClipboardBackend for Clipboard { + /// arboard takes the text, else the PNG as a bitmap; the Wayland core protocol offers the + /// SVG, PNG and text together ([`DataClipboard::copy`](super::wayland::DataClipboard::copy)). + /// The index answered is the flavour that went out: the text, else the PNG, and on the + /// core protocol the first flavour it offers. + fn write(&mut self, flavors: &[Flavor]) -> Result { + let cb = self.cb(Asker::User).map_err(ClipboardError::Other)?; + #[cfg(target_os = "linux")] + if let Backend::Wayland(wl) = cb { + use super::{SVG, engine_mime}; + let offered: Vec = + flavors.iter().filter_map(|f| Some(Flavour { mime: engine_mime(&f.mime)?, data: f.data.clone() })).collect(); + wl.copy(&offered).map_err(ClipboardError::Other)?; + // What a read got late was on the clipboard before this write. + wl.forget_unanswered(); + self.ours = None; + return Ok(flavors.iter().position(|f| !f.data.is_empty() && matches!(&*f.mime, SVG | PNG | TEXT)).unwrap_or(0)); + } + let text = flavors.iter().enumerate().find(|(_, f)| f.mime == TEXT).map(|(i, f)| (i, String::from_utf8_lossy(&f.data).into_owned())); + let image = match &text { + Some(_) => None, + None => flavors.iter().enumerate().find(|(_, f)| f.mime == PNG).and_then(|(i, f)| Some((i, decode_png(&f.data)?))), + }; + let (ours, wrote) = match (text, image) { + (Some((i, t)), _) => { + cb.set_text(t.as_str()).map_err(ClipboardError::Other)?; + (Some(Ours::Text(t)), i) + } + (None, Some((i, img))) => { + let (width, height) = (img.width() as usize, img.height() as usize); + cb.set_image(arboard::ImageData { width, height, bytes: Cow::Owned(img.into_raw()) }).map_err(ClipboardError::Other)?; + (Some(Ours::Image(width, height)), i) + } + (None, None) => { + cb.clear().map_err(ClipboardError::Other)?; + (None, 0) + } + }; + // What a read got late was on the clipboard before this write. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + cb.forget_unanswered(); + self.ours = ours; + Ok(wrote) + } + + fn read(&mut self, mimes: &[&str], limit: u64) -> Result, ClipboardError> { + read_flavor(mimes, limit, |m| self.read_now_or_later(m)) + } + + fn read_later(&mut self, mimes: &[&str], limit: u64) -> Result, ClipboardError> { + read_later_flavor(mimes, limit, |m| self.read_deferred(m)) + } + + fn read_image(&mut self, limit: u64) -> Result, ClipboardError> { + read_image_flavor(limit, |m| self.read_now_or_later(m)) + } + + /// The copied files of arboard's clipboard; the Wayland core protocol reads its file list + /// with the rest of a paste, so it lists none here. + fn read_files(&mut self, _limit: usize) -> Result>, ClipboardError> { + let cb = self.cb(Asker::User).map_err(ClipboardError::Other)?; + Ok(Some(cb.file_list()).filter(|files| !files.is_empty())) + } /// Text or files copied in a file manager (their list read, no file opened: /// [`arboard_has`]), on macOS vector art or a bitmap (by the pasteboard's types), and on the /// Wayland core protocol copied files, SVG, text or PNG (by the types offered, nothing read). /// arboard has no cheap way to ask for a bitmap (reading one costs as much as pasting it): /// the paste keys take it, the menu item waits for text or copied files. - fn has(&mut self, mimes: &[&'static str]) -> bool { + fn has(&mut self, mimes: &[&str]) -> bool { + let mimes = engine_mimes(mimes); #[cfg(target_os = "macos")] - if super::mac::has(mimes) { + if super::mac::has(&mimes) { return true; } let Ok(cb) = self.cb(Asker::Probe) else { return false }; #[cfg(target_os = "linux")] if let Backend::Wayland(wl) = cb { - return wl.has(mimes); + return wl.has(&mimes); } - arboard_has(mimes, cb, Backend::get_text, Backend::file_list) + arboard_has(&mimes, cb, Backend::get_text, Backend::file_list) + } + + /// Whether arboard's clipboard still holds the Copy made here, by its text or its bitmap's + /// size read with [`Backend::image_now`]'s wait, so the check on the UI thread waits no + /// longer than a text read. `None` (the platform clipboard compares what it reads) before a + /// handle is open and on the Wayland core protocol. + fn owns(&mut self) -> Option { + let cb = self.cb.opened()?; + #[cfg(target_os = "linux")] + if matches!(cb, Backend::Wayland(_)) { + return None; + } + Some(match self.ours.as_ref()? { + Ours::Text(t) => cb.get_text().is_ok_and(|now| now == *t), + Ours::Image(w, h) => cb.image_now().is_ok_and(|now| (now.width, now.height) == (*w, *h)), + }) } } @@ -1779,8 +1875,8 @@ mod portable { // The Paste check's handle is one of these: when the app quits, its unanswered X11 read // ends `X11_READ_LIMIT` after it was sent, and an idle worker stops within `LOAD_WAIT`. // Quitting waits for that handle until both are over. - assert!(vectorcraft_ui_egui::CLIPBOARD_PROBE_STOP_WAIT >= finish(false) + super::super::loads::LOAD_WAIT); - assert!(vectorcraft_ui_egui::CLIPBOARD_PROBE_STOP_WAIT >= finish(true) + super::super::loads::LOAD_WAIT); + assert!(craft::platform::clipboard::PROBE_STOP_WAIT >= finish(false) + super::super::loads::LOAD_WAIT); + assert!(craft::platform::clipboard::PROBE_STOP_WAIT >= finish(true) + super::super::loads::LOAD_WAIT); } #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] @@ -2037,9 +2133,9 @@ mod wayland { use std::sync::{Arc, Mutex, MutexGuard, PoisonError, mpsc}; use std::time::{Duration, Instant}; + use super::ClipboardRead; use rustix::event::{PollFd, PollFlags, Timespec}; use vectorcraft_engine::cmd::clipboard::names_a_picture; - use vectorcraft_ui_egui::ClipboardRead; use wayland_client::backend::ObjectData; use wayland_client::globals::{GlobalListContents, registry_queue_init}; use wayland_client::protocol::wl_callback::{self, WlCallback}; @@ -2460,11 +2556,6 @@ mod wayland { (takes_files(mimes) && file_list_type(&seen.offered).is_some()) || mimes.iter().any(|m| wire_type(m, &seen.offered).is_some()) } - /// Whether the clipboard holds this connection's last Copy. - pub(super) fn holds_ours(&self) -> bool { - lock(&self.seen).ours - } - /// The text read that got no answer in its wait, while its answer has still not come and a /// paste of one of `mimes` can take text. Once it has come the answer may be old, and it is /// dropped: a new read is made. @@ -2769,10 +2860,6 @@ mod wayland { self.reads.has(mimes) } - pub fn holds_ours(&self) -> bool { - self.reads.holds_ours() - } - /// The read that got no answer in its wait, when a paste of one of `mimes` can take its /// answer ([`Reads::unanswered`]). pub(super) fn unanswered(&mut self, mimes: &[&'static str]) -> Option { diff --git a/apps/vectorcraft/src/control_server.rs b/apps/vectorcraft/src/control_server.rs deleted file mode 100644 index 1a44eba288..0000000000 --- a/apps/vectorcraft/src/control_server.rs +++ /dev/null @@ -1,320 +0,0 @@ -//! Loopback JSON-lines control server: one request per line, one reply per line. -//! This is the transport the MCP server (`vectorcraft mcp --connect`) wraps. -//! -//! The server only ever reads requests: a line that is not a JSON object with a string `method` -//! (an HTTP request line from a browser's cross-origin `fetch`, a stray `nc`, binary junk) gets -//! one error reply and the connection is closed, so nothing after it is executed. Lines are -//! bounded ([`MAX_LINE`]) and so is the number of open connections ([`MAX_CONNECTIONS`]); junk -//! never reaches the UI thread. See `docs/control-protocol.md`. - -use std::io::{BufRead, BufReader, BufWriter, Read, Write}; -use std::net::{TcpListener, TcpStream}; -use std::sync::Arc; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::mpsc::{Receiver, Sender, channel}; -use std::time::Duration; - -use serde_json::{Value, json}; -use vectorcraft_ui_egui::ControlRequest; - -#[path = "control_deadlines.rs"] -mod deadlines; -use deadlines::{DeadlineReader, DeadlineWriter}; - -/// Longest accepted request line (bytes, without the newline). Requests are small JSON objects; -/// anything longer is refused and the connection closed. -pub const MAX_LINE: usize = 4 * 1024 * 1024; -/// Connections served at once; further ones get an error line and are closed. -pub const MAX_CONNECTIONS: usize = 16; -/// Size in bytes of the buffer that [`write_line`] writes a reply line through. -const REPLY_CHUNK: usize = 64 * 1024; - -/// How long a request waits for the app's reply. -const REPLY_WAIT: Duration = Duration::from_secs(60); - -/// The reply to a request the app didn't answer in [`REPLY_WAIT`]. One it had not started is -/// withdrawn, so it never runs after its caller was told it failed; one it is running can't be -/// stopped, and the reply says its outcome isn't known. -fn timed_out(ticket: &vectorcraft_ui_egui::ControlTicket) -> Value { - let error = if ticket.give_up() { - "timeout: the app did not start the request in time; it was withdrawn and will not run" - } else { - "timeout: the app is still running the request; it may yet complete" - }; - json!({"ok": false, "error": error}) -} - -#[derive(Clone, Copy)] -struct ConnectionTimeouts { - idle: Duration, - line: Duration, - write: Duration, -} - -impl Default for ConnectionTimeouts { - fn default() -> Self { - Self { idle: Duration::from_secs(300), line: Duration::from_secs(30), write: Duration::from_secs(60) } - } -} - -pub fn start(port: u16, ctx: egui::Context) -> Receiver { - let (tx, rx) = channel::(); - let listener = match TcpListener::bind(("127.0.0.1", port)) { - Ok(l) => l, - Err(e) => { - eprintln!("vectorcraft: control server failed to bind 127.0.0.1:{port}: {e}"); - return rx; - } - }; - eprintln!("vectorcraft: control server listening on 127.0.0.1:{port}"); - #[cfg(target_os = "macos")] - keep_answering(); - std::thread::spawn(move || accept_loop(listener, tx, ctx)); - rx -} - -/// The activity the control channel holds on macOS: work the user asked for, which may let the -/// system sleep when idle, with full timer precision. Without it, App Nap lowers every thread to -/// the lowest priority within about a minute of the window no longer being visible. -#[cfg(target_os = "macos")] -fn activity_options() -> objc2_foundation::NSActivityOptions { - use objc2_foundation::NSActivityOptions; - NSActivityOptions::UserInitiatedAllowingIdleSystemSleep | NSActivityOptions::LatencyCritical -} - -/// Begins the control channel's activity. It lasts until the process ends. -#[cfg(target_os = "macos")] -fn keep_answering() { - use objc2_foundation::{NSProcessInfo, NSString}; - let reason = NSString::from_str("Answering control requests"); - let activity = NSProcessInfo::processInfo().beginActivityWithOptions_reason(activity_options(), &reason); - // The token is never released or passed to `endActivity`, so the activity lasts for the process's lifetime. - std::mem::forget(activity); -} - -fn accept_loop(listener: TcpListener, tx: Sender, ctx: egui::Context) { - let open = Arc::new(AtomicUsize::new(0)); - for stream in listener.incoming().flatten() { - let Some(slot) = acquire_slot(&open) else { - let mut out = DeadlineWriter::new(stream, ConnectionTimeouts::default().write); - // Best effort: the connection is dropped either way, and a peer that can't read the reason loses nothing. - if out.begin_reply().is_ok() { - let _ = write_line(&mut out, &json!({"ok": false, "error": "too many control connections"})); - } - continue; - }; - if let Err(e) = spawn_connection(stream, tx.clone(), ctx.clone(), slot, ConnectionTimeouts::default()) { - eprintln!("vectorcraft: control worker failed to start: {e}"); - } - } -} - -struct ConnectionSlot(Arc); - -fn acquire_slot(open: &Arc) -> Option { - let mut n = open.load(Ordering::SeqCst); - loop { - if n >= MAX_CONNECTIONS { - return None; - } - match open.compare_exchange_weak(n, n + 1, Ordering::SeqCst, Ordering::SeqCst) { - Ok(_) => return Some(ConnectionSlot(Arc::clone(open))), - Err(current) => n = current, - } - } -} - -impl Drop for ConnectionSlot { - fn drop(&mut self) { - // Each successful acquisition creates exactly one non-cloneable guard. - self.0.fetch_sub(1, Ordering::SeqCst); - } -} - -fn spawn_connection( - stream: TcpStream, - tx: Sender, - ctx: egui::Context, - slot: ConnectionSlot, - timeouts: ConnectionTimeouts, -) -> std::io::Result> { - std::thread::Builder::new().name("vectorcraft-control".into()).spawn(move || { - let _slot = slot; - serve_socket(stream, timeouts, |method, params| { - let (req, rrx) = ControlRequest::new(method, params); - let ticket = req.ticket(); - tx.send(req).ok()?; - ctx.request_repaint(); - Some(rrx.recv_timeout(REPLY_WAIT).unwrap_or_else(|_| timed_out(&ticket))) - }); - }) -} - -fn serve_socket(stream: TcpStream, timeouts: ConnectionTimeouts, handle: impl FnMut(String, Value) -> Option) { - let Ok(read) = stream.try_clone() else { return }; - let closer = stream.try_clone().ok(); - let read = DeadlineReader::new(read, timeouts.idle, timeouts.line); - // Replies reach the writer in [`REPLY_CHUNK`] pieces ([`write_line`]), so checking the remaining - // budget costs one socket option call per piece, not one per JSON token. - let out = DeadlineWriter::new(stream, timeouts.write); - serve_lines_with( - read, - out, - handle, - |reader| { - let buffered = !reader.buffer().is_empty(); - reader.get_mut().begin_line(buffered) - }, - DeadlineWriter::begin_reply, - ); - if let Some(s) = closer { - close_gracefully(s); - } -} - -/// How long [`close_gracefully`] waits for the peer to close its side. -const CLOSE_DRAIN: Duration = Duration::from_secs(1); - -/// The most [`close_gracefully`] reads from a peer that keeps sending. -const MAX_DRAIN: usize = 1 << 20; - -/// Ends a connection: no more replies (the peer reads them all, then end of stream), then what the -/// peer still sends is read and dropped until it closes too, for at most [`CLOSE_DRAIN`] and -/// [`MAX_DRAIN`] bytes. On Windows, dropping a socket with unread input resets the connection, and -/// the reset can discard replies the peer has not read yet. -fn close_gracefully(mut s: TcpStream) { - // Each step is best effort: a peer that is already gone needs none of them. - let _ = s.shutdown(std::net::Shutdown::Write); - let _ = s.set_read_timeout(Some(CLOSE_DRAIN)); - let deadline = std::time::Instant::now() + CLOSE_DRAIN; - let (mut buf, mut left) = ([0u8; 4096], MAX_DRAIN); - while left > 0 && std::time::Instant::now() < deadline { - match s.read(&mut buf) { - Ok(0) | Err(_) => break, - Ok(n) => left = left.saturating_sub(n), - } - } -} - -/// One parsed line. -enum Line { - Request { - id: Value, - method: String, - params: Value, - }, - Blank, - /// Not a request: reply with this error and close the connection. - Reject(String), -} - -fn parse_line(bytes: &[u8]) -> Line { - let Ok(text) = std::str::from_utf8(bytes) else { - return Line::Reject("not a control request (invalid UTF-8); closing the connection".into()); - }; - let text = text.trim(); - if text.is_empty() { - return Line::Blank; - } - let msg = match serde_json::from_str::(text) { - Ok(v) => v, - Err(e) => return Line::Reject(format!("bad JSON ({e}); expected one JSON request object per line; closing the connection")), - }; - let Some(obj) = msg.as_object() else { - return Line::Reject("not a control request (expected a JSON object); closing the connection".into()); - }; - let Some(method) = obj.get("method").and_then(Value::as_str) else { - return Line::Reject("not a control request (missing string `method`); closing the connection".into()); - }; - Line::Request { - id: obj.get("id").cloned().unwrap_or(Value::Null), - method: method.to_string(), - params: obj.get("params").cloned().unwrap_or(json!({})), - } -} - -/// Read one `\n`-terminated line of at most `max` bytes into `buf` (newline stripped). -/// `Ok(false)` at end of stream; `Err` when the line is too long or the read fails. -fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec, max: usize) -> Result { - buf.clear(); - // `take` bounds the bytes buffered for one line: a peer can't make us allocate more than `max`. - let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1); - let n = reader.take(limit).read_until(b'\n', buf).map_err(|e| match e.kind() { - // The line's deadline ran out (Windows reports it as TimedOut, Unix as WouldBlock). - std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock => "request line not completed in time; closing the connection".to_string(), - _ => e.to_string(), - })?; - if n == 0 { - return Ok(false); - } - if buf.last() == Some(&b'\n') { - buf.pop(); - if buf.last() == Some(&b'\r') { - buf.pop(); - } - return Ok(true); - } - if buf.len() > max { - return Err(format!("request line longer than {max} bytes; closing the connection")); - } - // Last line without a newline, then end of stream. - Ok(true) -} - -/// Write `v` and a newline to `out` through a buffer of [`REPLY_CHUNK`] bytes, then flush `out`. -fn write_line(out: &mut impl Write, v: &Value) -> std::io::Result<()> { - let mut out = BufWriter::with_capacity(REPLY_CHUNK, out); - writeln!(out, "{v}")?; - out.flush() -} - -/// Serve requests from `read`, answering on `out`, until the peer closes, sends something that is -/// not a request, or `handle` returns `None` (app gone). `handle` gets `(method, params)` and -/// returns the reply object (the request's `id` is added here). -#[cfg(test)] -fn serve_lines(read: R, out: W, handle: impl FnMut(String, Value) -> Option) { - serve_lines_with(read, out, handle, |_| Ok(()), |_| Ok(())); -} - -fn serve_lines_with( - read: R, - mut out: W, - mut handle: impl FnMut(String, Value) -> Option, - mut begin_line: impl FnMut(&mut BufReader) -> std::io::Result<()>, - mut begin_reply: impl FnMut(&mut W) -> std::io::Result<()>, -) { - let mut reader = BufReader::new(read); - let mut buf = Vec::new(); - loop { - if begin_line(&mut reader).is_err() { - return; - } - let reject = match read_bounded_line(&mut reader, &mut buf, MAX_LINE) { - Ok(false) => return, - // Nothing of a line arrived (the idle wait ran out, or the peer is gone): close without - // a word. A line nobody asked for would be read as the reply to the client's next request. - Err(_) if buf.is_empty() => return, - Err(e) => e, - Ok(true) => match parse_line(&buf) { - Line::Blank => continue, - Line::Reject(e) => e, - Line::Request { id, method, params } => { - let Some(mut r) = handle(method, params) else { return }; - if let Some(o) = r.as_object_mut() { - o.insert("id".into(), id); - } - if begin_reply(&mut out).and_then(|()| write_line(&mut out, &r)).is_err() { - return; - } - continue; - } - }, - }; - // Best effort: the connection closes either way, and a peer that can't read the reason loses nothing. - let _ = begin_reply(&mut out).and_then(|()| write_line(&mut out, &json!({"ok": false, "error": reject}))); - return; - } -} - -#[cfg(test)] -mod tests; diff --git a/apps/vectorcraft/src/control_server/tests.rs b/apps/vectorcraft/src/control_server/tests.rs deleted file mode 100644 index 7aa290e01f..0000000000 --- a/apps/vectorcraft/src/control_server/tests.rs +++ /dev/null @@ -1,411 +0,0 @@ -use super::*; - -fn short_timeouts() -> ConnectionTimeouts { - ConnectionTimeouts { idle: Duration::from_millis(150), line: Duration::from_millis(120), write: Duration::from_millis(150) } -} - -/// How long a test waits for the server to reply or to close a connection. The wait only ends a -/// test whose server never does either; the budgets under test are 120 and 150 ms, and 1 s in the -/// persistent test. On a busy machine the server's thread can pause for seconds before or between -/// its reads and writes, and a wait of a few seconds then fails a server that closes the -/// connection on time. -const WAIT: Duration = Duration::from_secs(20); - -/// The short line deadline, with idle and reply budgets longer than [`WAIT`]. On a busy machine -/// either thread can pause for more than 150 ms between connecting and sending, or between -/// starting a reply and writing it, and a short budget then closes the connection with no reply. -fn line_timeouts() -> ConnectionTimeouts { - ConnectionTimeouts { idle: Duration::from_secs(30), write: Duration::from_secs(30), ..short_timeouts() } -} - -fn socket_fixture( - timeouts: ConnectionTimeouts, - handle: impl FnMut(String, Value) -> Option + Send + 'static, -) -> (TcpStream, Receiver<()>, std::thread::JoinHandle<()>) { - let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); - let addr = listener.local_addr().unwrap(); - let (finished, done) = channel(); - let worker = std::thread::spawn(move || { - let (stream, _) = listener.accept().unwrap(); - socket2::SockRef::from(&stream).set_send_buffer_size(4096).unwrap(); - serve_socket(stream, timeouts, handle); - finished.send(()).unwrap(); - }); - let client = TcpStream::connect(addr).unwrap(); - socket2::SockRef::from(&client).set_recv_buffer_size(4096).unwrap(); - client.set_read_timeout(Some(WAIT)).unwrap(); - (client, done, worker) -} - -fn expect_socket_deadline(client: TcpStream, done: Receiver<()>, worker: std::thread::JoinHandle<()>) { - let stopped = done.recv_timeout(WAIT).is_ok(); - // Always unblock the old implementation too, so a failed regression leaves no worker behind. - let _ = client.shutdown(std::net::Shutdown::Both); - drop(client); - worker.join().unwrap(); - assert!(stopped, "the server retained a stalled connection beyond its transport deadline"); -} - -#[test] -fn idle_control_socket_releases_its_worker() { - let (client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("no request expected")); - expect_socket_deadline(client, done, worker); -} - -/// An idle connection is closed without a line: a client that sends its next request late -/// must not find an error waiting where its reply should be. -#[test] -fn idle_expiry_closes_without_writing_a_line() { - let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("no request expected")); - let mut got = Vec::new(); - match client.read_to_end(&mut got) { - // On Windows the server's close can reach the client as a reset. - Err(e) if e.kind() == std::io::ErrorKind::ConnectionReset => {} - Ok(_) => {} - Err(e) => panic!("reading the idle connection: {e}"), - } - assert_eq!(String::from_utf8_lossy(&got), "", "the app wrote to an idle connection"); - expect_socket_deadline(client, done, worker); -} - -/// A line that stalls is refused in words a client's author can act on, not the system's. -#[test] -fn stalled_control_line_is_refused_with_the_reason() { - let (mut client, done, worker) = socket_fixture(line_timeouts(), |_, _| panic!("incomplete requests must not execute")); - client.write_all(b"{\"method\":").unwrap(); - let mut line = String::new(); - BufReader::new(client.try_clone().unwrap()).read_line(&mut line).unwrap(); - assert_eq!( - serde_json::from_str::(&line).unwrap(), - json!({"ok": false, "error": "request line not completed in time; closing the connection"}) - ); - expect_socket_deadline(client, done, worker); -} - -#[test] -fn partial_control_line_releases_its_worker() { - let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("incomplete requests must not execute")); - client.write_all(b"{\"method\":").unwrap(); - expect_socket_deadline(client, done, worker); -} - -#[test] -fn trickled_control_line_has_an_absolute_deadline() { - let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("incomplete requests must not execute")); - client.write_all(b"{").unwrap(); - let mut writer = client.try_clone().unwrap(); - let stop = Arc::new(std::sync::atomic::AtomicBool::new(false)); - let writing = Arc::clone(&stop); - let trickle = std::thread::spawn(move || { - while !writing.load(Ordering::SeqCst) { - if writer.write_all(b" ").is_err() { - break; - } - std::thread::sleep(Duration::from_millis(20)); - } - }); - let stopped = done.recv_timeout(WAIT).is_ok(); - stop.store(true, Ordering::SeqCst); - // Both socket copies belong to this fixture; shutdown cleans up the baseline failure as well. - let _ = client.shutdown(std::net::Shutdown::Both); - trickle.join().unwrap(); - worker.join().unwrap(); - assert!(stopped, "trickled bytes restarted the line's deadline"); -} - -#[test] -fn a_nonreading_control_peer_cannot_retain_the_writer() { - let payload = "x".repeat(2 * 1024 * 1024); - let (mut client, done, worker) = socket_fixture(short_timeouts(), move |_, _| Some(json!({"ok": true, "result": payload}))); - client.write_all(b"{\"method\":\"large\"}\n").unwrap(); - expect_socket_deadline(client, done, worker); -} - -/// Each request gets its own line and reply budgets. The handler takes longer than both budgets, -/// so a deadline kept from the previous request runs out. The line and reply budgets are 1 s, and -/// the idle budget is 30 s, longer than the client's [`WAIT`]: on a busy machine either thread can -/// pause for more than the short budgets of [`short_timeouts`] between starting a budget and the -/// read or write it covers. -#[test] -fn persistent_control_requests_get_fresh_transport_deadlines() { - let timeouts = ConnectionTimeouts { idle: Duration::from_secs(30), line: Duration::from_secs(1), write: Duration::from_secs(1) }; - let (mut client, done, worker) = socket_fixture(timeouts, |_, _| { - // Application processing is not transport time; begin the reply budget afterwards. - std::thread::sleep(Duration::from_millis(1250)); - Some(json!({"ok": true})) - }); - let mut reader = BufReader::new(client.try_clone().unwrap()); - for id in [1, 2] { - // The client sends each line in one write. `writeln!` on the socket sends the JSON in many - // small writes, and when the machine is busy, a pause of more than the line deadline between - // two of them closes the connection. - client.write_all(format!("{}\n", json!({"id": id, "method": "inspect"})).as_bytes()).unwrap(); - let mut line = String::new(); - reader.read_line(&mut line).unwrap(); - assert_eq!(serde_json::from_str::(&line).unwrap(), json!({"id": id, "ok": true})); - } - client.shutdown(std::net::Shutdown::Write).unwrap(); - done.recv_timeout(WAIT).unwrap(); - worker.join().unwrap(); -} - -#[test] -fn buffered_partial_control_line_also_expires() { - let (mut client, done, worker) = socket_fixture(line_timeouts(), |_, _| Some(json!({"ok": true}))); - client.write_all(b"{\"id\":1,\"method\":\"inspect\"}\n{").unwrap(); - let mut line = String::new(); - BufReader::new(client.try_clone().unwrap()).read_line(&mut line).unwrap(); - assert_eq!(serde_json::from_str::(&line).unwrap()["id"], 1); - expect_socket_deadline(client, done, worker); -} - -#[test] -fn timed_out_worker_returns_its_connection_slot() { - let open = Arc::new(AtomicUsize::new(0)); - let held: Vec<_> = (0..MAX_CONNECTIONS - 1).map(|_| acquire_slot(&open).unwrap()).collect(); - let slot = acquire_slot(&open).unwrap(); - assert!(acquire_slot(&open).is_none()); - let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); - let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); - let (stream, _) = listener.accept().unwrap(); - let (tx, _rx) = channel(); - let worker = spawn_connection(stream, tx, egui::Context::default(), slot, short_timeouts()).unwrap(); - let start = std::time::Instant::now(); - while open.load(Ordering::SeqCst) == MAX_CONNECTIONS && start.elapsed() < WAIT { - std::thread::sleep(Duration::from_millis(10)); - } - let released = open.load(Ordering::SeqCst) < MAX_CONNECTIONS; - // Clean up an old implementation that never returned its slot as well. - let _ = client.shutdown(std::net::Shutdown::Both); - worker.join().unwrap(); - assert!(released, "the deadline did not free capacity for the next client"); - let replacement = acquire_slot(&open).expect("a new client can reserve the freed slot"); - drop(replacement); - drop(held); - assert_eq!(open.load(Ordering::SeqCst), 0); -} - -fn run(input: &[u8]) -> (Vec, Vec) { - let mut out = Vec::new(); - let mut calls = Vec::new(); - serve_lines(input, &mut out, |m, _p| { - calls.push(m); - Some(json!({"ok": true, "result": null})) - }); - let replies = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str::(l).unwrap()).collect(); - (replies, calls) -} - -/// Counts the `write` calls made on it and keeps the bytes they write. -#[derive(Default)] -struct Writes { - calls: usize, - bytes: Vec, -} - -impl Write for Writes { - fn write(&mut self, buf: &[u8]) -> std::io::Result { - self.calls += 1; - self.bytes.extend_from_slice(buf); - Ok(buf.len()) - } - - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } -} - -/// A reply shaped like `document.inspect`'s for a layer of `n` squares in rows of 200. -fn inspect_reply(n: u64) -> Value { - let paths: Vec = (0..n) - .map(|k| { - let (x, y) = ((k % 200) as f64 * 20.0, (k / 200) as f64 * 20.0); - json!({"anchors": 4, "bounds": {"height": 10.0, "width": 10.0, "x": x, "y": y}, "closed": true, "fill": "#f4a261", - "id": k + 2, "kind": "Path", "locked": false, "name": "", "stroke": "None", "strokeWidth": 0.0, "visible": true}) - }) - .collect(); - json!({"ok": true, "result": {"layers": [{"children": paths, "id": 1, "kind": "Layer", "name": "Layer 1"}]}}) -} - -/// #1725: a request its caller gave up before the app took it never runs; one the app took -/// first can't be withdrawn, and the timeout says so. -#[test] -fn a_timed_out_request_is_withdrawn_unless_it_started() { - let (waiting, _rx) = ControlRequest::new("engine.execute", json!({})); - assert!(timed_out(&waiting.ticket())["error"].as_str().unwrap().contains("will not run")); - assert!(!waiting.claim(), "the app skips a withdrawn request"); - let (running, _rx) = ControlRequest::new("engine.execute", json!({})); - assert!(running.claim()); - assert!(timed_out(&running.ticket())["error"].as_str().unwrap().contains("still running")); - assert!(!running.claim(), "a request is taken once"); -} - -#[test] -fn requests_are_answered_in_order_with_ids() { - let (r, calls) = run(b"{\"id\":1,\"method\":\"a\"}\n\n{\"id\":2,\"method\":\"b\",\"params\":{}}\r\n{\"method\":\"c\"}"); - assert_eq!(calls, ["a", "b", "c"]); - assert_eq!(r.len(), 3); - assert_eq!(r[0]["id"], 1); - assert_eq!(r[1]["id"], 2); - assert_eq!(r[2]["id"], Value::Null); -} - -#[test] -fn replies_are_written_in_few_large_writes() { - for reply in [json!({"ok": true, "result": null}), inspect_reply(2_000)] { - let mut out = Writes::default(); - let mut once = Some(reply.clone()); - serve_lines(&b"{\"id\":1,\"method\":\"document.inspect\"}\n"[..], &mut out, |_, _| once.take()); - let mut want = reply; - want["id"] = json!(1); - let text = String::from_utf8(out.bytes).unwrap(); - // The writer receives the bytes that `writeln!(out, "{want}")` writes, in at most one write per 4 KiB. - assert_eq!(text, format!("{want}\n")); - assert!(out.calls <= text.len().div_ceil(4096), "{} writes for {} bytes", out.calls, text.len()); - } - // A refusal is one write as well. - let mut out = Writes::default(); - serve_lines(&b"hello\n"[..], &mut out, |_, _| None); - assert_eq!(out.calls, 1); -} - -#[test] -fn http_request_closes_before_the_body_runs() { - // A browser's cross-origin `fetch` POST: the request line is rejected and the - // connection closed, so the JSON body is never executed. - let http = b"POST / HTTP/1.1\r\nHost: 127.0.0.1:7979\r\nOrigin: https://attacker.example\r\nContent-Type: text/plain\r\n\r\n\ - {\"id\":7,\"method\":\"engine.execute\",\"params\":{\"command\":\"file.new\",\"params\":{}}}\n"; - let (r, calls) = run(http); - assert!(calls.is_empty(), "nothing may run: {calls:?}"); - assert_eq!(r.len(), 1); - assert_eq!(r[0]["ok"], false); - assert!(r[0]["error"].as_str().unwrap().contains("closing the connection")); -} - -#[test] -fn non_request_json_closes_the_connection() { - for junk in [ - &b"[1,2]\n{\"method\":\"a\"}\n"[..], - b"{\"id\":1}\n{\"method\":\"a\"}\n", - b"{\"method\":5}\n{\"method\":\"a\"}\n", - b"\xff\xfe\n{\"method\":\"a\"}\n", - ] { - let (r, calls) = run(junk); - assert!(calls.is_empty(), "{calls:?}"); - assert_eq!(r.len(), 1); - assert_eq!(r[0]["ok"], false); - } -} - -#[test] -fn a_request_before_junk_still_runs() { - let (r, calls) = run(b"{\"method\":\"a\"}\nGET / HTTP/1.1\n{\"method\":\"b\"}\n"); - assert_eq!(calls, ["a"]); - assert_eq!(r.len(), 2); - assert_eq!(r[1]["ok"], false); -} - -#[test] -fn overlong_line_is_refused() { - // One byte over the limit, then a valid request: neither runs. - let mut input = vec![b'x'; MAX_LINE + 1]; - input.extend_from_slice(b"\n{\"method\":\"a\"}\n"); - let (r, calls) = run(&input); - assert!(calls.is_empty(), "{calls:?}"); - assert_eq!(r.len(), 1); - assert!(r[0]["error"].as_str().unwrap().contains("longer than")); -} - -#[test] -fn line_at_the_limit_is_accepted() { - let mut buf = Vec::new(); - let line = vec![b'a'; 10]; - let mut input = line.clone(); - input.push(b'\n'); - assert_eq!(read_bounded_line(&mut &input[..], &mut buf, 10), Ok(true)); - assert_eq!(buf, line); - assert!(read_bounded_line(&mut &[b'a'; 11][..], &mut buf, 10).is_err()); -} - -#[test] -fn tcp_connection_is_closed_after_junk() { - // End to end over a real loopback socket (the transport the app uses). - let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); - let addr = listener.local_addr().unwrap(); - let server = std::thread::spawn(move || { - let (s, _) = listener.accept().unwrap(); - serve_socket(s, ConnectionTimeouts::default(), |_, _| Some(json!({"ok": true}))); - }); - let mut c = TcpStream::connect(addr).unwrap(); - c.set_read_timeout(Some(WAIT)).unwrap(); - // The server closes gracefully ([`close_gracefully`]): the client reads both replies and then - // the end of the stream, not a reset. - c.write_all(b"{\"id\":7,\"method\":\"x\"}\nhello\n").unwrap(); - let mut text = String::new(); - c.read_to_string(&mut text).unwrap(); // returns at EOF: the server closed the connection - server.join().unwrap(); - let lines: Vec<&str> = text.lines().collect(); - assert_eq!(lines.len(), 2, "{text}"); - assert!(lines[0].contains("\"id\":7")); - assert!(lines[1].contains("closing the connection")); -} - -#[test] -fn ten_inspect_replies_for_10000_objects_arrive_within_20_s() { - let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); - let addr = listener.local_addr().unwrap(); - let reply = inspect_reply(10_000); - let mut want = reply.clone(); - want["id"] = json!(1); - let want = format!("{want}\n"); - std::thread::spawn(move || { - let (s, _) = listener.accept().unwrap(); - let read = s.try_clone().unwrap(); - serve_lines(read, s, |_, _| Some(reply.clone())); - }); - // The client sends each request line and reads its reply line through a `BufReader`, as `vectorcraft_mcp::Remote` does. - let (tx, rx) = channel(); - std::thread::spawn(move || { - let mut c = TcpStream::connect(addr).unwrap(); - let mut read = BufReader::new(c.try_clone().unwrap()); - let mut lines = vec![]; - for _ in 0..10 { - c.write_all(b"{\"id\":1,\"method\":\"document.inspect\"}\n").unwrap(); - let mut line = String::new(); - read.read_line(&mut line).unwrap(); - lines.push(line); - } - tx.send(lines).ok(); - }); - let lines = rx.recv_timeout(Duration::from_secs(20)).unwrap_or_else(|_| panic!("ten replies did not arrive within 20 s")); - assert!(lines.iter().all(|l| *l == want), "a reply differs from the bytes `writeln!` writes"); -} - -#[test] -fn extra_connections_are_refused() { - let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); - let addr = listener.local_addr().unwrap(); - let (tx, _rx) = channel::(); - std::thread::spawn(move || accept_loop(listener, tx, egui::Context::default())); - // Idle connections are accepted in order and held open. - let held: Vec = (0..16).map(|_| TcpStream::connect(addr).unwrap()).collect(); - let mut extra = TcpStream::connect(addr).unwrap(); - extra.set_read_timeout(Some(WAIT)).unwrap(); - let mut line = String::new(); - BufReader::new(&mut extra).read_line(&mut line).unwrap(); - assert!(line.contains("too many control connections"), "{line}"); - drop(held); -} - -// A test process is not an app that App Nap applies to, so this checks the activity the -// channel asks for; the throttling itself shows only in a running app with its window hidden. -#[cfg(target_os = "macos")] -#[test] -fn the_control_channel_keeps_the_app_at_full_priority_on_macos() { - use objc2_foundation::NSActivityOptions; - let options = activity_options(); - assert!(options.contains(NSActivityOptions::LatencyCritical), "without it App Nap still lowers the priority to 20"); - assert!(options.contains(NSActivityOptions::UserInitiatedAllowingIdleSystemSleep)); - assert!(!options.contains(NSActivityOptions::IdleSystemSleepDisabled), "the channel must not keep the Mac awake"); - keep_answering(); -} diff --git a/apps/vectorcraft/src/cursor_theme.rs b/apps/vectorcraft/src/cursor_theme.rs index ebb8ce8718..b23d1099db 100644 --- a/apps/vectorcraft/src/cursor_theme.rs +++ b/apps/vectorcraft/src/cursor_theme.rs @@ -7,15 +7,11 @@ //! fails in a Flatpak sandbox (`XCURSOR_PATH` unset, no cursor theme in the runtime) and where the //! `default` theme is a dangling symlink; the desktop's own setting names a theme that loads. //! -//! Where no cursor theme can be found at all (KDE or sway without gsettings), the env fix does -//! nothing: [`theme_missing`] tells the canvas to keep the system pointer visible beside the tool glyph. -//! //! This reads the desktop's cursor theme and size and sets what the user left unset, once, before //! any thread starts and before the window opens. #![cfg_attr(not(target_os = "linux"), allow(dead_code))] use std::ffi::OsString; -use std::path::{Path, PathBuf}; /// Where a Flatpak sandbox mounts the host's cursor themes (user and system). const FLATPAK_HOST_ICONS: [&str; 2] = ["/run/host/user-share/icons", "/run/host/share/icons"]; @@ -52,67 +48,6 @@ pub fn plan(var: impl Fn(&str) -> Option, host_icons: &[&str], desktop out } -/// Xcursor's default search path when `XCURSOR_PATH` is unset (relative entries are in `$HOME`). -const DEFAULT_ICON_DIRS: [&str; 5] = ["~/.local/share/icons", "~/.icons", "/usr/share/icons", "/usr/share/pixmaps", "/usr/X11R6/lib/X11/icons"]; - -/// The themes `index.theme` lists after `Inherits=`. -fn inherits(index: &str) -> Vec { - index - .lines() - .find_map(|l| l.trim().strip_prefix("Inherits=")) - .map(|v| v.split([',', ';']).map(|t| t.trim().to_owned()).filter(|t| !t.is_empty()).collect()) - .unwrap_or_default() -} - -/// Can Xcursor load a pointer for the environment's theme (`XCURSOR_THEME`, else `default`)? It does -/// when the theme, or one it inherits from, has a `default` or `left_ptr` cursor file in a folder of -/// `XCURSOR_PATH` (else Xcursor's default folders). `read` returns a file's text, `exists` tells -/// whether a file is there. -pub fn theme_usable( - var: impl Fn(&str) -> Option, - home: Option<&Path>, - read: impl Fn(&Path) -> Option, - exists: impl Fn(&Path) -> bool, -) -> bool { - let dirs: Vec = match var("XCURSOR_PATH").filter(|v| !v.is_empty()) { - Some(v) => std::env::split_paths(&v).collect(), - None => DEFAULT_ICON_DIRS - .iter() - .filter_map(|d| match d.strip_prefix("~/") { - Some(rest) => home.map(|h| h.join(rest)), - None => Some(PathBuf::from(d)), - }) - .collect(), - }; - let first = var("XCURSOR_THEME").and_then(|v| v.into_string().ok()).filter(|t| !t.is_empty()).unwrap_or_else(|| "default".into()); - let mut todo = vec![first]; - let mut seen: Vec = Vec::new(); - while let Some(theme) = todo.pop() { - // Bounded: themes inherit in short chains, and a cycle must end. - if seen.contains(&theme) || seen.len() >= 16 { - continue; - } - for dir in &dirs { - let base = dir.join(&theme); - if ["default", "left_ptr"].iter().any(|c| exists(&base.join("cursors").join(c))) { - return true; - } - if let Some(index) = read(&base.join("index.theme")) { - todo.extend(inherits(&index)); - } - } - seen.push(theme); - } - false -} - -/// On this machine, after [`apply`]: is there no cursor theme Xcursor can load? Then winit never -/// sets a pointer, and the canvas must not hide the system one (#2450). -pub fn theme_missing() -> bool { - let home = std::env::var_os("HOME").filter(|h| !h.is_empty()).map(PathBuf::from); - !theme_usable(|n| std::env::var_os(n), home.as_deref(), |p| std::fs::read_to_string(p).ok(), |p| p.exists()) -} - /// The value of a `gsettings get` line: `'Adwaita'` becomes `Adwaita`, `24` stays `24`. fn gsettings_value(output: &str) -> &str { output.trim().trim_matches('\'') @@ -178,32 +113,6 @@ mod tests { assert!(plan(env(&[("WAYLAND_DISPLAY", "wayland-0")]), &[], odd).is_empty()); } - #[test] - fn a_theme_is_usable_directly_or_through_inherits_and_missing_otherwise() { - let files = ["/i/Bibata/cursors/left_ptr", "/i/Breeze/index.theme", "/i/Loop/index.theme"]; - // Compared as paths, so the joins match on Windows too, where they use `\`. - let exists = |p: &Path| files.iter().any(|f| Path::new(f) == p); - let read = |p: &Path| { - if p == Path::new("/i/Breeze/index.theme") { - Some("[Icon Theme]\nInherits=Other, Bibata\n".to_owned()) - } else if p == Path::new("/i/Loop/index.theme") { - Some("Inherits=Loop\n".to_owned()) - } else { - None - } - }; - let with = |theme: &'static str| { - move |n: &str| (n == "XCURSOR_PATH").then(|| OsString::from("/i")).or((n == "XCURSOR_THEME").then(|| OsString::from(theme))) - }; - assert!(theme_usable(with("Bibata"), None, read, exists)); - assert!(theme_usable(with("Breeze"), None, read, exists)); - // No such theme, a theme without cursors, an inheritance loop: nothing to load. - assert!(!theme_usable(with("Nope"), None, read, exists)); - assert!(!theme_usable(with("Loop"), None, read, exists)); - // Unset: Xcursor's default folders and the `default` theme. - assert!(!theme_usable(|_| None, Some(Path::new("/home/u")), read, exists)); - } - #[test] fn gsettings_output_is_unquoted() { assert_eq!(gsettings_value("'Adwaita'\n"), "Adwaita"); diff --git a/apps/vectorcraft/src/display_profile.rs b/apps/vectorcraft/src/display_profile.rs index ee35a407a7..11af0cf044 100644 --- a/apps/vectorcraft/src/display_profile.rs +++ b/apps/vectorcraft/src/display_profile.rs @@ -692,7 +692,7 @@ mod tests { assert_eq!(x11_choice(None, || Err("no X11".into())), Found::NoProfile("no X11".into())); // colord's file holds no usable profile: the property is used. let broken = usable(Found::Profile { icc: vec![1, 2, 3], from: "a.icc".into() }); - assert_eq!(broken, Found::NoProfile("a.icc: the file is not an ICC profile".into())); + assert!(matches!(&broken, Found::NoProfile(reason) if reason.starts_with("a.icc: ")), "{broken:?}"); assert_eq!(x11_choice(Some(Ok(Some(broken))), property), icc(2)); assert_eq!(usable(Found::NoProfile("none".into())), Found::NoProfile("none".into())); } diff --git a/apps/vectorcraft/src/hang_watch.rs b/apps/vectorcraft/src/hang_watch.rs index e5adb77dfa..93c7d4e368 100644 --- a/apps/vectorcraft/src/hang_watch.rs +++ b/apps/vectorcraft/src/hang_watch.rs @@ -31,9 +31,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; use std::time::{Duration, Instant, SystemTime}; -#[cfg(target_os = "macos")] -use vectorcraft_ui_egui::hang_beacon::Activity; -use vectorcraft_ui_egui::hang_beacon::{BEACON, Beacon, FrameTime, Sample, Stage}; +use vectorcraft_ui_egui::hang_beacon::{Activity, BEACON, Beacon, FrameTime, Sample, Stage}; use super::logging::timestamp; @@ -424,11 +422,9 @@ pub fn start(dir: Option, shared: Arc) { let mut held = None; loop { std::thread::sleep(POLL); - #[cfg_attr(not(target_os = "macos"), allow(unused_mut))] let mut sample = BEACON.sample(); // An open menu of the menu bar waits for the user. - #[cfg(target_os = "macos")] - if super::mac_menu::is_tracking() { + if craft::window::native_menu::menu_tracking() { sample.activity = Activity::Menu; } if let Some(event) = watch.check(shared.started.elapsed(), sample) { diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 3efdb9f93f..06be570630 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -1,229 +1,82 @@ -#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] -use super::portal_save; -#[cfg(windows)] -use super::windows_screen_color; +use std::collections::HashMap; +use std::path::PathBuf; + +use craft::dialogs::ShowHook; +use craft::dialogs::service::{ExtensionPolicy, FilePanels, FileService}; +use craft::host::Wake; +use craft::platform::clipboard::ClipboardBackend; +use craft::ui::runtime::pen::PenSource; +use vectorcraft_ui_egui::hang_beacon::{Activity, BEACON, Beacon}; + +#[cfg(target_os = "macos")] +use super::mac_tablet; +#[cfg(target_os = "linux")] +use super::tablet; #[cfg(all(windows, not(target_vendor = "win7")))] use super::windows_stylus; -use super::{ClipboardProbeFactory, FilePick, PickRequest, Services, clipboard, cursor_theme, fileio, printing}; -#[cfg(target_os = "linux")] -use super::{linux_screen_color, tablet}; -#[cfg(target_os = "macos")] -use super::{mac_save_format, mac_screen_color, mac_tablet}; +use super::{Services, clipboard, fileio, printing}; -/// The window file dialogs belong to. +/// The main window, which the pen reader looks at to tell an X11 window from a Wayland one. pub(crate) type Parent = Option>; -/// What rfd's blocking and asynchronous file dialogs are both set up with. -trait DialogSettings: Sized { - fn parent(self, window: &winit::window::Window) -> Self; - fn title(self, title: &str) -> Self; - fn filter(self, name: &str, exts: &[impl ToString]) -> Self; - fn folder(self, folder: &str) -> Self; - fn file_name(self, name: &str) -> Self; +/// The native file service and the panels that show its dialogs. `folders` are the folders the last +/// session's picks chose, so a pick of this one starts where that ended. +pub(crate) fn file_service(wake: Wake, folders: HashMap) -> (FileService, FilePanels) { + let (service, panels) = FileService::new(wake); + let panels = panels.extension_policy(ExtensionPolicy::AS_TYPED).show_hook(marking_dialogs(&BEACON)); + (service.with_last_folders(folders), panels) } -macro_rules! dialog_settings { - ($($dialog:ty),*) => {$( - impl DialogSettings for $dialog { - fn parent(self, window: &winit::window::Window) -> Self { - self.set_parent(window) - } - fn title(self, title: &str) -> Self { - self.set_title(title) - } - fn filter(self, name: &str, exts: &[impl ToString]) -> Self { - self.add_filter(name, exts) - } - fn folder(self, folder: &str) -> Self { - self.set_directory(folder) - } - fn file_name(self, name: &str) -> Self { - self.set_file_name(name) - } - } - )*}; +/// A hook that marks `beacon` as in a dialog while the dialog shows: it waits for the user, so the +/// hang report (`hang_watch`) doesn't take the wait for a stall. Making the dialog stays timed. +fn marking_dialogs(beacon: &'static Beacon) -> ShowHook { + Box::new(move |show: &mut dyn FnMut()| { + let _mark = beacon.activity(Activity::Dialog); + show(); + }) } -dialog_settings!(rfd::FileDialog, rfd::AsyncFileDialog); - -/// On Linux and the BSDs the dialog is GTK's or the desktop portal's, which match a file type's -/// `*.ext` patterns case-sensitively. -const CASE_SENSITIVE_FILTERS: bool = - cfg!(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")); - -/// The extensions an open dialog's filter is given for `exts`: with `any_case`, each extension -/// that has a letter is followed by a pattern with each letter as a `[xX]` pair, so the filter for -/// `dib` also lists `image.DIB` and `image.Dib`. -fn open_extensions(exts: &[impl AsRef], any_case: bool) -> Vec { - let mut out = Vec::with_capacity(exts.len() * 2); - for e in exts { - let e = e.as_ref(); - out.push(e.to_string()); - if any_case && e.chars().any(|c| c.is_ascii_alphabetic()) { - out.push( - e.chars() - .map(|c| if c.is_ascii_alphabetic() { format!("[{}{}]", c.to_ascii_lowercase(), c.to_ascii_uppercase()) } else { c.to_string() }) - .collect(), - ); - } - } - out -} - -/// `d` set up for `request`: its title, file types, folder and suggested name. -fn dialog_for(d: D, request: &PickRequest) -> D { - let pick = match request { - PickRequest::Open(pick) | PickRequest::Save(pick) | PickRequest::OpenFiles(pick) => pick, - PickRequest::OpenMany => { - return fileio::place_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| { - d.filter( - vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), - &open_extensions(exts, CASE_SENSITIVE_FILTERS), - ) - }); - } - PickRequest::Folder => return d, - PickRequest::FolderAt(folder) => return d.folder(folder), - }; - let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_) | PickRequest::OpenFiles(_)); - let d = pick.filters.iter().fold(d, |d, (name, exts)| { - d.filter( - vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name.as_str()), - &open_extensions(exts, any_case), - ) - }); - let d = match &pick.folder { - Some(folder) => d.folder(folder), - None => d, - }; - if pick.name.is_empty() { - return d; - } - // Windows' save dialog changes the extension when a different file type is chosen only when - // the suggested name has no explicit extension. rfd supplies the first filter's extension to - // that dialog, so leave the suffix to Windows for saves that offer several formats (#5451). - // A remaining dot in the stem would look like another explicit extension to Windows. - #[cfg(windows)] - if matches!(request, PickRequest::Save(_)) - && pick.filters.len() > 1 - && let Some(ext) = std::path::Path::new(&pick.name).extension().and_then(|e| e.to_str()) - && pick.filters.iter().any(|(_, exts)| exts.iter().any(|e| e.eq_ignore_ascii_case(ext))) - && let Some(stem) = std::path::Path::new(&pick.name).file_stem().and_then(|s| s.to_str()) - && !stem.contains('.') +/// Starts the host's tablet reader for `window`: the pen source it writes the pen's pressure and end +/// into. XInput2 under X11 and XWayland, AppKit's events on macOS, the pen's pointer messages on +/// Windows; other windows read the pen from touch events only (`None`). +pub(crate) fn start_pen(window: &Parent) -> Option { + #[cfg(target_os = "linux")] { - return d.file_name(stem); + use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle}; + let x11 = window + .as_ref() + .and_then(|w| w.window_handle().ok()) + .is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_))); + x11.then(tablet::start).flatten() + } + #[cfg(target_os = "macos")] + { + let _ = window; + mac_tablet::start() + } + #[cfg(all(windows, not(target_vendor = "win7")))] + { + let _ = window; + Some(windows_stylus::start()) + } + #[cfg(not(any(target_os = "linux", target_os = "macos", all(windows, not(target_vendor = "win7")))))] + { + let _ = window; + None } - d.file_name(&pick.name) } #[cfg(test)] #[test] -fn a_folder_picker_asked_for_a_folder_starts_there() { - /// The settings a dialog was given, by name. - #[derive(Default)] - struct Recorded(Vec); - impl DialogSettings for Recorded { - fn parent(self, _: &winit::window::Window) -> Self { - self - } - fn title(mut self, title: &str) -> Self { - self.0.push(format!("title {title}")); - self - } - fn filter(mut self, name: &str, _: &[impl ToString]) -> Self { - self.0.push(format!("filter {name}")); - self - } - fn folder(mut self, folder: &str) -> Self { - self.0.push(format!("folder {folder}")); - self - } - fn file_name(mut self, name: &str) -> Self { - self.0.push(format!("name {name}")); - self - } - } - assert_eq!(dialog_for(Recorded::default(), &PickRequest::FolderAt("/a/b".into())).0, ["folder /a/b"]); - assert!(dialog_for(Recorded::default(), &PickRequest::Folder).0.is_empty()); -} - -/// A native file dialog for `request` over `parent` (on Linux the portal then shows it over the -/// window and keeps it in front). -#[cfg(not(target_os = "macos"))] -fn file_dialog(request: &PickRequest, parent: &Parent) -> rfd::FileDialog { - match parent { - Some(w) => dialog_for(rfd::FileDialog::new().parent(w), request), - None => dialog_for(rfd::FileDialog::new(), request), - } -} - -/// Before `request`'s dialog shows: a save dialog's folder (the Templates folder) may not exist yet. -fn make_folder(request: &PickRequest) { - if let PickRequest::Save(FilePick { folder: Some(folder), .. }) = request { - let _ = std::fs::create_dir_all(folder); - } -} - -/// Show `dialog` for `request` (on the calling thread, until it closes) → the paths picked. On -/// Linux and the BSDs a save dialog with two or more file types is the desktop portal's, over -/// `parent`, and its answer also names the file type picked ([`portal_save`]); `dialog` shows when -/// the portal can't. -#[cfg(not(target_os = "macos"))] -#[cfg_attr(windows, allow(unused_variables))] -fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent) -> Vec { - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] - if let PickRequest::Save(pick) = request - && let Some(answer) = portal_save::pick(pick, parent.as_deref()) - { - return answer; - } - let paths = match request { - PickRequest::Open(_) => dialog.pick_file().into_iter().collect(), - PickRequest::OpenMany | PickRequest::OpenFiles(_) => dialog.pick_files().unwrap_or_default(), - PickRequest::Save(_) => dialog.save_file().into_iter().collect(), - PickRequest::Folder | PickRequest::FolderAt(_) => dialog.pick_folder().into_iter().collect(), - }; - paths.into_iter().map(|p| p.to_string_lossy().to_string()).collect() -} - -/// Show the dialog for `request` over `parent` now → the paths picked. -#[cfg(not(target_os = "macos"))] -fn pick_now(request: PickRequest, parent: &Parent) -> Vec { - let beacon = &vectorcraft_ui_egui::hang_beacon::BEACON; - marked_dialog(beacon, || make_folder(&request), || show_dialog(file_dialog(&request, parent), &request, parent)) -} - -/// Run `prepare` (making the dialog's folder), then `show`, marked on `beacon` as a dialog: the -/// dialog waits for the user and is not a stall for the hang report (`hang_watch`), while `prepare` -/// is still timed. -#[cfg(not(target_os = "macos"))] -fn marked_dialog(beacon: &vectorcraft_ui_egui::hang_beacon::Beacon, prepare: impl FnOnce(), show: impl FnOnce() -> T) -> T { - prepare(); - let _mark = beacon.activity(vectorcraft_ui_egui::hang_beacon::Activity::Dialog); - show() -} - -#[cfg(all(test, not(target_os = "macos")))] -#[test] -fn making_a_dialogs_folder_is_timed_and_the_dialog_is_not() { - use vectorcraft_ui_egui::hang_beacon::{Activity, Beacon}; - let beacon = Beacon::new(); - let mut preparing = None; - let showing = marked_dialog(&beacon, || preparing = Some(beacon.sample().activity), || beacon.sample().activity); - assert_eq!(preparing, Some(Activity::None), "making the folder is timed"); - assert_eq!(showing, Activity::Dialog, "the dialog is not"); +fn a_dialog_is_marked_while_it_shows_and_not_after() { + let beacon: &'static Beacon = Box::leak(Box::new(Beacon::new())); + let mut hook = marking_dialogs(beacon); + let mut showing = None; + hook(&mut || showing = Some(beacon.sample().activity)); + assert_eq!(showing, Some(Activity::Dialog), "a dialog waiting for the user is not a stall"); assert_eq!(beacon.sample().activity, Activity::None, "the mark ends with the dialog"); } -/// macOS shows no dialog in line: its modal loop would run inside winit's event handler, and an -/// event winit held back meanwhile aborts the app (#867). Dialogs are sheets there ([`start_pick`]); -/// one asked for any other way (a bug: outside a command, a dialog's OK or a button) picks nothing. -#[cfg(target_os = "macos")] -fn pick_now(request: PickRequest, _parent: &Parent) -> Vec { - log::error!("no file dialog shown for {request:?}: macOS shows them as sheets, from commands, dialogs' OK and buttons only"); - Vec::new() -} - /// File → Show in Folder: select `path` in Finder / Explorer, or open its folder elsewhere. fn reveal(path: &str) -> Result<(), String> { explorer_safe(path)?; @@ -300,134 +153,20 @@ fn write_file(path: &str, bytes: &[u8]) -> Result<(), String> { fileio::write_atomic(std::path::Path::new(path), bytes).map_err(|e| e.to_string()) } -/// Linux: show the dialog for `request` over `parent` on a thread of its own, answering on the -/// receiver. Shown on the UI thread, nothing would answer the compositor meanwhile, which then -/// offers to kill the window as not responding (#592). -#[cfg(not(target_os = "macos"))] -fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Option>> { - let dialog = file_dialog(&request, parent); - let (tx, rx) = std::sync::mpsc::channel(); - let ui = ui.clone(); - let parent = parent.clone(); - std::thread::Builder::new() - .name("file-dialog".into()) - .spawn(move || { - make_folder(&request); - // The app gone meanwhile has no use for the answer. - let _ = tx.send(show_dialog(dialog, &request, &parent)); - ui.request_repaint(); - }) - .ok()?; - Some(rx) -} - -/// The paths a dialog shown as a sheet picks, once it closes. -#[cfg(target_os = "macos")] -type SheetAnswer = std::pin::Pin> + Send>>; - -/// macOS: show the dialog for `request` as a sheet on `parent`'s window, answering on the receiver -/// (#867). Shown in line, the panel ran AppKit's modal event loop inside winit's event handler: an -/// event winit had held back meanwhile (one came as a resize of the panel ended) then re-entered -/// the handler, and winit's panic there, inside an AppKit callback, aborted the app. The sheet -/// returns at once and the window keeps running; a thread of its own waits for the answer. -#[cfg(target_os = "macos")] -fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Option>> { - use winit::raw_window_handle::HasWindowHandle as _; - // rfd runs the panel modally after all unless it has the running app's window to hold the - // sheet (and from another thread it can't reach the window): no dialog then (`pick_now`). - let mtm = objc2::MainThreadMarker::new(); - let running = mtm.is_some_and(|mtm| objc2_app_kit::NSApplication::sharedApplication(mtm).isRunning()); - let Some(window) = parent.as_ref().filter(|w| running && w.window_handle().is_ok()) else { - log::error!("no window to show the file dialog on (main thread: {}, running: {running})", mtm.is_some()); - return None; - }; - // The thread first, so the answer of a sheet once shown always has somewhere to go. - let (sheet_tx, sheet_rx) = std::sync::mpsc::channel::(); - let (tx, rx) = std::sync::mpsc::channel(); - let ui = ui.clone(); - std::thread::Builder::new() - .name("file-dialog".into()) - .spawn(move || { - if let Ok(answer) = sheet_rx.recv() { - // The app gone meanwhile has no use for the answer. - let _ = tx.send(pollster::block_on(answer)); - ui.request_repaint(); - } - }) - .ok()?; - make_folder(&request); - // The panel is built and the sheet is begun below, on the main thread (as it must). - let dialog = dialog_for(rfd::AsyncFileDialog::new().parent(window), &request); - let path = |f: &rfd::FileHandle| f.path().to_string_lossy().to_string(); - let answer: SheetAnswer = match request { - PickRequest::Open(_) => { - let picked = dialog.pick_file(); - Box::pin(async move { picked.await.iter().map(path).collect() }) - } - PickRequest::OpenMany | PickRequest::OpenFiles(_) => { - let picked = dialog.pick_files(); - Box::pin(async move { picked.await.unwrap_or_default().iter().map(path).collect() }) - } - // A save panel with two or more named file types is built by `mac_save_format`, which sets - // up its Format menu before the sheet begins (#866); rfd shows the others. - PickRequest::Save(pick) => match mac_save_format::begin(window, &pick) { - // The dialog thread blocks here until the sheet answers. - Ok(mac_save_format::Begin::Shown(picked)) => Box::pin(async move { picked.recv().unwrap_or_default() }), - Ok(mac_save_format::Begin::DeferToRfd) => { - // Nothing is added to the sheet once rfd has begun it: an accessory view set then - // made recent macOS versions dismiss the sheet at once (#1800). - let picked = dialog.save_file(); - Box::pin(async move { picked.await.iter().map(path).collect() }) - } - // AppKit returned nil for the panel. rfd uses the same `+savePanel` and would panic - // on that nil; treat the pick as cancelled instead (#5980). - Err(()) => Box::pin(async move { Vec::new() }), - }, - PickRequest::Folder | PickRequest::FolderAt(_) => { - let picked = dialog.pick_folder(); - Box::pin(async move { picked.await.iter().map(path).collect() }) - } - }; - // The thread can't be gone: it waits for this. If it were, its receiver answers as cancelled. - let _ = sheet_tx.send(answer); - Some(rx) -} - -/// The host's services; `ui` is woken when a file dialog answers. -pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { - use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle}; - let wayland = parent.as_ref().and_then(|w| w.window_handle().ok()).is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Wayland(_))); - // A window on X11 (XWayland included) reads a tablet pen's pressure itself (#764). - #[cfg(target_os = "linux")] - let x11 = parent - .as_ref() - .and_then(|w| w.window_handle().ok()) - .is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_))); - let (clip, clip_probe) = (parent.clone(), parent.clone()); - let (p1, p2, p3, p4, p5, p6, p7) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent); - #[cfg(any(target_os = "macos", target_os = "linux", windows))] - let sampled_ui = ui.clone(); - #[cfg(target_os = "linux")] - let sampled_parent = p1.clone(); +/// The host's services. File dialogs, the clipboard, URLs, the pen and the screen color picker are +/// the framework's. +pub(crate) fn services(window: Parent) -> Services { + let probe_window = window.clone(); Services { - pick_open: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Open(pick.clone()), &p1).into_iter().next())), - pick_open_multi: Some(Box::new(move || pick_now(PickRequest::OpenMany, &p2))), - pick_open_files: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::OpenFiles(pick.clone()), &p6))), - pick_save: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Save(pick.clone()), &p3).into_iter().next())), - // Linux shows dialogs on a thread of their own (#592), macOS as sheets (#867); Windows - // dialogs run the window's events while they are open. - start_pick: cfg!(unix).then(|| Box::new(move |request: PickRequest| start_pick(request, &p5, &ui)) as vectorcraft_ui_egui::picks::StartPick), - dialogs_are_sheets: cfg!(target_os = "macos"), - wayland, - no_cursor_theme: wayland && cursor_theme::theme_missing(), - #[cfg(target_os = "linux")] - stylus: if x11 { tablet::start() } else { None }, - // macOS reads it from AppKit's events (#852). - #[cfg(target_os = "macos")] - stylus: mac_tablet::start(), - // Windows reads it from the pen's pointer messages (`windows_stylus`). - #[cfg(windows)] - stylus: Some(windows_stylus::start()), + // Every format Copy offers and Paste reads. Its calls are marked for the hang report (`hang_watch`). + clipboard: Some(Box::new(vectorcraft_ui_egui::hang_beacon::Marked(clipboard::system_clipboard(window)))), + // Linux checks whether Paste has something to take on a background thread: an X11 clipboard + // owner that never answers holds a text read for up to 4 s for each format it tries, and + // quitting waits up to `craft::platform::clipboard::PROBE_STOP_WAIT` for that thread. Windows + // only asks which formats the clipboard holds and macOS asks the pasteboard server, so they + // check in line. The probe's handle is made on its own thread, from the window (`Send`). + clipboard_probe: cfg!(target_os = "linux") + .then(|| Box::new(move || clipboard::system_clipboard(probe_window)) as Box Box + Send>), read: Some(Box::new(read_file)), // Load Actions… refuses a file over its size limit without reading all of it. read_head: Some(Box::new(read_file_head)), @@ -441,19 +180,6 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { stream_shared: Some(std::sync::Arc::new(|p: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| { fileio::write_file_with(p, fill).map_err(|e| e.to_string()) })), - // Every format Copy offers and Paste reads (menu-bar Paste never sees egui's Paste event). - // Its calls are marked for the hang report (`hang_watch`). - system_clipboard: Some(Box::new(vectorcraft_ui_egui::hang_beacon::Marked(clipboard::system_clipboard(clip)))), - // Linux checks whether Paste has something to take on a background thread: an X11 clipboard - // owner that never answers holds a text read for up to 4 s for each format it tries, and - // quitting waits up to `CLIPBOARD_PROBE_STOP_WAIT` for that thread. Windows only asks which - // formats the clipboard holds and macOS asks the pasteboard server, so they check in line. - // The probe's handle is made on its own thread, from the window (`Send`), not its raw display. - clipboard_probe: cfg!(target_os = "linux").then(|| Box::new(move || clipboard::system_clipboard(clip_probe)) as ClipboardProbeFactory), - // Help → Discord / website / GitHub, the Discord button, About and Home links. - open_url: Some(Box::new(|url: &str| { - let _ = webbrowser::open(url); - })), reveal: Some(Box::new(reveal)), // Links panel: Edit Original; Package: Show Package. Relink to Folder and Package pick folders. open_file: Some(Box::new(open_file)), @@ -461,15 +187,6 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { open_in_photocraft: Some(Box::new(open_in_photocraft)), check_application: Some(Box::new(|p| check_app(std::path::Path::new(p)))), open_in_application: Some(Box::new(open_in_application)), - pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())), - pick_folder_at: Some(Box::new(move |start: &str| pick_now(PickRequest::FolderAt(start.to_string()), &p7).into_iter().next())), - // Sample Color from Screen: the system's color sampler. - #[cfg(target_os = "macos")] - screen_color: Some(mac_screen_color::sampler(sampled_ui)), - #[cfg(target_os = "linux")] - screen_color: Some(linux_screen_color::sampler(sampled_ui, sampled_parent)), - #[cfg(windows)] - screen_color: Some(windows_screen_color::sampler(sampled_ui)), // File → Print: the system's printers and print queue. print: Some(Box::new(printing::SystemPrint)), ..Default::default() @@ -836,105 +553,3 @@ mod open_with_tests { assert_eq!(super::registry_default_path(windows::Win32::System::Registry::HKEY_CURRENT_USER, &key), None, "deleted"); } } - -#[cfg(test)] -mod dialog_tests { - use super::{CASE_SENSITIVE_FILTERS, DialogSettings, FilePick, PickRequest, dialog_for, fileio, open_extensions}; - - /// The file types a dialog was given, by label. - #[derive(Default)] - struct Filters(Vec<(String, Vec)>, Option); - - impl DialogSettings for Filters { - fn parent(self, _window: &winit::window::Window) -> Self { - self - } - fn title(self, _title: &str) -> Self { - self - } - fn filter(mut self, name: &str, exts: &[impl ToString]) -> Self { - self.0.push((name.to_string(), exts.iter().map(ToString::to_string).collect())); - self - } - fn folder(self, _folder: &str) -> Self { - self - } - fn file_name(mut self, name: &str) -> Self { - self.1 = Some(name.to_string()); - self - } - } - - /// Does the case-sensitive pattern `*.{ext}` match `name`? `ext` may hold literal characters, - /// `*` and `[..]` sets. - fn matches(ext: &str, name: &str) -> bool { - fn here(p: &[char], n: &[char]) -> bool { - match p.split_first() { - None => n.is_empty(), - Some(('*', rest)) => (0..=n.len()).any(|i| here(rest, &n[i..])), - Some(('[', rest)) => { - let Some(end) = rest.iter().position(|&c| c == ']') else { return false }; - n.split_first().is_some_and(|(c, n)| rest[..end].contains(c) && here(&rest[end + 1..], n)) - } - Some((c, rest)) => n.split_first().is_some_and(|(d, n)| d == c && here(rest, n)), - } - } - let pattern: Vec = format!("*.{ext}").chars().collect(); - here(&pattern, &name.chars().collect::>()) - } - - /// Where filters match case-sensitively, every extension of File › Open and Place lists files - /// whose extension is in capitals or mixed case, `image.DIB` and `image.Pns` included. - #[test] - fn open_and_place_filters_list_extensions_in_any_case() { - let all = fileio::open_filters().chain(fileio::place_filters()); - for (label, exts) in all { - let patterns = open_extensions(exts, true); - for ext in exts { - let mut mixed = ext.to_ascii_uppercase(); - mixed.replace_range(..1, &ext[..1]); - for name in [format!("a.{ext}"), format!("a.{}", ext.to_ascii_uppercase()), format!("a.{mixed}")] { - assert!(patterns.iter().any(|p| matches(p, &name)), "{label}: {patterns:?} don't match {name}"); - } - } - } - assert_eq!(open_extensions(&["dib", "jp2", "*"], true), ["dib", "[dD][iI][bB]", "jp2", "[jJ][pP]2", "*"]); - assert_eq!(open_extensions(&["dib", "PNS"], false), ["dib", "PNS"]); - } - - /// Open and Place dialogs get the any-case patterns on Linux and the BSDs; a save dialog's file - /// types stay as listed. - #[test] - fn open_dialogs_get_any_case_patterns_where_filters_are_case_sensitive() { - let dib = vec![FilePick::filter("BMP", &["bmp", "dib"])]; - let pick = FilePick { filters: dib.clone(), ..Default::default() }; - let expected = |any_case: bool| open_extensions(&["bmp", "dib"], any_case); - let opened = dialog_for(Filters::default(), &PickRequest::Open(pick.clone())).0; - assert_eq!(opened[0].1, expected(CASE_SENSITIVE_FILTERS)); - let saved = dialog_for(Filters::default(), &PickRequest::Save(pick)).0; - assert_eq!(saved, dib); - let placed = dialog_for(Filters::default(), &PickRequest::OpenMany).0; - let first = fileio::place_filters().next().map(|(_, exts)| open_extensions(exts, CASE_SENSITIVE_FILTERS)); - assert_eq!(placed.first().map(|(_, exts)| exts.clone()), first); - } - - /// A format selected after the Windows Save As dialog opens can replace the suffix of the - /// suggested name. Single-format saves and open dialogs keep the supplied name verbatim. - #[cfg(windows)] - #[test] - fn save_dialog_with_several_formats_leaves_the_extension_to_windows() { - let filters = vec![FilePick::filter("VectorCraft", &["vectorcraft"]), FilePick::filter("PDF-compatible .ai", &["ai"])]; - let pick = FilePick { name: "Poster.vectorcraft".into(), filters: filters.clone(), ..Default::default() }; - assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick.clone())).1.as_deref(), Some("Poster")); - assert_eq!(dialog_for(Filters::default(), &PickRequest::Open(pick)).1.as_deref(), Some("Poster.vectorcraft")); - - let pick = FilePick { name: "Poster.AI".into(), filters: filters.clone(), ..Default::default() }; - assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster")); - let pick = FilePick { name: "Poster.design".into(), filters: filters.clone(), ..Default::default() }; - assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.design")); - let pick = FilePick { name: "draft.v1.vectorcraft".into(), filters: filters.clone(), ..Default::default() }; - assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("draft.v1.vectorcraft")); - let pick = FilePick { name: "Poster.vectorcraft".into(), filters: vec![filters[0].clone()], ..Default::default() }; - assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.vectorcraft")); - } -} diff --git a/apps/vectorcraft/src/linux_screen_color.rs b/apps/vectorcraft/src/linux_screen_color.rs deleted file mode 100644 index cfb8d7d69f..0000000000 --- a/apps/vectorcraft/src/linux_screen_color.rs +++ /dev/null @@ -1,41 +0,0 @@ -//! Linux: Sample Color from Screen (`vectorcraft_ui_egui::screen_color`) through the XDG desktop -//! portal's color sampler ([`portal`]). A thread of its own asks the portal and waits for the -//! person, so the UI keeps drawing; it sends the color to the UI and wakes the window. The dialog's -//! parent is the window, named on that thread as for the portal's save dialog (`portal_save`). - -mod portal; - -/// The portal's color sampler over the window `parent` holds; `ui` is woken when it answers. -pub fn sampler(ui: egui::Context, parent: super::host_services::Parent) -> vectorcraft_ui_egui::screen_color::StartSampler { - Box::new(move || { - let (tx, rx) = std::sync::mpsc::channel(); - let (ui, window) = (ui.clone(), parent.clone()); - std::thread::Builder::new() - .name("screen-color".into()) - .spawn(move || { - // The thread names the window and holds it until the export that names it is dropped. - let (handle, export) = match window.as_deref() { - Some(window) => { - let (handle, export) = super::portal_save::exported_parent(window); - (handle, Some(export)) - } - None => (String::new(), None), - }; - let picked = portal::connect(zbus::blocking::connection::Builder::session()).and_then(|conn| portal::pick(&conn, &handle)); - drop(export); - drop(window); - let answer = picked.map_err(|failure| { - log::warn!("the portal's screen color sampler gave no color: {}", failure.detail()); - failure.message().to_string() - }); - // The UI may be gone (the app quitting): nothing waits for the color then. - let _ = tx.send(answer); - ui.request_repaint(); - }) - .map_err(|e| { - log::warn!("could not start the screen color sampler's thread: {e}"); - "the screen color sampler failed".to_string() - })?; - Ok(rx) - }) -} diff --git a/apps/vectorcraft/src/linux_screen_color/portal.rs b/apps/vectorcraft/src/linux_screen_color/portal.rs deleted file mode 100644 index 21bcb34da5..0000000000 --- a/apps/vectorcraft/src/linux_screen_color/portal.rs +++ /dev/null @@ -1,291 +0,0 @@ -//! The XDG desktop portal's `Screenshot.PickColor` -//! (): -//! the call returns a request path at once, and the request's `Response` signal later carries the -//! color the person picked, as sRGB components from 0 to 1, or a code for a cancel or another end. - -use std::collections::HashMap; - -use zbus::blocking::{Connection, Proxy}; -use zbus::zvariant::{OwnedValue, Value}; - -/// How long the portal has to return a request path for `PickColor`. VectorCraft's own limit, -/// 25 seconds as libdbus's default for a method call. The portal returns the path before it shows -/// the sampler, so the person's time with the sampler does not count. -const CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(25); - -/// Why no color came back, as the status bar shows it. -#[derive(Clone, Debug, PartialEq, Eq)] -pub(super) enum Failure { - /// No session bus, no portal, or a portal without the Screenshot interface's `PickColor`. - Unavailable(String), - /// The portal did not return a request path in time, or it left the bus before it answered. - NoAnswer(String), - /// The portal ended the request without a color, or its answer can't be read. - Failed(String), -} - -impl Failure { - /// The status bar's message (English; the status bar translates it). - pub(super) fn message(&self) -> &'static str { - match self { - Failure::Unavailable(_) => "this system has no screen color sampler", - Failure::NoAnswer(_) => "the screen color sampler did not answer", - Failure::Failed(_) => "the screen color sampler failed", - } - } - - /// What went wrong, for the log. - pub(super) fn detail(&self) -> &str { - match self { - Failure::Unavailable(d) | Failure::NoAnswer(d) | Failure::Failed(d) => d, - } - } -} - -/// D-Bus errors that mean the session has no portal, or none that answers `PickColor`. -const UNAVAILABLE: &[&str] = &[ - "org.freedesktop.DBus.Error.ServiceUnknown", - "org.freedesktop.DBus.Error.NameHasNoOwner", - "org.freedesktop.DBus.Error.UnknownMethod", - "org.freedesktop.DBus.Error.UnknownInterface", - "org.freedesktop.DBus.Error.UnknownObject", -]; - -/// The connection `builder` makes, with [`CALL_TIMEOUT`] for its method calls. -pub(super) fn connect(builder: zbus::Result>) -> Result { - builder.and_then(|b| b.method_timeout(CALL_TIMEOUT).build()).map_err(|e| Failure::Unavailable(e.to_string())) -} - -/// Shows the portal's color sampler over the window `parent` names and waits for the color, `None` -/// when the person canceled it. `conn`'s method timeout bounds the call; the wait for the person -/// after it has no bound, and ends when the portal answers or leaves the bus. -pub(super) fn pick(conn: &Connection, parent: &str) -> Result, Failure> { - const DESKTOP: &str = "org.freedesktop.portal.Desktop"; - let token = crate::portal_request::token("vectorcraft_color").map_err(Failure::Failed)?; - // Made before the call: a portal can send its answer before the call returns. - let replies = crate::portal_request::Responses::new(conn).map_err(Failure::Failed)?; - let proxy = Proxy::new(conn, DESKTOP, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Screenshot") - .map_err(|e| Failure::Failed(e.to_string()))?; - let options = HashMap::from([("handle_token", Value::from(token.as_str()))]); - let call = proxy.call_method("PickColor", &(parent, options)).map_err(|e| call_failure(&e))?; - let reply = replies.wait(&call).map_err(Failure::NoAnswer)?; - let (code, results): (u32, HashMap) = reply.body().deserialize().map_err(|e| Failure::Failed(e.to_string()))?; - answer(code, &results) -} - -/// The [`Failure`] for an error the `PickColor` call returned. zbus reports a call that outlives -/// the connection's method timeout as an `InputOutput` error of kind `TimedOut`. -fn call_failure(e: &zbus::Error) -> Failure { - match e { - zbus::Error::MethodError(name, ..) if UNAVAILABLE.contains(&name.as_str()) => Failure::Unavailable(e.to_string()), - zbus::Error::InputOutput(io) if io.kind() == std::io::ErrorKind::TimedOut => Failure::NoAnswer(e.to_string()), - _ => Failure::Failed(e.to_string()), - } -} - -/// The color in a `Response` with `code` and `results`: response 0 carries it, 1 is a cancel, and -/// any other code ends the request without one. The components are passed on as given; -/// `screen_color::sampled` clamps them to 0 to 1, as for the other systems' samplers. -fn answer(code: u32, results: &HashMap) -> Result, Failure> { - match code { - 0 => {} - 1 => return Ok(None), - _ => return Err(Failure::Failed(format!("the portal ended the request (response {code})"))), - } - let color = results.get("color").ok_or_else(|| Failure::Failed("no color in the portal's answer".into()))?; - // Matched field by field: zvariant's tuple conversion panics on a structure with fewer fields. - match &**color { - Value::Structure(s) => match s.fields() { - [Value::F64(r), Value::F64(g), Value::F64(b)] => Ok(Some([*r, *g, *b].map(|v| v as f32))), - _ => Err(Failure::Failed(format!("the portal's color is not three numbers: {color:?}"))), - }, - _ => Err(Failure::Failed(format!("the portal's color is not three numbers: {color:?}"))), - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::portal_request::test_bus::private_bus; - - fn color(rgb: (f64, f64, f64)) -> HashMap { - HashMap::from([("color".into(), OwnedValue::try_from(Value::from(rgb)).unwrap())]) - } - - fn failed(r: Result) -> bool { - matches!(r, Err(Failure::Failed(_))) - } - - #[test] - fn a_picked_color_keeps_its_srgb_values() { - assert_eq!(answer(0, &color((0.25, 0.5, 0.75))), Ok(Some([0.25, 0.5, 0.75]))); - assert_eq!(answer(0, &color((0.0, 1.0, 0.0))), Ok(Some([0.0, 1.0, 0.0]))); - // Outside 0 to 1: passed on for `screen_color::sampled` to clamp. - assert_eq!(answer(0, &color((-0.5, 1.5, 1.0))), Ok(Some([-0.5, 1.5, 1.0]))); - } - - #[test] - fn a_cancel_needs_no_color() { - assert_eq!(answer(1, &HashMap::new()), Ok(None)); - assert_eq!(answer(1, &color((0.25, 0.5, 0.75))), Ok(None)); - } - - #[test] - fn other_response_codes_are_failures() { - for code in [2, 3, u32::MAX] { - assert!(failed(answer(code, &color((0.25, 0.5, 0.75)))), "{code}"); - } - } - - #[test] - fn a_success_without_a_valid_color_is_a_failure() { - assert!(failed(answer(0, &HashMap::new()))); - let wrong = HashMap::from([("color".into(), OwnedValue::from(1_u32))]); - assert!(failed(answer(0, &wrong))); - // Fewer fields, more fields, and fields of another type: an error, not a panic. - for wrong in [Value::from((0.5, 0.5)), Value::from((0.5, 0.5, 0.5, 0.5)), Value::from((1_u32, 0.5, 0.5)), Value::from(vec![0.5, 0.5, 0.5])] { - let wrong = HashMap::from([("color".into(), OwnedValue::try_from(wrong).unwrap())]); - assert!(failed(answer(0, &wrong))); - } - } - - #[test] - fn call_errors_say_whether_the_system_has_a_sampler() { - let reply = |name: &str| { - let call = zbus::Message::method_call("/org/freedesktop/portal/desktop", "PickColor").unwrap().build(&()).unwrap(); - let error = zbus::Message::error(&call.header(), name).unwrap().build(&("detail",)).unwrap(); - zbus::Error::from(error) - }; - for name in UNAVAILABLE { - assert!(matches!(call_failure(&reply(name)), Failure::Unavailable(_)), "{name}"); - } - assert!(matches!(call_failure(&reply("org.freedesktop.portal.Error.NotAllowed")), Failure::Failed(_))); - let timed_out = zbus::Error::InputOutput(std::sync::Arc::new(std::io::ErrorKind::TimedOut.into())); - assert!(matches!(call_failure(&timed_out), Failure::NoAnswer(_))); - let broken = zbus::Error::InputOutput(std::sync::Arc::new(std::io::ErrorKind::BrokenPipe.into())); - assert!(matches!(call_failure(&broken), Failure::Failed(_))); - let messages = [Failure::Unavailable(String::new()), Failure::NoAnswer(String::new()), Failure::Failed(String::new())].map(|f| f.message()); - assert_eq!( - messages, - ["this system has no screen color sampler", "the screen color sampler did not answer", "the screen color sampler failed"] - ); - assert_eq!(call_failure(&broken).detail(), broken.to_string()); - } - - /// Every language that translates the sampler's other messages translates these too. The - /// i18n tests of `vectorcraft-ui-egui` do not read this crate's messages. - #[test] - fn the_messages_are_translated_where_the_sampler_is() { - use vectorcraft_ui_egui::i18n::{Lang, message}; - const OPEN: &str = "the screen color sampler is already open"; - let langs: Vec = Lang::all().filter(|&lang| message(lang, OPEN) != OPEN).collect(); - assert!(!langs.is_empty(), "no language translates {OPEN:?}"); - for lang in langs { - for failure in [Failure::Unavailable(String::new()), Failure::NoAnswer(String::new()), Failure::Failed(String::new())] { - assert_ne!(message(lang, failure.message()), failure.message(), "{}", lang.code()); - } - } - } - - /// The client's connection to the private bus at `address`, made as the sampler makes its own. - fn client(address: &str) -> Connection { - connect(zbus::blocking::connection::Builder::address(address)).unwrap() - } - - /// The portal's name, owned on the private bus at `address` before any call, so the bus never - /// starts an installed portal in its place. - fn portal(address: &str) -> Connection { - zbus::blocking::connection::Builder::address(address).unwrap().name("org.freedesktop.portal.Desktop").unwrap().build().unwrap() - } - - /// Through a real D-Bus: an answer that comes before the call returns is kept; answers on - /// other request paths or from other connections are ignored; a cancel gives no color; and a - /// portal that leaves the bus while the person picks ends the wait. - #[test] - fn the_answer_is_the_portals_response_on_the_returned_path() { - use zbus::blocking::MessageIterator; - use zbus::zvariant::OwnedObjectPath; - - let Some((_daemon, address)) = private_bus() else { return }; - let address = address.as_str(); - let server = portal(address); - let impostor = zbus::blocking::connection::Builder::address(address).unwrap().build().unwrap(); - let incoming = MessageIterator::from(&server); - let worker = std::thread::spawn(move || { - let mut calls = Vec::new(); - for msg in incoming { - let msg = msg.unwrap(); - let header = msg.header(); - if header.message_type() != zbus::message::Type::MethodCall || header.member().map(|m| m.as_str()) != Some("PickColor") { - continue; - } - let (parent, options): (String, HashMap) = msg.body().deserialize().unwrap(); - let token = String::try_from(options.get("handle_token").unwrap().try_clone().unwrap()).unwrap(); - assert!(token.starts_with("vectorcraft_color_")); - assert!(token.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_')); - assert!(!calls.iter().any(|(_, old)| old == &token)); - calls.push((parent, token)); - // A portal older than version 0.9 answers on a path of its own, not the token's. - let path = format!("/org/freedesktop/portal/desktop/request/independent/pick_{}", calls.len()); - let handle = OwnedObjectPath::try_from(path.as_str()).unwrap(); - if calls.len() == 4 { - server.reply(&header, &handle).unwrap(); - assert!(server.release_name("org.freedesktop.portal.Desktop").unwrap()); - break; - } - let to = header.sender().cloned().map(zbus::names::BusName::from); - // Another connection can't end the wait by claiming the portal left. - impostor - .emit_signal( - to.clone(), - "/org/freedesktop/DBus", - "org.freedesktop.DBus", - "NameOwnerChanged", - &("org.freedesktop.portal.Desktop", server.unique_name().unwrap().as_str(), ""), - ) - .unwrap(); - let wrong = color((1.0, 0.0, 0.0)); - impostor.emit_signal(to.clone(), path.as_str(), "org.freedesktop.portal.Request", "Response", &(0_u32, &wrong)).unwrap(); - let unrelated = "/org/freedesktop/portal/desktop/request/unrelated"; - server.emit_signal(to.clone(), unrelated, "org.freedesktop.portal.Request", "Response", &(0_u32, &wrong)).unwrap(); - let code = if calls.len() == 2 { 1_u32 } else { 0_u32 }; - server.emit_signal(to, path.as_str(), "org.freedesktop.portal.Request", "Response", &(code, &color((0.25, 0.5, 0.75)))).unwrap(); - // The reply that names the path goes last: every answer above came before it. - server.reply(&header, &handle).unwrap(); - } - calls - }); - let client = client(address); - assert_eq!(pick(&client, "x11:12"), Ok(Some([0.25, 0.5, 0.75]))); - assert_eq!(pick(&client, "wayland:example"), Ok(None)); - assert_eq!(pick(&client, ""), Ok(Some([0.25, 0.5, 0.75]))); - assert!(matches!(pick(&client, ""), Err(Failure::NoAnswer(_)))); - let calls = worker.join().unwrap(); - assert_eq!(calls.iter().map(|(parent, _)| parent.as_str()).collect::>(), ["x11:12", "wayland:example", "", ""]); - } - - /// Through a real D-Bus: a portal without `PickColor` ends the request as a system without a - /// sampler, and the sampler's connection gives the call [`CALL_TIMEOUT`]. - #[test] - fn a_portal_without_pick_color_ends_the_request() { - let Some((_daemon, address)) = private_bus() else { return }; - let address = address.as_str(); - let server = portal(address); - let incoming = zbus::blocking::MessageIterator::from(&server); - let worker = std::thread::spawn(move || { - for msg in incoming { - let msg = msg.unwrap(); - let header = msg.header(); - if header.member().map(|m| m.as_str()) == Some("PickColor") { - server.reply_error(&header, "org.freedesktop.DBus.Error.UnknownMethod", &("no PickColor",)).unwrap(); - break; - } - } - }); - let client = client(address); - assert_eq!(client.method_timeout(), Some(CALL_TIMEOUT)); - let failure = pick(&client, ""); - assert!(matches!(failure, Err(Failure::Unavailable(_))), "{failure:?}"); - worker.join().unwrap(); - } -} diff --git a/apps/vectorcraft/src/mac_cursor.rs b/apps/vectorcraft/src/mac_cursor.rs deleted file mode 100644 index 69685a35b5..0000000000 --- a/apps/vectorcraft/src/mac_cursor.rs +++ /dev/null @@ -1,238 +0,0 @@ -//! AppKit delivery of the UI's existing cursor artwork, independent of canvas presentation. -#![forbid(unsafe_code)] -// Interim #2292: remove when pinned winit correctly handles macOS cursor image and hotspot sizing. - -use egui::{Context, FullOutput, Plugin, ViewportId}; -use objc2::{AllocAnyThread, MainThreadMarker, rc::Retained}; -use objc2_app_kit::{NSApplication, NSBitmapImageRep, NSCursor, NSImage, NSWindow}; -use objc2_foundation::{NSData, NSPoint, NSSize}; -use std::cell::RefCell; -use vectorcraft_ui_egui::cursors::native_request::{self, Bitmap, Key, Request}; - -const CAPACITY: usize = 128; - -fn build(bitmap: &Bitmap) -> Option> { - let one = &bitmap.representations[0]; - let size = NSSize::new(f64::from(one.size[0]), f64::from(one.size[1])); - let image = NSImage::initWithSize(NSImage::alloc(), size); - for bitmap in &bitmap.representations { - let pixels = image::RgbaImage::from_raw(u32::from(bitmap.size[0]), u32::from(bitmap.size[1]), bitmap.rgba.to_vec())?; - let mut png = std::io::Cursor::new(Vec::new()); - pixels.write_to(&mut png, image::ImageFormat::Png).ok()?; - let rep = NSBitmapImageRep::imageRepWithData(&NSData::with_bytes(png.get_ref()))?; - rep.setSize(size); - image.addRepresentation(&rep); - } - Some(NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, NSPoint::new(f64::from(one.hotspot[0]), f64::from(one.hotspot[1])))) -} - -/// The ownership protocol also runs against a headless backend in tests. -trait Backend { - type Window: Clone + PartialEq; - type Cursor: Clone + PartialEq; - fn window(&self) -> Option; - fn enabled(&self, window: &Self::Window) -> bool; - fn suspend(&mut self, window: &Self::Window); - fn restore(&mut self, window: &Self::Window); - fn build(&mut self, request: &Request) -> Option; - fn set(&mut self, cursor: &Self::Cursor); -} - -struct State { - backend: B, - candidate: Option, - cache: Vec<(Key, Option)>, - // Retain the active object independently of cache eviction. - active: Option<(Key, B::Window, B::Cursor)>, -} - -impl State { - fn new(backend: B) -> Self { - Self { backend, candidate: None, cache: Vec::new(), active: None } - } - - fn begin(&mut self) { - self.candidate = self.backend.window(); - } - - fn release(&mut self) { - self.candidate = None; - if let Some((_, window, _)) = self.active.take() { - self.backend.restore(&window); - } - } - - fn finish(&mut self, request: Option) { - let window = self.candidate.take().filter(|w| self.backend.window().as_ref() == Some(w)); - let (Some(request), Some(window)) = (request, window) else { - self.release(); - return; - }; - if let Some((key, owned, cursor)) = &self.active - && *key == request.key - && *owned == window - { - // AppKit can show the system arrow when the pointer moves while - // `NSCursor.currentCursor` (the app's last set cursor) still reads as ours, so a - // comparison would keep the arrow. Setting the cursor again costs nothing. - self.backend.set(cursor); - return; - } - self.release(); - // Never take another component's suspension (a sheet or native tracking session). - if !self.backend.enabled(&window) { - return; - } - let cursor = if let Some((_, cursor)) = self.cache.iter().find(|(key, _)| *key == request.key) { - cursor.clone() - } else { - let cursor = self.backend.build(&request); - if self.cache.len() >= CAPACITY { - self.cache.clear(); - } - self.cache.push((request.key, cursor.clone())); - cursor - }; - if let Some(cursor) = cursor { - self.backend.suspend(&window); - self.backend.set(&cursor); - self.active = Some((request.key, window, cursor)); - } - } -} - -#[derive(Default)] -struct AppKit { - root: std::sync::Weak, -} -impl Backend for AppKit { - type Window = Retained; - type Cursor = Retained; - fn window(&self) -> Option { - let mtm = MainThreadMarker::new()?; - // Bind the candidate to the host's actual root window without converting raw pointers. - // A floating native panel may be key while egui still has stale root focus input. - let root = self.root.upgrade()?; - if !root.has_focus() || root.is_visible() == Some(false) || root.is_minimized() == Some(true) { - return None; - } - NSApplication::sharedApplication(mtm).keyWindow().filter(|w| w.isVisible() && w.isKeyWindow()) - } - fn enabled(&self, window: &Self::Window) -> bool { - window.areCursorRectsEnabled() - } - fn suspend(&mut self, window: &Self::Window) { - window.disableCursorRects(); - } - fn restore(&mut self, window: &Self::Window) { - window.enableCursorRects(); - window.resetCursorRects(); - // egui-winit may skip an unchanged fallback icon. Rebuild its stored rectangle anyway. - if let Some(view) = window.contentView() { - window.invalidateCursorRectsForView(&view); - } - } - fn build(&mut self, request: &Request) -> Option { - build(&request.bitmap) - } - fn set(&mut self, cursor: &Self::Cursor) { - cursor.set(); - } -} - -thread_local! { static STATE: RefCell> = RefCell::new(State::new(AppKit::default())); } - -fn with_state(f: impl FnOnce(&mut State)) { - // All production AppKit access, including restoration, stays on the main thread. - if MainThreadMarker::new().is_some() { - STATE.with(|state| { - if let Ok(mut state) = state.try_borrow_mut() { - f(&mut state); - } - }); - } -} - -/// Also called synchronously when native menu tracking begins and before process teardown. -pub(crate) fn release() { - with_state(State::release); -} - -struct EndedPass { - viewport: ViewportId, - discarded: bool, - request: Option, -} - -struct Delivery { - begin: fn(), - finish: fn(Option), - release: fn(), - tracking: fn() -> bool, - ended: Vec, -} - -impl Plugin for Delivery { - fn debug_name(&self) -> &'static str { - "macOS canvas cursor" - } - fn on_begin_pass(&mut self, ui: &mut egui::Ui) { - native_request::clear(ui.ctx()); - // Floating panels must not acquire or release the main canvas's window. - if ui.ctx().viewport_id() == ViewportId::ROOT { - (self.begin)(); - } - } - fn on_end_pass(&mut self, ui: &mut egui::Ui) { - // egui restores the parent viewport before output_hook. Capture this pass here so - // a floating panel's output cannot consume or release its parent's cursor. - self.ended.push(EndedPass { viewport: ui.ctx().viewport_id(), discarded: ui.ctx().will_discard(), request: native_request::take(ui.ctx()) }); - } - fn input_hook(&mut self, _: &Context, input: &mut egui::RawInput) { - if input.viewport_id == ViewportId::ROOT - && (!input.focused || input.viewports.get(&ViewportId::ROOT).is_some_and(|v| v.minimized == Some(true))) - { - (self.release)(); - } - } - fn output_hook(&mut self, ctx: &Context, output: &mut FullOutput) { - let Some(ended) = self.ended.pop() else { return }; - if ended.viewport != ViewportId::ROOT { - return; - } - if ended.discarded - || (output.platform_output.requested_discard() && output.platform_output.num_completed_passes < ctx.options(|o| o.max_passes.get())) - { - return; - } - let request = ended.request.filter(|r| { - r.viewport == ended.viewport - && r.pass.checked_add(1) == Some(ctx.cumulative_pass_nr_for(ended.viewport)) - && ctx.input(|i| i.focused && i.pointer.hover_pos().is_some()) - && output.platform_output.cursor_icon == r.fallback - && output.platform_output.cursor_image.is_none() - && !(self.tracking)() - }); - // This is BEFORE egui-winit's platform output. In pinned winit, fallback changes update - // the view's stored cursor and invalidate rectangles. Our owned suspension is intended - // to keep that update from replacing the native cursor; native timing needs hand testing. - (self.finish)(request); - } - fn on_exit(&mut self, _: &Context) { - (self.release)(); - } -} - -pub(crate) fn install(ctx: &Context, window: Option<&std::sync::Arc>) { - with_state(|state| state.backend.root = window.map(std::sync::Arc::downgrade).unwrap_or_default()); - ctx.add_plugin(Delivery { - begin: || with_state(State::begin), - finish: |request| with_state(|state| state.finish(request)), - release, - tracking: super::mac_menu::is_tracking, - ended: Vec::new(), - }); -} - -#[cfg(test)] -mod tests; diff --git a/apps/vectorcraft/src/mac_cursor/tests.rs b/apps/vectorcraft/src/mac_cursor/tests.rs deleted file mode 100644 index ad13a11336..0000000000 --- a/apps/vectorcraft/src/mac_cursor/tests.rs +++ /dev/null @@ -1,227 +0,0 @@ -use super::*; -use egui::{CursorIcon, RawInput}; -use std::cell::Cell; - -#[derive(Default)] -struct Fake { - window: Option, - suspended: Vec, - sets: usize, - builds: usize, - restores: Vec, - fail: bool, -} -impl Backend for Fake { - type Window = u8; - type Cursor = Key; - fn window(&self) -> Option { - self.window - } - fn enabled(&self, w: &u8) -> bool { - !self.suspended.contains(w) - } - fn suspend(&mut self, w: &u8) { - self.suspended.push(*w); - } - fn restore(&mut self, w: &u8) { - self.suspended.retain(|v| v != w); - self.restores.push(*w); - } - fn build(&mut self, r: &Request) -> Option { - self.builds += 1; - (!self.fail).then_some(r.key) - } - fn set(&mut self, _: &Key) { - self.sets += 1; - } -} -fn fake_state() -> State { - State::new(Fake { window: Some(1), ..Default::default() }) -} -fn raw(id: ViewportId, focused: bool) -> RawInput { - let mut input = RawInput { viewport_id: id, focused, events: vec![egui::Event::PointerMoved(egui::pos2(10.0, 10.0))], ..Default::default() }; - input.viewports.entry(id).or_default(); - input -} -fn publish(ctx: &Context, scale: f32) { - let mut session = vectorcraft_engine::Session::new(); - let cursor = session.cursor(Default::default(), Default::default(), Default::default()); - let fallback = native_request::request(ctx, cursor, CursorIcon::Default, true, scale); - ctx.set_cursor_icon(fallback); -} -fn request(scale: f32) -> Request { - let ctx = Context::default(); - let _ = headless(&ctx, raw(ViewportId::ROOT, true), |ui| publish(ui.ctx(), scale)); - native_request::take(&ctx).unwrap() -} -fn deliver(state: &mut State, request: Option) { - state.begin(); - state.finish(request); -} - -#[test] -fn mac_cursor_ownership_reasserts_every_pass_and_restores() { - let req = request(1.0); - let mut state = fake_state(); - deliver(&mut state, Some(req.clone())); - assert_eq!(state.backend.suspended, [1]); - assert_eq!((state.backend.builds, state.backend.sets), (1, 1)); - // The pointer moves and AppKit shows the system arrow, but the app's current cursor - // still reads as ours. The next pass sets it again without rebuilding or re-suspending. - deliver(&mut state, Some(req.clone())); - assert_eq!((state.backend.builds, state.backend.sets, state.backend.suspended.len()), (1, 2, 1)); - deliver(&mut state, None); - assert_eq!(state.backend.restores, [1]); - deliver(&mut state, Some(req.clone())); - state.backend.window = None; - deliver(&mut state, Some(req.clone())); - assert!(state.active.is_none()); - state.backend.window = Some(1); - deliver(&mut state, Some(req.clone())); - state.begin(); - state.backend.window = Some(2); - state.finish(Some(req)); - assert!(state.active.is_none(), "never acquire a different key window mid-pass"); - assert_eq!(state.backend.restores, [1, 1, 1]); -} - -#[test] -fn mac_cursor_respects_other_suspensions_failures_and_cache_eviction() { - let mut state = fake_state(); - state.backend.suspended.push(1); - deliver(&mut state, Some(request(1.0))); - assert_eq!(state.backend.builds, 0); - state.release(); - assert_eq!(state.backend.suspended, [1]); - assert!(state.backend.restores.is_empty()); - state.backend.suspended.clear(); - state.backend.fail = true; - for _ in 0..2 { - deliver(&mut state, Some(request(1.0))); - } - assert_eq!(state.backend.builds, 1, "cache failed constructions"); - state.backend.fail = false; - for i in 1..140 { - deliver(&mut state, Some(request(1.0 + i as f32 / 1000.0))); - } - assert!(state.cache.len() <= CAPACITY); - let active = state.active.unwrap(); - state.cache.clear(); - assert_eq!(state.active, Some(active)); - state.release(); - assert!(state.backend.suspended.is_empty()); -} - -thread_local! { - static FAKE: RefCell> = RefCell::new(fake_state()); - static TRACKING: Cell = const { Cell::new(false) }; -} -fn install_fake(ctx: &Context) { - ctx.add_plugin(Delivery { - begin: || FAKE.with(|s| s.borrow_mut().begin()), - finish: |r| FAKE.with(|s| s.borrow_mut().finish(r)), - release: || FAKE.with(|s| s.borrow_mut().release()), - tracking: || TRACKING.with(Cell::get), - ended: Vec::new(), - }); -} -#[test] -fn mac_cursor_plugin_consumes_passes_and_releases_for_menu_focus_and_overrides() { - FAKE.with(|s| *s.borrow_mut() = fake_state()); - TRACKING.with(|t| t.set(false)); - let ctx = Context::default(); - install_fake(&ctx); - install_fake(&ctx); - let root = ViewportId::ROOT; - let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0)); - FAKE.with(|s| assert_eq!(s.borrow().backend.sets, 1, "one installed plugin consumes the request")); - let _ = headless(&ctx, raw(ViewportId::from_hash_of("floating-panel"), true), |_| {}); - FAKE.with(|s| assert!(s.borrow().active.is_some())); - let _ = headless(&ctx, raw(root, true), |_| {}); - FAKE.with(|s| assert!(s.borrow().active.is_none(), "empty pass hands back even an unchanged Default icon")); - let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0)); - let _ = headless(&ctx, raw(root, true), |ui| { - publish(ui.ctx(), 1.0); - ui.ctx().set_cursor_icon(CursorIcon::Text); - }); - FAKE.with(|s| assert!(s.borrow().active.is_none(), "changed-icon handback")); - let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0)); - // The notification calls release without waiting for another UI pass. - TRACKING.with(|t| t.set(true)); - FAKE.with(|s| s.borrow_mut().release()); - FAKE.with(|s| assert!(s.borrow().active.is_none())); - let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0)); - FAKE.with(|s| assert!(s.borrow().active.is_none())); - TRACKING.with(|t| t.set(false)); - let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0)); - let _ = headless(&ctx, raw(root, false), |_| {}); - FAKE.with(|s| assert!(s.borrow().active.is_none())); - let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0)); - FAKE.with(|s| assert!(s.borrow().active.is_some())); -} - -#[test] -fn mac_cursor_discarded_pass_does_not_commit_and_installation_does_not_repaint() { - FAKE.with(|s| *s.borrow_mut() = fake_state()); - TRACKING.with(|t| t.set(false)); - let ctx = Context::default(); - install_fake(&ctx); - let mut passes = 0; - let _ = headless(&ctx, raw(ViewportId::ROOT, true), |ui| { - passes += 1; - if passes == 1 { - publish(ui.ctx(), 1.0); - ui.ctx().request_discard("cursor regression"); - } - }); - assert_eq!(passes, 2); - FAKE.with(|s| assert_eq!(s.borrow().backend.sets, 0)); - let idle = || { - let mut input = raw(ViewportId::ROOT, true); - input.events.clear(); - input.time = Some(ctx.input(|i| i.time) + 0.1); - input - }; - for _ in 0..3 { - let _ = headless(&ctx, idle(), |ui| publish(ui.ctx(), 1.0)); - } - let out = headless(&ctx, idle(), |ui| publish(ui.ctx(), 1.0)); - assert!(out.viewport_output[&ViewportId::ROOT].repaint_delay > std::time::Duration::ZERO); -} - -#[test] -fn mac_cursor_appkit_representations_have_pixel_sizes_and_point_hotspots() { - // Only construct and inspect image/cursor objects: no NSApplication, window or cursor.set(). - for scale in [0.75, 1.0, 1.25, 1.5, 2.0] { - let request = request(scale); - let cursor = build(&request.bitmap).unwrap(); - let image = cursor.image(); - let one = &request.bitmap.representations[0]; - let size = NSSize::new(f64::from(one.size[0]), f64::from(one.size[1])); - assert_eq!(image.size(), size); - assert_eq!(cursor.hotSpot(), NSPoint::new(f64::from(one.hotspot[0]), f64::from(one.hotspot[1]))); - let reps = image.representations(); - assert_eq!(reps.len(), 2); - let mut dimensions: Vec<_> = reps - .iter() - .map(|rep| { - assert_eq!(rep.size(), size); - (rep.pixelsWide(), rep.pixelsHigh()) - }) - .collect(); - dimensions.sort_unstable(); - assert_eq!( - dimensions, - [ - (isize::try_from(one.size[0]).unwrap(), isize::try_from(one.size[1]).unwrap()), - (isize::try_from(one.size[0]).unwrap() * 2, isize::try_from(one.size[1]).unwrap() * 2) - ] - ); - } -} - -fn headless(ctx: &egui::Context, input: egui::RawInput, draw: impl FnMut(&mut egui::Ui)) -> egui::FullOutput { - let mut output = ctx.run_ui(input, draw); - output.textures_delta.clear(); - output -} diff --git a/apps/vectorcraft/src/mac_menu.rs b/apps/vectorcraft/src/mac_menu.rs deleted file mode 100644 index 53b610a210..0000000000 --- a/apps/vectorcraft/src/mac_menu.rs +++ /dev/null @@ -1,503 +0,0 @@ -//! The macOS menu bar, through muda (Tauri's menu crate: AppKit menus behind a safe API, no GTK -//! with default features off). The menus, their Mac layout and how their keys reach VectorCraft -//! are in `vectorcraft_ui_egui::native_menu`; this file only builds and updates the `NSMenu`s. -//! -//! - Item ids are the items' places (`vc12`, depth first): one command can run from several items -//! (each language of VectorCraft › Language is `app.language` with its own code). -//! - A structure change (a recent file added, the language or a shortcut changed) rebuilds the -//! menu; labels, enabled and checked are updated in place. -//! - A chosen item is a click or a key equivalent: AppKit's current event says which. A key -//! equivalent goes back to egui as the key press that was made (the event's modifiers, not the -//! item's: AppKit may match ⌘R to a ⇧⌘R item), so VectorCraft's key rules still apply. -//! - Hide and Hide Others are items of ours calling `NSApplication`: AppKit's own always take ⌘H -//! (View › Hide Edges) and ⌥⌘H. - -use std::sync::Once; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::mpsc::{Receiver, channel}; - -use block2::RcBlock; - -use egui::{Key, KeyboardShortcut}; -use muda::accelerator::{Accelerator, Code, Modifiers}; -use muda::{CheckMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuItem, Submenu}; -use objc2::MainThreadMarker; -use objc2_app_kit::{NSApplication, NSEventModifierFlags, NSEventType, NSMenuDidBeginTrackingNotification, NSMenuDidEndTrackingNotification}; -use objc2_foundation::{NSNotification, NSNotificationCenter}; -use vectorcraft_ui_egui::VectorcraftApp; -use vectorcraft_ui_egui::native_menu::{self, Backend, Event, MenuBar, MenuRole, Node, Standard}; - -// AppKit can deliver window input while its system menu is still tracking (especially with -// asynchronous menu presentation). Keep the native tracking state separate from egui popups. -static TRACKING: AtomicBool = AtomicBool::new(false); -/// A tracking session began since the last [`Backend::drain`], which reports it as -/// [`Event::Opened`]. -static OPENED: AtomicBool = AtomicBool::new(false); - -pub(crate) fn is_tracking() -> bool { - TRACKING.load(Ordering::Relaxed) -} - -fn observe_tracking(ctx: &egui::Context) { - static INSTALL: Once = Once::new(); - INSTALL.call_once(|| { - // SAFETY: AppKit initializes these immutable notification-name constants. - #[allow(unsafe_code)] - let notifications = unsafe { [(NSMenuDidBeginTrackingNotification, true), (NSMenuDidEndTrackingNotification, false)] }; - for (name, tracking) in notifications { - let repaint = ctx.clone(); - let block = RcBlock::new(move |_: std::ptr::NonNull| { - TRACKING.store(tracking, Ordering::Relaxed); - if tracking { - OPENED.store(true, Ordering::Relaxed); - super::mac_cursor::release(); - } - // Report the opened menu and apply any deferred menu updates as soon as the - // tracking session ends. - if !tracking { - repaint.request_repaint(); - } - }); - // SAFETY: these are AppKit's notification names. The notification center retains - // the observer and block for the application's lifetime; callbacks update tracking, restore - // owned cursor rectangles and request repaint. - #[allow(unsafe_code)] - unsafe { - NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock(Some(name), None, None, &block); - } - } - }); -} - -fn cancel_tracking() { - if let Some(mtm) = MainThreadMarker::new() - && let Some(menu) = NSApplication::sharedApplication(mtm).mainMenu() - { - menu.cancelTracking(); - } - TRACKING.store(false, Ordering::Relaxed); -} - -/// A dismissing click belongs to the menu, so the canvas and panel controls must not see it. -fn dismiss_input(raw: &mut egui::RawInput, tracking: bool) -> bool { - if !raw - .events - .iter() - .any(|e| matches!(e, egui::Event::PointerButton { pressed: true, .. } | egui::Event::Key { key: egui::Key::Escape, pressed: true, .. })) - { - return false; - } - if tracking { - raw.events.retain(|e| !matches!(e, egui::Event::PointerButton { .. } | egui::Event::Key { key: egui::Key::Escape, .. })); - } - true -} - -/// Inspect real window input before native key equivalents and control events are added. -pub fn raw_input_hook(raw: &mut egui::RawInput) { - // Asynchronous menu presentation may leave a displayed menu after its tracking notification. - // Still cancel it, but consume the dismissing input only during a reported tracking session. - if dismiss_input(raw, TRACKING.load(Ordering::Relaxed)) { - cancel_tracking(); - } -} - -enum Handle { - Plain(MenuItem), - Check(CheckMenuItem), -} - -/// One native item, in the order of [`MenuBar::items`]. -struct Entry { - handle: Handle, - item: native_menu::Item, - /// Its shortcut, when it is a key equivalent. - chord: Option, -} - -/// How an item was chosen, read from AppKit's current event while it calls the handler. -struct Chosen { - id: String, - /// A key press (not a mouse click), and the modifiers held: ⌘, ⌃, ⌥, ⇧. - key: bool, - mods: [bool; 4], -} - -pub struct MacMenu { - menu: Option, - entries: Vec, - rx: Receiver, - structure: u64, - /// Latest menu state to apply after AppKit finishes tracking; item ids stay stable meanwhile. - pending: Option, -} - -impl MacMenu { - fn new(ctx: &egui::Context) -> MacMenu { - observe_tracking(ctx); - let (tx, rx) = channel(); - let repaint = ctx.clone(); - MenuEvent::set_event_handler(Some(move |e: MenuEvent| { - // AppKit calls this on the main thread, from the event that chose the item: a key - // equivalent is a key-down, a click a mouse-up (or ↩ inside the open menu). - let event = MainThreadMarker::new().and_then(|mtm| NSApplication::sharedApplication(mtm).currentEvent()); - let key = event.as_ref().is_some_and(|ev| ev.r#type() == NSEventType::KeyDown); - let flags = event.as_ref().map_or(NSEventModifierFlags::empty(), |ev| ev.modifierFlags()); - let mods = [NSEventModifierFlags::Command, NSEventModifierFlags::Control, NSEventModifierFlags::Option, NSEventModifierFlags::Shift] - .map(|m| flags.contains(m)); - // The receiver only goes away with the app. - let _ = tx.send(Chosen { id: e.id.0, key, mods }); - // Wake egui, so the item runs now rather than on the next mouse move. - repaint.request_repaint(); - })); - MacMenu { menu: None, entries: Vec::new(), rx, structure: 0, pending: None } - } - - /// Build the menus of `bar` and make them the app's, in place of the ones before. - fn build(&mut self, bar: &MenuBar) -> muda::Result<()> { - let mut entries = Vec::new(); - let menu = Menu::new(); - let mut special = Vec::new(); - for m in &bar.menus { - let sub = Submenu::new(escape(&m.title), true); - append(&sub, &m.children, &mut entries)?; - menu.append(&sub)?; - if matches!(m.role, MenuRole::Window | MenuRole::Help) { - special.push((m.role, sub)); - } - } - if let Some(old) = self.menu.take() { - old.remove_for_nsapp(); - } - menu.init_for_nsapp(); - // Only once the menu is the app's: muda looks the submenus up in the installed main menu. - for (role, sub) in special { - match role { - MenuRole::Window => sub.set_as_windows_menu_for_nsapp(), - _ => sub.set_as_help_menu_for_nsapp(), - } - } - self.menu = Some(menu); - self.entries = entries; - self.structure = native_menu::structure_key(bar); - Ok(()) - } -} - -fn append(sub: &Submenu, nodes: &[Node], entries: &mut Vec) -> muda::Result<()> { - for n in nodes { - match n { - Node::Separator => sub.append(&PredefinedMenuItem::separator())?, - Node::Header(label) => sub.append(&MenuItem::new(escape(label), false, None))?, - Node::Submenu { label, children } => { - let s = Submenu::new(escape(label), !children.is_empty()); - append(&s, children, entries)?; - sub.append(&s)?; - } - Node::Standard(item) => { - let text = Some(vectorcraft_ui_egui::i18n::t(item.label())); - let p = match item { - Standard::Services => PredefinedMenuItem::services(text), - Standard::ShowAll => PredefinedMenuItem::show_all(text), - Standard::Zoom => PredefinedMenuItem::maximize(text), - Standard::BringAllToFront => PredefinedMenuItem::bring_all_to_front(text), - }; - sub.append(&p)?; - } - Node::Item(it) => { - let id = format!("vc{}", entries.len()); - let chord = it.shortcut.and_then(vectorcraft_ui_egui::shortcuts::parse).filter(native_menu::native_ok); - let accel = chord.as_ref().and_then(accelerator); - let handle = match it.checked { - Some(c) => { - let h = CheckMenuItem::with_id(id, escape(&it.label), it.enabled, c, accel); - sub.append(&h)?; - Handle::Check(h) - } - None => { - let h = MenuItem::with_id(id, escape(&it.label), it.enabled, accel); - sub.append(&h)?; - Handle::Plain(h) - } - }; - entries.push(Entry { handle, item: it.clone(), chord }); - } - } - } - Ok(()) -} - -impl Backend for MacMenu { - fn sync(&mut self, bar: &MenuBar) { - // Replacing or mutating an NSMenu during tracking can strand its displayed menu. Keep - // the latest state: the shared model considers this sync complete and may not resend it. - if TRACKING.load(Ordering::Relaxed) { - self.pending = Some(bar.clone()); - return; - } - self.pending = None; - let items = bar.items(); - if self.menu.is_none() || native_menu::structure_key(bar) != self.structure || items.len() != self.entries.len() { - if let Err(e) = self.build(bar) { - // The menus as they were stay up (a failed build changed nothing). - log::warn!("couldn't rebuild the macOS menu bar: {e}"); - } - return; - } - for (e, it) in self.entries.iter_mut().zip(items) { - if e.item.label != it.label { - let text = escape(&it.label); - match &e.handle { - Handle::Plain(h) => h.set_text(text), - Handle::Check(h) => h.set_text(text), - } - } - if e.item.enabled != it.enabled { - match &e.handle { - Handle::Plain(h) => h.set_enabled(it.enabled), - Handle::Check(h) => h.set_enabled(it.enabled), - } - } - // Compare with AppKit's own state: muda toggles a check item when it's clicked. - if let (Handle::Check(h), Some(c)) = (&e.handle, it.checked) - && h.is_checked() != c - { - h.set_checked(c); - } - if e.item != *it { - e.item = it.clone(); - } - } - } - - fn drain(&mut self) -> Vec { - let mut out = Vec::new(); - if OPENED.swap(false, Ordering::Relaxed) { - out.push(Event::Opened); - } - while let Ok(chosen) = self.rx.try_recv() { - cancel_tracking(); - // Ids that aren't ours are AppKit's own items (Services, Zoom…), already handled. - let Some(e) = chosen.id.strip_prefix("vc").and_then(|n| n.parse::().ok()).and_then(|i| self.entries.get(i)) else { continue }; - if let Some(command @ (native_menu::HIDE | native_menu::HIDE_OTHERS)) = e.item.command { - if let Some(mtm) = MainThreadMarker::new() { - let app = NSApplication::sharedApplication(mtm); - if command == native_menu::HIDE { app.hide(None) } else { app.hideOtherApplications(None) } - } - continue; - } - // A key-down chose it: its key equivalent, unless it was ↩ or Space inside the open - // menu (no ⌘ or ⌃ while the item's shortcut has one). The key is the item's (AppKit - // matched on it); the modifiers are the ones held. - let [cmd, ctrl, alt, shift] = chosen.mods; - let key = e - .chord - .filter(|c| { - chosen.key && e.item.command != Some(native_menu::MINIMIZE) && (cmd || ctrl || !(c.modifiers.command || c.modifiers.ctrl)) - }) - .map(|c| KeyboardShortcut::new(egui::Modifiers { alt, ctrl, shift, mac_cmd: cmd, command: cmd }, c.logical_key)); - out.push(match key { - Some(k) => Event::Key(k), - None => Event::Click(e.item.clone()), - }); - } - // Drain against the old item ids before a deferred structure change replaces them. - if !TRACKING.load(Ordering::Relaxed) - && let Some(bar) = self.pending.take() - { - self.sync(&bar); - } - out - } -} - -/// Install the menu bar (in eframe's creator closure, so winit's default menu doesn't stay up). -/// `None` keeps the menus in the window: AppKit refused them (logged), never a crash. -pub fn install(ctx: &egui::Context, app: &VectorcraftApp) -> Option { - vectorcraft_ui_egui::i18n::set_current(app.ui_language()); - let bar = native_menu::layout(app).bar; - let built = vectorcraft_engine::guard::catch_panic(|| { - let mut menu = MacMenu::new(ctx); - menu.build(&bar).map(|()| menu) - }); - match built { - Ok(Ok(menu)) => Some(native_menu::NativeMenu::new(Box::new(menu))), - Ok(Err(e)) => { - log::warn!("couldn't install the macOS menu bar ({e}); the menus stay in the window"); - None - } - Err(e) => { - log::warn!("couldn't install the macOS menu bar ({e}); the menus stay in the window"); - None - } - } -} - -/// `&` marks a mnemonic in muda labels: "Fill & Stroke" keeps its ampersand. -fn escape(s: &str) -> String { - s.replace('&', "&&") -} - -/// A key equivalent for AppKit. `Cmd` is ⌘ (`META`) and `Ctrl` is ⌃: never folded together. -fn accelerator(c: &KeyboardShortcut) -> Option { - let m = c.modifiers; - let mut mods = Modifiers::empty(); - for (on, flag) in [(m.command || m.mac_cmd, Modifiers::META), (m.ctrl, Modifiers::CONTROL), (m.alt, Modifiers::ALT), (m.shift, Modifiers::SHIFT)] - { - if on { - mods |= flag; - } - } - Some(Accelerator::new(mods, code(c.logical_key)?)) -} - -/// The key code AppKit matches for an egui key. -fn code(key: Key) -> Option { - Some(match key { - Key::A => Code::KeyA, - Key::B => Code::KeyB, - Key::C => Code::KeyC, - Key::D => Code::KeyD, - Key::E => Code::KeyE, - Key::F => Code::KeyF, - Key::G => Code::KeyG, - Key::H => Code::KeyH, - Key::I => Code::KeyI, - Key::J => Code::KeyJ, - Key::K => Code::KeyK, - Key::L => Code::KeyL, - Key::M => Code::KeyM, - Key::N => Code::KeyN, - Key::O => Code::KeyO, - Key::P => Code::KeyP, - Key::Q => Code::KeyQ, - Key::R => Code::KeyR, - Key::S => Code::KeyS, - Key::T => Code::KeyT, - Key::U => Code::KeyU, - Key::V => Code::KeyV, - Key::W => Code::KeyW, - Key::X => Code::KeyX, - Key::Y => Code::KeyY, - Key::Z => Code::KeyZ, - Key::Num0 => Code::Digit0, - Key::Num1 => Code::Digit1, - Key::Num2 => Code::Digit2, - Key::Num3 => Code::Digit3, - Key::Num4 => Code::Digit4, - Key::Num5 => Code::Digit5, - Key::Num6 => Code::Digit6, - Key::Num7 => Code::Digit7, - Key::Num8 => Code::Digit8, - Key::Num9 => Code::Digit9, - Key::F1 => Code::F1, - Key::F2 => Code::F2, - Key::F3 => Code::F3, - Key::F4 => Code::F4, - Key::F5 => Code::F5, - Key::F6 => Code::F6, - Key::F7 => Code::F7, - Key::F8 => Code::F8, - Key::F9 => Code::F9, - Key::F10 => Code::F10, - Key::F11 => Code::F11, - Key::F12 => Code::F12, - Key::F13 => Code::F13, - Key::F14 => Code::F14, - Key::F15 => Code::F15, - Key::F16 => Code::F16, - Key::F17 => Code::F17, - Key::F18 => Code::F18, - Key::F19 => Code::F19, - Key::F20 => Code::F20, - Key::F21 => Code::F21, - Key::F22 => Code::F22, - Key::F23 => Code::F23, - Key::F24 => Code::F24, - Key::OpenBracket => Code::BracketLeft, - Key::CloseBracket => Code::BracketRight, - Key::Backslash => Code::Backslash, - Key::Slash => Code::Slash, - // `+` is Shift+`=` on the keyboards AppKit matches by key: Zoom In shows ⌘=. - Key::Equals | Key::Plus => Code::Equal, - Key::Minus => Code::Minus, - Key::Quote => Code::Quote, - Key::Semicolon => Code::Semicolon, - Key::Comma => Code::Comma, - Key::Period => Code::Period, - Key::Backtick => Code::Backquote, - Key::Backspace => Code::Backspace, - Key::Delete => Code::Delete, - Key::Enter => Code::Enter, - Key::Tab => Code::Tab, - Key::Space => Code::Space, - Key::Escape => Code::Escape, - Key::ArrowLeft => Code::ArrowLeft, - Key::ArrowRight => Code::ArrowRight, - Key::ArrowUp => Code::ArrowUp, - Key::ArrowDown => Code::ArrowDown, - _ => return None, - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Every shortcut the Mac menu shows as a key equivalent has one AppKit can match. - #[test] - fn every_menu_shortcut_maps_to_a_key_equivalent() { - let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let bar = native_menu::layout(&app).bar; - let mut native = 0; - for it in bar.items() { - let Some(c) = it.shortcut.and_then(vectorcraft_ui_egui::shortcuts::parse).filter(native_menu::native_ok) else { continue }; - assert!(accelerator(&c).is_some(), "{:?} ({:?}) has no key equivalent", it.shortcut, it.command); - native += 1; - } - assert!(native > 70, "{native} key equivalents"); - } - - #[test] - fn control_and_command_stay_distinct() { - let parse = |s| vectorcraft_ui_egui::shortcuts::parse(s).and_then(|c| accelerator(&c)); - assert_ne!(parse("Cmd+M"), parse("Ctrl+Cmd+M")); - assert!(parse("Cmd+M").is_some()); - } - - fn press() -> egui::Event { - egui::Event::PointerButton { - pos: egui::pos2(300.0, 200.0), - button: egui::PointerButton::Primary, - pressed: true, - modifiers: Default::default(), - } - } - - #[test] - fn outside_press_dismisses_without_starting_a_canvas_gesture() { - let moved = egui::Event::PointerMoved(egui::pos2(300.0, 200.0)); - let mut raw = egui::RawInput { events: vec![moved.clone(), press()], ..Default::default() }; - assert!(dismiss_input(&mut raw, true)); - assert_eq!(raw.events, [moved]); - assert!(!dismiss_input(&mut raw, true)); - raw.events.push(press()); - assert!(dismiss_input(&mut raw, false)); - assert_eq!(raw.events.len(), 2, "ordinary canvas presses still reach egui"); - } - - #[test] - fn escape_dismisses_without_reaching_the_active_tool() { - let escape = |pressed| egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; - let mut raw = egui::RawInput { events: vec![escape(true), escape(false)], ..Default::default() }; - assert!(dismiss_input(&mut raw, true)); - assert!(raw.events.is_empty()); - } - - #[test] - fn moving_the_pointer_does_not_dismiss_a_tracking_menu() { - let mut raw = egui::RawInput { events: vec![egui::Event::PointerMoved(egui::pos2(300.0, 200.0))], ..Default::default() }; - assert!(!dismiss_input(&mut raw, true)); - assert_eq!(raw.events.len(), 1); - } -} diff --git a/apps/vectorcraft/src/mac_save_format.rs b/apps/vectorcraft/src/mac_save_format.rs deleted file mode 100644 index 17bad11efe..0000000000 --- a/apps/vectorcraft/src/mac_save_format.rs +++ /dev/null @@ -1,293 +0,0 @@ -//! macOS: the Format menu on save sheets (#866). A save panel with two or more file types (Save As, -//! Save a Copy, Save as Template and the first Save of a new document) is an `NSSavePanel` made here -//! instead of by rfd, whose Cocoa backend lists the extensions of every filter but not their names. -//! The panel gets a Format menu as its accessory view -//! () before -//! `beginSheetModalForWindow:completionHandler:` -//! () -//! shows it: an accessory set after the sheet began made recent macOS versions dismiss the sheet at -//! once (#1800, #1831, #1518). Choosing a format changes the extension in the name field and puts -//! the format's extension first in the allowed file types, which AppKit adds to a name typed without -//! one. The save command takes the format from the extension, so an extension typed by hand still -//! decides it. -//! -//! The panel retains the accessory, and the completion handler holds the panel until the sheet -//! closes; the popup's target is the accessory itself. The accessory holds the panel weakly, so -//! closing the sheet releases both. Reading the window from its handle and subclassing `NSView` for -//! the menu's action have no safe API; this module allows `unsafe_code`. -#![allow(unsafe_code)] - -use std::sync::mpsc::{Receiver, channel}; - -use block2::RcBlock; -use objc2::rc::{Retained, Weak}; -use objc2::{ClassType, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel}; -use objc2_app_kit::{NSModalResponse, NSModalResponseOK, NSPopUpButton, NSSavePanel, NSTextField, NSView}; -use objc2_foundation::{NSArray, NSObjectProtocol, NSPoint, NSRect, NSSize, NSString, NSURL}; -use raw_window_handle::{HasWindowHandle, RawWindowHandle}; -use vectorcraft_engine::cmd::fileio; -use vectorcraft_ui_egui::{FileFilter as Filter, FilePick, i18n}; - -/// The accessory's height and the room around and between its label and menu, in points. -const HEIGHT: f64 = 38.0; -const MARGIN: f64 = 12.0; -const GAP: f64 = 8.0; -/// The Format menu's size, in points. -const MENU: NSSize = NSSize::new(260.0, 26.0); - -struct Ivars { - panel: Weak, - filters: Vec, -} - -define_class!( - // SAFETY: NSView has no extra subclassing requirements; the subclass implements no Drop. - #[unsafe(super = NSView)] - #[thread_kind = MainThreadOnly] - #[ivars = Ivars] - #[name = "VectorcraftSaveFormatAccessory"] - struct FormatAccessory; - - // SAFETY: NSObjectProtocol has no additional requirements. - unsafe impl NSObjectProtocol for FormatAccessory {} - - impl FormatAccessory { - // SAFETY: AppKit's target/action sends the popup as the single object argument. - #[unsafe(method(chooseFormat:))] - fn choose_format(&self, sender: &NSPopUpButton) { - let Some(panel) = self.ivars().panel.load() else { return }; - let Some(index) = usize::try_from(sender.indexOfSelectedItem()).ok() else { return }; - let Some(extension) = self.ivars().filters.get(index).and_then(|(_, extensions)| extensions.first()) else { return }; - set_allowed_types(&panel, &self.ivars().filters, index); - let name = panel.nameFieldStringValue().to_string(); - panel.setNameFieldStringValue(&NSString::from_str(&filename(&name, extension, &self.ivars().filters))); - } - } -); - -/// The file types a Format menu lists: `filters` without "every file" ones. Empty when fewer than -/// two remain, and the panel is then left to rfd. -fn menu_formats(filters: &[Filter]) -> Vec { - let named: Vec = - filters.iter().filter(|(_, extensions)| !extensions.is_empty() && !extensions.iter().any(|x| x == "*")).cloned().collect(); - if named.len() < 2 { Vec::new() } else { named } -} - -/// The menu entry of the suggested name's type, or the first (the request's default). -fn initial_format(name: &str, filters: &[Filter]) -> usize { - let extension = fileio::extension(name); - filters.iter().position(|(_, extensions)| extensions.iter().any(|x| extension.eq_ignore_ascii_case(x))).unwrap_or(0) -} - -/// `name` with `extension`: a format's extension (one in the menu, or any other the app reads or -/// writes) is replaced, and other dots stay part of the name (a version number). -fn filename(name: &str, extension: &str, filters: &[Filter]) -> String { - if name.is_empty() { - return String::new(); - } - let has = fileio::extension(name); - let known = - filters.iter().any(|(_, extensions)| extensions.iter().any(|x| has.eq_ignore_ascii_case(x))) || fileio::format_for_name(name).is_some(); - if known { std::path::Path::new(name).with_extension(extension).to_string_lossy().into_owned() } else { format!("{name}.{extension}") } -} - -/// The extensions a panel with menu `filters` allows, those of entry `selected` first. AppKit adds -/// the first one to a name typed without an extension, and a name typed with another of them is -/// saved in that format. -fn allowed_types(filters: &[Filter], selected: usize) -> Vec<&str> { - let first = filters.get(selected).map_or(&[][..], |(_, extensions)| extensions.as_slice()); - let others = filters.iter().enumerate().filter(|(i, _)| *i != selected).flat_map(|(_, (_, extensions))| extensions.iter()); - first.iter().chain(others).map(String::as_str).collect() -} - -/// Set `panel`'s allowed file types ([`allowed_types`]). -fn set_allowed_types(panel: &NSSavePanel, filters: &[Filter], selected: usize) { - let types: Vec> = allowed_types(filters, selected).into_iter().map(NSString::from_str).collect(); - // rfd sets the same deprecated property (`add_filters` in its `panel_ffi.rs`). - #[allow(deprecated)] - panel.setAllowedFileTypes(Some(&NSArray::from_retained_slice(&types))); -} - -/// How [`begin`] decided to show a save sheet. -#[derive(Debug)] -pub enum Begin { - /// The Format-menu sheet is open; wait on the receiver for the path (empty when canceled). - Shown(Receiver>), - /// Fewer than two named file types: the caller should show an rfd panel instead. - DeferToRfd, -} - -/// Show the save panel for `pick` as a sheet on `window`, with a Format menu. -/// -/// `Ok(Begin::Shown(…))` when the sheet is open. `Ok(Begin::DeferToRfd)` when the request has -/// fewer than two named file types (or no AppKit window yet) so rfd should show the panel. -/// `Err(())` when AppKit returned no panel: the caller must not call rfd, whose `+savePanel` -/// panics on the same nil (#5980). -pub fn begin(window: &winit::window::Window, pick: &FilePick) -> Result { - let Some(mtm) = MainThreadMarker::new() else { - return Ok(Begin::DeferToRfd); - }; - let filters = menu_formats(&pick.filters); - if filters.is_empty() { - return Ok(Begin::DeferToRfd); - } - let Some(RawWindowHandle::AppKit(handle)) = window.window_handle().ok().map(|h| h.as_raw()) else { - return Ok(Begin::DeferToRfd); - }; - // SAFETY: the handle's view is the window's content view, which AppKit keeps alive while the - // window is open, and winit hands out the handle only while it is. - let view = unsafe { handle.ns_view.cast::().as_ref() }; - let Some(parent) = view.window() else { - return Ok(Begin::DeferToRfd); - }; - let Some(panel) = new_panel(mtm) else { - log::error!("macOS save panel unavailable: AppKit returned nil for NSSavePanel (#5980)"); - return Err(()); - }; - let selected = initial_format(&pick.name, &filters); - set_allowed_types(&panel, &filters, selected); - if let Some(folder) = &pick.folder { - panel.setDirectoryURL(Some(&NSURL::fileURLWithPath_isDirectory(&NSString::from_str(folder), true))); - } - panel.setExtensionHidden(false); - if !pick.name.is_empty() { - panel.setNameFieldStringValue(&NSString::from_str(&pick.name)); - } - let accessory = accessory(mtm, &panel, filters, selected); - panel.setAccessoryView(Some(&accessory)); - let (tx, rx) = channel(); - let answered = panel.clone(); - let handler = RcBlock::new(move |response: NSModalResponse| { - let picked = answered.URL().and_then(|url| url.path()).map(|p| p.to_string()); - let paths = if response == NSModalResponseOK { picked.into_iter().collect() } else { Vec::new() }; - // The app gone meanwhile has no use for the answer. - let _ = tx.send(paths); - }); - // The panel and its accessory are set up; AppKit keeps the handler (and the panel it holds) - // until the sheet closes. - panel.beginSheetModalForWindow_completionHandler(&parent, &handler); - Ok(Begin::Shown(rx)) -} - -/// An `NSSavePanel` without panicking when AppKit returns nil (#5980). -/// -/// Prefers `-[NSSavePanel init]` (Apple's current Swift API) over `+[NSSavePanel savePanel]`, -/// which objc2 turns into a panic on nil. Falls back to the class method, still as `Option`. -fn new_panel(mtm: MainThreadMarker) -> Option> { - // SAFETY: designated initializer for a bare save panel; returns nil when AppKit refuses. - let panel: Option> = unsafe { msg_send![NSSavePanel::alloc(mtm), init] }; - if panel.is_some() { - return panel; - } - // SAFETY: class method; returns an autoreleased panel or nil. Typed as Option so nil is not a - // panic (unlike `NSSavePanel::savePanel`). - let panel: Option> = unsafe { msg_send![NSSavePanel::class(), savePanel] }; - panel -} - -/// The "Format:" label and menu of `filters`, `selected` chosen, that rename `panel`'s file. -fn accessory(mtm: MainThreadMarker, panel: &NSSavePanel, filters: Vec, selected: usize) -> Retained { - let label = NSTextField::labelWithString(&NSString::from_str(i18n::t("Format:")), mtm); - label.sizeToFit(); - let size = label.frame().size; - label.setFrameOrigin(NSPoint::new(MARGIN, (HEIGHT - size.height) / 2.0)); - let x = MARGIN + size.width + GAP; - let popup = - NSPopUpButton::initWithFrame_pullsDown(NSPopUpButton::alloc(mtm), NSRect::new(NSPoint::new(x, (HEIGHT - MENU.height) / 2.0), MENU), false); - for (name, _) in &filters { - popup.addItemWithTitle(&NSString::from_str(i18n::tr_ctx(i18n::current(), "file-filter", name))); - } - // The filter list comes from the built-in format registry, small enough for NSInteger. - if let Ok(index) = isize::try_from(selected) { - popup.selectItemAtIndex(index); - } - let this = FormatAccessory::alloc(mtm).set_ivars(Ivars { panel: Weak::new(panel), filters }); - let frame = NSRect::new(NSPoint::ZERO, NSSize::new(x + MENU.width + MARGIN, HEIGHT)); - // SAFETY: NSView's designated initializer is called once on the allocated subclass. - let accessory: Retained = unsafe { msg_send![super(this), initWithFrame: frame] }; - // SAFETY: the accessory holds the popup as a subview and AppKit keeps the accessory while the - // sheet is open. The selector has the target/action signature NSControl calls it with. - unsafe { - popup.setTarget(Some(&accessory)); - popup.setAction(Some(sel!(chooseFormat:))); - } - accessory.addSubview(&label); - accessory.addSubview(&popup); - accessory -} - -#[cfg(test)] -mod tests { - use super::*; - - fn filters() -> Vec { - FilePick::filters([("VectorCraft", &["vectorcraft"][..]), ("SVG", &["svg"]), ("PDF", &["pdf"])]) - } - - /// Save, Save As and Save a Copy list every save format with the default first; a panel with one - /// named type, or one for every file, gets no menu, and rfd shows it. - #[test] - fn save_panels_with_several_formats_get_the_menu() { - let save = menu_formats(&FilePick::filters(fileio::save_filters("vectorcraft"))); - assert!(save.len() >= 2, "{save:?}"); - assert_eq!(save.first().map(|(_, e)| e.as_slice()), Some(&["vectorcraft".to_owned()][..])); - assert!(menu_formats(&FilePick::filters(fileio::save_filters("svg"))).first().is_some_and(|(_, e)| e.iter().any(|e| e == "svg"))); - assert!(menu_formats(&FilePick::filters(fileio::template_filters("template"))).len() >= 2); - assert!(menu_formats(&FilePick::filters([("PDF", &["pdf"][..])])).is_empty()); - assert!(menu_formats(&FilePick::filters([("PDF", &["pdf"][..]), ("All files", &["*"]), ("Any", &[])])).is_empty()); - assert_eq!(menu_formats(&FilePick::filters([("PDF", &["pdf"][..]), ("All files", &["*"]), ("SVG", &["svg"])])).len(), 2); - } - - #[test] - fn the_suggested_name_selects_its_format_and_an_unknown_one_the_default() { - for (name, index) in [("Untitled-1", 0), ("a b.SVG", 1), ("art.pdf", 2), ("version.2", 0), ("", 0)] { - assert_eq!(initial_format(name, &filters()), index, "{name}"); - } - } - - #[test] - fn choosing_a_format_changes_the_extension_and_keeps_the_name() { - for (name, expected) in [ - ("図面 1.vectorcraft", "図面 1.svg"), - ("a.PDF", "a.svg"), - ("art", "art.svg"), - ("art.v2", "art.v2.svg"), - ("art.svg", "art.svg"), - ("old.drawcraft", "old.svg"), - ("photo.png", "photo.svg"), - ("", ""), - ] { - assert_eq!(filename(name, "svg", &filters()), expected, "{name}"); - } - } - - /// A name typed without an extension gets the chosen format's: AppKit adds the first allowed - /// type. The others stay allowed. - #[test] - fn the_chosen_format_is_the_first_allowed_type() { - assert_eq!(allowed_types(&filters(), 0), ["vectorcraft", "svg", "pdf"]); - assert_eq!(allowed_types(&filters(), 1), ["svg", "vectorcraft", "pdf"]); - assert_eq!(allowed_types(&filters(), 2), ["pdf", "vectorcraft", "svg"]); - assert_eq!(allowed_types(&filters(), 9), ["vectorcraft", "svg", "pdf"]); - } - - /// A nil AppKit panel must be `None`, not a panic. `NSSavePanel::savePanel` used to panic here - /// (#5980); `new_panel` types the same message send as `Option`. - #[test] - fn a_null_save_panel_pointer_is_none_not_a_panic() { - let null: *mut NSSavePanel = std::ptr::null_mut(); - // SAFETY: retaining a null object pointer is defined to yield None. - let panel: Option> = unsafe { Retained::retain(null) }; - assert!(panel.is_none()); - } - - /// Each entry of the Save As menu gives a name the save command reads as that entry's format. - #[test] - fn each_menu_entry_names_a_file_the_save_command_writes_in_that_format() { - let filters = menu_formats(&FilePick::filters(fileio::save_filters("vectorcraft"))); - for (label, extensions) in &filters { - let name = filename("Untitled-1.vectorcraft", &extensions[0], &filters); - assert_eq!(fileio::format_for_name(&name).map(|f| f.label), Some(label.as_str()), "{name}"); - } - } -} diff --git a/apps/vectorcraft/src/mac_screen_color.rs b/apps/vectorcraft/src/mac_screen_color.rs deleted file mode 100644 index 65e1f3cfde..0000000000 --- a/apps/vectorcraft/src/mac_screen_color.rs +++ /dev/null @@ -1,69 +0,0 @@ -//! macOS: Sample Color from Screen (`vectorcraft_ui_egui::screen_color`) through the system's color -//! sampler, `NSColorSampler` (macOS 10.15 and later), which "displays the system’s color-sampling -//! interface and returns the selected color to your app" -//! (). AppKit calls the handler on -//! the main thread with the color the person clicked, or with nil when they pressed Escape. The -//! color is converted to sRGB before it is sent to the UI; AppKit clips a color outside sRGB to it -//! (Display P3 red arrives as sRGB red). -//! -//! `showSamplerWithSelectionHandler:` has no safe binding; this module allows `unsafe_code`. -#![allow(unsafe_code)] - -use std::sync::mpsc::channel; - -use block2::RcBlock; -use objc2::MainThreadMarker; -use objc2_app_kit::{NSColor, NSColorSampler, NSColorSpace}; -use vectorcraft_ui_egui::screen_color::{Answer, StartSampler}; - -/// The system's color sampler; `ui` is woken when it answers. -pub fn sampler(ui: egui::Context) -> StartSampler { - Box::new(move || { - MainThreadMarker::new().ok_or("the color sampler can only be shown from the main thread")?; - let (tx, rx) = channel(); - let ui = ui.clone(); - let handler = RcBlock::new(move |color: *mut NSColor| { - // SAFETY: AppKit passes the selected color, or nil when the person canceled, and keeps - // it alive while the handler runs. - let answer: Answer = match unsafe { color.as_ref() } { - None => Ok(None), - Some(color) => srgb(color).map(Some).ok_or_else(|| "the sampled color has no sRGB value".into()), - }; - // The UI may be gone (the app quitting): nothing waits for the color then. - let _ = tx.send(answer); - ui.request_repaint(); - }); - let sampler = NSColorSampler::new(); - // SAFETY: on the main thread (checked above); the handler has the signature AppKit calls it - // with, and AppKit keeps the block and the sampler until the session ends. - unsafe { sampler.showSamplerWithSelectionHandler(&handler) }; - Ok(rx) - }) -} - -/// The components of `color` in sRGB, or `None` when it has no RGB form (a pattern color). -fn srgb(color: &NSColor) -> Option<[f32; 3]> { - let c = color.colorUsingColorSpace(&NSColorSpace::sRGBColorSpace())?; - Some([c.redComponent() as f32, c.greenComponent() as f32, c.blueComponent() as f32]) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// A color in another space arrives as its sRGB components. - #[test] - fn sampled_colors_convert_to_srgb() { - let red = NSColor::colorWithSRGBRed_green_blue_alpha(1.0, 0.0, 0.0, 1.0); - assert_eq!(srgb(&red), Some([1.0, 0.0, 0.0])); - // Display P3 (0.6, 0.4, 0.3) lies inside sRGB with other numbers: more red, less green and blue. - let p3 = NSColor::colorWithDisplayP3Red_green_blue_alpha(0.6, 0.4, 0.3, 1.0); - let [r, g, b] = srgb(&p3).unwrap(); - assert!(r > 0.61 && g < 0.39 && b < 0.29, "converted, not read as sRGB numbers: {r} {g} {b}"); - // A color outside sRGB is clipped to it. - assert_eq!(srgb(&NSColor::colorWithDisplayP3Red_green_blue_alpha(1.0, 0.0, 0.0, 1.0)), Some([1.0, 0.0, 0.0])); - let gray = NSColor::colorWithWhite_alpha(0.5, 1.0); - let [r, g, b] = srgb(&gray).unwrap(); - assert!((r - g).abs() < 1e-4 && (g - b).abs() < 1e-4, "{r} {g} {b}"); - } -} diff --git a/apps/vectorcraft/src/mac_tablet.rs b/apps/vectorcraft/src/mac_tablet.rs index ade798a393..1ebe750cb9 100644 --- a/apps/vectorcraft/src/mac_tablet.rs +++ b/apps/vectorcraft/src/mac_tablet.rs @@ -1,8 +1,8 @@ //! macOS: a drawing tablet's pen pressure (#852), tilt and barrel rotation (#764), and an airbrush //! pen's finger wheel. winit 0.30 //! hands a pen to the window there as a mouse, without them, so the app reads them from AppKit -//! itself and writes them into the UI's [`StylusFeed`] (`Services::stylus`), which the canvas -//! reads, as on X11 ([`crate::tablet`]). +//! itself and writes them into the framework's [`PenSource`], which the tool host reads, as on X11 +//! ([`crate::tablet`]). //! //! A local event monitor (`addLocalMonitorForEventsMatchingMask:handler:`, which AppKit calls "with //! each event it is about to dispatch" in this app: @@ -10,8 +10,8 @@ //! reads each mouse and tablet event on the main thread before winit's view handles it, and passes //! it on unchanged: //! - A mouse event whose `subtype` is `NSEventSubtypeTabletPoint` comes from a pen: its `pressure` -//! (0..1) goes into the feed, kept for the pointer move winit makes of the event -//! ([`StylusFeed::set_move`]), so each move of a fast stroke has its own pressure. Its `tilt` +//! (0..1) goes into the source, which queues every reading, so each move of a fast stroke has +//! its own pressure. Its `tilt` //! (−1..1 on each axis, ±[`TILT_DEGREES`] at the ends) and its `rotation` go into the feed as the //! pen's pose, kept for that move too. AppKit gives a rotation of 0 for a pen that does not read //! one and a tilt of 0 for an upright pen, so one event cannot tell a pen without tilt or rotation @@ -33,7 +33,8 @@ //! works on plain values and is tested on every platform; the monitor reads them. #![cfg_attr(not(target_os = "macos"), allow(dead_code))] -use vectorcraft_ui_egui::stylus::{PenPose, PenSample, StylusFeed}; +use craft::behavior::PointerSample; +use craft::ui::runtime::pen::PenSource; use crate::tablet::TILT_DEGREES; @@ -91,12 +92,12 @@ impl RawEvent { self.kind == event_type::TABLET_POINT || (self.mouse() && self.subtype == subtype::TABLET_POINT) } - /// The pen's tilt and rotation in [`PenPose`]'s units. + /// The pen's reading as a [`PointerSample`], tilt and rotation in radians. /// /// AppKit's `tilt` is −1.0..1.0 on each axis and 0.0 on both with the pen perpendicular to the /// tablet. A negative x is a tilt to the left and a positive x a tilt to the right; a negative y /// is a tilt to the top and a positive y a tilt to the bottom - /// (). [`PenPose`]'s x is positive + /// (). The sample's x is positive /// to the right and its y positive down the page, the same signs, so each axis keeps its sign. /// Apple gives the ends of the range as maximum tilt and does not give them in degrees /// (), so @@ -108,22 +109,29 @@ impl RawEvent { /// no direction for rotation; the Cocoa Event Handling Guide gives the `rotation` accessor's /// degrees as counterclockwise for the rotate gesture /// (), - /// and the pen's rotation is taken the same way. [`PenPose`]'s rotation runs clockwise, so the - /// angle is negated and brought into 0..360. + /// and the pen's rotation is taken the same way. The sample's rotation runs clockwise, so the + /// angle is negated and brought into 0..360 degrees. /// /// AppKit's `tangentialPressure` is −1.0..1.0, the finger wheel of an airbrush pen on the /// devices that have one (). - /// It becomes [`PenPose`]'s wheel of 0..1, −1.0 at 0 and 1.0 at 1; a value past either end is + /// It becomes the sample's wheel of 0..1, −1.0 at 0 and 1.0 at 1; a value past either end is /// clamped. /// /// The tilt is left out unless `read.tilts`, the rotation unless `read.turns`, and the wheel /// unless `read.wheels` ([`Pen`]). - fn pose(&self, read: Reads) -> PenPose { - let degrees = |v: f64| (v.clamp(-1.0, 1.0) * TILT_DEGREES) as f32; - // `0.0 - r` rather than `-r`: a rotation of 0 gives 0, not −0. - let rotation = read.turns.then(|| (0.0 - self.rotation).rem_euclid(360.0)); - let wheel = read.wheels.then(|| (self.tangential.clamp(-1.0, 1.0) + 1.0) / 2.0); - PenPose { tilt: read.tilts.then(|| [degrees(self.tilt.0), degrees(self.tilt.1)]), rotation, wheel } + fn sample(&self, read: Reads, eraser: bool) -> PointerSample { + let radians = |v: f64| ((v.clamp(-1.0, 1.0) * TILT_DEGREES) as f32).to_radians(); + let mut sample = PointerSample::new(self.pressure); + sample.eraser = eraser; + if read.tilts { + sample.tilt = [radians(self.tilt.0), radians(self.tilt.1)]; + } + if read.turns { + // `0.0 - r` rather than `-r`: a rotation of 0 gives 0, not −0. + sample.rotation = (0.0 - self.rotation).rem_euclid(360.0).to_radians(); + } + sample.wheel = read.wheels.then(|| (self.tangential.clamp(-1.0, 1.0) + 1.0) / 2.0); + sample } /// Whether the event reports a tilt other than 0, a rotation other than 0, and a tangential @@ -161,17 +169,14 @@ enum Update { /// Nothing: an event the monitor doesn't map. Keep, /// The sample of a pen, or `None` for a mouse. - Set(Option), - /// A pen's sample that comes with a pointer move. - Move(PenSample), + Set(Option), } impl Update { - fn apply(self, feed: &StylusFeed) { + fn apply(self, pen: &PenSource) { match self { Update::Keep => {} - Update::Set(sample) => feed.set_sample(sample), - Update::Move(sample) => feed.set_move(sample), + Update::Set(sample) => pen.set(sample), } } } @@ -193,29 +198,25 @@ impl Pen { self.eraser = e.entering && e.device == device::ERASER; self.read = Reads::default(); let pen = e.entering && e.device != device::CURSOR; - return Update::Set(pen.then_some(PenSample { pressure: 0.0, eraser: self.eraser, ..PenSample::default() })); + let mut near = PointerSample::new(0.0); + near.eraser = self.eraser; + return Update::Set(pen.then_some(near)); } if e.point() { self.read.add(e.reads()); + return Update::Set(Some(e.sample(self.read, self.eraser))); } - let sample = PenSample { pressure: e.pressure, eraser: self.eraser, pose: e.pose(self.read) }; - match (e.point(), e.mouse()) { - (true, true) => Update::Move(sample), - (true, false) => Update::Set(Some(sample)), - (false, true) => Update::Set(None), - (false, false) => Update::Keep, - } + if e.mouse() { Update::Set(None) } else { Update::Keep } } } -/// Start reading pen pressure: the feed the monitor writes into, or `None` (logged) when AppKit +/// Start reading pen pressure: the source the monitor writes into, or `None` (logged) when AppKit /// refuses the monitor or this isn't the main thread. #[cfg(target_os = "macos")] -pub fn start() -> Option { - // The monitor writes on the main thread before winit hands the event on: a press never waits. - let feed = StylusFeed::on_ui_thread(); - match monitor::install(feed.clone()) { - Ok(()) => Some(feed), +pub fn start() -> Option { + let pen = PenSource::default(); + match monitor::install(pen.clone()) { + Ok(()) => Some(pen), Err(e) => { log::warn!("tablet pressure: {e}"); None @@ -229,14 +230,14 @@ mod monitor { use std::ptr::NonNull; use block2::RcBlock; + use craft::ui::runtime::pen::PenSource; use objc2::MainThreadMarker; use objc2_app_kit::{NSEvent, NSEventMask}; - use vectorcraft_ui_egui::stylus::StylusFeed; use super::{Pen, RawEvent, event_mask}; /// Install the monitor for the life of the app. Main thread only. - pub(super) fn install(feed: StylusFeed) -> Result<(), &'static str> { + pub(super) fn install(source: PenSource) -> Result<(), &'static str> { MainThreadMarker::new().ok_or("the event monitor can only be installed from the main thread")?; let pen = Cell::new(Pen::default()); let handler = RcBlock::new(move |event: NonNull| -> *mut NSEvent { @@ -245,7 +246,7 @@ mod monitor { #[allow(unsafe_code)] let e = unsafe { event.as_ref() }; let mut p = pen.get(); - p.handle(&read(e)).apply(&feed); + p.handle(&read(e)).apply(&source); pen.set(p); event.as_ptr() }); @@ -298,20 +299,29 @@ mod tests { } /// A sample of the tip of a pen that has reported no tilt or rotation. - fn tip(pressure: f32) -> PenSample { - PenSample { pressure, eraser: false, pose: PenPose::default() } + fn tip(pressure: f32) -> PointerSample { + PointerSample::new(pressure) } - /// A sample of the pen near the tablet but not yet read: no pose. - fn near(eraser: bool) -> PenSample { - PenSample { pressure: 0.0, eraser, pose: PenPose::default() } + /// A sample of the pen near the tablet but not yet read: no tilt or rotation. + fn near(eraser: bool) -> PointerSample { + let mut sample = PointerSample::new(0.0); + sample.eraser = eraser; + sample + } + + /// `sample` held as `tilt` and `rotation` (radians). + fn held(mut sample: PointerSample, tilt: [f32; 2], rotation: f32) -> PointerSample { + sample.tilt = tilt; + sample.rotation = rotation; + sample } #[test] fn a_pens_mouse_events_are_moves_with_its_pressure() { let mut p = Pen::default(); - assert_eq!(p.handle(&pen(DRAG, 0.5)), Update::Move(tip(0.5))); - assert_eq!(p.handle(&pen(1, 0.25)), Update::Move(tip(0.25)), "a press"); + assert_eq!(p.handle(&pen(DRAG, 0.5)), Update::Set(Some(tip(0.5)))); + assert_eq!(p.handle(&pen(1, 0.25)), Update::Set(Some(tip(0.25))), "a press"); assert_eq!(p.handle(&pen(event_type::TABLET_POINT, 0.8)), Update::Set(Some(tip(0.8))), "no move"); } @@ -332,11 +342,15 @@ mod tests { #[test] fn proximity_says_which_end_is_near() { let mut p = Pen::default(); - let eraser = |pressure| PenSample { pressure, eraser: true, pose: PenPose::default() }; + let eraser = |pressure| { + let mut sample = near(true); + sample.pressure = pressure; + sample + }; assert_eq!(p.handle(&proximity(device::ERASER, true)), Update::Set(Some(near(true)))); - assert_eq!(p.handle(&pen(DRAG, 0.4)), Update::Move(eraser(0.4))); + assert_eq!(p.handle(&pen(DRAG, 0.4)), Update::Set(Some(eraser(0.4)))); assert_eq!(p.handle(&proximity(device::ERASER, false)), Update::Set(None), "it left"); - assert_eq!(p.handle(&pen(DRAG, 0.4)), Update::Move(tip(0.4))); + assert_eq!(p.handle(&pen(DRAG, 0.4)), Update::Set(Some(tip(0.4)))); assert_eq!(p.handle(&proximity(1, true)), Update::Set(Some(near(false))), "the tip"); assert_eq!(p.handle(&proximity(0, true)), Update::Set(Some(near(false))), "an unknown tool draws as the tip"); assert_eq!(p.handle(&proximity(device::CURSOR, true)), Update::Set(None), "a puck is a mouse"); @@ -345,42 +359,39 @@ mod tests { } /// #764: AppKit's tilt (−1..1, x positive to the right, y positive to the bottom) reaches the - /// feed in degrees with the same signs, and its rotation, taken as counterclockwise, reaches it - /// clockwise. + /// source in radians with the same signs, and its rotation, taken as counterclockwise, reaches + /// it clockwise. #[test] fn a_pens_tilt_and_rotation_go_into_the_feed() { let mut p = Pen::default(); - let sample = |pressure, pose| PenSample { pressure, eraser: false, pose }; - assert_eq!(p.handle(&pen(DRAG, 0.5)), Update::Move(tip(0.5)), "no tilt or rotation reported yet"); + let deg = f32::to_radians; + assert_eq!(p.handle(&pen(DRAG, 0.5)), Update::Set(Some(tip(0.5))), "no tilt or rotation reported yet"); let leaning = RawEvent { tilt: (0.5, -0.25), rotation: 30.0, ..pen(DRAG, 0.5) }; - let pose = PenPose { tilt: Some([30.0, -15.0]), rotation: Some(330.0), wheel: None }; - assert_eq!(p.handle(&leaning), Update::Move(sample(0.5, pose))); + assert_eq!(p.handle(&leaning), Update::Set(Some(held(tip(0.5), [deg(30.0), deg(-15.0)], deg(330.0))))); let past_the_ends = RawEvent { tilt: (-4.0, 1.5), rotation: 270.0, ..pen(event_type::TABLET_POINT, 0.8) }; - let pose = PenPose { tilt: Some([-60.0, 60.0]), rotation: Some(90.0), wheel: None }; - assert_eq!(p.handle(&past_the_ends), Update::Set(Some(sample(0.8, pose))), "clamped"); - let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None }; - let Update::Move(upright) = p.handle(&pen(DRAG, 0.6)) else { panic!("a pen's drag is a move") }; - assert_eq!(upright, sample(0.6, pose), "once reported, 0 is upright and unturned"); - assert!(upright.pose.rotation.is_some_and(f32::is_sign_positive), "{upright:?}"); - let feed = StylusFeed::default(); - p.handle(&RawEvent { tilt: (f64::NAN, 0.0), rotation: -90.0, ..pen(DRAG, 0.3) }).apply(&feed); - assert_eq!(feed.pose(), Some(PenPose { rotation: Some(90.0), ..PenPose::default() }), "a tilt that is not a number is left out"); + assert_eq!(p.handle(&past_the_ends), Update::Set(Some(held(tip(0.8), [deg(-60.0), deg(60.0)], deg(90.0)))), "clamped"); + let Update::Set(Some(upright)) = p.handle(&pen(DRAG, 0.6)) else { panic!("a pen's drag is a sample") }; + assert_eq!(upright, tip(0.6), "once reported, 0 is upright and unturned"); + assert!(upright.rotation.is_sign_positive(), "{upright:?}"); + let source = PenSource::default(); + p.handle(&RawEvent { tilt: (f64::NAN, 0.0), rotation: -90.0, ..pen(DRAG, 0.3) }).apply(&source); + let sample = source.current().unwrap(); + assert_eq!((sample.tilt, sample.rotation), ([0.0, 0.0], deg(90.0)), "a tilt that is not a number is left out"); p.handle(&proximity(1, true)); let tilted = RawEvent { tilt: (0.0, 0.5), ..pen(event_type::TABLET_POINT, 0.8) }; - let pose = PenPose { tilt: Some([0.0, 30.0]), ..PenPose::default() }; - assert_eq!(p.handle(&tilted), Update::Set(Some(sample(0.8, pose))), "no rotation reported since the pen came near"); - p.handle(&RawEvent { kind: DRAG, ..Default::default() }).apply(&feed); - assert_eq!(feed.pose(), None, "a mouse moved"); + assert_eq!(p.handle(&tilted), Update::Set(Some(held(tip(0.8), [0.0, deg(30.0)], 0.0))), "no rotation reported since the pen came near"); + p.handle(&RawEvent { kind: DRAG, ..Default::default() }).apply(&source); + assert_eq!(source.current(), None, "a mouse moved"); } - /// An airbrush pen's finger wheel (AppKit's `tangentialPressure`, −1..1) reaches the feed as + /// An airbrush pen's finger wheel (AppKit's `tangentialPressure`, −1..1) reaches the source as /// 0..1, once the pen has reported a value other than 0 since it came near. #[test] fn an_airbrush_wheel_goes_into_the_feed() { let mut p = Pen::default(); let wheel = |p: &mut Pen, tangential: f32| match p.handle(&RawEvent { tangential, ..pen(DRAG, 0.5) }) { - Update::Move(s) => s.pose.wheel, - u => panic!("a pen's drag is a move: {u:?}"), + Update::Set(Some(s)) => s.wheel, + u => panic!("a pen's drag is a sample: {u:?}"), }; assert_eq!(wheel(&mut p, 0.0), None, "no wheel reported yet"); assert_eq!(wheel(&mut p, -1.0), Some(0.0)); @@ -393,15 +404,14 @@ mod tests { #[test] fn the_feed_gets_each_moves_pressure_within_0_to_1() { - let feed = StylusFeed::default(); + let source = PenSource::default(); let mut p = Pen::default(); - for e in [pen(DRAG, f32::NAN), pen(DRAG, 4.0), pen(DRAG, -1.0), pen(event_type::TABLET_POINT, 0.3)] { - p.handle(&e).apply(&feed); + for (e, expected) in [(pen(DRAG, f32::NAN), 1.0), (pen(DRAG, 4.0), 1.0), (pen(DRAG, -1.0), 0.0), (pen(event_type::TABLET_POINT, 0.3), 0.3)] { + p.handle(&e).apply(&source); + assert_eq!(source.current().map(|s| s.pressure), Some(expected)); } - let pressures: Vec = feed.take_moves().into_iter().map(|(p, _)| p).collect(); - assert_eq!((pressures, feed.held()), (vec![1.0, 1.0, 0.0], Some(0.3))); - p.handle(&RawEvent { kind: DRAG, ..Default::default() }).apply(&feed); - assert_eq!(feed.held(), None, "a mouse moved"); + p.handle(&RawEvent { kind: DRAG, ..Default::default() }).apply(&source); + assert_eq!(source.current(), None, "a mouse moved"); } #[test] diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index a7454d896b..0a1f938ced 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -11,11 +11,13 @@ //! (Windows and Linux; `single_instance`). //! //! `--in-window-menus` (or `VECTORCRAFT_IN_WINDOW_MENUS=1`) keeps the menus inside the window on -//! macOS instead of the macOS menu bar (`mac_menu`). +//! macOS instead of the macOS menu bar. //! -//! `--control ` (or `VECTORCRAFT_CONTROL_PORT`; a port from 1 to 65535, or the app doesn't -//! start) starts a localhost JSON-lines control server: +//! `--control ` (or `VECTORCRAFT_CONTROL_PORT`; a port from 0 to 65535, 0 picking a free +//! one, or the app doesn't start) starts a localhost JSON-lines control server: //! `{"id":1,"method":"ui.inspect","params":{}}` → `{"id":1,"ok":true,"result":…}`. +//! `--control-token ` (or `VECTORCRAFT_CONTROL_TOKEN`) or `--control-token-file ` +//! (or `VECTORCRAFT_CONTROL_TOKEN_FILE`) sets the token each connection sends first. //! See `vectorcraft_ui_egui::control` for the methods. `--automation-read-root` and //! `--automation-write-root` (or `VECTORCRAFT_AUTOMATION_READ_ROOT` / `_WRITE_ROOT`) confine the //! files its requests read and write (`vectorcraft_engine::file_access`); the person at the @@ -26,42 +28,26 @@ #![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")] mod automation_args; -mod caps_lock; mod clipboard; #[cfg(feature = "wgpu")] mod compositor_gpu; -mod control_server; mod cursor_theme; mod display_profile; #[cfg(feature = "wgpu")] mod gpu; mod hang_watch; #[cfg(target_os = "linux")] -mod linux_screen_color; -#[cfg(target_os = "linux")] mod linux_stylus; mod logging; #[cfg(all(target_os = "macos", feature = "wgpu"))] mod mac_color_space; #[cfg(target_os = "macos")] -mod mac_cursor; -#[cfg(target_os = "macos")] mod mac_fonts; -#[cfg(target_os = "macos")] -mod mac_menu; -#[cfg(target_os = "macos")] -mod mac_save_format; -#[cfg(target_os = "macos")] -mod mac_screen_color; mod mac_tablet; #[cfg(target_os = "macos")] mod mac_window; #[cfg(target_os = "macos")] mod open_documents; -#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] -mod portal_request; -#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd", test))] -mod portal_save; mod prefs_dir; mod presentation; mod printing; @@ -72,54 +58,111 @@ mod single_instance; #[cfg(windows)] mod system_fonts; mod tablet; -mod window; mod window_frame; mod windows_alt_codes; #[cfg(windows)] mod windows_cores; -mod windows_screen_color; mod windows_stylus; mod windows_symbol_chars; mod xwayland; +use std::sync::{Arc, Mutex}; + +use craft::automation::args::{ControlOptions, EnvNames}; +use craft::automation::server::{self, Listening}; +use craft::dialogs::service::{FilePanels, FileService}; +use craft::host::target::{Backend, ShellInfo}; +use craft::host::{AppInfo, Wake}; +use craft::settings::SharedSettings; +use craft::ui::InstallSpec; +use craft::ui::shell::embed; +use craft::window::Prefix; +use craft::window::policy::{TitleBarPref, decide_for}; +use craft::window::restore::Store; +use craft::window::system::SystemWindows; use vectorcraft_engine::Session; use vectorcraft_engine::cmd::fileio; use vectorcraft_engine::file_access::{self, AutomationRoots}; use vectorcraft_ui_egui::dialogs::safe_mode; use vectorcraft_ui_egui::graphics::GraphicsLoss; -use vectorcraft_ui_egui::picks::PickRequest; -use vectorcraft_ui_egui::{ClipboardProbeFactory, FilePick, Services, VectorcraftApp}; +use vectorcraft_ui_egui::{AppSettings, Services, VectorcraftApp}; mod app; mod host_services; mod prefs; -mod titlebar; #[cfg(all(test, feature = "wgpu"))] use app::bring_window_forward; -use app::native_input_hook; use app::open_or_hold; -use host_services::services; -#[cfg(all(test, feature = "wgpu"))] -use prefs::{KEEP_UI_PREFS, decode_saved_prefs, keep_prefs_copy, prefs_bytes}; -use prefs::{load_prefs, log_dir, prefs_enabled, prefs_path, read_prefs}; -#[cfg(all(test, feature = "wgpu", any(target_os = "macos", target_os = "windows")))] -use titlebar::CUSTOM_TITLEBAR; -#[cfg(feature = "wgpu")] -use titlebar::adapter_summary; -#[cfg(all(test, feature = "wgpu"))] -use titlebar::custom_titlebar_from; -#[cfg(all(test, feature = "wgpu"))] -use titlebar::opted_into_system_title_bar; +use host_services::{file_service, services, start_pen}; +use prefs::{load_prefs, log_dir, open_store, prefs_enabled}; + +/// The window's size when no saved placement overrides it, and the smallest it may be, in points. +const DEFAULT_SIZE: [f32; 2] = [1440.0, 900.0]; +const MIN_SIZE: [f32; 2] = [800.0, 500.0]; + +/// The app id every OS window carries; it matches `packaging/linux/ai.storyteller.vectorcraft.desktop`. +const WINDOW_APP_ID: &str = "ai.storyteller.vectorcraft"; + +/// The window, Dock, taskbar and app-switcher icon (`assets/app-icon/`, see its README). macOS gets +/// the version with Apple's transparent margin; elsewhere the full-bleed tile. The app ID matches +/// `packaging/linux/ai.storyteller.vectorcraft.desktop` so Wayland docks find the launcher icon. +fn app_icon() -> egui::IconData { + #[cfg(target_os = "macos")] + let png: &[u8] = include_bytes!("../../../assets/app-icon/vectorcraft-macos-512.png"); + #[cfg(not(target_os = "macos"))] + let png: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.vectorcraft.png"); + eframe::icon_data::from_png_bytes(png).unwrap_or_default() +} + +/// Windows shows a window's big icon (`ICON_BIG`) in the taskbar and Alt+Tab; eframe sets only the +/// small one (the title bar's), so the taskbar showed a generic icon. Set the big one too. #[cfg(windows)] -use titlebar::set_taskbar_icon; -#[cfg(all(test, feature = "wgpu"))] -use titlebar::{app_draws_frame, caption_layout_from, opted_into_app_title_bar, start_frame, system_title_bar_applies}; -use titlebar::{custom_titlebar, native_options, titlebar_from_env}; +fn set_taskbar_icon(w: &winit::window::Window) { + use winit::platform::windows::WindowExtWindows as _; + let icon = app_icon(); + // An icon that can't be made leaves the generic one: nothing else depends on it. + if let Ok(i) = winit::window::Icon::from_rgba(icon.rgba, icon.width, icon.height) { + w.set_taskbar_icon(Some(i)); + } +} + +/// "name (backend, kind)" of the adapter the window renders with, for Help › About and bug reports. +#[cfg(feature = "wgpu")] +fn adapter_summary(info: &eframe::wgpu::AdapterInfo) -> String { + format!("{} ({:?}, {:?})", info.name.trim(), info.backend, info.device_type) +} + +/// The window's options: the app draws the title bar when `custom_titlebar`, else the desktop does. +fn native_options(custom_titlebar: bool) -> eframe::NativeOptions { + eframe::NativeOptions { + viewport: egui::ViewportBuilder::default() + .with_title("VectorCraft") + .with_inner_size(DEFAULT_SIZE) + .with_min_inner_size(MIN_SIZE) + .with_drag_and_drop(true) + .with_decorations(!custom_titlebar) + .with_fullsize_content_view(true) + .with_titlebar_shown(false) + .with_title_shown(false) + .with_icon(app_icon()) + .with_app_id(WINDOW_APP_ID), + ..Default::default() + } +} struct App { app: VectorcraftApp, - host_caps_lock: caps_lock::HostCapsLock, + /// The preferences, written through [`prefs::save_tick`] and on exit. + settings: SharedSettings, + /// The file service the host's `Files` is, kept for the folders its picks chose. + files: Arc, + /// Shows the native dialogs the file service was asked for. + file_panels: FilePanels, + /// The interface language the Replace question of [`Self::file_panels`] is worded in. + replace_lang: Option, + /// Keeps the control server running while the app does. + _control_server: Option, /// Reported by wgpu when the window's graphics device is lost (a driver reset). graphics_loss: GraphicsLoss, /// The graphics device was lost and the unsaved changes are kept for Data Recovery. @@ -131,14 +174,8 @@ struct App { /// The main window; used to read and set maximized state the UI layer does not see on Linux (#3635), /// and to take the window off screen on quit before the clipboard handles let go (`quit_windows`). winit_window: Option>, - /// A saved or fitted geometry asked for maximize once the window is mapped (Linux). - pending_maximize: bool, - /// Frames left to retry [`window::apply_pending_maximize`]. - maximize_tries: u8, /// The command line's files, held back until the choice about a stopped plug-in is made. held_files: Vec, - /// The time and UI zoom of the last monitor list ([`window::monitors_due`]). - monitors_listed: Option<(f64, f32)>, /// Reads the profile of the display that shows the main window, for the canvas. display_profile: display_profile::Reader, /// When this frame's input hook started, for the hang report's frame times (`hang_watch`). @@ -159,6 +196,10 @@ Opens the VectorCraft desktop app with the given files. Options: --control Start the localhost JSON-lines control server on (or VECTORCRAFT_CONTROL_PORT) + --control-token The token control connections send first + (or VECTORCRAFT_CONTROL_TOKEN) + --control-token-file Read that token from + (or VECTORCRAFT_CONTROL_TOKEN_FILE) --automation-read-root Confine the files control requests read to (may be given more than once) --automation-write-root Confine the files control requests write to @@ -273,10 +314,28 @@ fn read_command_line( Ok(CommandLine { files, in_window_menus, new_instance, safe_mode }) } +/// Whether the window opens through XWayland, for Linux Display Server `pref` (`main`). +#[cfg(target_os = "linux")] +fn opens_through_xwayland(pref: Option<&str>) -> bool { + if !xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) { + return false; + } + if !xwayland::x11_libraries_found() { + log::warn!("Linux Display Server is X11, but the X11 libraries aren't all installed: opening the window on Wayland"); + return false; + } + if pref != Some("x11") { + log::info!("pen found: opening the window through XWayland, where the pen works (VECTORCRAFT_NATIVE_WAYLAND=1 keeps Wayland)"); + } else { + log::info!("opening the window through XWayland (Preferences › Performance › Linux Display Server)"); + } + true +} + fn main() -> std::process::ExitCode { // Windows: the update helper is a copy of this program started with `--finish-update`. #[cfg(windows)] - if let Some(result) = craft_update::self_update::finish(&vectorcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { + if let Some(result) = craft::update::self_update::finish(&vectorcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { std::process::exit(i32::from(result.is_err())); } // Before any thread starts: the pointer must find a cursor theme on Wayland (#2450). @@ -289,22 +348,29 @@ fn main() -> std::process::ExitCode { let mut roots_args = automation_args::AutomationArgs::new(root_env("VECTORCRAFT_AUTOMATION_READ_ROOT"), root_env("VECTORCRAFT_AUTOMATION_WRITE_ROOT")); let mut presentation = presentation::Overrides::default(); - let CommandLine { files, in_window_menus, new_instance, safe_mode: safe_mode_flag } = + let CommandLine { files: command_line_files, in_window_menus, new_instance, safe_mode: safe_mode_flag } = match read_command_line(std::env::args().skip(1), &mut control, &mut roots_args, &mut presentation) { Ok(command_line) => command_line, Err(code) => return code, }; let automation_args::AutomationArgs { read_roots, write_roots, .. } = roots_args; - // After the arguments: `--control` and `--version` win over a bad environment value. - let control_port = match control.port { - Some(port) => Some(port), - None => match automation_args::env_control_port(std::env::var_os("VECTORCRAFT_CONTROL_PORT")) { - Ok(port) => port, - Err(e) => { - eprintln!("vectorcraft: {e}"); - return std::process::ExitCode::FAILURE; - } - }, + // After the arguments: the flags and `--version` win over a bad environment value. + let control_options = match ControlOptions::resolve(control.options(), &EnvNames::for_app("VECTORCRAFT")) { + Ok(options) => options, + Err(e) => { + eprintln!("vectorcraft: {e}"); + return std::process::ExitCode::FAILURE; + } + }; + let control_port = control_options.port; + // Read before the window opens: a token file that can't be read keeps the app from starting + // rather than leaving the channel open without one. + let control_token = match control_port.map(|_| control_options.server_token()).transpose() { + Ok(token) => token.map(|token| (control_options.token_notice(&token), token)), + Err(e) => { + eprintln!("vectorcraft: {e}"); + return std::process::ExitCode::FAILURE; + } }; // Before desktop services, so every start-up warning is recorded (`logging`). let logger = logging::install(); @@ -312,13 +378,12 @@ fn main() -> std::process::ExitCode { // the log file is attached: a launch that hands its files over leaves the running app's log be. #[cfg(not(target_os = "macos"))] // A launch that sets the presentation runs as its own app: a running app keeps its own surface. - match single_instance::start(control_port.is_some(), new_instance || presentation.is_set(), safe_mode_flag, &files) { + match single_instance::start(control_port.is_some(), new_instance || presentation.is_set(), safe_mode_flag, &command_line_files) { single_instance::Start::Forwarded => return std::process::ExitCode::SUCCESS, single_instance::Start::Running(primary) => single_instance::hold(primary), } #[cfg(target_os = "macos")] let _ = new_instance; - vectorcraft_ui_egui::i18n::detect_system_lang_in_background(); // Before the first render: the cores the process may run on. #[cfg(windows)] windows_cores::install(); @@ -367,14 +432,19 @@ fn main() -> std::process::ExitCode { } } }; - let saved = read_prefs(); - let saved_window = saved.as_ref().and_then(|ui| ui.window); + let (settings, settings_report) = open_store(); + if settings_report.has_problems() { + log::warn!("the preferences were not read as saved: {settings_report:?}"); + } + // An engine preference the window's start reads before the app exists. + let engine_pref = |key: &str| settings.lock().get().ui.engine_prefs.get(key).cloned(); #[cfg(feature = "wgpu")] - let gpu_pref = saved.as_ref().and_then(|ui| ui.engine_prefs.get("gpuPreference")).and_then(serde_json::Value::as_str); + let gpu_pref_value = engine_pref("gpuPreference"); + #[cfg(feature = "wgpu")] + let gpu_pref = gpu_pref_value.as_ref().and_then(serde_json::Value::as_str); // Preferences › Performance › Low-Latency Drawing; anything but `true` in the file is off. #[cfg(feature = "wgpu")] - let low_latency_drawing = - saved.as_ref().and_then(|ui| ui.engine_prefs.get("lowLatencyDrawing")).and_then(serde_json::Value::as_bool).unwrap_or(false); + let low_latency_drawing = engine_pref("lowLatencyDrawing").and_then(|v| v.as_bool()).unwrap_or(false); #[cfg(feature = "wgpu")] let power_env = eframe::wgpu::PowerPreference::from_env(); #[cfg(feature = "wgpu")] @@ -408,40 +478,33 @@ fn main() -> std::process::ExitCode { }; #[cfg(feature = "wgpu")] let crash = left_out.crash.clone(); - let (custom_titlebar, caption_layout) = custom_titlebar(saved.as_ref()); - let options = native_options(custom_titlebar); // winit picks Wayland whenever `WAYLAND_DISPLAY` is set; Preferences › Performance › Linux // Display Server › X11 opens the window through XWayland instead, where file drops work (#1151), // and the other choices do so when a pen is attached, where the pen draws (#2028, #4967). #[cfg(target_os = "linux")] - let mut forced_to_x11 = false; + let forced_to_x11 = opens_through_xwayland(engine_pref("linuxDisplayServer").as_ref().and_then(serde_json::Value::as_str)); + #[cfg(not(target_os = "linux"))] + let forced_to_x11 = false; + // A window forced onto XWayland runs on X11, whose window manager draws the frame: the + // framework decides the frame for that backend, from the platform, `VECTORCRAFT_TITLEBAR` and + // Preferences › User Interface › System Title Bar. + let shell_info = if forced_to_x11 { ShellInfo::current().backend(Backend::X11) } else { ShellInfo::current() }; + let titlebar_pref = + if engine_pref("systemTitleBar").and_then(|v| v.as_bool()).unwrap_or(false) { TitleBarPref::System } else { TitleBarPref::Integrated }; + let decision = decide_for(Prefix::new("VECTORCRAFT"), shell_info.backend, titlebar_pref); + let custom_titlebar = matches!(decision.frame, craft::window::policy::Frame::Integrated(_)); + let options = native_options(custom_titlebar); #[cfg(target_os = "linux")] let options = { let mut options = options; - let pref = saved.as_ref().and_then(|ui| ui.engine_prefs.get("linuxDisplayServer")).and_then(serde_json::Value::as_str); - if xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) { - if xwayland::x11_libraries_found() { - forced_to_x11 = true; - if pref != Some("x11") { - log::info!("pen found: opening the window through XWayland, where the pen works (VECTORCRAFT_NATIVE_WAYLAND=1 keeps Wayland)"); - } else { - log::info!("opening the window through XWayland (Preferences › Performance › Linux Display Server)"); - } - use winit::platform::x11::EventLoopBuilderExtX11 as _; - options.event_loop_builder = Some(Box::new(|builder| { - builder.with_x11(); - })); - } else { - log::warn!("Linux Display Server is X11, but the X11 libraries aren't all installed: opening the window on Wayland"); - } + if forced_to_x11 { + use winit::platform::x11::EventLoopBuilderExtX11 as _; + options.event_loop_builder = Some(Box::new(|builder| { + builder.with_x11(); + })); } options }; - #[cfg(not(target_os = "linux"))] - let forced_to_x11 = false; - // Preferences › User Interface notes under System Title Bar when the desktop draws the frame - // with it on or off. - let desktop_keeps_frame = titlebar::desktop_keeps_frame(forced_to_x11); // With Windows Ink, winit reports a pen as a touch and drops its barrel button and which end // is down; the message hook notes each pointer contact and whether it starts with the barrel // button held, and writes the pen's end into the pen feed (`windows_stylus`). It also notes the @@ -539,7 +602,32 @@ fn main() -> std::process::ExitCode { run( options, Box::new(move |cc| { - VectorcraftApp::install_ime_reset_hooks(&cc.egui_ctx); + let ctx = &cc.egui_ctx; + let winit_window = cc.winit_window().cloned(); + let spec = InstallSpec::new(shell_info, Arc::new(SystemWindows)) + .app_id(WINDOW_APP_ID) + .placement(Arc::new(Mutex::new(Store::open("vectorcraft")))) + .frame(decision); + let spec = match start_pen(&winit_window) { + Some(pen) => spec.pen(pen), + None => spec, + }; + embed::install(ctx, spec, &vectorcraft_ui_egui::ui_fonts()).map_err(|e| e.to_string())?; + egui_extras::install_image_loaders(ctx); + craft::ui::primitives::register_app_icons(&vectorcraft_ui_egui::icons::APP_ICONS); + craft::ui::primitives::register_app_icons(&vectorcraft_ui_egui::cursors::CURSOR_ICONS); + let folders = settings.lock().get().ui.last_folders.clone(); + let wake = { + let ctx = ctx.clone(); + Wake::new(move || ctx.request_repaint()) + }; + let (files, file_panels) = file_service(wake, folders); + let files = Arc::new(files); + craft::host::Host::builder(AppInfo { id: "vectorcraft", name: "VectorCraft", version: env!("CARGO_PKG_VERSION") }) + .i18n(vectorcraft_ui_egui::i18n::shared()) + .settings(Arc::new(settings.clone())) + .files(files.clone()) + .install(ctx); let mut session = Session::new(); // The profiles loaded before come back before the preferences name any of them. prefs_dir::attach_profile_store(&mut session); @@ -547,7 +635,8 @@ fn main() -> std::process::ExitCode { prefs_dir::attach_color_settings(&mut session); // Before any plug-in loads: this launch's marker in the Launch folder next to the // preferences (none for runs without preferences), and Safe Mode. - let launch_dir = prefs_path().filter(|_| prefs_enabled()).and_then(|p| Some(p.parent()?.join("Launch"))); + let launch_dir = prefs_dir::prefs_dir().filter(|_| prefs_enabled()).map(|d| d.join("Launch")); + let folder = |name: &str| prefs_dir::prefs_dir().map(|d| d.join(name).to_string_lossy().to_string()); let stopped = safe_mode::begin_launch(launch_dir.as_deref(), safe_mode_flag); prefs_dir::attach_plugin_store(&mut session); // File › Scripts lists the scripts of the Scripts folder next to the preferences. @@ -557,9 +646,10 @@ fn main() -> std::process::ExitCode { prefs_dir::attach_new_doc_profiles(&mut session); prefs_dir::attach_proof_setups(&mut session); prefs_dir::attach_script_data(&mut session); - let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone())); + let mut app = VectorcraftApp::new(session, services(winit_window.clone())); + app.adopt_context(&cc.egui_ctx); app.set_startup_update_check(true); - load_prefs(&mut app, saved); + load_prefs(&mut app, &settings); safe_mode::after_start(&mut app, stopped); // The saved PDF presets live in their own folder (also read by vectorcraft-cli), // which takes over from the copy the preferences file used to hold. @@ -570,38 +660,27 @@ fn main() -> std::process::ExitCode { prefs_dir::attach_arrowheads(&mut app.session); // The custom bevels, kept in their own file next to the preferences. prefs_dir::attach_bevels(&mut app.session); - // Fit the window to its monitor, or put it back where it was (still hidden). - let winit_window = cc.winit_window().cloned(); + // The window's placement comes back through the framework's placement store. + #[cfg(windows)] if let Some(w) = &winit_window { - let g = window::restore(w, saved_window); - app.ui.window = Some(g); - #[cfg(windows)] set_taskbar_icon(w); } - // Linux may not map the window before the first frames, so a saved maximize is retried then (#3635). - let pending_maximize = cfg!(target_os = "linux") && app.ui.window.as_ref().is_some_and(|g| g.maximized); // User Defined swatch, graphic style, symbol and brush libraries live next to the preferences. - let swatches = prefs_path().and_then(|p| Some(p.parent()?.join("Swatches").to_string_lossy().to_string())); - app.session.swatch_libraries.set_user_dir(swatches); - let styles = prefs_path().and_then(|p| Some(p.parent()?.join("Graphic Styles").to_string_lossy().to_string())); - app.session.style_libraries.set_user_dir(styles); - let symbols = prefs_path().and_then(|p| Some(p.parent()?.join("Symbols").to_string_lossy().to_string())); - app.session.symbol_libraries.set_user_dir(symbols); - let brushes = prefs_path().and_then(|p| Some(p.parent()?.join("Brushes").to_string_lossy().to_string())); - app.session.brush_libraries.set_user_dir(brushes); + app.session.swatch_libraries.set_user_dir(folder("Swatches")); + app.session.style_libraries.set_user_dir(folder("Graphic Styles")); + app.session.symbol_libraries.set_user_dir(folder("Symbols")); + app.session.brush_libraries.set_user_dir(folder("Brushes")); // With the User Defined libraries listed, the persistent library panels reopen. vectorcraft_ui_egui::panels::library_panel::restore(&mut app); // So do the Libraries panel's libraries; runs without preferences (agents' test // runs) keep theirs for the session only, never touching the user's. if prefs_enabled() { - let libraries = prefs_path().and_then(|p| Some(p.parent()?.join("Libraries").to_string_lossy().to_string())); - app.session.libraries.set_dir(libraries); + app.session.libraries.set_dir(folder("Libraries")); } // Data Recovery copies live next to the preferences too (none for runs without // preferences, such as agents' test runs, unless the recoveryFolder preference is set). if std::env::var_os("VECTORCRAFT_NO_PREFS").is_none() { - let recovery = prefs_path().and_then(|p| Some(p.parent()?.join("Data Recovery").to_string_lossy().to_string())); - app.session.recovery.set_default_folder(recovery); + app.session.recovery.set_default_folder(folder("Data Recovery")); } let graphics_loss = GraphicsLoss::default(); #[cfg(feature = "wgpu")] @@ -664,19 +743,25 @@ fn main() -> std::process::ExitCode { if previous_hang.is_some() && app.ui.status.is_empty() { vectorcraft_ui_egui::troubleshooting::last_session_stopped(&mut app); } - app.titlebar_from_env = titlebar_from_env(); - app.custom_titlebar = custom_titlebar; - app.caption_layout = caption_layout; - app.desktop_frame = !custom_titlebar; - app.desktop_keeps_frame = desktop_keeps_frame; - if let Some(port) = control_port { - let rx = control_server::start(port, cc.egui_ctx.clone()); - app = app.with_control(rx).with_automation_roots(roots.clone()); - if let Some(roots) = &roots { - // Everywhere the app doesn't say whose work it is (worker threads), the - // roots hold: unconfined is only what the person at the keyboard does. - file_access::confine_process(roots.clone()); - log::info!("control channel confined to the automation roots: {}", roots.describe()); + let mut control_server = None; + if let (Some(port), Some((notice, token))) = (control_port, control_token) { + match server::listen(port, token, craft::ui::runtime::windows::WindowHost::of(&cc.egui_ctx)) { + Ok((rx, listening)) => { + eprintln!("{notice}"); + log::info!("control channel: {listening:?}"); + control_server = Some(listening); + app = app.with_control(rx).with_automation_roots(roots.clone()); + if let Some(roots) = &roots { + // Everywhere the app doesn't say whose work it is (worker threads), the + // roots hold: unconfined is only what the person at the keyboard does. + file_access::confine_process(roots.clone()); + log::info!("control channel confined to the automation roots: {}", roots.describe()); + } + } + Err(e) => { + log::error!("no control channel on port {port}: {e}"); + eprintln!("vectorcraft: can't listen on port {port}: {e}"); + } } } #[cfg(target_os = "macos")] @@ -684,34 +769,33 @@ fn main() -> std::process::ExitCode { open_documents::set_ui(&cc.egui_ctx); // The macOS menu bar, installed now so winit's default menu doesn't stay up. if !in_window_menus { - app.services.native_menu = mac_menu::install(&cc.egui_ctx, &app); + app.services.native_menu = vectorcraft_ui_egui::menus::native::install(&cc.egui_ctx, &mut app); } - mac_cursor::install(&cc.egui_ctx, winit_window.as_ref()); } #[cfg(not(target_os = "macos"))] { let _ = in_window_menus; single_instance::set_ui(&cc.egui_ctx); } - app.services.native_input_hook = native_input_hook(&app); - let held_files = file_access::unconfined(|| open_or_hold(&mut app, files)); + let held_files = file_access::unconfined(|| open_or_hold(&mut app, command_line_files)); // The first frame is due from now (`gpu::watch_first_frame`). #[cfg(feature = "wgpu")] created.ready(); // The content and the pointer stay aligned on Windows (#1758). let window_frame = window_frame::service(cc, custom_titlebar); Ok(Box::new(App { - host_caps_lock: caps_lock::HostCapsLock::new(winit_window.as_deref()), app, + settings, + files, + file_panels, + replace_lang: None, + _control_server: control_server, graphics_loss, graphics_lost: false, frames: 0, window_frame, winit_window, - pending_maximize, - maximize_tries: 8, held_files, - monitors_listed: None, display_profile: Default::default(), frame_start: None, min_frame, @@ -743,19 +827,10 @@ fn main() -> std::process::ExitCode { /// this process has open, until it runs that program. A file lock held through such a copy outlives /// its own handle, so a GPU start test that released the start file and opened it again found it /// still locked, as if another copy of the app were running, and failed. A test that starts a -/// program holds [`spawning`]; a test that depends on the start file's lock holds [`no_spawns`]. -#[cfg(all( - test, - any(feature = "wgpu", any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")) -))] +/// program holds its write side; a test that depends on the start file's lock holds [`no_spawns`]. +#[cfg(all(test, feature = "wgpu"))] static CHILD_SPAWN: std::sync::RwLock<()> = std::sync::RwLock::new(()); -/// Held while a test starts another program (see [`CHILD_SPAWN`]). -#[cfg(all(test, any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")))] -fn spawning() -> std::sync::RwLockWriteGuard<'static, ()> { - CHILD_SPAWN.write().unwrap_or_else(std::sync::PoisonError::into_inner) -} - /// Held by a test that releases a locked file and opens it again (see [`CHILD_SPAWN`]). #[cfg(all(test, feature = "wgpu"))] fn no_spawns() -> std::sync::RwLockReadGuard<'static, ()> { diff --git a/apps/vectorcraft/src/portal_request.rs b/apps/vectorcraft/src/portal_request.rs deleted file mode 100644 index da4cb9ad23..0000000000 --- a/apps/vectorcraft/src/portal_request.rs +++ /dev/null @@ -1,231 +0,0 @@ -//! Linux and the BSDs: the answer to an XDG desktop portal request -//! (), -//! for the save dialog (`portal_save`) and, on Linux, the screen color sampler -//! (`linux_screen_color`). The wait ends with the request's `Response`, or with an error when the -//! portal leaves the bus first. - -use futures_lite::{StreamExt as _, future}; -use zbus::blocking::{Connection, MessageIterator}; -use zbus::zvariant::OwnedObjectPath; - -const DESKTOP: &str = "org.freedesktop.portal.Desktop"; - -/// A request token: `prefix`, then 128 bits from the operating system's random device, so the -/// token is unique and can't be guessed, as the Request documentation asks. -#[cfg(target_os = "linux")] -pub(crate) fn token(prefix: &str) -> Result { - use std::io::Read as _; - - let mut bytes = [0; 16]; - std::fs::File::open("/dev/urandom") - .and_then(|mut file| file.read_exact(&mut bytes)) - .map_err(|e| format!("could not create a portal request token: {e}"))?; - let random: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect(); - Ok(format!("{prefix}_{random}")) -} - -/// Subscriptions made before a portal method call, on every request path: a portal older than -/// version 0.9 ignores `handle_token` and answers on the request path it returns, and its answer -/// can come before the call's reply. Each stream keeps every signal from the time it is made. -pub(crate) struct Responses { - replies: MessageIterator, - owners: MessageIterator, -} - -impl Responses { - pub(crate) fn new(conn: &Connection) -> Result { - let reply_rule = zbus::MatchRule::builder() - .msg_type(zbus::message::Type::Signal) - .sender(DESKTOP) - .and_then(|b| b.interface("org.freedesktop.portal.Request")) - .and_then(|b| b.member("Response")) - .map_err(|e| e.to_string())? - .build(); - let owner_rule = zbus::MatchRule::builder() - .msg_type(zbus::message::Type::Signal) - .sender("org.freedesktop.DBus") - .and_then(|b| b.path("/org/freedesktop/DBus")) - .and_then(|b| b.interface("org.freedesktop.DBus")) - .and_then(|b| b.member("NameOwnerChanged")) - .and_then(|b| b.arg(0, DESKTOP)) - .map_err(|e| e.to_string())? - .build(); - Ok(Self { - replies: MessageIterator::for_match_rule(reply_rule, conn, None).map_err(|e| e.to_string())?, - owners: MessageIterator::for_match_rule(owner_rule, conn, None).map_err(|e| e.to_string())?, - }) - } - - /// The `Response` on the request path `call` returned, from the connection that returned it. - /// An error when that connection leaves the bus first, or the bus connection closes. A - /// `Response` the portal sent before it left is still the answer. - pub(crate) fn wait(self, call: &zbus::Message) -> Result { - enum Event { - Reply(Option>), - Owner(Option>), - } - let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?; - let portal = call.header().sender().map(|s| s.as_str().to_string()).ok_or("the portal answered without a sender")?; - let answers = |reply: &zbus::Message| { - let header = reply.header(); - header.path().map(|p| p.as_str()) == Some(handle.as_str()) && header.sender().map(|s| s.as_str()) == Some(portal.as_str()) - }; - let mut replies = self.replies.into_inner(); - let mut owners = self.owners.into_inner(); - future::block_on(async { - loop { - let event = future::or(async { Event::Owner(owners.next().await) }, async { Event::Reply(replies.next().await) }).await; - match event { - Event::Reply(reply) => { - let reply = reply.ok_or("the portal closed without an answer")?.map_err(|e| e.to_string())?; - if answers(&reply) { - return Ok(reply); - } - } - Event::Owner(message) => { - let message = message.ok_or("the portal connection closed")?.map_err(|e| e.to_string())?; - if owner_disappeared(&message, &portal)? { - // zbus puts each message in every matching stream before it reads the - // next one, so a `Response` that came before the bus's report is - // already queued: it is still the answer. - while let Some(Some(reply)) = future::poll_once(replies.next()).await { - if let Ok(reply) = reply - && answers(&reply) - { - return Ok(reply); - } - } - return Err("the desktop portal disappeared while waiting for its answer".into()); - } - } - } - } - }) - } -} - -/// Whether `message` is the bus's `NameOwnerChanged` saying that the connection `portal` no longer -/// owns the portal's name. The bus itself must send it: another connection can't end the wait. -fn owner_disappeared(message: &zbus::Message, portal: &str) -> Result { - if message.header().sender().map(|s| s.as_str()) != Some("org.freedesktop.DBus") { - return Ok(false); - } - let (name, old, new): (String, String, String) = message.body().deserialize().map_err(|e| e.to_string())?; - Ok(name == DESKTOP && old == portal && new != portal) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn only_the_bus_can_report_portal_owner_loss() { - let changed = |sender, name, old, new| { - zbus::Message::signal("/org/freedesktop/DBus", "org.freedesktop.DBus", "NameOwnerChanged") - .unwrap() - .sender(sender) - .unwrap() - .build(&(name, old, new)) - .unwrap() - }; - let forged = changed(":1.42", DESKTOP, ":1.7", ""); - assert!(!owner_disappeared(&forged, ":1.7").unwrap()); - let real = changed("org.freedesktop.DBus", DESKTOP, ":1.7", ""); - assert!(owner_disappeared(&real, ":1.7").unwrap()); - let other = changed("org.freedesktop.DBus", "org.example.Other", ":1.7", ""); - assert!(!owner_disappeared(&other, ":1.7").unwrap()); - let old = changed("org.freedesktop.DBus", DESKTOP, ":1.8", ""); - assert!(!owner_disappeared(&old, ":1.7").unwrap()); - let acquired = changed("org.freedesktop.DBus", DESKTOP, "", ":1.7"); - assert!(!owner_disappeared(&acquired, ":1.7").unwrap()); - } - - /// Through a real D-Bus: when the bus has reported the portal gone, a `Response` the portal sent - /// before it left is still the answer; without one the wait ends with an error. - #[test] - fn a_queued_answer_wins_over_the_portal_leaving() { - use std::collections::HashMap; - - use zbus::blocking::connection::Builder; - use zbus::zvariant::OwnedValue; - - for answered in [true, false] { - let Some((_daemon, address)) = test_bus::private_bus() else { return }; - let address = address.as_str(); - let portal = Builder::address(address).unwrap().name(DESKTOP).unwrap().build().unwrap(); - let unique = portal.unique_name().unwrap().to_string(); - let client = Builder::address(address).unwrap().build().unwrap(); - let responses = Responses::new(&client).unwrap(); - // zbus puts each message in every matching stream before it reads the next one - // (`src/connection/socket_reader.rs`), so once this stream has the bus's report, - // `responses` holds the `Response` sent before it. - let gone_rule = zbus::MatchRule::builder() - .msg_type(zbus::message::Type::Signal) - .sender("org.freedesktop.DBus") - .unwrap() - .member("NameOwnerChanged") - .unwrap() - .arg(0, DESKTOP) - .unwrap() - .build(); - let gone = MessageIterator::for_match_rule(gone_rule, &client, None).unwrap(); - let path = "/org/freedesktop/portal/desktop/request/test/t1"; - if answered { - let results = HashMap::::new(); - portal.emit_signal(None::<&str>, path, "org.freedesktop.portal.Request", "Response", &(0_u32, results)).unwrap(); - } - portal.close().unwrap(); - // On a thread of its own, so a report that never comes fails the test instead of - // hanging it. - let (seen, report) = std::sync::mpsc::channel(); - let left = unique.clone(); - std::thread::spawn(move || { - let mut gone = gone; - let _ = seen.send(gone.any(|m| m.is_ok_and(|m| owner_disappeared(&m, &left).unwrap_or(false)))); - }); - assert_eq!(report.recv_timeout(std::time::Duration::from_secs(30)), Ok(true), "the bus did not report the portal gone"); - // The call's reply as `wait` reads it: the request path, from the portal's connection. - let call = zbus::Message::signal("/", "org.example.Test", "Reply") - .unwrap() - .sender(unique.as_str()) - .unwrap() - .build(&OwnedObjectPath::try_from(path).unwrap()) - .unwrap(); - let waited = responses.wait(&call); - assert_eq!(waited.is_ok(), answered, "{waited:?}"); - } - } -} - -/// The private session bus that the D-Bus tests of the portal requests run on. -#[cfg(test)] -pub(crate) mod test_bus { - /// A session bus of its own (`dbus-daemon`), `None` when there is none to run. - pub(crate) fn private_bus() -> Option<(Daemon, String)> { - use std::io::BufRead as _; - let spawning = crate::spawning(); - let daemon = std::process::Command::new("dbus-daemon") - .args(["--session", "--nofork", "--print-address=1"]) - .stdout(std::process::Stdio::piped()) - .spawn(); - drop(spawning); - let Ok(daemon) = daemon else { - eprintln!("no dbus-daemon: skipped"); - return None; - }; - let mut daemon = Daemon(daemon); - let mut address = String::new(); - std::io::BufReader::new(daemon.0.stdout.take().unwrap()).read_line(&mut address).unwrap(); - Some((daemon, address.trim().to_string())) - } - - /// Stops the private bus when the test ends, unwinding included. - pub(crate) struct Daemon(std::process::Child); - - impl Drop for Daemon { - fn drop(&mut self) { - let _ = self.0.kill(); - let _ = self.0.wait(); - } - } -} diff --git a/apps/vectorcraft/src/portal_save.rs b/apps/vectorcraft/src/portal_save.rs deleted file mode 100644 index 65970c87f7..0000000000 --- a/apps/vectorcraft/src/portal_save.rs +++ /dev/null @@ -1,658 +0,0 @@ -//! Linux and the BSDs: the save dialog of a save with two or more file types (Save, Save As, Save a -//! Copy, Save as Template; #2679), asked of the XDG desktop portal here -//! (). -//! rfd 0.17 sends no `current_filter` with `SaveFile` and reads only `uris` from the answer -//! (PolyMeilex/rfd#341), and the GTK file chooser behind the portal keeps the typed name when the -//! user picks another file type, so the type picked was lost. This call sends the first file type as -//! `current_filter`, reads the one picked back, and answers its first extension after the path -//! ([`vectorcraft_ui_egui::picks::PickAnswer`]); the app gives the name that type's extension. -//! rfd shows the dialog when the portal can't (no session bus, no file chooser), with zenity as its -//! own fallback. PhotoCraft's `portal_save.rs` (storytold/photocraft#6151) makes the same call. -//! rfd also shows the dialog when the portal leaves the bus before it answers. -//! -//! The dialog's parent is the window: `x11:` on X11, and on Wayland (Linux) a handle -//! from the compositor's xdg-foreign protocol, as rfd names it (its `window_identifier`). - -use std::collections::HashMap; - -use vectorcraft_ui_egui::FilePick; -use zbus::zvariant::{OwnedValue, Value}; - -/// A file type in the dialog: its label and its extensions without the dot. -type Filter = (String, Vec); - -/// A save dialog to show. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -struct SaveRequest { - /// The portal's identifier of the parent window, or empty. - parent: String, - /// The suggested name; empty for none. - name: String, - folder: Option, - /// The file types, labeled in the interface's language; the dialog starts on the first. - filters: Vec, -} - -impl SaveRequest { - /// The dialog for `pick` over the window `parent` names. - fn new(pick: &FilePick, parent: String) -> Self { - let lang = vectorcraft_ui_egui::i18n::current(); - let filters = pick - .filters - .iter() - .map(|(label, exts)| { - (vectorcraft_ui_egui::i18n::tr_ctx(lang, "file-filter", label).to_string(), exts.iter().map(|e| e.to_string()).collect()) - }) - .collect(); - Self { parent, name: pick.name.clone(), folder: pick.folder.clone(), filters } - } -} - -/// What the dialog answered: the path, as typed, and the label of the file type picked. -#[derive(Clone, Debug, PartialEq, Eq)] -struct Saved { - path: String, - filter: Option, -} - -/// `filter` as the portal takes it: its label and a `*.ext` pattern for each extension (`*` for -/// every file), as rfd sends them. -fn wire(filter: &Filter) -> (String, Vec<(u32, String)>) { - let globs = filter.1.iter().map(|e| (0, if e.is_empty() || e == "*" { "*".to_string() } else { format!("*.{e}") })).collect(); - (filter.0.clone(), globs) -} - -/// The `SaveFile` options for `request`, answering on `token`. -fn options<'a>(request: &'a SaveRequest, token: &'a str) -> HashMap<&'static str, Value<'a>> { - let mut o = HashMap::from([("handle_token", Value::from(token))]); - if !request.name.is_empty() { - o.insert("current_name", Value::from(request.name.as_str())); - } - if let Some(folder) = &request.folder { - // A byte string ending in NUL, as the portal specifies. - let mut bytes = folder.as_bytes().to_vec(); - bytes.push(0); - o.insert("current_folder", Value::from(bytes)); - } - if let Some(first) = request.filters.first() { - o.insert("filters", Value::from(request.filters.iter().map(wire).collect::>())); - o.insert("current_filter", Value::from(wire(first))); - } - o -} - -/// The portal's `Response`: code 0 with the first of its `uris` and the label of its -/// `current_filter`. Any other code ends the dialog without a file (1 is Cancel, 2 a dialog closed -/// some other way), as rfd reads it. -fn answer(code: u32, results: &HashMap) -> Result, String> { - if code != 0 { - return Ok(None); - } - let uris: Vec = results - .get("uris") - .ok_or("no file in the portal's answer")? - .try_clone() - .map_err(|e| e.to_string())? - .try_into() - .map_err(|e: zbus::zvariant::Error| e.to_string())?; - let uri = uris.first().ok_or("no file in the portal's answer")?; - let path = file_uri_path(uri).ok_or_else(|| format!("not a local file: {uri}"))?; - // A name that isn't UTF-8 can't be written as picked: replacing its bytes would save over (and - // ask to replace) another file. The dialog ends without a file instead. - let Ok(path) = String::from_utf8(path) else { - log::warn!("the portal's save dialog picked a file name that isn't UTF-8: nothing is saved"); - return Ok(None); - }; - let filter = results.get("current_filter").and_then(|v| filter_label(v)); - Ok(Some(Saved { path, filter })) -} - -/// The label of a file type as the portal sends it, a `(sa(us))` structure; `None` for a value of -/// another shape. -fn filter_label(value: &Value<'_>) -> Option { - match value { - Value::Structure(s) => match s.fields() { - [Value::Str(label), Value::Array(globs)] if globs.element_signature() == "(us)" => Some(label.to_string()), - _ => None, - }, - _ => None, - } -} - -/// `file:///home/me/A%20b.svg` → `/home/me/A b.svg` (its bytes); `None` for a file elsewhere -/// (`file://host/`) or another scheme. -fn file_uri_path(uri: &str) -> Option> { - let rest = uri.strip_prefix("file://")?; - let rest = rest.strip_prefix("localhost").unwrap_or(rest); - if !rest.starts_with('/') { - return None; - } - let mut out = Vec::with_capacity(rest.len()); - let mut rest = rest.as_bytes(); - while let Some((&b, tail)) = rest.split_first() { - let hex = tail.get(..2).filter(|h| b == b'%' && h.iter().all(u8::is_ascii_hexdigit)); - match hex.and_then(|h| std::str::from_utf8(h).ok()).and_then(|h| u8::from_str_radix(h, 16).ok()) { - Some(decoded) => { - out.push(decoded); - rest = tail.get(2..).unwrap_or_default(); - } - None => { - out.push(b); - rest = tail; - } - } - } - Some(out) -} - -/// `saved` as the answer of the save dialog for `request`: the path, then the first extension of -/// the file type picked, found by its label. Empty when the dialog was canceled. -fn pick_answer(saved: Option, request: &SaveRequest) -> Vec { - let Some(saved) = saved else { return Vec::new() }; - let picked = saved.filter.and_then(|label| request.filters.iter().find(|(l, _)| *l == label)).and_then(|(_, exts)| exts.first().cloned()); - std::iter::once(saved.path).chain(picked).collect() -} - -/// The portal's identifier of an X11 window. -fn x11_parent(window: impl std::fmt::LowerHex) -> String { - format!("x11:{window:x}") -} - -/// Show the portal's save dialog for `pick` over `window` and wait for it → the answer (see the -/// module's comment). `None` when `pick` offers fewer than two file types, or the portal couldn't -/// show the dialog; rfd shows it then. -#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] -pub fn pick(pick: &FilePick, window: Option<&winit::window::Window>) -> Option> { - if pick.filters.len() < 2 { - return None; - } - // The export stays until the dialog has answered: the handle is valid while it lives. - let (parent, _export) = window.map(parent).unwrap_or_default(); - let request = SaveRequest::new(pick, parent); - let saved = zbus::blocking::Connection::session().map_err(|e| e.to_string()).and_then(|conn| save_file(&conn, &request)); - match saved { - Ok(saved) => Some(pick_answer(saved, &request)), - Err(e) => { - log::info!("the portal's save dialog failed ({e}): rfd shows it"); - None - } - } -} - -/// Ask the portal on `conn` for the save dialog of `request` and wait for its answer. -#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] -fn save_file(conn: &zbus::blocking::Connection, request: &SaveRequest) -> Result, String> { - use std::sync::atomic::{AtomicU32, Ordering}; - - use zbus::blocking::Proxy; - - const DESKTOP: &str = "org.freedesktop.portal.Desktop"; - static NEXT: AtomicU32 = AtomicU32::new(0); - let token = format!("vectorcraft_save_{}_{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)); - // Made before the call: a portal can send its answer before the call returns, and a portal - // that leaves the bus while its dialog is open ends the wait. - let responses = crate::portal_request::Responses::new(conn)?; - let chooser = Proxy::new(conn, DESKTOP, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.FileChooser").map_err(|e| e.to_string())?; - // The title is empty, as rfd sends it for a save. - let call = chooser.call_method("SaveFile", &(request.parent.as_str(), "", options(request, &token))).map_err(|e| e.to_string())?; - let reply = responses.wait(&call)?; - let (code, results): (u32, HashMap) = reply.body().deserialize().map_err(|e| e.to_string())?; - answer(code, &results) -} - -/// The portal's identifier of `window` when it is an X11 window. -#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] -fn x11_window(window: &winit::window::Window) -> Option { - use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle}; - match window.window_handle().ok()?.as_raw() { - RawWindowHandle::Xlib(h) => Some(x11_parent(h.window)), - RawWindowHandle::Xcb(h) => Some(x11_parent(h.window.get())), - _ => None, - } -} - -/// The portal's identifier of `window`, and on Wayland the export that keeps it valid; empty when -/// the window has neither an X11 id nor a Wayland handle. -#[cfg(target_os = "linux")] -fn parent(window: &winit::window::Window) -> (String, Option) { - if let Some(id) = x11_window(window) { - return (id, None); - } - match wayland::export(window) { - Some(export) => (format!("wayland:{}", export.handle), Some(export)), - None => (String::new(), None), - } -} - -/// [`parent`] for another dialog of the portal (the screen color sampler, `linux_screen_color`): -/// the identifier stays valid until the second value is dropped. -#[cfg(target_os = "linux")] -pub(crate) fn exported_parent(window: &winit::window::Window) -> (String, impl Send + 'static) { - parent(window) -} - -/// The portal's identifier of `window`: its X11 id, else empty (no Wayland export is made off -/// Linux). -#[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] -fn parent(window: &winit::window::Window) -> (String, Option<()>) { - (x11_window(window).unwrap_or_default(), None) -} - -/// The Wayland window's handle for the portal: an xdg-foreign v2 export of its surface -/// (), made as rfd's `window_identifier` -/// makes it. -#[cfg(target_os = "linux")] -pub(crate) mod wayland { - use wayland_client::globals::{GlobalListContents, registry_queue_init}; - use wayland_client::protocol::wl_registry::{self, WlRegistry}; - use wayland_client::protocol::wl_surface::WlSurface; - use wayland_client::{Connection, Dispatch, Proxy, QueueHandle}; - use wayland_protocols::xdg::foreign::zv2::client::zxdg_exported_v2::{self, ZxdgExportedV2}; - use wayland_protocols::xdg::foreign::zv2::client::zxdg_exporter_v2::{self, ZxdgExporterV2}; - - /// A window exported for the portal: `handle` names it until this is dropped. - pub struct Export { - pub handle: String, - exported: ZxdgExportedV2, - conn: Connection, - } - - impl Drop for Export { - fn drop(&mut self) { - self.exported.destroy(); - let _ = self.conn.flush(); - } - } - - /// The events the export waits for. - #[derive(Default)] - struct State { - handle: Option, - } - - impl Dispatch for State { - fn event(_: &mut Self, _: &WlRegistry, _: wl_registry::Event, _: &GlobalListContents, _: &Connection, _: &QueueHandle) {} - } - - impl Dispatch for State { - fn event(_: &mut Self, _: &ZxdgExporterV2, _: zxdg_exporter_v2::Event, _: &(), _: &Connection, _: &QueueHandle) {} - } - - impl Dispatch for State { - fn event(state: &mut Self, _: &ZxdgExportedV2, event: zxdg_exported_v2::Event, _: &(), _: &Connection, _: &QueueHandle) { - if let zxdg_exported_v2::Event::Handle { handle } = event { - state.handle = Some(handle); - } - } - } - - /// Export `window`'s surface on the window's own Wayland connection, with an event queue of its - /// own → `None` when the compositor has no xdg-foreign v2 or answers no handle. - pub fn export(window: &winit::window::Window) -> Option { - let (conn, surface) = surface(window)?; - let (globals, mut queue) = registry_queue_init::(&conn).ok()?; - let qh = queue.handle(); - let exporter: ZxdgExporterV2 = globals.bind(&qh, 1..=1, ()).ok()?; - let exported = exporter.export_toplevel(&surface, &qh, ()); - let mut state = State::default(); - let answered = queue.roundtrip(&mut state); - exporter.destroy(); - match (answered, state.handle) { - (Ok(_), Some(handle)) => Some(Export { handle, exported, conn }), - _ => { - exported.destroy(); - let _ = conn.flush(); - log::info!("the compositor gave no xdg-foreign handle: the save dialog has no parent window"); - None - } - } - } - - /// `window`'s Wayland connection and surface, from its raw handles. The caller holds `window` - /// while it uses them (`quit_windows` unmaps the main window's surface through them). - #[allow(unsafe_code)] - pub(crate) fn surface(window: &winit::window::Window) -> Option<(Connection, WlSurface)> { - use wayland_backend::sys::client::{Backend, ObjectId}; - use winit::raw_window_handle::{HasDisplayHandle as _, HasWindowHandle as _, RawDisplayHandle, RawWindowHandle}; - let (RawWindowHandle::Wayland(w), RawDisplayHandle::Wayland(d)) = - (window.window_handle().ok()?.as_raw(), window.display_handle().ok()?.as_raw()) - else { - return None; - }; - // SAFETY: the display is winit's open `wl_display`, which outlives `window` (the caller - // holds it while it uses the connection, and the export holds it until it is dropped); a - // backend made from a foreign display does not close it when dropped. - let backend = unsafe { Backend::from_foreign_display(d.display.as_ptr().cast()) }; - let conn = Connection::from_backend(backend); - // SAFETY: the pointer is the window's live `wl_surface` proxy on that display. - let id = unsafe { ObjectId::from_ptr(WlSurface::interface(), w.surface.as_ptr().cast()) }.ok()?; - let surface = WlSurface::from_id(&conn, id).ok()?; - Some((conn, surface)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn request() -> SaveRequest { - let pick = FilePick { - name: "Untitled-1.vectorcraft".into(), - folder: Some("/home/me/Art".into()), - filters: vec![ - FilePick::filter("VectorCraft", &["vectorcraft"]), - FilePick::filter("SVG", &["svg"]), - FilePick::filter("PDF-compatible .ai", &["ai"]), - ], - }; - SaveRequest::new(&pick, "x11:3a0000f".into()) - } - - /// The dialog starts on the first file type (the document's format) and shows the suggested - /// name in its folder. - #[test] - fn the_request_names_the_file_type_the_dialog_starts_on() { - let request = request(); - let o = options(&request, "t1"); - assert_eq!(o.get("current_filter"), Some(&Value::from(("VectorCraft".to_string(), vec![(0u32, "*.vectorcraft".to_string())])))); - let filters = vec![ - ("VectorCraft".to_string(), vec![(0u32, "*.vectorcraft".to_string())]), - ("SVG".to_string(), vec![(0u32, "*.svg".to_string())]), - ("PDF-compatible .ai".to_string(), vec![(0u32, "*.ai".to_string())]), - ]; - assert_eq!(o.get("filters"), Some(&Value::from(filters))); - assert_eq!(o.get("current_name"), Some(&Value::from("Untitled-1.vectorcraft"))); - assert_eq!(o.get("current_folder"), Some(&Value::from(b"/home/me/Art\0".to_vec()))); - assert_eq!(o.get("handle_token"), Some(&Value::from("t1"))); - let bare = SaveRequest { name: String::new(), folder: None, filters: Vec::new(), ..request }; - let o = options(&bare, "t2"); - assert_eq!(o.keys().copied().collect::>(), ["handle_token"]); - } - - /// The portal's answer as a D-Bus dictionary: `uris` and `current_filter`. - fn results(uri: &str, filter: Option<&str>) -> HashMap { - let mut r = HashMap::new(); - r.insert("uris".to_string(), OwnedValue::try_from(Value::from(vec![uri.to_string()])).unwrap()); - if let Some(label) = filter { - let picked = Value::from((label.to_string(), vec![(0u32, "*.ai".to_string())])); - r.insert("current_filter".to_string(), OwnedValue::try_from(picked).unwrap()); - } - r - } - - /// The file type picked comes back with the path as typed, and its first extension follows - /// the path in the answer. - #[test] - fn the_answer_carries_the_file_type_picked() { - let request = request(); - let saved = answer(0, &results("file:///home/me/Art/poster", Some("PDF-compatible .ai"))).unwrap(); - assert_eq!(saved, Some(Saved { path: "/home/me/Art/poster".into(), filter: Some("PDF-compatible .ai".into()) })); - assert_eq!(pick_answer(saved, &request), ["/home/me/Art/poster", "ai"]); - // A portal that names no file type, or one the dialog did not offer: the path alone. - let saved = answer(0, &results("file:///home/me/Art/poster.svg", None)).unwrap(); - assert_eq!(pick_answer(saved, &request), ["/home/me/Art/poster.svg"]); - let saved = answer(0, &results("file:///home/me/Art/poster", Some("PNG"))).unwrap(); - assert_eq!(pick_answer(saved, &request), ["/home/me/Art/poster"]); - } - - /// A `current_filter` of another shape than `(sa(us))` (a structure with fewer, other or more - /// fields, a string) gives the path alone; `uris` of another shape is an error. - #[test] - fn an_answer_of_another_shape_is_not_read() { - let malformed = [ - Value::from(("SVG".to_string(),)), - Value::from(("SVG".to_string(), vec![(0u32,)])), - Value::from(("SVG".to_string(), vec![("*.svg".to_string(), 0u32)])), - Value::from((1u32, vec![(0u32, "*.svg".to_string())])), - Value::from(("SVG".to_string(), vec![(0u32, "*.svg".to_string())], 1u32)), - Value::from("SVG"), - ]; - for filter in malformed { - let mut r = results("file:///tmp/card", None); - r.insert("current_filter".to_string(), OwnedValue::try_from(filter).unwrap()); - assert_eq!(answer(0, &r), Ok(Some(Saved { path: "/tmp/card".into(), filter: None }))); - } - let malformed = [ - Value::from(vec![1u32]), - Value::from(vec![("file:///tmp/card".to_string(),)]), - Value::from(Vec::::new()), - Value::from("file:///tmp/card"), - ]; - for uris in malformed { - let mut r = HashMap::new(); - r.insert("uris".to_string(), OwnedValue::try_from(uris).unwrap()); - assert!(answer(0, &r).is_err()); - } - } - - /// Cancel (1) and a dialog closed another way (2) answer no file; an answer without a local file - /// is an error, and rfd shows the dialog instead. - #[test] - fn a_canceled_dialog_answers_no_file() { - let request = request(); - for code in [1, 2] { - assert_eq!(answer(code, &HashMap::new()), Ok(None)); - assert!(pick_answer(None, &request).is_empty()); - } - assert!(answer(0, &HashMap::new()).is_err()); - assert!(answer(0, &results("sftp://host/poster.svg", Some("SVG"))).is_err()); - } - - #[test] - fn file_uris_become_local_paths() { - let file_uri_path = |uri: &str| super::file_uri_path(uri).map(|b| String::from_utf8(b).unwrap()); - assert_eq!(file_uri_path("file:///home/me/Untitled-1.vectorcraft").as_deref(), Some("/home/me/Untitled-1.vectorcraft")); - assert_eq!(file_uri_path("file:///home/me/A%20b%C3%A9.svg").as_deref(), Some("/home/me/A bé.svg")); - assert_eq!(file_uri_path("file://localhost/tmp/x.pdf").as_deref(), Some("/tmp/x.pdf")); - // A `%` without two hex digits after it stays as it is. - assert_eq!(file_uri_path("file:///tmp/100%+1%2").as_deref(), Some("/tmp/100%+1%2")); - assert_eq!(file_uri_path("file://host/x.svg"), None); - assert_eq!(file_uri_path("sftp://host/x.svg"), None); - // Not UTF-8: the bytes as they are, which `answer` refuses rather than changing them. - assert_eq!(super::file_uri_path("file:///tmp/a%FF.svg"), Some(b"/tmp/a\xff.svg".to_vec())); - assert!(matches!(answer(0, &results("file:///tmp/a%FF.svg", None)), Ok(None))); - } - - #[test] - fn x11_windows_are_named_by_their_id() { - assert_eq!(x11_parent(0x3a0000f), "x11:3a0000f"); - } - - /// What the mock portal answers to each `SaveFile` call: the response code, and the file and - /// the label of the file type "picked". - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] - type Script = Vec<(u32, Option<(&'static str, &'static str)>)>; - - /// What each `SaveFile` call carried: `current_name` and the label of `current_filter`. - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] - type Seen = std::sync::Arc, Option)>>>; - - /// How the mock portal answers `SaveFile`. - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] - #[derive(Clone, Copy, PartialEq, Eq)] - enum Portal { - /// On the request path that `handle_token` names, after its reply. - Current, - /// As a portal older than 0.9: on a request path of its own, 300 ms after its reply, as a - /// person answers the dialog. - Old, - /// As `Old`, with the `Response` sent before the reply that names its path. - OldEarly, - /// As `Current`, but it leaves the bus 300 ms after its reply without a `Response`, as a - /// portal that exits while its dialog is open. - Exits, - /// Leaves the bus right after its reply, without a `Response`. - ExitsAtOnce, - /// Sends its `Response` right after its reply, then leaves the bus. - AnswersAndExits, - } - - /// A session bus of its own (`dbus-daemon`) with a mock `org.freedesktop.portal.FileChooser` - /// that answers `SaveFile` from `script` as `portal` says, as PhotoCraft's portal tests run it. - /// `None` when there is no `dbus-daemon` to run. - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] - fn mock_portal(script: Script, portal: Portal) -> Option<(zbus::blocking::Connection, Seen, crate::portal_request::test_bus::Daemon)> { - use zbus::zvariant::OwnedObjectPath; - let (daemon, address) = crate::portal_request::test_bus::private_bus()?; - let server = - zbus::blocking::connection::Builder::address(address.as_str()).ok()?.name("org.freedesktop.portal.Desktop").ok()?.build().ok()?; - let seen = Seen::default(); - let log = seen.clone(); - // Made before the client exists: the connection drops a call that comes while no stream - // reads it. - let incoming = zbus::blocking::MessageIterator::from(&server); - std::thread::spawn(move || { - let mut script = script.into_iter(); - for msg in incoming { - let Ok(msg) = msg else { break }; - let header = msg.header(); - if header.message_type() != zbus::message::Type::MethodCall || header.member().map(|m| m.as_str()) != Some("SaveFile") { - continue; - } - let Ok((_parent, _title, options)) = msg.body().deserialize::<(String, String, HashMap)>() else { break }; - let text = |key: &str| options.get(key).and_then(|v| String::try_from(v.try_clone().ok()?).ok()); - let filter = options.get("current_filter").and_then(|v| filter_label(v)); - let calls = log.lock().map(|mut l| { - l.push((text("current_name"), filter)); - l.len() - }); - let Some(sender) = header.sender().map(|s| s.as_str().trim_start_matches(':').replace('.', "_")) else { break }; - let token = match portal { - Portal::Old | Portal::OldEarly => format!("old{}", calls.unwrap_or_default()), - Portal::Current | Portal::Exits | Portal::ExitsAtOnce | Portal::AnswersAndExits => text("handle_token").unwrap_or_default(), - }; - let path = format!("/org/freedesktop/portal/desktop/request/{sender}/{token}"); - let Ok(handle) = OwnedObjectPath::try_from(path.as_str()) else { break }; - let (code, pick) = script.next().unwrap_or((2, None)); - let mut results: HashMap<&str, Value<'_>> = HashMap::new(); - if let Some((uri, label)) = pick { - results.insert("uris", Value::from(vec![uri.to_string()])); - results.insert("current_filter", Value::from((label.to_string(), vec![(0u32, "*.x".to_string())]))); - } - let to = header.sender().cloned().map(zbus::names::BusName::from); - let respond = || server.emit_signal(to.clone(), path.as_str(), "org.freedesktop.portal.Request", "Response", &(code, &results)); - if portal == Portal::OldEarly && respond().is_err() { - break; - } - if server.reply(&header, &handle).is_err() { - break; - } - if matches!(portal, Portal::Old | Portal::Exits) { - // As a person answers the dialog: after the caller has the path returned. - std::thread::sleep(std::time::Duration::from_millis(300)); - } - if matches!(portal, Portal::Exits | Portal::ExitsAtOnce) { - break; - } - if portal != Portal::OldEarly && respond().is_err() { - break; - } - if portal == Portal::AnswersAndExits { - break; - } - } - // The portal leaves the bus: the bus sends `NameOwnerChanged` for its name. - let _ = server.close(); - }); - let client = zbus::blocking::connection::Builder::address(address.as_str()).ok()?.build().ok()?; - Some((client, seen, daemon)) - } - - /// [`save_file`] on `conn`, given 30 seconds to answer: an answer that is never awaited fails - /// the test instead of leaving it waiting. - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] - fn save_within(conn: &zbus::blocking::Connection, request: &SaveRequest) -> Result, String> { - let (tx, rx) = std::sync::mpsc::channel(); - let (conn, request) = (conn.clone(), request.clone()); - std::thread::spawn(move || { - let _ = tx.send(save_file(&conn, &request)); - }); - rx.recv_timeout(std::time::Duration::from_secs(30)).expect("the portal's answer was not awaited within 30 seconds") - } - - /// Through a real D-Bus: the call starts the dialog on the first file type with the suggested - /// name, and the answer names the file and the type picked; Cancel answers no file. - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] - #[test] - fn the_portal_is_asked_on_the_first_file_type_and_answers_the_one_picked() { - let script = vec![(0, Some(("file:///home/me/Art/poster", "PDF-compatible .ai"))), (1, None)]; - let Some((conn, seen, _daemon)) = mock_portal(script, Portal::Current) else { - eprintln!("no dbus-daemon: skipped"); - return; - }; - let request = request(); - let saved = save_within(&conn, &request).unwrap(); - assert_eq!(pick_answer(saved, &request), ["/home/me/Art/poster", "ai"]); - assert_eq!(save_within(&conn, &request), Ok(None)); - let seen = seen.lock().map(|s| s.clone()).unwrap_or_default(); - assert_eq!(seen.first(), Some(&(Some("Untitled-1.vectorcraft".to_string()), Some(request.filters[0].0.clone())))); - } - - /// A portal older than 0.9 answers on the request path it returns, and the answer is awaited - /// there. - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] - #[test] - fn the_answer_is_awaited_on_the_path_the_portal_returns() { - let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::Old) else { - eprintln!("no dbus-daemon: skipped"); - return; - }; - let request = request(); - assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]); - } - - /// A portal older than 0.9 can answer before its reply names the request path: the answer is - /// kept until the path is known, and the next dialog does not take it. - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] - #[test] - fn an_answer_that_comes_before_the_path_is_kept() { - let script = vec![(0, Some(("file:///tmp/card", "SVG"))), (1, None)]; - let Some((conn, _seen, _daemon)) = mock_portal(script, Portal::OldEarly) else { - eprintln!("no dbus-daemon: skipped"); - return; - }; - let request = request(); - assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]); - assert_eq!(save_within(&conn, &request), Ok(None)); - } - - /// A portal that leaves the bus after its reply without answering, while its dialog is open or - /// at once, ends the wait with an error, and rfd shows the dialog. - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] - #[test] - fn a_portal_that_exits_during_the_dialog_ends_the_wait() { - for portal in [Portal::Exits, Portal::ExitsAtOnce] { - let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], portal) else { - eprintln!("no dbus-daemon: skipped"); - return; - }; - assert_eq!(save_within(&conn, &request()), Err("the desktop portal disappeared while waiting for its answer".to_string())); - } - } - - /// A portal that answers and then leaves the bus: the save reads the answer. Whether the answer - /// or the bus's report comes first depends on timing here; `portal_request`'s - /// `a_queued_answer_wins_over_the_portal_leaving` queues both before the wait. - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] - #[test] - fn an_answer_sent_just_before_the_portal_exits_is_kept() { - let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::AnswersAndExits) else { - eprintln!("no dbus-daemon: skipped"); - return; - }; - let request = request(); - assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]); - } - - /// The labels go to the dialog in the interface's language, which is how the answer is matched. - #[test] - fn the_file_types_are_labeled_as_the_other_dialogs_label_them() { - let request = request(); - let labels: Vec<&str> = request.filters.iter().map(|(l, _)| l.as_str()).collect(); - let lang = vectorcraft_ui_egui::i18n::current(); - let expected: Vec<&str> = - ["VectorCraft", "SVG", "PDF-compatible .ai"].iter().map(|l| vectorcraft_ui_egui::i18n::tr_ctx(lang, "file-filter", l)).collect(); - assert_eq!(labels, expected); - assert_eq!(request.parent, "x11:3a0000f"); - } -} diff --git a/apps/vectorcraft/src/prefs.rs b/apps/vectorcraft/src/prefs.rs index c57ab6b582..09c57f22e4 100644 --- a/apps/vectorcraft/src/prefs.rs +++ b/apps/vectorcraft/src/prefs.rs @@ -1,20 +1,26 @@ -use super::{VectorcraftApp, fileio, prefs_dir}; +//! The preferences file: opened before the window, sampled while the app runs and saved on exit. -/// Where UI preferences live: ~/Library/Application Support/VectorCraft (macOS), -/// %APPDATA%\VectorCraft (Windows), $XDG_CONFIG_HOME or ~/.config/vectorcraft (Linux). -pub(crate) fn prefs_path() -> Option { - prefs_dir::prefs_path_for("VectorCraft", "vectorcraft") -} +use std::path::PathBuf; +use std::sync::{Mutex, PoisonError}; +use std::time::{Duration, Instant}; -/// The same place under the project's former name (DrawCraft): read once if there are no -/// VectorCraft preferences yet, so settings survive the rename. -fn legacy_prefs_path() -> Option { - prefs_dir::prefs_path_for("DrawCraft", "drawcraft") +use craft::settings::{LegacyFile, LoadReport, Location, OpenOptions, SettingsStore, SharedSettings}; +use vectorcraft_ui_egui::{AppSettings, from_app, parse_legacy}; + +use super::{VectorcraftApp, prefs_dir}; + +/// The file the settings were kept in before `config.toml`. +const LEGACY_FILE: &str = "ui.json"; + +/// The DrawCraft folder (the project's former name), read once if there are no VectorCraft +/// preferences yet, so settings survive the rename. +fn legacy_dir() -> Option { + prefs_dir::profile::prefs_dir(true) } /// Where the log files live: `logs` in the preferences folder (see `logging`). -pub(crate) fn log_dir() -> Option { - Some(prefs_path()?.parent()?.join("logs")) +pub(crate) fn log_dir() -> Option { + Some(prefs_dir::prefs_dir()?.join("logs")) } /// Runs without preferences (`VECTORCRAFT_NO_PREFS`, agents' test runs) neither read nor write them. @@ -22,503 +28,164 @@ pub(crate) fn prefs_enabled() -> bool { std::env::var_os("VECTORCRAFT_NO_PREFS").is_none() } -/// The saved UI preferences, read before the window opens (they hold its size and position). -/// A file read only in part, or with layouts converted from an older version, is copied beside -/// itself before anything saves over it. -pub(crate) fn read_prefs() -> Option { - if !prefs_enabled() { - return None; - } - if let Some(p) = prefs_path() - && let Ok(bytes) = std::fs::read(&p) - { - let read = vectorcraft_ui_egui::UiState::read_preferences(&bytes); - if read.as_ref().is_none_or(|read| !read.intact) { - keep_prefs_copy(&p, &bytes, "ui.unreadable"); +/// The saved preferences, opened before the window (they hold its size and position). The folder is +/// `profile.rs`'s; the old `ui.json` files are read once when there is no `config.toml` yet. A run +/// without preferences keeps them in memory. +pub(crate) fn open_store() -> (SharedSettings, LoadReport) { + let (location, legacy) = match prefs_dir::prefs_dir().filter(|_| prefs_enabled()) { + Some(dir) => { + let file = |dir: PathBuf| LegacyFile { path: dir.join(LEGACY_FILE), parse: parse_legacy }; + let legacy = std::iter::once(file(dir.clone())).chain(legacy_dir().map(file)).collect(); + (Location::Dir(dir), legacy) } - if read.as_ref().is_some_and(|read| read.converted) { - keep_prefs_copy(&p, &bytes, "ui.before-layout-migration"); - } - return read.map(|read| read.ui); - } - let bytes = legacy_prefs_path().and_then(|p| std::fs::read(p).ok())?; - decode_saved_prefs(&bytes) + None => (Location::Memory, Vec::new()), + }; + let (store, report) = SettingsStore::open_with(OpenOptions::new(location).legacy(legacy)); + (SharedSettings::new(store), report) } -/// Saved preferences, with what this version cannot read of their docking data dropped and -/// older layouts converted (`vectorcraft_ui_egui::layout_migration`). -pub(crate) fn decode_saved_prefs(bytes: &[u8]) -> Option { - vectorcraft_ui_egui::UiState::read_preferences(bytes).map(|read| read.ui) -} - -/// Set when `ui.json` needed a copy kept ([`keep_prefs_copy`]) and none could be: the file is -/// then left as it is rather than overwritten. -pub(crate) static KEEP_UI_PREFS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - -/// Copy `ui.json` beside it as `.json` or the first free `-N.json`, before the next -/// save replaces it: `ui.unreadable` when it could not be read in full (a newer VectorCraft may -/// have written it), `ui.before-layout-migration` when its layouts were converted. -pub(crate) fn keep_prefs_copy(path: &std::path::Path, bytes: &[u8], stem: &str) { - use std::io::Write as _; - for n in 1..100u32 { - let name = if n == 1 { format!("{stem}.json") } else { format!("{stem}-{n}.json") }; - let mut options = std::fs::OpenOptions::new(); - options.write(true).create_new(true); - // The preferences hold recent document paths: the copy is owner-only, whatever the umask. - #[cfg(unix)] - std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); - match options.open(path.with_file_name(name)) { - Ok(mut file) => { - if file.write_all(bytes).is_ok() { - return; - } - break; - } - Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} - Err(_) => break, - } - } - KEEP_UI_PREFS.store(true, std::sync::atomic::Ordering::Relaxed); -} - -pub(crate) fn load_prefs(app: &mut VectorcraftApp, saved: Option) { +pub(crate) fn load_prefs(app: &mut VectorcraftApp, store: &SharedSettings) { if !prefs_enabled() { return; } - if let Some(ui) = saved { - app.ui = ui.sanitized(); - } + let ui = store.lock().get().ui.clone(); + app.ui = ui.sanitized(); vectorcraft_ui_egui::prefs_dialog::restore(app); - // What this window started from: only what changes after it is this window's to save. - set_saved_base(prefs_value(app).ok()); } -/// Save what this window changed since it last read or saved the preferences, merged into the -/// file as it is now ([`merge_changes`]): another VectorCraft window open at the same time, which -/// read the file before this one saved, then keeps this window's changes when it saves or quits -/// (#4625). Nothing is written when nothing changed. -pub(crate) fn save_prefs(app: &VectorcraftApp) { - if !prefs_enabled() || KEEP_UI_PREFS.load(std::sync::atomic::Ordering::Relaxed) { +/// How often [`save_tick`] samples the UI state for changes. +const SAVE_EVERY: Duration = Duration::from_secs(2); + +/// Once per frame: hand the store the current settings when a preference was confirmed (#1747) or +/// every [`SAVE_EVERY`] (the workspace, panels, toolbars and the other UI settings change without +/// the dialog, #4625), then let the store write what it holds. The store decides when to write and +/// merges another window's changes; a sample equal to what it holds saves nothing. +pub(crate) fn save_tick(app: &mut VectorcraftApp, store: &SharedSettings, now: Instant) { + static LAST: Mutex> = Mutex::new(None); + let confirmed = app.take_prefs_changed(); + let sample = { + let mut last = LAST.lock().unwrap_or_else(PoisonError::into_inner); + let sample = confirmed || last.is_none_or(|t| now.duration_since(t) >= SAVE_EVERY); + if sample { + *last = Some(now); + } + sample + }; + let mut store = store.lock(); + if sample && store.is_persistent() { + store.set(from_app(app)); + } + store.tick(now); +} + +/// On exit: save the app's last state, with what changed since the last sample. +pub(crate) fn flush(app: &VectorcraftApp, store: &SharedSettings) { + let mut store = store.lock(); + if !store.is_persistent() { return; } - let Some(p) = prefs_path() else { return }; - let Ok(mine) = prefs_value(app) else { return }; - let base = saved_base(); - if base.as_ref().is_some_and(|b| same_lasting(b, &mine)) { - return; + store.set(from_app(app)); + // Preferences are best effort: a failed write is logged, never fatal at exit. + if let Err(e) = store.flush() { + log::warn!("the preferences were not saved: {e}"); } - // The file as another window may have saved it since (none, or unreadable: this one's own). - let on_disk = std::fs::read(&p).ok().and_then(|b| serde_json::from_slice::(&b).ok()); - let merged = match (base.as_ref(), on_disk) { - (Some(base), Some(on_disk)) => merge_changes(base, &mine, on_disk), - _ => mine.clone(), - }; - let _ = std::fs::create_dir_all(p.parent().unwrap_or(std::path::Path::new("."))); - let Ok(bytes) = serde_json::to_vec_pretty(&merged) else { return }; - // Preferences are best effort: a failed write keeps the previous file, and the changes are - // tried again on the next save. - if fileio::write_atomic(&p, &bytes).is_ok() { - set_saved_base(Some(mine)); - } -} - -/// How often [`save_prefs_soon`] looks for changes to save. -const SAVE_EVERY: std::time::Duration = std::time::Duration::from_secs(2); - -/// Save the preferences at most every [`SAVE_EVERY`] while the app runs, when something changed: -/// the workspace, panels, toolbars and the other UI settings kept only in the UI state were saved -/// only on quitting, so a session ended any other way (the window closed by the system, the -/// process ended or crashing) started the next one from the settings before it (#4625). -pub(crate) fn save_prefs_soon(app: &VectorcraftApp) { - static LAST: std::sync::Mutex> = std::sync::Mutex::new(None); - let Ok(mut last) = LAST.lock() else { return }; - if last.is_some_and(|t| t.elapsed() < SAVE_EVERY) { - return; - } - *last = Some(std::time::Instant::now()); - drop(last); - save_prefs(app); -} - -/// The preferences as this window last read or saved them (`None`: not read yet). -static SAVED_BASE: std::sync::Mutex> = std::sync::Mutex::new(None); - -fn saved_base() -> Option { - SAVED_BASE.lock().ok().and_then(|b| b.clone()) -} - -fn set_saved_base(value: Option) { - if let Ok(mut b) = SAVED_BASE.lock() { - *b = value; - } -} - -/// Fields of the UI state that a start resets ([`vectorcraft_ui_egui::UiState::sanitized`]): a -/// change to them alone isn't saved, and they are never merged over another window's. -const PASSING: &[&str] = &["status", "dialog", "flyout", "palette_open", "palette_query", "about", "open_panel"]; - -/// Do `a` and `b` hold the same preferences, leaving out what a start resets ([`PASSING`])? -fn same_lasting(a: &serde_json::Value, b: &serde_json::Value) -> bool { - match (a.as_object(), b.as_object()) { - (Some(a), Some(b)) => { - let keys: std::collections::BTreeSet<&String> = a.keys().chain(b.keys()).filter(|k| !PASSING.contains(&k.as_str())).collect(); - keys.into_iter().all(|k| a.get(k) == b.get(k)) - } - _ => a == b, - } -} - -/// Fields that a read fills in from other fields when the file lacks them -/// (`vectorcraft_ui_egui::layout_migration`): `help_bar` follows `status_bar`. A save writes them -/// whenever the file lacks them, so the next read does not fill them in again from a changed field. -const DERIVED: &[&str] = &["help_bar"]; - -/// `on_disk` with what changed from `base` to `mine` put over it: each top-level field of the UI -/// state, and each engine preference (`engine_prefs`) on its own, so two windows that change -/// different settings keep both. A field both changed takes this window's value (it saves last). -fn merge_changes(base: &serde_json::Value, mine: &serde_json::Value, on_disk: serde_json::Value) -> serde_json::Value { - use serde_json::Value; - let (Some(base), Some(mine), Value::Object(mut out)) = (base.as_object(), mine.as_object(), on_disk) else { - return mine.clone(); - }; - // The current Actions set (`action_set`, an index) is this window's when this window chose - // another one or the other window did not; otherwise it is the other window's. - let use_mine = chose_another_action_set(base, mine) || !chose_another_action_set(base, &out); - // The list the saved current set was chosen from. - let chosen_from = if use_mine { mine.get("action_sets").cloned() } else { out.get("action_sets").cloned() }; - let keys: std::collections::BTreeSet<&String> = base.keys().chain(mine.keys()).collect(); - for key in keys { - if PASSING.contains(&key.as_str()) { - if let Some(v) = mine.get(key) { - out.entry(key.clone()).or_insert_with(|| v.clone()); - } - continue; - } - let (was, now) = (base.get(key), mine.get(key)); - if was == now || key == "action_set" { - continue; - } - if key == "engine_prefs" - && let (Some(Value::Object(was)), Some(Value::Object(now)), Some(Value::Object(theirs))) = (was, now, out.get_mut(key)) - { - let names: std::collections::BTreeSet<&String> = was.keys().chain(now.keys()).collect(); - for name in names { - match (was.get(name), now.get(name)) { - (a, b) if a == b => {} - (_, Some(v)) => { - theirs.insert(name.clone(), v.clone()); - } - (_, None) => { - theirs.remove(name); - } - } - } - continue; - } - match now { - Some(v) => { - out.insert(key.clone(), v.clone()); - } - None => { - out.remove(key); - } - } - } - for key in DERIVED { - if !out.contains_key(*key) - && let Some(v) = mine.get(*key) - { - out.insert((*key).to_string(), v.clone()); - } - } - if use_mine { - match mine.get("action_set") { - Some(v) => { - out.insert("action_set".to_string(), v.clone()); - } - None => { - out.remove("action_set"); - } - } - } - keep_current_action_set(&mut out, chosen_from.as_ref()); - Value::Object(out) -} - -/// Point the saved current Actions set (`action_set`) at the same set in the merged -/// `action_sets` when the merge took the index from one window and the list from another -/// ([`find_action_set`]). With no such set, no set is current. -fn keep_current_action_set(out: &mut serde_json::Map, chosen_from: Option<&serde_json::Value>) { - use serde_json::Value; - let Some(i) = out.get("action_set").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()) else { return }; - let merged = out.get("action_sets"); - if merged == chosen_from { - return; - } - match find_action_set(chosen_from, i, merged) { - Some(j) => { - out.insert("action_set".to_string(), Value::from(j)); - } - None => { - out.remove("action_set"); - } - } -} - -/// Was another Actions set made current from `base` to `now`? Recording into the current set, -/// renaming it, deleting it, or deleting a set before it changes the list or the index without -/// choosing another set. -fn chose_another_action_set(base: &serde_json::Map, now: &serde_json::Map) -> bool { - use serde_json::Value; - let index = |v: &serde_json::Map| v.get("action_set").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); - let (was, sets) = (base.get("action_sets"), now.get("action_sets")); - let (Some(i), Some(k)) = (index(base), index(now)) else { - return match (index(base), index(now)) { - (None, None) => false, - // No set is current: another set was chosen only if the current one is still there. - (Some(i), None) => find_action_set(was, i, sets).is_some(), - _ => true, - }; - }; - if was == sets { - return i != k; - } - if let Some(j) = find_action_set(was, i, sets) { - return j != k; - } - // The set at the same place changed while every other set stayed as it was: it was edited. - let edited_in_place = was - .and_then(Value::as_array) - .zip(sets.and_then(Value::as_array)) - .is_some_and(|(was, sets)| was.len() == sets.len() && was.iter().zip(sets).enumerate().all(|(j, (a, b))| j == i || a == b)); - !(i == k && edited_in_place) -} - -/// Where the Actions set at index `i` of `old` is in `new` (two `action_sets` lists): found by -/// its contents when no other set in either list has the same contents, otherwise by its name when -/// no other set in either list has it. -fn find_action_set(old: Option<&serde_json::Value>, i: usize, new: Option<&serde_json::Value>) -> Option { - use serde_json::Value; - let (old, new) = (old?.as_array()?, new?.as_array()?); - let set = old.get(i)?; - let only = |list: &[Value], same: &dyn Fn(&Value) -> bool| { - let mut found = list.iter().enumerate().filter(|(_, s)| same(s)); - match (found.next(), found.next()) { - (Some((j, _)), None) => Some(j), - _ => None, - } - }; - let same_contents = |s: &Value| s == set; - if only(old, &same_contents).is_some() - && let Some(j) = only(new, &same_contents) - { - return Some(j); - } - let name = set.get("name")?; - let same_name = |s: &Value| s.get("name") == Some(name); - only(old, &same_name)?; - only(new, &same_name) -} - -/// The preferences file's contents: the UI state with the engine preferences. -#[cfg(test)] -pub(crate) fn prefs_bytes(app: &VectorcraftApp) -> serde_json::Result> { - serde_json::to_vec_pretty(&prefs_value(app)?) -} - -/// [`prefs_bytes`] as JSON. -fn prefs_value(app: &VectorcraftApp) -> serde_json::Result { - let mut ui = app.ui.clone(); - // An open dialog is never restored, and its fields can hold passwords (PDF import and save). - ui.dialog = None; - ui.engine_prefs = app.session.prefs.to_json(); - serde_json::to_value(&ui) } #[cfg(test)] mod tests { - use serde_json::json; + use std::path::Path; - use super::{merge_changes, same_lasting}; + use super::*; - /// Two windows open at once (#4625): the one that saves last keeps the other's changes and - /// adds its own, instead of putting back the preferences it started from. - #[cfg(unix)] - #[test] - fn a_kept_preferences_copy_is_owner_only() { - use std::os::unix::fs::PermissionsExt as _; - let temp = tempfile::Builder::new().prefix("vc-prefs-copy-").tempdir().unwrap(); - let dir = temp.path(); - super::keep_prefs_copy(&dir.join("ui.json"), b"{}", "ui.unreadable"); - let mode = std::fs::metadata(dir.join("ui.unreadable.json")).unwrap().permissions().mode() & 0o777; - assert_eq!(mode, 0o600); + /// One VectorCraft window: its store over the folder and its app, as loaded from it. + struct Window { + store: SettingsStore, + app: VectorcraftApp, } - #[test] - fn a_window_saves_only_what_it_changed_over_another_windows_save() { - let base = json!({"workspace": "Essentials", "toolbar": true, "engine_prefs": {"uiAccent": "blue", "uiScaling": 1.0}}); - // The other window switched the workspace and the accent, and saved. - let on_disk = json!({"workspace": "Painting", "toolbar": true, "engine_prefs": {"uiAccent": "violet", "uiScaling": 1.0}}); - // This one changed only the UI scaling. - let mine = json!({"workspace": "Essentials", "toolbar": true, "engine_prefs": {"uiAccent": "blue", "uiScaling": 1.25}}); - let merged = merge_changes(&base, &mine, on_disk); - assert_eq!(merged, json!({"workspace": "Painting", "toolbar": true, "engine_prefs": {"uiAccent": "violet", "uiScaling": 1.25}})); + impl Window { + fn open(dir: &Path) -> Self { + let (store, _) = SettingsStore::::open_at(dir); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.ui = store.get().ui.clone(); + Window { store, app } + } + + fn save(&mut self) { + self.store.set(from_app(&self.app)); + self.store.flush().unwrap(); + } + + fn set_sets(&mut self, names: &[&str]) { + self.app.ui.actions = craft::automation::actions::ActionList::new(); + for name in names { + self.app.ui.actions.new_set(name).unwrap(); + } + } } - #[test] - fn a_setting_both_windows_changed_takes_the_last_saved() { - let base = json!({"workspace": "Essentials", "engine_prefs": {"uiAccent": "blue"}}); - let on_disk = json!({"workspace": "Painting", "engine_prefs": {"uiAccent": "violet"}}); - let mine = json!({"workspace": "Typography", "engine_prefs": {"uiAccent": "green"}}); - assert_eq!(merge_changes(&base, &mine, on_disk), json!({"workspace": "Typography", "engine_prefs": {"uiAccent": "green"}})); + fn temp() -> tempfile::TempDir { + tempfile::Builder::new().prefix("vc-prefs-").tempdir().unwrap() } - #[test] - fn fields_added_or_removed_by_this_window_are_saved() { - let base = json!({"docking": {"root": 1}, "engine_prefs": {"old": 1}}); - let on_disk = json!({"docking": {"root": 1}, "recent_files": ["a.svg"], "engine_prefs": {"old": 1}}); - let mine = json!({"dock_width": 300.0, "engine_prefs": {"new": 2}}); - assert_eq!(merge_changes(&base, &mine, on_disk), json!({"dock_width": 300.0, "recent_files": ["a.svg"], "engine_prefs": {"new": 2}})); + fn saved(dir: &Path) -> AppSettings { + SettingsStore::::open_at(dir).0.get().clone() } - /// The status line and open dialogs reset at start: they don't make a save, and they don't - /// replace another window's. + fn set_names(settings: &AppSettings) -> Vec { + settings.ui.actions.sets().into_iter().map(str::to_string).collect() + } + + /// The status line and open palette reset at start: a window that has them up neither saves + /// them nor writes over another window's setting it did not change. #[test] fn what_a_start_resets_is_left_out() { - let base = json!({"status": "", "dialog": null, "workspace": "Essentials"}); - let mine = json!({"status": "Saved", "dialog": {"kind": "preferences"}, "workspace": "Essentials"}); - assert!(same_lasting(&base, &mine)); - let on_disk = json!({"status": "Opened", "dialog": null, "workspace": "Painting"}); - let mine = json!({"status": "Saved", "dialog": {"kind": "preferences"}, "workspace": "Essentials", "toolbar": false}); - let merged = merge_changes(&base, &mine, on_disk); - assert_eq!(merged, json!({"status": "Opened", "dialog": null, "workspace": "Painting", "toolbar": false})); - assert!(!same_lasting(&base, &mine)); + let dir = temp(); + Window::open(dir.path()).save(); + let (mut first, mut second) = (Window::open(dir.path()), Window::open(dir.path())); + second.store.update(|s| s.ui.status_bar = false); + second.store.flush().unwrap(); + first.app.ui.status = "Saved".to_string(); + first.app.ui.palette_query = "find".to_string(); + first.save(); + let back = saved(dir.path()); + assert!(!back.ui.status_bar, "the other window's setting survives"); + assert!(back.ui.status.is_empty() && back.ui.palette_query.is_empty(), "nothing a start resets is written"); } - /// A file from before the Help Bar setting: the read shows the Help Bar with the status bar. - /// After the status bar is hidden and the Help Bar left showing, the save writes `help_bar`, - /// so the next read does not hide it with the status bar. A value on disk is kept. - #[test] - fn a_help_bar_setting_the_file_lacks_is_saved() { - let base = json!({"status_bar": true, "help_bar": true}); - let mine = json!({"status_bar": false, "help_bar": true}); - let on_disk = json!({"status_bar": true}); - assert_eq!(merge_changes(&base, &mine, on_disk), json!({"status_bar": false, "help_bar": true})); - // Another window saved its own Help Bar setting: it stays. - let on_disk = json!({"status_bar": true, "help_bar": false}); - assert_eq!(merge_changes(&base, &mine, on_disk), json!({"status_bar": false, "help_bar": false})); - } - - /// One window deleted the first Actions set and saved; this one made the second set current. - /// The saved index follows that set to its place in the merged list. + /// The current Actions set is saved by name: another window inserting a set before it does not + /// make a different set current. #[test] fn the_current_action_set_follows_its_set_in_the_merged_list() { - let set = |name: &str| json!({"name": name, "actions": []}); - let base = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 0}); - let on_disk = json!({"action_sets": [set("B"), set("C")]}); - let mine = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 1}); - assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("B"), set("C")], "action_set": 0})); - // The other window also recorded into B: B is found by its name. - let on_disk = json!({"action_sets": [{"name": "B", "actions": [{"name": "Action 1", "steps": []}]}, set("C")]}); - let merged = merge_changes(&base, &mine, on_disk); - assert_eq!(merged["action_set"], json!(0)); - // The other window deleted B: no set is current. - let on_disk = json!({"action_sets": [set("A"), set("C")]}); - assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("A"), set("C")]})); + let dir = temp(); + let mut base = Window::open(dir.path()); + base.set_sets(&["A", "B", "C"]); + base.save(); + let (mut chooser, mut inserter) = (Window::open(dir.path()), Window::open(dir.path())); + chooser.app.ui.action_set = Some("C".to_string()); + chooser.save(); + inserter.set_sets(&["Z", "A", "B", "C"]); + inserter.save(); + let back = saved(dir.path()); + assert_eq!(back.ui.action_set.as_deref(), Some("C")); + assert_eq!(set_names(&back), ["Z", "A", "B", "C"]); } - /// This window deleted the first set while the index saved by the other window still stands. + /// The window that did not choose keeps the other's choice, still by name after it deleted the + /// set before it. #[test] fn the_other_windows_current_action_set_follows_its_set() { - let set = |name: &str| json!({"name": name, "actions": []}); - let base = json!({"action_sets": [set("A"), set("B"), set("C")]}); - let on_disk = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 2}); - let mine = json!({"action_sets": [set("B"), set("C")]}); - assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("B"), set("C")], "action_set": 1})); - } - - /// The other window replaced or renamed the set this one made current (the saved sets do not - /// tell the two apart): no set is current. - #[test] - fn a_set_in_the_place_of_the_current_set_is_not_made_current() { - let set = |name: &str| json!({"name": name, "actions": []}); - let base = json!({"action_sets": [set("A"), set("B"), set("C")]}); - let on_disk = json!({"action_sets": [set("A"), set("D"), set("C")]}); - let mine = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 1}); - assert_eq!(merge_changes(&base, &mine, on_disk).get("action_set"), None); - let on_disk = json!({"action_sets": [set("A"), set("C"), set("D")]}); - assert_eq!(merge_changes(&base, &mine, on_disk).get("action_set"), None); - } - - /// This window deleted a set and made the set now at the old index current: its choice is - /// saved, though the index is the same number. - #[test] - fn a_new_current_set_at_the_same_index_is_saved() { - let set = |name: &str| json!({"name": name, "actions": []}); - let base = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 1}); - let on_disk = json!({"action_sets": [{"name": "A", "actions": [{"name": "Action 1", "steps": []}]}, set("B"), set("C")], "action_set": 1}); - let mine = json!({"action_sets": [set("B"), set("C")], "action_set": 1}); - assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("B"), set("C")], "action_set": 1})); - } - - /// Recording into the current set does not choose it again: the other window's choice stays. - #[test] - fn recording_into_the_current_set_keeps_the_other_windows_choice() { - let set = |name: &str| json!({"name": name, "actions": []}); - let recorded = json!({"name": "A", "actions": [{"name": "Action 1", "steps": []}]}); - let base = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 0}); - let on_disk = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 2}); - let mine = json!({"action_sets": [recorded.clone(), set("B"), set("C")], "action_set": 0}); - assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [recorded, set("B"), set("C")], "action_set": 2})); - } - - /// Renaming the current set does not choose it again: the other window's choice stays. With no - /// other choice, the renamed set stays current. - #[test] - fn renaming_the_current_set_keeps_the_other_windows_choice() { - let set = |name: &str| json!({"name": name, "actions": []}); - let base = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 0}); - let on_disk = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 1}); - let mine = json!({"action_sets": [set("A2"), set("B"), set("C")], "action_set": 0}); - assert_eq!(merge_changes(&base, &mine, on_disk)["action_set"], json!(1)); - assert_eq!(merge_changes(&base, &mine, base.clone())["action_set"], json!(0)); - } - - /// Deleting the current set does not override the other window's choice. - #[test] - fn deleting_the_current_set_keeps_the_other_windows_choice() { - let set = |name: &str| json!({"name": name, "actions": []}); - let base = json!({"action_sets": [set("A"), set("B")], "action_set": 0}); - let on_disk = json!({"action_sets": [set("A"), set("B")], "action_set": 1}); - let mine = json!({"action_sets": [set("B")]}); - assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("B")], "action_set": 0})); - assert_eq!(merge_changes(&base, &mine, base.clone()), json!({"action_sets": [set("B")]})); - } - - /// Deleting a set before the current one moves its index without choosing it again. - #[test] - fn deleting_a_set_before_the_current_one_keeps_it_current() { - let set = |name: &str| json!({"name": name, "actions": []}); - let base = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 2}); - let mine = json!({"action_sets": [set("B"), set("C")], "action_set": 1}); - assert_eq!(merge_changes(&base, &mine, base.clone()), json!({"action_sets": [set("B"), set("C")], "action_set": 1})); - } - - /// Two sets with the same contents: when the other window deleted the one this window made - /// current, the one left is not made current in its place. - #[test] - fn a_set_with_the_same_contents_does_not_take_the_place_of_the_current_set() { - let set = |name: &str| json!({"name": name, "actions": []}); - let base = json!({"action_sets": [set("A"), set("A"), set("C")]}); - let on_disk = json!({"action_sets": [set("A"), set("C")]}); - let mine = json!({"action_sets": [set("A"), set("A"), set("C")], "action_set": 1}); - assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("A"), set("C")]})); - } - - #[test] - fn a_file_that_is_not_an_object_is_replaced() { - let base = json!({"workspace": "Essentials"}); - let mine = json!({"workspace": "Painting"}); - assert_eq!(merge_changes(&base, &mine, json!([1, 2])), mine); + let dir = temp(); + let mut base = Window::open(dir.path()); + base.set_sets(&["A", "B", "C"]); + base.save(); + let (mut chooser, mut deleter) = (Window::open(dir.path()), Window::open(dir.path())); + deleter.set_sets(&["B", "C"]); + deleter.save(); + chooser.app.ui.action_set = Some("C".to_string()); + chooser.save(); + let back = saved(dir.path()); + assert_eq!(back.ui.action_set.as_deref(), Some("C")); + assert_eq!(set_names(&back), ["B", "C"]); } } diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 492e2ea7bf..d4dc0e8cb0 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -1,25 +1,25 @@ -//! Where VectorCraft keeps its settings, `ui.json`, and next to it folders of the user's own +//! Where VectorCraft keeps its settings (`config.toml`, see `prefs.rs`), and next to it folders of the user's own //! (Swatches, Graphic Styles, Fonts, Data Recovery, logs). The desktop app and `vectorcraft-cli` //! (which shares this file) read the same Fonts folder. use std::path::PathBuf; +// `prefs.rs` asks it for DrawCraft's folder, which only the app reads. #[path = "profile.rs"] -mod profile; +pub(crate) mod profile; -/// The settings file `ui.json` of the app `name`: in a folder named `name` in ~/Library/Application -/// Support (macOS) or %APPDATA% (Windows), or `lower` in $XDG_CONFIG_HOME or ~/.config (Linux and -/// BSD). -pub fn prefs_path_for(name: &str, lower: &str) -> Option { - let legacy = name == "DrawCraft" || lower == "drawcraft"; - profile::prefs_path(legacy) +/// The settings folder: `VectorCraft` in ~/Library/Application Support (macOS) or %APPDATA% +/// (Windows), or `vectorcraft` in $XDG_CONFIG_HOME or ~/.config (Linux and BSD), unless +/// `profile.rs` chooses another. +pub fn prefs_dir() -> Option { + profile::prefs_dir(false) } /// Have the font scans read VectorCraft's own Fonts folder, next to the settings, which /// `text.addFontFiles` copies font files into. The folder is set whether or not /// `VECTORCRAFT_NO_PREFS` is set, as the Swatches and Graphic Styles folders are. pub fn install_fonts() { - if let Some(dir) = prefs_path_for("VectorCraft", "vectorcraft").and_then(|p| Some(p.parent()?.join("Fonts"))) { + if let Some(dir) = prefs_dir().map(|dir| dir.join("Fonts")) { vectorcraft_text::set_app_font_dir(dir); } } @@ -30,7 +30,7 @@ fn store_dir(name: &str) -> Option { if std::env::var_os("VECTORCRAFT_NO_PREFS").is_some() { return None; } - Some(prefs_path_for("VectorCraft", "vectorcraft")?.parent()?.join(name)) + Some(prefs_dir()?.join(name)) } /// Register the ICC profiles `color.loadProfile` kept in the `Color Profiles` folder (#2174), and @@ -137,7 +137,7 @@ mod tests { #[test] fn the_font_scans_read_the_fonts_folder_next_to_the_settings() { install_fonts(); - let fonts = prefs_path_for("VectorCraft", "vectorcraft").and_then(|p| Some(p.parent()?.join("Fonts"))); + let fonts = prefs_dir().map(|dir| dir.join("Fonts")); assert!(fonts.is_some(), "a home folder to keep the settings in"); assert_eq!(vectorcraft_text::app_font_dir().map(std::path::Path::to_path_buf), fonts); assert!(vectorcraft_text::system_font_dirs().contains(&fonts.unwrap_or_default())); diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index a5d450b854..fb28192f05 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -42,7 +42,7 @@ fn sent(title: &str, printer: Option<&str>, note: &str) -> String { mod system { use super::{Command, PrintJob, Printer}; pub fn printers() -> Vec { - craft_print::printers().into_iter().map(|p| Printer { name: p.name, default: p.default }).collect() + craft::print::printers().into_iter().map(Printer::from).collect() } pub fn print(job: &PrintJob) -> Result { if job.direct_pdf { @@ -50,8 +50,8 @@ mod system { } // Copies, layout, marks and colour management are already in the PDF. Preserve its // physical sheet size and the queue's duplex default without printing copies twice. - let settings = craft_print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() }; - craft_print::submit(job.pdf, &settings).map_err(|e| e.to_string()) + let settings = craft::print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() }; + craft::print::submit(job.pdf, &settings).map_err(|e| e.to_string()) } #[cfg(windows)] pub(crate) fn setup_command(printer: Option<&str>, default_printer: Option<&str>) -> Command { @@ -113,14 +113,6 @@ mod tests { assert_eq!(args, ["printui.dll,PrintUIEntry", "/e", "/n", "Office Laser"]); } - #[test] - fn setup_command_falls_back_to_default_printer() { - let cmd = setup_command(None, Some("Default Proofer")); - assert_eq!(cmd.get_program(), "rundll32.exe"); - let args: Vec<&OsStr> = cmd.get_args().collect(); - assert_eq!(args, ["printui.dll,PrintUIEntry", "/e", "/n", "Default Proofer"]); - } - #[test] fn setup_command_trims_whitespace_and_skips_empty() { let cmd = setup_command(Some(" "), Some("Default Proofer")); @@ -140,19 +132,11 @@ mod tests { #[cfg(test)] mod turn_tests { - use super::{SystemPrint, sent}; - use vectorcraft_ui_egui::print::PrintService; - - #[test] - fn the_sent_status_names_the_job_the_printer_and_the_note() { - assert_eq!(sent("Poster", None, ""), "Sent “Poster” to the default printer"); - assert_eq!(sent("Poster", Some("Office Laser"), ""), "Sent “Poster” to Office Laser"); - assert_eq!(sent("Poster", Some("Office Laser"), "job 12"), "Sent “Poster” to Office Laser. The spooler replied: job 12"); - } + use super::sent; #[test] fn a_printer_name_ending_in_parentheses_stays_whole_in_a_translation() { - use vectorcraft_ui_egui::i18n::{Lang, message}; + use vectorcraft_ui_egui::i18n::{Lang, LangExt, message}; let Some(de) = Lang::from_code("de") else { panic!("no German catalog") }; let printer = Some("HP LaserJet (Copy 1)"); assert_eq!(message(de, &sent("Poster", printer, "")), "“Poster” an HP LaserJet (Copy 1) gesendet"); @@ -161,9 +145,4 @@ mod turn_tests { "“Poster” an HP LaserJet (Copy 1) gesendet. Antwort der Druckwarteschlange: job 12" ); } - - #[test] - fn only_macos_queues_need_landscape_pages_turned() { - assert_eq!(SystemPrint.turns_landscape(), !cfg!(target_os = "macos")); - } } diff --git a/apps/vectorcraft/src/printing/direct_pdf.rs b/apps/vectorcraft/src/printing/direct_pdf.rs index 93e657cce9..64f0b2f9e9 100644 --- a/apps/vectorcraft/src/printing/direct_pdf.rs +++ b/apps/vectorcraft/src/printing/direct_pdf.rs @@ -19,7 +19,7 @@ mod imp { let printer = job .printer .map(str::to_string) - .or_else(|| craft_print::printers().into_iter().find(|p| p.default).map(|p| p.name)) + .or_else(|| craft::print::printers().into_iter().find(|p| p.default).map(|p| p.name)) .ok_or("direct PDF needs a selected printer")?; let (host, port) = tcp_port(&printer)?; send(&host, port, &pjl(job.title, job.pdf))?; diff --git a/apps/vectorcraft/src/profile.rs b/apps/vectorcraft/src/profile.rs index 0048323f03..672ae61baa 100644 --- a/apps/vectorcraft/src/profile.rs +++ b/apps/vectorcraft/src/profile.rs @@ -24,25 +24,26 @@ pub const PORTABLE_MARKERS: [&str; 2] = ["portable.txt", "VectorCraft.portable"] /// The settings folder created in the install folder in portable mode. pub const PORTABLE_DATA_DIR: &str = "VectorCraftData"; -pub fn prefs_path(legacy: bool) -> Option { - prefs_path_with(std::env::consts::OS, legacy, |key| std::env::var_os(key), portable_dir) +/// The settings folder of VectorCraft, or of DrawCraft (`legacy`). +pub fn prefs_dir(legacy: bool) -> Option { + prefs_dir_with(std::env::consts::OS, legacy, |key| std::env::var_os(key), portable_dir) } /// `portable` is the portable settings folder, if any: only asked for when no override is set and /// preferences are in use. -fn prefs_path_with(os: &str, legacy: bool, env: impl Fn(&str) -> Option, portable: impl FnOnce() -> Option) -> Option { +fn prefs_dir_with(os: &str, legacy: bool, env: impl Fn(&str) -> Option, portable: impl FnOnce() -> Option) -> Option { if let Some(root) = env("VECTORCRAFT_CONFIG_DIR") { // Never fall back to DrawCraft's real profile when the isolated file does not exist. - return (!legacy && !root.is_empty()).then(|| PathBuf::from(root).join("ui.json")); + return (!legacy && !root.is_empty()).then(|| PathBuf::from(root)); } // A run without preferences reads and writes nothing, so it must not create the portable folder. if env("VECTORCRAFT_NO_PREFS").is_none() && let Some(dir) = portable() { // A portable copy is self-contained: DrawCraft's old profile is not read into it. - return (!legacy).then(|| dir.join("ui.json")); + return (!legacy).then_some(dir); } - platform_dir(os, legacy, &env).map(|p| p.join("ui.json")) + platform_dir(os, legacy, &env) } /// The platform's settings folder of VectorCraft, or of DrawCraft (`legacy`). @@ -229,27 +230,27 @@ mod tests { let env = |key: &str| { if key == "VECTORCRAFT_CONFIG_DIR" { Some("/isolated".into()) } else { environment(key) } }; - assert_eq!(prefs_path_with(os, false, env, installed), Some("/isolated/ui.json".into())); - assert_eq!(prefs_path_with(os, true, env, installed), None); + assert_eq!(prefs_dir_with(os, false, env, installed), Some("/isolated".into())); + assert_eq!(prefs_dir_with(os, true, env, installed), None); } } #[test] fn empty_override_does_not_fall_back_to_user_files() { let env = |key: &str| if key == "VECTORCRAFT_CONFIG_DIR" { Some(OsString::new()) } else { environment(key) }; - assert_eq!(prefs_path_with("macos", false, env, installed), None); - assert_eq!(prefs_path_with("macos", true, env, installed), None); + assert_eq!(prefs_dir_with("macos", false, env, installed), None); + assert_eq!(prefs_dir_with("macos", true, env, installed), None); } #[test] fn unset_override_keeps_platform_paths_and_legacy_migration() { - assert_eq!(prefs_path_with("macos", false, environment, installed), Some("/user/Library/Application Support/VectorCraft/ui.json".into())); - assert_eq!(prefs_path_with("macos", true, environment, installed), Some("/user/Library/Application Support/DrawCraft/ui.json".into())); - assert_eq!(prefs_path_with("windows", false, environment, installed), Some("/roaming/VectorCraft/ui.json".into())); - assert_eq!(prefs_path_with("linux", false, environment, installed), Some("/xdg-config/vectorcraft/ui.json".into())); + assert_eq!(prefs_dir_with("macos", false, environment, installed), Some("/user/Library/Application Support/VectorCraft".into())); + assert_eq!(prefs_dir_with("macos", true, environment, installed), Some("/user/Library/Application Support/DrawCraft".into())); + assert_eq!(prefs_dir_with("windows", false, environment, installed), Some("/roaming/VectorCraft".into())); + assert_eq!(prefs_dir_with("linux", false, environment, installed), Some("/xdg-config/vectorcraft".into())); assert_eq!( - prefs_path_with("linux", true, |key| if key == "HOME" { environment(key) } else { None }, installed), - Some("/user/.config/drawcraft/ui.json".into()) + prefs_dir_with("linux", true, |key| if key == "HOME" { environment(key) } else { None }, installed), + Some("/user/.config/drawcraft".into()) ); } @@ -257,9 +258,9 @@ mod tests { fn portable_mode_keeps_the_settings_beside_the_executable_and_skips_the_drawcraft_profile() { let portable = || Some(PathBuf::from("/usb/VectorCraft/VectorCraftData")); for os in ["macos", "windows", "linux"] { - assert_eq!(prefs_path_with(os, false, environment, portable), Some("/usb/VectorCraft/VectorCraftData/ui.json".into()), "{os}"); + assert_eq!(prefs_dir_with(os, false, environment, portable), Some("/usb/VectorCraft/VectorCraftData".into()), "{os}"); // A portable copy is self-contained: the one-time read of DrawCraft's old settings is skipped. - assert_eq!(prefs_path_with(os, true, environment, portable), None, "{os}"); + assert_eq!(prefs_dir_with(os, true, environment, portable), None, "{os}"); } } @@ -267,16 +268,16 @@ mod tests { fn the_config_dir_override_wins_over_portable_mode_without_probing_it() { let env = |key: &str| if key == "VECTORCRAFT_CONFIG_DIR" { Some("/isolated".into()) } else { environment(key) }; let portable = || -> Option { panic!("the portable folder is not looked for under VECTORCRAFT_CONFIG_DIR") }; - assert_eq!(prefs_path_with("windows", false, env, portable), Some("/isolated/ui.json".into())); - assert_eq!(prefs_path_with("windows", true, env, portable), None); + assert_eq!(prefs_dir_with("windows", false, env, portable), Some("/isolated".into())); + assert_eq!(prefs_dir_with("windows", true, env, portable), None); } #[test] fn a_run_without_preferences_never_looks_for_the_portable_folder() { let env = |key: &str| if key == "VECTORCRAFT_NO_PREFS" { Some("1".into()) } else { environment(key) }; let portable = || -> Option { panic!("the portable folder is not looked for under VECTORCRAFT_NO_PREFS") }; - assert_eq!(prefs_path_with("windows", false, env, portable), Some("/roaming/VectorCraft/ui.json".into())); - assert_eq!(prefs_path_with("windows", true, env, portable), Some("/roaming/DrawCraft/ui.json".into())); + assert_eq!(prefs_dir_with("windows", false, env, portable), Some("/roaming/VectorCraft".into())); + assert_eq!(prefs_dir_with("windows", true, env, portable), Some("/roaming/DrawCraft".into())); } #[test] @@ -336,17 +337,6 @@ mod tests { let _ = std::fs::remove_dir_all(&folder); } - #[test] - fn without_a_marker_file_there_is_no_portable_folder() { - let exe = temp("installed"); - assert_eq!(portable_dir_in(&exe, None), Ok(None)); - // A folder named like the marker is not a marker. - std::fs::create_dir_all(exe.join("portable.txt")).unwrap(); - assert_eq!(portable_dir_in(&exe, None), Ok(None)); - assert!(!exe.join(PORTABLE_DATA_DIR).exists(), "no data folder without a marker"); - let _ = std::fs::remove_dir_all(&exe); - } - #[test] fn an_unwritable_portable_folder_is_reported_instead_of_used() { let exe = temp("unwritable"); @@ -386,16 +376,6 @@ mod tests { let _ = std::fs::remove_dir_all(&previous); } - #[test] - fn without_a_user_profile_the_data_folder_starts_empty() { - let exe = temp("fresh"); - std::fs::write(exe.join("portable.txt"), b"").unwrap(); - let missing = exe.join("no-such-profile"); - let data = portable_dir_in(&exe, Some(&missing)).unwrap().unwrap(); - assert_eq!(std::fs::read_dir(&data).unwrap().count(), 0); - let _ = std::fs::remove_dir_all(&exe); - } - #[test] fn a_copy_that_fails_halfway_reports_what_it_skipped_and_keeps_the_rest() { let from = temp("copy-from"); diff --git a/apps/vectorcraft/src/quit_windows.rs b/apps/vectorcraft/src/quit_windows.rs index 36497f4f4f..cb5337e6f1 100644 --- a/apps/vectorcraft/src/quit_windows.rs +++ b/apps/vectorcraft/src/quit_windows.rs @@ -1,5 +1,5 @@ //! Takes the app's windows off screen when it quits on Linux and the BSDs, before eframe drops the -//! app. Dropping the app waits up to [`vectorcraft_ui_egui::CLIPBOARD_PROBE_STOP_WAIT`] for the +//! app. Dropping the app waits up to `craft::platform::clipboard::PROBE_STOP_WAIT` for the //! clipboard handles to let go, and eframe closes the windows only after that wait. //! //! The main window is hidden on X11 (XWayland included). winit cannot hide a Wayland window, so on @@ -170,10 +170,8 @@ fn unmap_x11(windows: &[u32]) { /// compositor stops showing it, and the window and its connection stay open. #[cfg(target_os = "linux")] fn unmap_wayland(window: &winit::window::Window) { - let Some((conn, surface)) = super::portal_save::wayland::surface(window) else { return }; - surface.attach(None, 0, 0); - surface.commit(); - if let Err(e) = conn.flush() { + // PLAN: assumed `craft::wayland::unmap_window(&winit::window::Window) -> Result<(), impl Display>` (fl.F39, files-w1) + if let Err(e) = craft::wayland::unmap_window(window) { log::warn!("couldn't reach the compositor to hide the window on quit: {e}"); } } diff --git a/apps/vectorcraft/src/single_instance.rs b/apps/vectorcraft/src/single_instance.rs index 37a836f6fe..ec411158a1 100644 --- a/apps/vectorcraft/src/single_instance.rs +++ b/apps/vectorcraft/src/single_instance.rs @@ -29,7 +29,8 @@ use std::time::Duration; use serde_json::{Value, json}; -use super::prefs::{prefs_enabled, prefs_path}; +use super::prefs::prefs_enabled; +use super::prefs_dir::prefs_dir; /// The endpoint file, next to the preferences. const FILE_NAME: &str = "instance.json"; @@ -66,7 +67,7 @@ pub fn start(automation: bool, new_instance: bool, safe_mode: bool, files: &[Str if automation || !prefs_enabled() { return Start::Running(None); } - let Some(path) = prefs_path().and_then(|p| Some(p.parent()?.join(FILE_NAME))) else { return Start::Running(None) }; + let Some(path) = prefs_dir().map(|dir| dir.join(FILE_NAME)) else { return Start::Running(None) }; start_at(&path, new_instance, safe_mode, files) } diff --git a/apps/vectorcraft/src/tablet.rs b/apps/vectorcraft/src/tablet.rs index f9371bd368..4dd8f7d9ec 100644 --- a/apps/vectorcraft/src/tablet.rs +++ b/apps/vectorcraft/src/tablet.rs @@ -1,8 +1,8 @@ //! Linux: a drawing tablet's pen pressure, tilt, barrel rotation and airbrush finger wheel under //! X11, XWayland included //! (#764). winit 0.30 hands a pen to the window there as a mouse, without any of them, so the app -//! reads them from XInput2 itself and writes them into the UI's [`StylusFeed`] -//! (`Services::stylus`), which the canvas reads. +//! reads them from XInput2 itself and writes them into the framework's [`PenSource`], which the +//! tool host reads. //! //! The reader opens a second connection to the X server (x11rb's `RustConnection`, without //! `unsafe` or libxcb) and selects XInput2 raw events for every device on the root window. Raw @@ -43,7 +43,8 @@ use std::collections::HashMap; -use vectorcraft_ui_egui::stylus::{PenPose, PenSample, StylusFeed}; +use craft::behavior::PointerSample; +use craft::ui::runtime::pen::PenSource; /// The tilt of a valuator whose range does not fit in ±90 (so does not give degrees), at the ends /// of its range. @@ -180,7 +181,7 @@ enum Update { /// Nothing: a device the last listing didn't have (a master, or one added since). Keep, /// The pressure, end, tilt and rotation of a pen, or `None` for another pointer. - Set(Option), + Set(Option), } /// The pointer devices and the last pressure, tilt and rotation of each pen. @@ -217,17 +218,21 @@ impl Pens { // An axis the pen has reads 0 until an event carries it; one it lacks reads nothing. The // wheel reads nothing until an event carries it: XWayland lists the axis for every pen. let value = |kind: AxisKind| device.axis(kind).map(|_| last.get(kind.slot()).copied().flatten().unwrap_or(0.0)); - let tilt = value(AxisKind::TiltX).zip(value(AxisKind::TiltY)).map(|(x, y)| [x, y]); - let wheel = device.axis(AxisKind::Wheel).and_then(|_| last.get(AxisKind::Wheel.slot()).copied().flatten()); - let pose = PenPose { tilt, rotation: value(AxisKind::Rotation), wheel }; - Update::Set(Some(PenSample { pressure: value(AxisKind::Pressure).unwrap_or(0.0), eraser: device.eraser, pose })) + // The valuators give degrees; the framework's samples are in radians. + let tilt = value(AxisKind::TiltX).zip(value(AxisKind::TiltY)).map_or([0.0, 0.0], |(x, y)| [x.to_radians(), y.to_radians()]); + let mut sample = PointerSample::new(value(AxisKind::Pressure).unwrap_or(0.0)); + sample.tilt = tilt; + sample.rotation = value(AxisKind::Rotation).map_or(0.0, f32::to_radians); + sample.eraser = device.eraser; + sample.wheel = device.axis(AxisKind::Wheel).and_then(|_| last.get(AxisKind::Wheel.slot()).copied().flatten()); + Update::Set(Some(sample)) } /// A raw event as the X server sends it: its valuator mask and the values of the valuators - /// set in it. A pen's sample or another pointer's `None` goes into `feed`. - fn raw_event(&mut self, feed: &StylusFeed, id: u16, mask: &[u32], values: &[f64]) { + /// set in it. A pen's sample or another pointer's `None` goes into `pen`. + fn raw_event(&mut self, pen: &PenSource, id: u16, mask: &[u32], values: &[f64]) { if let Update::Set(sample) = self.handle(id, valuators(mask, values)) { - feed.set_sample(sample); + pen.set(sample); } } } @@ -247,13 +252,13 @@ fn fp3232(integral: i32, frac: u32) -> f64 { f64::from(integral) + f64::from(frac) / 4_294_967_296.0 } -/// Start reading pen pressure, tilt and rotation for a window on X11: the feed the reader writes +/// Start reading pen pressure, tilt and rotation for a window on X11: the source the reader writes /// into, or `None` (logged) when the X server can't be reached or has no XInput 2.1. #[cfg(target_os = "linux")] -pub fn start() -> Option { - let feed = StylusFeed::default(); - match x11::spawn(feed.clone()) { - Ok(()) => Some(feed), +pub fn start() -> Option { + let pen = PenSource::default(); + match x11::spawn(pen.clone()) { + Ok(()) => Some(pen), Err(e) => { log::warn!("tablet pressure: {e}"); None @@ -265,7 +270,7 @@ pub fn start() -> Option { mod x11 { use std::collections::HashMap; - use vectorcraft_ui_egui::stylus::StylusFeed; + use craft::ui::runtime::pen::PenSource; use x11rb::connection::{Connection as _, RequestConnection as _}; use x11rb::protocol::Event; use x11rb::protocol::xinput::{self, ConnectionExt as _, DeviceClassData, DeviceType, XIEventMask}; @@ -280,7 +285,7 @@ mod x11 { /// Connect to `$DISPLAY` (the display winit opened the window on), check for XInput 2.1 (raw /// events for every client that selects them), select the raw events, and read them on a /// thread of its own until the connection closes. - pub fn spawn(feed: StylusFeed) -> Result<(), String> { + pub fn spawn(pen: PenSource) -> Result<(), String> { let (conn, screen) = RustConnection::connect(None).map_err(|e| format!("can't connect to the X server: {e}"))?; let root = conn.setup().roots.get(screen).map(|s| s.root).ok_or_else(|| format!("X screen {screen} not found"))?; let version = @@ -301,12 +306,12 @@ mod x11 { pens.set_devices(query_devices(&conn)); std::thread::Builder::new() .name("vectorcraft-tablet-x11".into()) - .spawn(move || run(&conn, &mut pens, &feed)) + .spawn(move || run(&conn, &mut pens, &pen)) .map(drop) .map_err(|e| format!("can't start the tablet thread: {e}")) } - fn run(conn: &RustConnection, pens: &mut Pens, feed: &StylusFeed) { + fn run(conn: &RustConnection, pens: &mut Pens, pen: &PenSource) { // A connection error (the display went away) ends the loop; an event that x11rb cannot // parse is skipped, and `Pens` bounds what the rest can hold. while let Ok(raw) = conn.wait_for_raw_event() { @@ -314,7 +319,7 @@ mod x11 { match event { Event::XinputRawMotion(e) | Event::XinputRawButtonPress(e) | Event::XinputRawButtonRelease(e) => { let values: Vec = e.axisvalues.iter().map(|v| fp3232(v.integral, v.frac)).collect(); - pens.raw_event(feed, e.deviceid, &e.valuator_mask, &values); + pens.raw_event(pen, e.deviceid, &e.valuator_mask, &values); } Event::XinputHierarchy(_) | Event::XinputDeviceChanged(_) => pens.set_devices(query_devices(conn)), _ => {} @@ -384,6 +389,16 @@ mod tests { Device::new(id, "Logitech USB Optical Mouse", Some("MOUSE"), [(0, "Rel X".to_string(), -1.0, -1.0), (1, "Rel Y".to_string(), -1.0, -1.0)]) } + /// A reading as the reader gives it: tilt and rotation in radians. + fn reading(pressure: f32, eraser: bool, tilt: [f32; 2], rotation: f32, wheel: Option) -> PointerSample { + let mut sample = PointerSample::new(pressure); + sample.eraser = eraser; + sample.tilt = tilt; + sample.rotation = rotation; + sample.wheel = wheel; + sample + } + #[test] fn the_mask_pairs_valuator_numbers_with_values() { let v: Vec<_> = valuators(&[0b10_0101, 1], &[1.0, 2.0, 3.0, 4.0]).collect(); @@ -445,58 +460,57 @@ mod tests { fn the_eraser_device_sets_the_eraser_end() { let mut pens = Pens::default(); pens.set_devices([pen(9), Device::new(10, "Wacom Intuos Pro M Pen eraser", Some("ERASER"), pen_valuators()), mouse(12)]); - let feed = StylusFeed::default(); - let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None }; - pens.raw_event(&feed, 9, &[0b100], &[32767.5]); - assert_eq!(pens.handle(9, []), Update::Set(Some(PenSample { pressure: 0.5, eraser: false, pose }))); - assert_eq!(feed.eraser(), Some(false)); + let pen = PenSource::default(); + let end = || pen.current().map(|s| (s.eraser, s.pressure)); + pens.raw_event(&pen, 9, &[0b100], &[32767.5]); + assert_eq!(pens.handle(9, []), Update::Set(Some(reading(0.5, false, [0.0, 0.0], 0.0, None)))); + assert_eq!(end(), Some((false, 0.5))); // Turned over, the pen hovers with its eraser end: the eraser device's first event, with // no pressure yet. - pens.raw_event(&feed, 10, &[0b1], &[100.0]); - assert_eq!(pens.handle(10, []), Update::Set(Some(PenSample { pressure: 0.0, eraser: true, pose }))); - assert_eq!((feed.eraser(), feed.held()), (Some(true), Some(0.0))); - pens.raw_event(&feed, 10, &[0b100], &[65535.0]); - assert_eq!((feed.eraser(), feed.held()), (Some(true), Some(1.0))); + pens.raw_event(&pen, 10, &[0b1], &[100.0]); + assert_eq!(pens.handle(10, []), Update::Set(Some(reading(0.0, true, [0.0, 0.0], 0.0, None)))); + assert_eq!(end(), Some((true, 0.0))); + pens.raw_event(&pen, 10, &[0b100], &[65535.0]); + assert_eq!(end(), Some((true, 1.0))); // Back to the tip, with the tip's own last pressure. - pens.raw_event(&feed, 9, &[0b1], &[200.0]); - assert_eq!((feed.eraser(), feed.held()), (Some(false), Some(0.5))); + pens.raw_event(&pen, 9, &[0b1], &[200.0]); + assert_eq!(end(), Some((false, 0.5))); // A mouse: no pen end. - pens.raw_event(&feed, 12, &[0b1], &[3.0]); - assert_eq!(feed.eraser(), None); + pens.raw_event(&pen, 12, &[0b1], &[3.0]); + assert_eq!(end(), None); } - /// #764: a pen's tilt goes into the feed in degrees and its barrel rotation as a turn, the - /// middle of the valuator's range at 0°; a pen without those valuators reads neither. + /// #764: a pen's tilt goes into the source in radians and its barrel rotation as a turn, the + /// middle of the valuator's range at 0; a pen without those valuators reads neither. #[test] fn a_pens_tilt_and_rotation_go_into_the_feed() { let mut pens = Pens::default(); let pressure_only = Device::new(10, "", Some("STYLUS"), pen_valuators().into_iter().take(3)); let one_tilt = Device::new(11, "", Some("STYLUS"), pen_valuators().into_iter().take(4)); pens.set_devices([pen(9), pressure_only, one_tilt, mouse(12)]); - let feed = StylusFeed::default(); + let pen_source = PenSource::default(); // Pressure, tilt x, tilt y and rotation: valuators 2 to 5. - pens.raw_event(&feed, 9, &[0b11_1100], &[32767.5, -30.0, 45.0, 0.0]); - let pose = feed.pose().unwrap(); - assert_eq!((feed.held(), pose.tilt), (Some(0.5), Some([-30.0, 45.0]))); - assert!(pose.rotation.is_some_and(|r| r < 0.2), "{pose:?}"); + pens.raw_event(&pen_source, 9, &[0b11_1100], &[32767.5, -30.0, 45.0, 0.0]); + let sample = pen_source.current().unwrap(); + assert_eq!((sample.pressure, sample.tilt), (0.5, [(-30.0f32).to_radians(), 45.0f32.to_radians()])); + assert!(sample.rotation < 0.2f32.to_radians(), "{sample:?}"); // A quarter of the range back is a quarter turn back; the tilt stays as it was. - pens.raw_event(&feed, 9, &[0b10_0000], &[-450.0]); - let pose = feed.pose().unwrap(); - assert_eq!(pose.tilt, Some([-30.0, 45.0])); - assert!(pose.rotation.is_some_and(|r| (r - 270.0).abs() < 0.2), "{pose:?}"); + pens.raw_event(&pen_source, 9, &[0b10_0000], &[-450.0]); + let sample = pen_source.current().unwrap(); + assert_eq!(sample.tilt, [(-30.0f32).to_radians(), 45.0f32.to_radians()]); + assert!((sample.rotation - (-90.0f32).to_radians()).abs() < 0.2f32.to_radians(), "{sample:?}"); // A pen with no tilt or rotation valuators, or with one tilt valuator only, reads none. - pens.raw_event(&feed, 10, &[0b100], &[65535.0]); - assert_eq!((feed.held(), feed.pose()), (Some(1.0), None)); - pens.raw_event(&feed, 11, &[0b1100], &[65535.0, 20.0]); - assert_eq!(feed.pose(), None); + pens.raw_event(&pen_source, 10, &[0b100], &[65535.0]); + assert_eq!(pen_source.current(), Some(reading(1.0, false, [0.0, 0.0], 0.0, None))); + pens.raw_event(&pen_source, 11, &[0b1100], &[65535.0, 20.0]); + assert_eq!(pen_source.current().map(|s| s.tilt), Some([0.0, 0.0])); // The mouse: none. - pens.raw_event(&feed, 12, &[0b1], &[3.0]); - assert_eq!(feed.pose(), None); + pens.raw_event(&pen_source, 12, &[0b1], &[3.0]); + assert_eq!(pen_source.current(), None); // A pen whose tilt and rotation no event has carried yet is upright and unturned. let mut fresh = Pens::default(); fresh.set_devices([pen(9)]); - let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None }; - assert_eq!(fresh.handle(9, [(2, 0.0)]), Update::Set(Some(PenSample { pressure: 0.0, eraser: false, pose: upright }))); + assert_eq!(fresh.handle(9, [(2, 0.0)]), Update::Set(Some(reading(0.0, false, [0.0, 0.0], 0.0, None)))); } /// An airbrush pen's "Abs Wheel" valuator goes into the feed as 0..1 of its range, once an @@ -510,19 +524,20 @@ mod tests { let pad = Device::new(13, "Wacom Intuos Pro M Pad pad", Some("PAD"), [(6, "Abs Wheel".to_string(), 0.0, 71.0)]); let mut pens = Pens::default(); pens.set_devices([airbrush, pad, pen(10)]); - let feed = StylusFeed::default(); - pens.raw_event(&feed, 9, &[0b100], &[32767.5]); - assert_eq!(feed.pose().and_then(|q| q.wheel), None, "no event has carried the wheel yet"); - pens.raw_event(&feed, 9, &[0b100_0000], &[255.75]); - assert_eq!(feed.pose().and_then(|q| q.wheel), Some(0.25)); - pens.raw_event(&feed, 9, &[0b100_0000], &[5000.0]); - assert_eq!(feed.pose().and_then(|q| q.wheel), Some(1.0), "clamped to the range"); - pens.raw_event(&feed, 9, &[0b100], &[100.0]); - assert_eq!(feed.pose().and_then(|q| q.wheel), Some(1.0), "kept while other valuators move"); - pens.raw_event(&feed, 13, &[0b100_0000], &[30.0]); - assert_eq!((feed.held(), feed.pose()), (None, None), "the pad is not a pen"); - pens.raw_event(&feed, 10, &[0b100_0000], &[512.0]); - assert_eq!(feed.pose().and_then(|q| q.wheel), None, "a pen without the valuator"); + let pen_source = PenSource::default(); + let wheel = || pen_source.current().and_then(|s| s.wheel); + pens.raw_event(&pen_source, 9, &[0b100], &[32767.5]); + assert_eq!(wheel(), None, "no event has carried the wheel yet"); + pens.raw_event(&pen_source, 9, &[0b100_0000], &[255.75]); + assert_eq!(wheel(), Some(0.25)); + pens.raw_event(&pen_source, 9, &[0b100_0000], &[5000.0]); + assert_eq!(wheel(), Some(1.0), "clamped to the range"); + pens.raw_event(&pen_source, 9, &[0b100], &[100.0]); + assert_eq!(wheel(), Some(1.0), "kept while other valuators move"); + pens.raw_event(&pen_source, 13, &[0b100_0000], &[30.0]); + assert_eq!(pen_source.current(), None, "the pad is not a pen"); + pens.raw_event(&pen_source, 10, &[0b100_0000], &[512.0]); + assert_eq!(wheel(), None, "a pen without the valuator"); } /// A device listed again unchanged keeps its last tilt and rotation; another device listed @@ -533,12 +548,11 @@ mod tests { pens.set_devices([pen(9)]); pens.handle(9, [(3, -30.0), (4, 45.0), (5, -450.0)]); pens.set_devices([pen(9)]); - let Update::Set(Some(PenSample { pose, .. })) = pens.handle(9, [(2, 0.0)]) else { panic!("no pen") }; - assert_eq!(pose.tilt, Some([-30.0, 45.0])); + let Update::Set(Some(sample)) = pens.handle(9, [(2, 0.0)]) else { panic!("no pen") }; + assert_eq!(sample.tilt, [(-30.0f32).to_radians(), 45.0f32.to_radians()]); let other = Device::new(9, "HUION Kamvas Pen Pen (0x1)", Some("STYLUS"), pen_valuators()); pens.set_devices([other]); - let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None }; - assert_eq!(pens.handle(9, [(2, 0.0)]), Update::Set(Some(PenSample { pressure: 0.0, eraser: false, pose: upright }))); + assert_eq!(pens.handle(9, [(2, 0.0)]), Update::Set(Some(reading(0.0, false, [0.0, 0.0], 0.0, None)))); } /// Tilt valuators whose range does not fit in ±90 are scaled to ±60°. @@ -552,34 +566,35 @@ mod tests { ); let mut pens = Pens::default(); pens.set_devices([d]); - let Update::Set(Some(PenSample { pose, .. })) = pens.handle(1, [(3, 127.0), (4, -1000.0)]) else { panic!("no pen") }; - assert_eq!(pose.tilt, Some([60.0, -60.0])); + let Update::Set(Some(sample)) = pens.handle(1, [(3, 127.0), (4, -1000.0)]) else { panic!("no pen") }; + assert_eq!(sample.tilt, [60.0f32.to_radians(), (-60.0f32).to_radians()]); } #[test] fn a_pens_valuator_becomes_its_pressure_and_another_pointer_clears_it() { let mut pens = Pens::default(); pens.set_devices([pen(9), mouse(12)]); - let feed = StylusFeed::default(); - pens.raw_event(&feed, 9, &[0b101], &[100.0, 32767.5]); - assert_eq!(feed.held(), Some(0.5)); + let pen_source = PenSource::default(); + let pressure = || pen_source.current().map(|s| s.pressure); + pens.raw_event(&pen_source, 9, &[0b101], &[100.0, 32767.5]); + assert_eq!(pressure(), Some(0.5)); // Raw events carry only the valuators that changed: a move without pressure keeps it. - pens.raw_event(&feed, 9, &[0b1], &[200.0]); - assert_eq!(feed.held(), Some(0.5)); - pens.raw_event(&feed, 9, &[0b100], &[65535.0]); - assert_eq!(feed.held(), Some(1.0)); + pens.raw_event(&pen_source, 9, &[0b1], &[200.0]); + assert_eq!(pressure(), Some(0.5)); + pens.raw_event(&pen_source, 9, &[0b100], &[65535.0]); + assert_eq!(pressure(), Some(1.0)); // The mouse moves: no pen pressure until the pen moves again. - pens.raw_event(&feed, 12, &[0b1], &[3.0]); - assert_eq!(feed.held(), None); - pens.raw_event(&feed, 9, &[0b1], &[300.0]); - assert_eq!(feed.held(), Some(1.0), "the pen's last pressure"); + pens.raw_event(&pen_source, 12, &[0b1], &[3.0]); + assert_eq!(pressure(), None); + pens.raw_event(&pen_source, 9, &[0b1], &[300.0]); + assert_eq!(pressure(), Some(1.0), "the pen's last pressure"); // A master device or one not listed yet changes nothing. - pens.raw_event(&feed, 2, &[0b100], &[0.0]); - assert_eq!(feed.held(), Some(1.0)); - // A pen whose first event carries no pressure is hovering: it presses with 0. + pens.raw_event(&pen_source, 2, &[0b100], &[0.0]); + assert_eq!(pressure(), Some(1.0)); + // A pen whose first event carries no pressure is hovering: it reads 0. pens.set_devices([pen(9), pen(10)]); - pens.raw_event(&feed, 10, &[0b1], &[5.0]); - assert_eq!(feed.press(), Some(0.0)); + pens.raw_event(&pen_source, 10, &[0b1], &[5.0]); + assert_eq!(pressure(), Some(0.0)); } #[test] @@ -590,13 +605,11 @@ mod tests { let labels = ["Abs Pressure", "Abs Tilt X", "Abs Tilt Y", "Abs Rotary Z"]; pens.set_devices([Device::new(1, "", None, (2..).zip(labels).map(|(n, l)| (n, l.to_string(), min, max)))]); for v in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::MAX, f64::MIN, -0.0, 1e300, 0.5] { - let Update::Set(Some(PenSample { pressure: p, pose, .. })) = pens.handle(1, (2..6).map(|n| (n, v))) else { - panic!("{min}..{max}: {v} gave no pressure") - }; - assert!((0.0..=1.0).contains(&p), "{min}..{max}: {v} gave {p}"); - let tilt = pose.tilt.unwrap_or_default(); - assert!(tilt.iter().all(|t| (-90.0..=90.0).contains(t)), "{min}..{max}: {v} gave {pose:?}"); - assert!(pose.rotation.is_some_and(|r| (-180.0..=180.0).contains(&r)), "{min}..{max}: {v} gave {pose:?}"); + let Update::Set(Some(s)) = pens.handle(1, (2..6).map(|n| (n, v))) else { panic!("{min}..{max}: {v} gave no pressure") }; + assert!((0.0..=1.0).contains(&s.pressure), "{min}..{max}: {v} gave {s:?}"); + let quarter = std::f32::consts::FRAC_PI_2 + 1e-6; + assert!(s.tilt.iter().all(|t| t.abs() <= quarter), "{min}..{max}: {v} gave {s:?}"); + assert!(s.rotation.abs() <= std::f32::consts::PI + 1e-6, "{min}..{max}: {v} gave {s:?}"); } } let mut pens = Pens::default(); @@ -604,10 +617,10 @@ mod tests { assert!(pens.devices.len() <= MAX_DEVICES, "the device list is bounded"); // Values for valuators the pen doesn't have are ignored. pens.set_devices([pen(3)]); - let Update::Set(Some(PenSample { pressure: p, .. })) = pens.handle(3, valuators(&[u32::MAX; 2048], &[0.5; 4096]).collect::>()) else { + let Update::Set(Some(s)) = pens.handle(3, valuators(&[u32::MAX; 2048], &[0.5; 4096]).collect::>()) else { panic!("the pen gave no pressure") }; - assert!(p < 0.001, "{p}"); + assert!(s.pressure < 0.001, "{}", s.pressure); } #[test] diff --git a/apps/vectorcraft/src/tests.rs b/apps/vectorcraft/src/tests.rs index 54fa01da03..4f6d7c6e7c 100644 --- a/apps/vectorcraft/src/tests.rs +++ b/apps/vectorcraft/src/tests.rs @@ -1,39 +1,34 @@ use super::*; -fn ui_state_with_prefs(engine_prefs: serde_json::Value) -> vectorcraft_ui_egui::UiState { - vectorcraft_ui_egui::UiState { engine_prefs, ..Default::default() } +/// The saved UI state of an old `ui.json`, as the legacy import reads it. +fn legacy_ui(bytes: &[u8]) -> Option { + vectorcraft_ui_egui::parse_legacy(bytes).ok().map(|(settings, _)| settings.ui) } -/// Shortcut overrides an earlier version saved still load: its spellings, `panel:` keys, an -/// override that can't fire (#487), an entry for a command this version lacks, and an old set -/// name. +/// Shortcut overrides an earlier version saved still load: its spellings, `panel:` keys, a cleared +/// shortcut and an entry for a command this version lacks become a set of the user's. #[test] fn shortcut_overrides_from_an_earlier_version_load() { use serde_json::json; - use vectorcraft_ui_egui::{keymap, shortcut_editor}; + use vectorcraft_ui_egui::{keymap::stored_key, shortcut_editor}; let mut raw = serde_json::to_value(vectorcraft_ui_egui::UiState::default()).unwrap(); + raw.as_object_mut().unwrap().remove("shortcut_sets"); raw["shortcut_overrides"] = json!({ "tool:pen": "Shift+9", "edit.preferences": "", "panel:layers": "Cmd+Alt+Shift+F7", - "tool:groupSelection": "Shift+ShiftLeft", "test.unknown": "Cmd+Alt+Shift+F9", - "view.grid": "Cmd+Period", }); raw["shortcut_set"] = json!(shortcut_editor::LEGACY_PRESETS[0].0); - let ui = decode_saved_prefs(&serde_json::to_vec(&raw).unwrap()).unwrap().sanitized(); - assert_eq!(ui.shortcut_set, shortcut_editor::LEGACY_PRESETS[0].1); - let km = keymap::keymap_with(&ui.shortcut_overrides); - let text = |key: &str| keymap::effective_with(&km, key); - assert_eq!(text("tool:pen").as_deref(), Some("Shift+9")); - assert_eq!(text("edit.preferences"), None); - assert_eq!(text("panel:layers").as_deref(), Some("Cmd+Alt+Shift+F7")); - assert_eq!(text("tool:groupSelection").as_deref(), shortcut_editor::default_of("tool:groupSelection"), "back on its default"); - assert_eq!(text("view.grid").as_deref(), Some("Cmd+Period")); - let period = keymap::vc_chord("Cmd+.").unwrap(); - assert_eq!(keymap::lookup(&km, &period).map(|c| c.id), Some("view.grid".to_string())); - assert_eq!(text("test.unknown").as_deref(), Some("Cmd+Alt+Shift+F9"), "kept"); - assert!(km.problems().iter().any(|p| format!("{p:?}") == r#"UnknownCommand { key: "test.unknown" }"#), "reported"); + let ui = legacy_ui(&serde_json::to_vec(&raw).unwrap()).unwrap().sanitized(); + let sets = &ui.shortcut_sets; + assert!(!shortcut_editor::PRESETS.contains(&sets.active_name(&shortcut_editor::BUILTINS)), "the overrides are a set of the user's"); + let overrides = sets.active_overrides(&shortcut_editor::BUILTINS); + let text = |key: &str| overrides.get(&stored_key(key)).map(|t| t.iter().map(String::as_str).collect::>()); + assert_eq!(text("tool:pen"), Some(vec!["Shift+9"])); + assert!(text("edit.preferences").is_none_or(|t| t.iter().all(|k| k.is_empty())), "cleared"); + assert_eq!(text("panel:layers"), Some(vec!["Cmd+Alt+Shift+F7"])); + assert_eq!(text("test.unknown"), Some(vec!["Cmd+Alt+Shift+F9"]), "kept"); } /// The command line's files wait for the choice about a stopped plug-in, so they open with the @@ -74,304 +69,55 @@ fn opening_files_unminimizes_and_focuses_the_window() { assert!(cmds.contains(&egui::ViewportCommand::Focus)); } +/// An old file whose docking data this version can't read keeps its preferences and every one of +/// its workspaces: only the unreadable layout is dropped. #[test] fn unreadable_saved_docking_keeps_preferences_and_every_workspace() { use serde_json::json; + let prefs = json!({"interfaceLanguage": "fr", "uiBrightness": "light"}); + for layout in [json!({"root": {"FutureNode": {}}, "floating": []}), json!(false)] { + for hidden in [json!({"layers": {"placement": {"FuturePlacement": {}}}}), json!(["malformed"])] { + let saved = json!({ + "engine_prefs": prefs, + "control_bar": false, + "docking": layout, + "docking_hidden": hidden, + "custom_workspaces": [{"name": "Future", "docking": layout, "dockingHidden": hidden}, {"name": "Valid", "dockTab": "Layers"}], + "workspace_changes": [{"name": "Future", "docking": layout, "dockingHidden": hidden}], + }); + let ui = legacy_ui(&serde_json::to_vec(&saved).unwrap()).unwrap(); + assert_eq!(ui.engine_prefs, prefs); + assert!(!ui.control_bar); + let names = vectorcraft_ui_egui::workspaces::names(&ui); + for name in ["Future", "Valid"] { + assert!(names.iter().any(|n| n == name), "{name} kept: {names:?}"); + } + } + } +} + +/// The format boundary of the preferences file: a state with its saved fields off their defaults +/// goes through `config.toml` and comes back equal (a field TOML cannot hold fails here). +#[test] +fn a_saved_ui_state_survives_a_config_toml_round_trip() { + use craft::settings::SettingsStore; + use serde_json::json; + use vectorcraft_ui_egui::{AppSettings, from_app, workspaces}; let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); app.run("window.panel.float", json!({"panel":"layers"})).unwrap(); - app.ui.toolbar = false; - app.ui.engine_prefs = json!({"interfaceLanguage":"fr", "uiBrightness":"light"}); - app.ui.custom_workspaces = - vec![vectorcraft_ui_egui::workspaces::capture(&app.ui, "Future"), vectorcraft_ui_egui::workspaces::capture(&app.ui, "Valid")]; - app.ui.workspace_changes = vec![vectorcraft_ui_egui::workspaces::capture(&app.ui, "Future")]; - let original = serde_json::to_value(&app.ui).unwrap(); - let valid_location = original["docking_hidden"]["layers"].clone(); - assert!(valid_location.is_object()); - for invalid_layout in [json!({"root":{"FutureNode":{}},"floating":[]}), json!(false)] { - for invalid_hidden in [json!({"layers":{"placement":{"FuturePlacement":{}}},"swatches":valid_location}), json!(["malformed"])] { - let mut raw = original.clone(); - raw["docking"] = invalid_layout.clone(); - raw["docking_hidden"] = invalid_hidden.clone(); - raw["custom_workspaces"][0]["docking"] = invalid_layout.clone(); - raw["custom_workspaces"][0]["dockingHidden"] = invalid_hidden.clone(); - raw["workspace_changes"][0]["docking"] = invalid_layout.clone(); - raw["workspace_changes"][0]["dockingHidden"] = invalid_hidden.clone(); - assert!(serde_json::from_value::(raw.clone()).is_err(), "runtime serde stays strict"); - let loaded = decode_saved_prefs(&serde_json::to_vec(&raw).unwrap()).unwrap(); - assert_eq!(loaded.engine_prefs, app.ui.engine_prefs); - assert!(!loaded.toolbar); - assert!(loaded.docking.is_none()); - assert!(!loaded.docking_hidden.contains_key("layers")); - if invalid_hidden.is_object() { - assert_eq!(serde_json::to_value(loaded.docking_hidden.get("swatches")).unwrap(), valid_location); - } else { - assert!(loaded.docking_hidden.is_empty()); - } - assert_eq!(loaded.custom_workspaces.len(), 2); - assert_eq!(loaded.custom_workspaces[0].name, "Future"); - assert!(loaded.custom_workspaces[0].docking.is_none()); - assert!(!loaded.custom_workspaces[0].docking_hidden.contains_key("layers")); - assert_eq!(serde_json::to_value(&loaded.custom_workspaces[1]).unwrap(), original["custom_workspaces"][1]); - assert_eq!(loaded.workspace_changes.len(), 1, "a remembered layout is recovered, not the whole file lost"); - assert!(loaded.workspace_changes[0].docking.is_none()); - } - } - let roundtrip = decode_saved_prefs(&serde_json::to_vec(&original).unwrap()).unwrap(); - assert_eq!(serde_json::to_value(roundtrip).unwrap(), original); - assert!( - decode_saved_prefs(&serde_json::to_vec(&json!({"toolbar":"invalid"})).unwrap()).is_none(), - "unrelated fields retain normal strict parsing" - ); -} - -#[test] -fn an_unreadable_ui_json_is_kept_beside_it() { - let temp = tempfile::Builder::new().prefix("vectorcraft-ui-prefs-").tempdir().unwrap(); - let dir = temp.path(); - let path = dir.join("ui.json"); - super::keep_prefs_copy(&path, b"{\"docking\": {\"root\": {\"FutureNode\": {}}}}", "ui.unreadable"); - super::keep_prefs_copy(&path, b"not json", "ui.unreadable"); - super::keep_prefs_copy(&path, b"{}", "ui.before-layout-migration"); - let first = std::fs::read(dir.join("ui.unreadable.json")).unwrap(); - let second = std::fs::read(dir.join("ui.unreadable-2.json")).unwrap(); - let before = std::fs::read(dir.join("ui.before-layout-migration.json")).unwrap(); - assert!(first.starts_with(b"{\"docking\""), "the first copy is not replaced"); - assert_eq!(second, b"not json"); - assert_eq!(before, b"{}"); - assert!(!super::KEEP_UI_PREFS.load(std::sync::atomic::Ordering::Relaxed), "ui.json can be saved once a copy is kept"); -} - -#[test] -fn the_image_trace_preview_setting_is_kept_across_a_restart() { - for preview in [false, true] { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - app.ui.image_trace_preview = preview; - let saved = prefs_bytes(&app).unwrap(); - let loaded = decode_saved_prefs(&saved).unwrap().sanitized(); - assert_eq!(loaded.image_trace_preview, preview, "Preview {preview} after a restart"); - } -} - -#[test] -fn the_system_title_bar_preference_keeps_the_window_decorations() { - use craft_window::{Frame, Layout}; - - // The System Title Bar preference (Preferences › User Interface) is read the same way on - // every platform; a missing or unreadable value is `false`. - assert!(!super::opted_into_system_title_bar(None), "no preferences: the default"); - let off = ui_state_with_prefs(serde_json::json!({"systemTitleBar": false})); - assert!(!super::opted_into_system_title_bar(Some(&off))); - let on = ui_state_with_prefs(serde_json::json!({"systemTitleBar": true})); - assert!(super::opted_into_system_title_bar(Some(&on))); - - // The suite-wide mapping (Frame + preference -> whether VectorCraft draws its own title - // bar). The desktop frame (macOS, Windows, X11, KDE/Wayland, …) always keeps native - // decorations; the app frame (GNOME/Wayland, or a `VECTORCRAFT_TITLEBAR` override) draws - // our own title bar — unless the user opted into the system title bar, which forces the - // native frame back on. - let app = Frame::App(Layout::default()); - let desktop = Frame::Desktop; - #[cfg(not(any(target_os = "macos", target_os = "windows")))] - { - assert!(super::custom_titlebar_from(&app, false), "GNOME/Wayland: VectorCraft draws its own"); - assert!(!super::custom_titlebar_from(&app, true), "System Title Bar preference forces native"); - assert!(!super::custom_titlebar_from(&desktop, false), "KDE/X11/…: keep the compositor's frame"); - assert!(!super::custom_titlebar_from(&desktop, true)); - } - // macOS and Windows keep today's behavior, independent of the probed frame: the pref still - // forces the native frame back on where a custom one would otherwise be drawn. - #[cfg(any(target_os = "macos", target_os = "windows"))] - { - assert_eq!(super::custom_titlebar_from(&desktop, false), super::CUSTOM_TITLEBAR); - assert_eq!(super::custom_titlebar_from(&app, false), super::CUSTOM_TITLEBAR, "the probe does not change macOS/Windows"); - assert!(!super::custom_titlebar_from(&desktop, true)); - } - - assert_eq!(super::native_options(false).viewport.decorations, Some(true)); - assert_eq!(super::native_options(true).viewport.decorations, Some(false)); -} - -/// Preferences › User Interface › VectorCraft Title Bar on Every Desktop gives the app frame where -/// the probe chose the desktop's (KDE, X11, a window opened through XWayland); without it the probe -/// decides, and `VECTORCRAFT_TITLEBAR` set to `app`, `system` or `desktop` takes precedence over -/// both. -#[test] -fn the_app_title_bar_preference_gives_the_app_frame_on_desktop_frames() { - assert!(!super::opted_into_app_title_bar(None), "no preferences: the default"); - let off = ui_state_with_prefs(serde_json::json!({"appTitleBar": false})); - assert!(!super::opted_into_app_title_bar(Some(&off))); - let on = ui_state_with_prefs(serde_json::json!({"appTitleBar": true})); - assert!(super::opted_into_app_title_bar(Some(&on))); - - // (probed_app, overridden, forced_to_x11): without the preference, then with it. - let cases = [ - ((false, None, false), false, true), // KDE, Sway, X11: the desktop frame - ((true, None, false), true, true), // GNOME on Wayland: the app frame either way - ((true, None, true), false, true), // GNOME, the window opened through XWayland - ((false, Some(true), false), true, true), // VECTORCRAFT_TITLEBAR=app - ((false, Some(true), true), true, true), // VECTORCRAFT_TITLEBAR=app, the window opened through XWayland - ((true, Some(false), false), false, false), // VECTORCRAFT_TITLEBAR=desktop takes precedence over the preference - ((false, Some(false), true), false, false), - ]; - for ((probed_app, overridden, forced_to_x11), without, with) in cases { - assert_eq!(super::app_draws_frame(probed_app, overridden, forced_to_x11, false), without, "{probed_app} {overridden:?} {forced_to_x11}"); - assert_eq!(super::app_draws_frame(probed_app, overridden, forced_to_x11, true), with, "{probed_app} {overridden:?} {forced_to_x11}"); - } -} - -/// The frame a start uses: the preference turns the desktop frame the probe chose into the app frame -/// with the default window buttons, an app frame the desktop left to the app keeps its own buttons, -/// one that `VECTORCRAFT_TITLEBAR=app` forced or the preference kept through XWayland gets the -/// default buttons, and the desktop frame stays -/// where the app frame is not drawn. System Title Bar takes precedence over the preference. -#[test] -fn the_start_frame_applies_the_app_title_bar_preference() { - use craft_window::{Button, Frame, Layout}; - let gnome = Layout { left: vec![Button::Close], right: vec![] }; - let cases = [ - // (probed, overridden, forced_to_x11, opted_into_app), expected - ((Frame::Desktop, None, false, false), Frame::Desktop), - ((Frame::Desktop, None, false, true), Frame::App(Layout::default())), - ((Frame::Desktop, None, true, true), Frame::App(Layout::default())), - ((Frame::App(gnome.clone()), None, false, false), Frame::App(gnome.clone())), - ((Frame::App(gnome.clone()), None, true, false), Frame::Desktop), - ((Frame::App(gnome.clone()), None, true, true), Frame::App(Layout::default())), - ((Frame::Desktop, Some(false), false, true), Frame::Desktop), - ((Frame::App(gnome.clone()), Some(true), true, false), Frame::App(Layout::default())), - ((Frame::App(gnome.clone()), Some(true), false, false), Frame::App(Layout::default())), - ]; - for ((probed, overridden, forced_to_x11, opted_into_app), expected) in cases { - let label = format!("{probed:?} {overridden:?} {forced_to_x11} {opted_into_app}"); - assert_eq!(super::start_frame(probed, overridden, forced_to_x11, opted_into_app), expected, "{label}"); - } - // With both preferences on, System Title Bar takes precedence: the desktop draws the frame. - let both = super::start_frame(Frame::Desktop, None, false, true); - assert!(!super::custom_titlebar_from(&both, true), "System Title Bar takes precedence over the app title bar preference"); -} - -/// The app bar's caption buttons follow the window-button layout of the app frame on Linux and the -/// BSDs (Close alone at the right, or all three at the left with Close outermost); the desktop frame, -/// macOS and Windows keep all three at the right. -#[test] -fn the_caption_buttons_follow_the_frame_layout() { - use craft_window::{Button, Frame, Layout}; - use vectorcraft_ui_egui::titlebar::{Caption, CaptionLayout}; - let close_only = Layout::parse("appmenu:close"); - let at_left = Layout { left: vec![Button::Close, Button::Minimize, Button::Maximize], right: vec![] }; - let split = Layout { left: vec![Button::Close], right: vec![Button::Minimize, Button::Maximize] }; - let probed = [ - (close_only, CaptionLayout { left: vec![], right: vec![Caption::Close] }), - (at_left, CaptionLayout { left: vec![Caption::Close, Caption::Minimize, Caption::Maximize], right: vec![] }), - (split, CaptionLayout { left: vec![Caption::Close], right: vec![Caption::Minimize, Caption::Maximize] }), - ]; - for (layout, expected) in probed { - let shown = super::caption_layout_from(&Frame::App(layout.clone())); - let expected = if cfg!(any(target_os = "macos", target_os = "windows")) { CaptionLayout::default() } else { expected }; - assert_eq!(shown, expected, "{layout:?}"); - } - assert_eq!(super::caption_layout_from(&Frame::Desktop), CaptionLayout::default()); - assert_eq!(CaptionLayout::default().right, vec![Caption::Minimize, Caption::Maximize, Caption::Close]); -} - -/// `VECTORCRAFT_TITLEBAR` chooses the frame for the run it is set in, with System Title Bar off and -/// on. The saved preference still decides while the variable is unset. -#[test] -fn the_titlebar_variable_takes_precedence_over_system_title_bar() { - use craft_window::Frame; - assert!(super::system_title_bar_applies(true, false)); - assert!(!super::system_title_bar_applies(true, true)); - assert!(!super::system_title_bar_applies(false, false)); - assert!(!super::system_title_bar_applies(false, true)); - // VECTORCRAFT_TITLEBAR=app with System Title Bar on: VectorCraft draws its own title bar. - let frame = super::start_frame(Frame::Desktop, Some(true), false, false); - assert_eq!(super::custom_titlebar_from(&frame, super::system_title_bar_applies(true, true)), !cfg!(target_os = "macos")); - // VECTORCRAFT_TITLEBAR=desktop with System Title Bar off keeps the desktop's frame. - #[cfg(not(any(target_os = "macos", target_os = "windows")))] - { - let frame = super::start_frame(Frame::App(craft_window::Layout::default()), Some(false), false, false); - assert!(!super::custom_titlebar_from(&frame, super::system_title_bar_applies(false, true))); - } -} - -/// `VECTORCRAFT_TITLEBAR` read from the environment at startup, with System Title Bar off and on. -/// The variable is process-wide and read once, so each value runs in a separate test process. -#[test] -fn the_titlebar_variable_decides_the_frame_before_the_window_opens() { - const CHILD: &str = "VECTORCRAFT_TEST_TITLEBAR_CHILD"; - if std::env::var_os(CHILD).is_none() { - for value in ["app", "system", "desktop", "unknown"] { - // Linux and the BSDs: hold `spawning` while the child starts, so it does not keep a - // copy of a GPU start test's locked start file (see `CHILD_SPAWN`). - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] - let spawning = super::spawning(); - let child = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", "tests::the_titlebar_variable_decides_the_frame_before_the_window_opens", "--nocapture"]) - .env(CHILD, "1") - .env("VECTORCRAFT_TITLEBAR", value) - .stdin(std::process::Stdio::null()) - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn(); - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] - drop(spawning); - let output = child.unwrap().wait_with_output().unwrap(); - assert!( - output.status.success(), - "VECTORCRAFT_TITLEBAR={value}\n{}\n{}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - ); - } - return; - } - let value = std::env::var("VECTORCRAFT_TITLEBAR").unwrap(); - let not_read = cfg!(any(target_os = "macos", target_os = "windows")); - assert_eq!(super::titlebar_from_env(), !not_read && value != "unknown", "VECTORCRAFT_TITLEBAR={value}"); - let off = ui_state_with_prefs(serde_json::json!({"systemTitleBar": false})); - let on = ui_state_with_prefs(serde_json::json!({"systemTitleBar": true})); - for (saved, opted_into_system) in [(None, false), (Some(&off), false), (Some(&on), true)] { - let (custom, _) = super::custom_titlebar(saved); - let expected = match value.as_str() { - _ if not_read => !cfg!(target_os = "macos") && !opted_into_system, - "app" => true, - "system" | "desktop" => false, - // Not a value the variable takes: System Title Bar decides when it is on. Otherwise the - // `craft-window` probe decides, the same with System Title Bar off as with no saved - // preferences. - _ if opted_into_system => false, - _ => super::custom_titlebar(None).0, - }; - assert_eq!(custom, expected, "{value}, preference {opted_into_system}"); - assert_eq!(super::native_options(custom).viewport.decorations, Some(!custom), "{value}, preference {opted_into_system}"); - } -} - -/// Preferences says under System Title Bar that the desktop draws the frame with it on or off -/// exactly where the start frame without VectorCraft Title Bar on Every Desktop is the desktop's -/// with System Title Bar off as well as on and `VECTORCRAFT_TITLEBAR` is unset: Linux and the BSDs -/// only. -#[test] -fn the_desktop_keeps_the_frame_where_system_title_bar_does_not_change_it() { - use crate::titlebar::desktop_keeps_frame_from; - use craft_window::{Frame, Layout}; - let linux = cfg!(not(any(target_os = "macos", target_os = "windows"))); - for probed in [Frame::Desktop, Frame::App(Layout::default())] { - for forced_to_x11 in [false, true] { - let frame = super::start_frame(probed.clone(), None, forced_to_x11, false); - let either_way = !super::custom_titlebar_from(&frame, false) && !super::custom_titlebar_from(&frame, true); - assert_eq!(desktop_keeps_frame_from(&probed, None, forced_to_x11), linux && either_way, "{probed:?} {forced_to_x11}"); - } - } - // KDE, Sway and X11, and GNOME through XWayland, keep the desktop's frame; GNOME on Wayland does not. - assert_eq!(desktop_keeps_frame_from(&Frame::Desktop, None, false), linux); - assert_eq!(desktop_keeps_frame_from(&Frame::App(Layout::default()), None, true), linux); - assert!(!desktop_keeps_frame_from(&Frame::App(Layout::default()), None, false)); - // While `VECTORCRAFT_TITLEBAR` chooses the frame, System Title Bar does not apply and there is no note. - for (frame, overridden) in [(Frame::App(Layout::default()), Some(true)), (Frame::Desktop, Some(false))] { - for forced_to_x11 in [false, true] { - assert!(!desktop_keeps_frame_from(&frame, overridden, forced_to_x11), "{overridden:?} {forced_to_x11}"); - } - } + app.run("prefs.set", json!({"key": "showToolTips", "value": false})).unwrap(); + app.ui.status_bar = false; + app.ui.image_trace_preview = false; + app.ui.last_folders.insert("open".to_string(), std::env::temp_dir()); + workspaces::save_as(&mut app.ui, "Mine").unwrap(); + let temp = tempfile::Builder::new().prefix("vectorcraft-config-toml-").tempdir().unwrap(); + let wanted = from_app(&app); + let (mut store, _) = SettingsStore::::open_at(temp.path()); + store.set(wanted.clone()); + store.flush().unwrap(); + let (back, report) = SettingsStore::::open_at(temp.path()); + assert!(report.section_errors.is_empty(), "{:?}", report.section_errors); + assert_eq!(back.get(), &wanted); } /// The file extensions the macOS bundle declares: its document types and its own exported type. diff --git a/apps/vectorcraft/src/titlebar.rs b/apps/vectorcraft/src/titlebar.rs deleted file mode 100644 index cb98fa2648..0000000000 --- a/apps/vectorcraft/src/titlebar.rs +++ /dev/null @@ -1,228 +0,0 @@ -use super::window; -#[cfg(target_os = "linux")] -use super::xwayland; - -/// The window, Dock, taskbar and app-switcher icon (`assets/app-icon/`, see its README). macOS gets -/// the version with Apple's transparent margin; elsewhere the full-bleed tile. The app ID matches -/// `packaging/linux/ai.storyteller.vectorcraft.desktop` so Wayland docks find the launcher icon. -fn app_icon() -> egui::IconData { - #[cfg(target_os = "macos")] - let png: &[u8] = include_bytes!("../../../assets/app-icon/vectorcraft-macos-512.png"); - #[cfg(not(target_os = "macos"))] - let png: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.vectorcraft.png"); - eframe::icon_data::from_png_bytes(png).unwrap_or_default() -} - -/// Windows shows a window's big icon (`ICON_BIG`) in the taskbar and Alt+Tab; eframe sets only the -/// small one (the title bar's), so the taskbar showed a generic icon. Set the big one too. -#[cfg(windows)] -pub(crate) fn set_taskbar_icon(w: &winit::window::Window) { - use winit::platform::windows::WindowExtWindows as _; - let icon = app_icon(); - // An icon that can't be made leaves the generic one: nothing else depends on it. - if let Ok(i) = winit::window::Icon::from_rgba(icon.rgba, icon.width, icon.height) { - w.set_taskbar_icon(Some(i)); - } -} - -/// "name (backend, kind)" of the adapter the window renders with, for Help › About and bug reports. -#[cfg(feature = "wgpu")] -pub(crate) fn adapter_summary(info: &eframe::wgpu::AdapterInfo) -> String { - format!("{} ({:?}, {:?})", info.name.trim(), info.backend, info.device_type) -} - -/// Windows: no OS title bar; the app bar is the title bar (`vectorcraft_ui_egui::titlebar`). -/// macOS keeps its traffic lights over the integrated title strip. -/// -/// Used on macOS and Windows (where VectorCraft keeps today's frame regardless of the -/// `craft-window` probe) and by the tests; Linux and the BSDs take the decision from the probe. -#[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))] -pub(crate) const CUSTOM_TITLEBAR: bool = !cfg!(target_os = "macos"); - -/// Whether the user asked for the system title bar in Preferences › User Interface › System Title -/// Bar. Read from the saved preferences before the window opens; a missing or unreadable value is -/// `false` (the default). This preference forces the desktop/native frame back on unless -/// `VECTORCRAFT_TITLEBAR` is set to `app`, `system` or `desktop` ([`system_title_bar_applies`]). -pub(crate) fn opted_into_system_title_bar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool { - saved.map(|ui| ui.engine_prefs.get("systemTitleBar").and_then(serde_json::Value::as_bool).unwrap_or(false)).unwrap_or(false) -} - -/// Whether the user asked for VectorCraft's own title bar in Preferences › User Interface › -/// VectorCraft Title Bar on Every Desktop (Linux and the BSDs). Read like -/// [`opted_into_system_title_bar`]; a missing or unreadable value is `false` (the default). -pub(crate) fn opted_into_app_title_bar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool { - saved.map(|ui| ui.engine_prefs.get("appTitleBar").and_then(serde_json::Value::as_bool).unwrap_or(false)).unwrap_or(false) -} - -/// Whether the app draws the frame on this start, before the System Title Bar preference is -/// applied ([`custom_titlebar_from`]). `probed_app` is the `craft-window` probe's answer and -/// `overridden` its `VECTORCRAFT_TITLEBAR` override. In order: the override decides when the -/// variable is set to `app`, `system` or `desktop`;VectorCraft Title Bar on Every Desktop (`opted_into_app`) gives the app frame; a window -/// that opens through XWayland (`forced_to_x11`) gets the desktop frame; otherwise the probe -/// decides. -pub(crate) fn app_draws_frame(probed_app: bool, overridden: Option, forced_to_x11: bool, opted_into_app: bool) -> bool { - match overridden { - Some(app) => app, - None => opted_into_app || (probed_app && !forced_to_x11), - } -} - -/// The frame this start uses, before the System Title Bar preference is applied -/// ([`custom_titlebar_from`]): [`app_draws_frame`] applied to the frame the probe chose. An app frame -/// the desktop left to the app (no `VECTORCRAFT_TITLEBAR` override, not forced onto XWayland) keeps -/// its window-button layout. An app frame turned on by `VECTORCRAFT_TITLEBAR=app` or by VectorCraft -/// Title Bar on Every Desktop gets the default layout: on those desktops the `button-layout` key that `craft-window` reads can -/// hold its schema default (`appmenu:close`) rather than the desktop's own buttons. -pub(crate) fn start_frame(probed: craft_window::Frame, overridden: Option, forced_to_x11: bool, opted_into_app: bool) -> craft_window::Frame { - let probed_app = matches!(probed, craft_window::Frame::App(_)); - match (app_draws_frame(probed_app, overridden, forced_to_x11, opted_into_app), probed) { - (true, frame @ craft_window::Frame::App(_)) if overridden.is_none() && !forced_to_x11 => frame, - (true, _) => craft_window::Frame::App(craft_window::Layout::default()), - (false, _) => craft_window::Frame::Desktop, - } -} - -/// Where the app bar puts its caption buttons for `frame`: on Linux and the BSDs, the window-button -/// layout of an app frame, which `craft-window` reads from the desktop (the `button-layout` key of -/// `org.gnome.desktop.wm.preferences`); otherwise all three at the right. Each list is copied in the -/// key's order, first item leftmost, so `close,minimize,maximize:` puts Close at the left edge. -#[cfg(not(any(target_os = "macos", target_os = "windows")))] -pub(crate) fn caption_layout_from(frame: &craft_window::Frame) -> vectorcraft_ui_egui::titlebar::CaptionLayout { - use vectorcraft_ui_egui::titlebar::{Caption, CaptionLayout}; - let caption = |b: &craft_window::Button| match b { - craft_window::Button::Minimize => Caption::Minimize, - craft_window::Button::Maximize => Caption::Maximize, - craft_window::Button::Close => Caption::Close, - }; - match frame.layout() { - Some(layout) => CaptionLayout { left: layout.left.iter().map(caption).collect(), right: layout.right.iter().map(caption).collect() }, - None => CaptionLayout::default(), - } -} - -/// macOS and Windows: all three caption buttons at the right, whatever the probe says (see -/// [`custom_titlebar_from`]). -#[cfg(any(target_os = "macos", target_os = "windows"))] -pub(crate) fn caption_layout_from(_frame: &craft_window::Frame) -> vectorcraft_ui_egui::titlebar::CaptionLayout { - vectorcraft_ui_egui::titlebar::CaptionLayout::default() -} - -/// The `craft-window` probe's answer for this process (its override variable is -/// `VECTORCRAFT_TITLEBAR`). The probe runs once; on a Wayland session it opens a connection. -fn probed_choice() -> &'static craft_window::Choice { - static CHOICE: std::sync::OnceLock = std::sync::OnceLock::new(); - CHOICE.get_or_init(|| craft_window::Choice::probe(craft_window::Prefix::new("VECTORCRAFT"))) -} - -/// Whether `VECTORCRAFT_TITLEBAR` chose this window's frame (Linux and the BSDs), so Preferences › -/// User Interface › System Title Bar and VectorCraft Title Bar on Every Desktop do not apply while -/// it is set to `app`, `system` or `desktop`. Always `false` on macOS and Windows. -pub(crate) fn titlebar_from_env() -> bool { - cfg!(not(any(target_os = "macos", target_os = "windows"))) && probed_choice().overridden().is_some() -} - -/// Whether System Title Bar decides this start: `opted_into_system` unless `VECTORCRAFT_TITLEBAR` -/// is set to `app`, `system` or `desktop` (`from_env`), which chooses the frame for the run it is -/// set in. -pub(crate) fn system_title_bar_applies(opted_into_system: bool, from_env: bool) -> bool { - opted_into_system && !from_env -} - -/// Whether this start draws its own title bar, given the frame the shared `craft-window` crate -/// decided and the user's System Title Bar preference. -/// -/// The suite-wide rule (`craft_window::Choice`) is: the desktop draws the frame -/// ([`craft_window::Frame::Desktop`]) on macOS, Windows, X11 and any Wayland compositor with -/// server-side decorations (KDE, Sway, Hyprland, COSMIC); the app draws it -/// ([`craft_window::Frame::App`]) only where the compositor leaves it to the app (GNOME's Mutter), -/// or when `VECTORCRAFT_TITLEBAR` set to `app`, `system` or `desktop` overrides the probe. VectorCraft draws its own title bar exactly -/// when `craft-window` says the app owns the frame **and** the user has not opted into the system -/// title bar; the preference forces the native frame back on unless `VECTORCRAFT_TITLEBAR` is set -/// to one of those values ([`system_title_bar_applies`]). -/// -/// macOS and Windows keep today's behavior and are decided by [`CUSTOM_TITLEBAR`] rather than the -/// probe: `craft-window` returns `Frame::Desktop` for both (the OS always draws a frame), but -/// VectorCraft insets its content under the macOS traffic lights and draws its own caption buttons -/// on Windows — an overdraw on an OS-decorated window that is VectorCraft's choice, not -/// `craft-window`'s. Only Linux and the BSDs take the decision from the probe. -#[cfg(not(any(target_os = "macos", target_os = "windows")))] -pub(crate) fn custom_titlebar_from(frame: &craft_window::Frame, opted_into_system: bool) -> bool { - matches!(frame, craft_window::Frame::App(_)) && !opted_into_system -} - -/// macOS and Windows: today's behavior, independent of the `craft-window` probe (see -/// [`custom_titlebar_from`]). macOS never draws its own frame (`CUSTOM_TITLEBAR` is `false`); -/// Windows draws its own caption unless the user opted into the system title bar. -#[cfg(any(target_os = "macos", target_os = "windows"))] -pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_system: bool) -> bool { - CUSTOM_TITLEBAR && !opted_into_system -} - -/// Whether this start draws its own title bar, and where its caption buttons go -/// ([`caption_layout_from`]). Probes the shared `craft-window` crate once (its -/// override variable is `VECTORCRAFT_TITLEBAR`) and combines its decision with the saved System -/// Title Bar preference, which does not apply while the variable is set to `app`, `system` or -/// `desktop`. Call once at startup, -/// before [`native_options`]. -/// -/// On Linux, Preferences › Performance › Linux Display Server › X11 opens the window through -/// XWayland (below). A GNOME/Wayland probe would say `Frame::App` there, but the window really runs -/// on X11, whose window manager draws the frame — so when XWayland is being forced, keep the native -/// frame, the same as a real X11 session. A recognized `VECTORCRAFT_TITLEBAR` override still wins, -/// and so does VectorCraft Title Bar on Every Desktop ([`app_draws_frame`]). -pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> (bool, vectorcraft_ui_egui::titlebar::CaptionLayout) { - let choice = probed_choice(); - let opted_into_system = system_title_bar_applies(opted_into_system_title_bar(saved), titlebar_from_env()); - // macOS and Windows never read VectorCraft Title Bar on Every Desktop (`custom_titlebar_from` - // ignores the frame there). - let opted_into_app = cfg!(not(any(target_os = "macos", target_os = "windows"))) && opted_into_app_title_bar(saved); - #[cfg(target_os = "linux")] - // When the window will actually open on X11 (XWayland) — the user asked for it *and* the X11 - // libraries are present, the same two conditions the launch path checks below — that run is - // effectively X11, so keep the native frame. If the libraries are missing, startup stays on - // Wayland, so the probe's own decision (app-drawn on GNOME) must stand. - let forced_to_x11 = { - let pref = saved.and_then(|ui| ui.engine_prefs.get("linuxDisplayServer")).and_then(serde_json::Value::as_str); - xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) && xwayland::x11_libraries_found() - }; - #[cfg(not(target_os = "linux"))] - let forced_to_x11 = false; - let frame = start_frame(choice.frame().clone(), choice.overridden(), forced_to_x11, opted_into_app); - (custom_titlebar_from(&frame, opted_into_system), caption_layout_from(&frame)) -} - -/// Whether the desktop would draw this window's frame with System Title Bar on or off while -/// VectorCraft Title Bar on Every Desktop is off: `VECTORCRAFT_TITLEBAR` is not set to `app`, -/// `system` or `desktop` (`overridden` is `None`), and the probe chose -/// [`craft_window::Frame::Desktop`] or the window opens through XWayland (`forced_to_x11`) -/// ([`app_draws_frame`]). The saved VectorCraft Title Bar on Every Desktop is left out, so the value -/// stays `true` on such a desktop while that preference gives the app the frame. Always `false` on -/// macOS and Windows, where System Title Bar decides the frame by itself. -pub(crate) fn desktop_keeps_frame_from(probed: &craft_window::Frame, overridden: Option, forced_to_x11: bool) -> bool { - let probed_app = matches!(probed, craft_window::Frame::App(_)); - cfg!(not(any(target_os = "macos", target_os = "windows"))) && overridden.is_none() && !app_draws_frame(probed_app, None, forced_to_x11, false) -} - -/// [`desktop_keeps_frame_from`] for this start's probe, given whether the launch path opens the -/// window through XWayland. -pub(crate) fn desktop_keeps_frame(forced_to_x11: bool) -> bool { - let choice = probed_choice(); - desktop_keeps_frame_from(choice.frame(), choice.overridden(), forced_to_x11) -} - -pub(crate) fn native_options(custom_titlebar: bool) -> eframe::NativeOptions { - eframe::NativeOptions { - viewport: egui::ViewportBuilder::default() - .with_title("VectorCraft") - .with_inner_size(window::DEFAULT_SIZE) - .with_min_inner_size(window::MIN_SIZE) - .with_drag_and_drop(true) - .with_decorations(!custom_titlebar) - .with_fullsize_content_view(true) - .with_titlebar_shown(false) - .with_title_shown(false) - .with_icon(app_icon()) - .with_app_id("ai.storyteller.vectorcraft"), - ..Default::default() - } -} diff --git a/apps/vectorcraft/src/window.rs b/apps/vectorcraft/src/window.rs deleted file mode 100644 index e36add3d08..0000000000 --- a/apps/vectorcraft/src/window.rs +++ /dev/null @@ -1,603 +0,0 @@ -//! The main window's size and position. The first launch fits the window to its monitor, opening -//! it maximized where the default size leaves no room for a taskbar or Dock. Later launches restore -//! the size, position and maximized state saved with the UI preferences (`UiState::window`), moved -//! onto a monitor that is still connected. - -use vectorcraft_ui_egui::DockMonitor; -use vectorcraft_ui_egui::state::WindowGeometry; -use winit::dpi::{LogicalSize, PhysicalPosition, PhysicalSize}; - -/// The first window's size, in points. -pub const DEFAULT_SIZE: [f32; 2] = [1440.0, 900.0]; -/// The smallest window, in points. -pub const MIN_SIZE: [f32; 2] = [800.0, 500.0]; -/// Room the first window leaves around itself for a taskbar, Dock or menu bar when it decides -/// whether to open maximized: a monitor with less room opens it maximized. This check uses the -/// fixed allowance on every platform, including where the system reports a work area. -const SCREEN_ROOM: [f32; 2] = [64.0, 128.0]; - -/// Seconds between readings of the monitor list, which picks up a monitor connected while the app runs. -const MONITORS_EVERY: f64 = 1.0; - -/// A monitor: its top-left corner and size in physical pixels, its scale factor, and the part -/// windows may use where the system reports one. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct Monitor { - pos: [i64; 2], - size: [i64; 2], - scale: f32, - /// `[x, y, width, height]` in physical pixels, without the taskbar, Dock or menu bar. - work: Option<[i64; 4]>, -} - -/// A monitor's rect and its work area as the system lists them, `[x, y, width, height]` in -/// physical pixels. Only Windows and macOS list them. -#[derive(Clone, Copy, Debug, PartialEq)] -#[cfg_attr(not(any(all(windows, feature = "wgpu"), target_os = "macos")), allow(dead_code))] -pub struct WorkArea { - monitor: [i64; 4], - work: [i64; 4], -} - -impl Monitor { - pub fn new(pos: PhysicalPosition, size: PhysicalSize, scale: f64) -> Self { - let scale = scale as f32; - let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 }; - Self { pos: [pos.x.into(), pos.y.into()], size: [size.width.into(), size.height.into()], scale, work: None } - } - - /// This monitor with the work area of the entry in `areas` whose monitor rect matches its own, - /// to the pixel either way to allow for rounding. Without a match, or when the matching work - /// area has no width or height, it has none. - fn with_work_area(self, areas: &[WorkArea]) -> Self { - let [x, y] = self.pos; - let [w, h] = self.size; - let rect = [x, y, w, h]; - let work = - areas.iter().find(|a| a.monitor.iter().zip(rect).all(|(a, b)| a.abs_diff(b) <= 1)).map(|a| a.work).filter(|&[_, _, w, h]| w > 0 && h > 0); - Self { work, ..self } - } - - /// Its size in points. - fn points(&self) -> [f32; 2] { - self.size.map(|s| s as f32 / self.scale) - } - - /// This monitor with its work area made smaller by a window frame of `frame` physical pixels - /// (outer size less inner size), so a window whose inner size fits the result fits the work area - /// with its frame. - fn less_frame(self, frame: [i64; 2]) -> Self { - let work = self.work.map(|[x, y, w, h]| [x, y, (w - frame[0].max(0)).max(1), (h - frame[1].max(0)).max(1)]); - Self { work, ..self } - } - - /// The size of its work area in points, or of the whole monitor when it has none. - fn work_points(&self) -> [f32; 2] { - self.work.map_or_else(|| self.points(), |[_, _, w, h]| [w, h].map(|s| s as f32 / self.scale)) - } - - /// Its size in points less room for a taskbar, Dock or menu bar. - fn usable(&self) -> [f32; 2] { - let points = self.points(); - std::array::from_fn(|i| points[i] - SCREEN_ROOM[i]) - } - - /// A window of `size` points on this monitor, in physical pixels. - fn pixels(&self, size: [f32; 2]) -> [i64; 2] { - size.map(|s| (s * self.scale) as i64) - } - - /// How much of a window at `pos` of `size` points this monitor shows, in square pixels. - fn overlap(&self, pos: [i32; 2], size: [f32; 2]) -> i64 { - let px = self.pixels(size); - let span = |i: usize| { - let start = i64::from(pos[i]).max(self.pos[i]); - let end = i64::from(pos[i]).saturating_add(px[i]).min(self.pos[i] + self.size[i]); - (end - start).max(0) - }; - span(0).saturating_mul(span(1)) - } - - /// The top-left corner nearest to `pos` (centred when none) that keeps a window of `size` - /// points on this monitor, inside its work area when it has one. A window bigger than the area - /// gets the area's top-left corner. - fn keep_on(&self, pos: Option<[i32; 2]>, size: [f32; 2]) -> [i32; 2] { - let px = self.pixels(size); - let [x, y] = self.pos; - let [w, h] = self.size; - let [ax, ay, aw, ah] = self.work.unwrap_or([x, y, w, h]); - let (start, extent) = ([ax, ay], [aw, ah]); - std::array::from_fn(|i| { - let lo = start[i]; - let hi = lo + extent[i].saturating_sub(px[i]).max(0); - let want = pos.map_or(lo + (hi - lo) / 2, |p| i64::from(p[i])); - i32::try_from(want.max(lo).min(hi)).unwrap_or_default() - }) - } - - /// This monitor for floating panels, in the points egui reports for a window on it: physical - /// pixels divided by the monitor's scale factor and the UI zoom. The work area is converted the - /// same way. - fn docking(&self, name: Option, zoom: f32) -> DockMonitor { - let scale = self.scale * zoom; - let [x, y] = self.pos; - let [w, h] = self.size; - let points = |rect: [i64; 4]| rect.map(|v| v as f32 / scale); - DockMonitor { name, rect: points([x, y, w, h]), scale, work_area: self.work.map(points) } - } -} - -/// Where the window opens: `saved` (the last session's geometry) kept on a connected monitor, else -/// the default size on `home` (the monitor the system opens it on). Without monitors (the system -/// doesn't list them, so nothing to check a saved geometry against) the default size. -pub fn place(saved: Option, monitors: &[Monitor], home: Option) -> WindowGeometry { - let default = WindowGeometry { pos: None, size: DEFAULT_SIZE, maximized: false }; - let Some(home) = home.and_then(|i| monitors.get(i)).or(monitors.first()) else { - return default; - }; - let Some(saved) = saved else { - let usable = home.usable(); - if (0..2).all(|i| DEFAULT_SIZE[i] <= usable[i]) { - return default; - } - // A small screen: maximized, with a size that fits once un-maximized. - let size = fit(DEFAULT_SIZE, usable); - return WindowGeometry { pos: Some(home.keep_on(None, size)), size, maximized: true }; - }; - // The monitor showing most of the window; none when it was on a monitor that is gone. - let shown = saved.pos.and_then(|p| { - let (area, m) = monitors.iter().map(|m| (m.overlap(p, saved.size), m)).max_by_key(|(area, _)| *area)?; - (area > 0).then_some(m) - }); - let m = shown.unwrap_or(home); - // Bigger than its monitor (a smaller screen than last time): maximized, like the first window. - let room = m.points(); - let too_big = (0..2).any(|i| saved.size[i] > room[i]); - // No bigger than the work area either, so the window fits below or beside the taskbar. - let work = m.work_points(); - let room = if too_big { m.usable() } else { room }; - let size = fit(saved.size, std::array::from_fn(|i| room[i].min(work[i]))); - WindowGeometry { - // Moved fully onto its monitor, or centred on the home monitor. - pos: saved.pos.map(|p| m.keep_on(shown.map(|_| p), size)), - size, - maximized: saved.maximized || too_big, - } -} - -/// `size` no bigger than `room`, and no smaller than the smallest window unless `room` is. -fn fit(size: [f32; 2], room: [f32; 2]) -> [f32; 2] { - std::array::from_fn(|i| size[i].min(room[i]).max(MIN_SIZE[i].min(room[i])).max(1.0)) -} - -/// The smallest size a window of `size` points may take: [`MIN_SIZE`], lowered to `size` in each -/// dimension where [`fit`] made the window smaller than that to fit a small work area. -fn min_size(size: [f32; 2]) -> [f32; 2] { - std::array::from_fn(|i| MIN_SIZE[i].min(size[i])) -} - -/// Whether to list the monitors again: on the first frame, when the UI zoom changed, and at most -/// every [`MONITORS_EVERY`] seconds while the app draws. `listed` holds the last list's time and zoom. -pub fn monitors_due(listed: Option<(f64, f32)>, now: f64, zoom: f32) -> bool { - listed.is_none_or(|(at, listed_zoom)| listed_zoom != zoom || now - at >= MONITORS_EVERY) -} - -/// The connected monitors for floating panels (`Services::dock_monitors`), with the work area the -/// system reports for each (Windows and macOS). -pub fn dock_monitors(window: &winit::window::Window, zoom: f32) -> Vec { - let areas = work_areas::list(); - let monitors: Vec<_> = - window.available_monitors().map(|m| (Monitor::new(m.position(), m.size(), m.scale_factor()).with_work_area(&areas), m.name())).collect(); - docking_list(&monitors, zoom, cfg!(target_os = "macos")) -} - -/// A rect in macOS screen coordinates (points, origin at the bottom-left of the primary screen, -/// y up) in the physical pixels winit gives a monitor's position and size: points from the top-left -/// of the primary screen, `primary_height` points tall, times `scale`. -#[cfg(any(target_os = "macos", test))] -fn from_bottom_left([x, y, w, h]: [f64; 4], primary_height: f64, scale: f64) -> Option<[i64; 4]> { - let rect = [x, primary_height - (y + h), w, h].map(|v| (v * scale).round()); - // `as` saturates; a coordinate of 1e12 pixels or more is not a monitor's. - rect.iter().all(|v| v.is_finite() && v.abs() < 1e12).then(|| rect.map(|v| v as i64)) -} - -/// Each monitor's rect and work area as the system reports them. -mod work_areas { - pub use platform::list; - - /// `GetMonitorInfo` for every monitor: `rcMonitor` and `rcWork`, in the physical pixels winit - /// reports for a per-monitor DPI aware process. - #[cfg(all(windows, feature = "wgpu"))] - mod platform { - use super::super::WorkArea; - use winsafe::prelude::Handle; - use winsafe::{HDC, RECT}; - - pub fn list() -> Vec { - let rect = |r: RECT| { - let [left, top, right, bottom] = [r.left, r.top, r.right, r.bottom].map(i64::from); - [left, top, right - left, bottom - top] - }; - let mut areas = Vec::new(); - // Without a list the panels keep to the monitors' whole rects, as before. - let _ = HDC::NULL.EnumDisplayMonitors(None, |monitor, _, _| { - if let Ok(info) = monitor.GetMonitorInfo() { - areas.push(WorkArea { monitor: rect(info.rcMonitor), work: rect(info.rcWork) }); - } - true - }); - areas - } - } - - /// `NSScreen`'s `frame` and `visibleFrame` for every screen, turned into the top-left origin - /// and physical pixels winit uses for its monitors. - #[cfg(target_os = "macos")] - mod platform { - use super::super::{WorkArea, from_bottom_left}; - use objc2_app_kit::NSScreen; - use objc2_foundation::{MainThreadMarker, NSRect}; - - pub fn list() -> Vec { - // `NSScreen::screens` needs the main thread, where the UI frame runs. - let Some(mtm) = MainThreadMarker::new() else { - return Vec::new(); - }; - let screens: Vec<_> = NSScreen::screens(mtm).iter().collect(); - // The first screen holds the menu bar and is the origin of the screen coordinates. - let Some(primary) = screens.first().map(|s| s.frame().size.height) else { - return Vec::new(); - }; - let rect = |r: NSRect| [r.origin.x, r.origin.y, r.size.width, r.size.height]; - screens - .iter() - .filter_map(|s| { - let scale = s.backingScaleFactor(); - let monitor = from_bottom_left(rect(s.frame()), primary, scale)?; - let work = from_bottom_left(rect(s.visibleFrame()), primary, scale)?; - Some(WorkArea { monitor, work }) - }) - .collect() - } - } - - /// No work areas: the panels keep to the monitors' whole rects. - #[cfg(not(any(all(windows, feature = "wgpu"), target_os = "macos")))] - mod platform { - pub fn list() -> Vec { - Vec::new() - } - } -} - -/// The list for floating panels, empty when `monitors` have different scales and `shared_points` is -/// false. macOS has one desktop of points. Elsewhere a new window multiplies its saved position by the -/// scale of the monitor it is created on, which can put a window saved on another scale off every -/// monitor. With an empty list craft-ui opens the window on the main window's monitor. -/// -/// A name that two monitors share is left out, so craft-ui finds those monitors by their rects: macOS -/// can give two displays of one model the same name. -fn docking_list(monitors: &[(Monitor, Option)], zoom: f32, shared_points: bool) -> Vec { - if !shared_points && monitors.windows(2).any(|pair| pair[0].0.scale != pair[1].0.scale) { - return Vec::new(); - } - let unique = |name: &String| monitors.iter().filter(|(_, other)| other.as_ref() == Some(name)).count() == 1; - monitors.iter().map(|(monitor, name)| monitor.docking(name.clone().filter(unique), zoom)).collect() -} - -/// Size and place the new window (eframe shows it after drawing the first frame) and return its -/// geometry. On Linux the window may not be mapped yet, so [`apply_pending_maximize`] must run -/// until the host reports maximized (fixes #3635). -pub fn restore(window: &winit::window::Window, saved: Option) -> WindowGeometry { - let handles: Vec<_> = window.available_monitors().collect(); - let areas = work_areas::list(); - // The system title bar and border, which the inner size leaves out, in points: each monitor - // draws them at its own scale. - let (outer, inner, scale) = (window.outer_size(), window.inner_size(), window.scale_factor()); - let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 }; - let frame = [outer.width.saturating_sub(inner.width), outer.height.saturating_sub(inner.height)].map(|px| f64::from(px) / scale); - let monitors: Vec = handles - .iter() - .map(|m| { - let px = frame.map(|f| (f * m.scale_factor()).ceil().min(1e6) as i64); - Monitor::new(m.position(), m.size(), m.scale_factor()).with_work_area(&areas).less_frame(px) - }) - .collect(); - let home = window.current_monitor().or_else(|| window.primary_monitor()).and_then(|c| handles.iter().position(|m| *m == c)); - let g = place(saved, &monitors, home); - if let Some([x, y]) = g.pos { - window.set_outer_position(PhysicalPosition::new(x, y)); - } - // The native minimum (`MIN_SIZE`, set in `native_options`) would keep the window bigger than a - // size fitted to a small work area, so it is lowered to that size first. - let min = min_size(g.size); - if min != MIN_SIZE { - window.set_min_inner_size(Some(LogicalSize::new(min[0], min[1]))); - } - // Returns the new size when it applies at once; either way the window gets it. - let _ = window.request_inner_size(LogicalSize::new(g.size[0], g.size[1])); - #[cfg(not(target_os = "linux"))] - if g.maximized { - window.set_maximized(true); - } - g -} - -/// Keep asking the host to maximize until it sticks, or give up after a few frames. -pub fn apply_pending_maximize(window: &winit::window::Window, want: bool, tries: &mut u8) -> bool { - if !want { - return false; - } - if window.is_maximized() { - return false; - } - if *tries == 0 { - return false; - } - *tries -= 1; - window.set_maximized(true); - true -} - -/// Per frame: remember the window's geometry for the next launch. Minimized or full screen keeps -/// the last one; maximized only sets its flag, so un-maximizing next time restores the last size. -/// `host_maximized` is the window manager's idea of maximized when egui does not report it (#3635). -pub fn track(ctx: &egui::Context, geometry: &mut Option, host_maximized: Option) { - let zoom = ctx.zoom_factor(); - ctx.input(|i| { - let v = i.viewport(); - if v.minimized == Some(true) || v.fullscreen == Some(true) { - return; - } - let maximized = v.maximized == Some(true) || host_maximized == Some(true); - if maximized { - if let Some(g) = geometry { - g.maximized = true; - } - return; - } - let Some(inner) = v.inner_rect else { return }; - let pos = v.outer_rect.map(|r| [r.min.x, r.min.y].map(|c| (c * i.pixels_per_point).round() as i32)); - *geometry = Some(WindowGeometry { pos, size: [inner.width() * zoom, inner.height() * zoom], maximized: false }); - }); -} - -#[cfg(test)] -mod tests { - use super::*; - - fn monitor(x: i32, y: i32, w: u32, h: u32, scale: f64) -> Monitor { - Monitor::new(PhysicalPosition::new(x, y), PhysicalSize::new(w, h), scale) - } - - fn saved(pos: Option<[i32; 2]>, size: [f32; 2], maximized: bool) -> Option { - Some(WindowGeometry { pos, size, maximized }) - } - - #[test] - fn the_first_window_fits_its_screen() { - // 1920 × 1080: the default size, where the system puts it. - let big = [monitor(0, 0, 1920, 1080, 1.0)]; - assert_eq!(place(None, &big, Some(0)), WindowGeometry { pos: None, size: DEFAULT_SIZE, maximized: false }); - // 1600 × 900, 1366 × 768 and 1920 × 1080 at 150% (1280 × 720 points): maximized, and a - // size that fits the screen with room for the taskbar once un-maximized. - for (m, size) in [ - (monitor(0, 0, 1600, 900, 1.0), [1440.0, 772.0]), - (monitor(0, 0, 1366, 768, 1.0), [1302.0, 640.0]), - (monitor(0, 0, 1920, 1080, 1.5), [1216.0, 592.0]), - ] { - let g = place(None, &[m], Some(0)); - assert!(g.maximized, "{m:?}"); - assert_eq!(g.size, size, "{m:?}"); - let [x, y] = g.pos.unwrap(); - let px = m.pixels(g.size); - assert!(x >= 0 && y >= 0 && i64::from(x) + px[0] <= m.size[0] && i64::from(y) + px[1] <= m.size[1], "{m:?}: {g:?}"); - } - // No monitor information: the default size, whatever was saved. - assert_eq!(place(None, &[], None), WindowGeometry { pos: None, size: DEFAULT_SIZE, maximized: false }); - assert_eq!(place(saved(Some([9000, 9000]), [1e9, 1e9], true), &[], None).size, DEFAULT_SIZE); - } - - #[test] - fn floating_panels_get_monitors_in_the_points_a_window_on_them_reports() { - let dock = |m: Monitor, zoom| m.docking(Some("m".into()), zoom); - let plain = dock(monitor(1920, 0, 1920, 1080, 1.0), 1.0); - assert_eq!(plain, DockMonitor { name: Some("m".into()), rect: [1920.0, 0.0, 1920.0, 1080.0], scale: 1.0, work_area: None }); - // A window at (3000, 200) on this monitor reports (1500, 100). - let scaled = dock(monitor(1920, -200, 3840, 2160, 2.0), 1.0); - assert_eq!(scaled, DockMonitor { name: Some("m".into()), rect: [960.0, -100.0, 1920.0, 1080.0], scale: 2.0, work_area: None }); - // The UI zoom divides what egui reports as well. - let zoomed = dock(monitor(-2560, 0, 2560, 1440, 1.0), 1.25); - assert_eq!(zoomed, DockMonitor { name: Some("m".into()), rect: [-2048.0, 0.0, 2048.0, 1152.0], scale: 1.25, work_area: None }); - } - - #[test] - fn floating_panels_get_each_monitors_work_area_in_the_same_points() { - // A 4K monitor at 200% with a 96-pixel taskbar along its bottom, and one at 100% to its - // right with a 48-pixel taskbar along its left edge. - let areas = [ - WorkArea { monitor: [0, 0, 3840, 2160], work: [0, 0, 3840, 2064] }, - WorkArea { monitor: [3840, 0, 1920, 1080], work: [3888, 0, 1872, 1080] }, - ]; - let left = monitor(0, 0, 3840, 2160, 2.0).with_work_area(&areas); - assert_eq!(left.docking(None, 1.0).work_area, Some([0.0, 0.0, 1920.0, 1032.0])); - // The UI zoom divides the work area as it divides the rect. - assert_eq!(left.docking(None, 1.25).work_area, Some([0.0, 0.0, 1536.0, 825.6])); - // Rounding of a fractional scale can move a rect by a pixel. - let right = monitor(3841, 0, 1919, 1080, 1.0).with_work_area(&areas); - assert_eq!(right.docking(None, 1.0).work_area, Some([3888.0, 0.0, 1872.0, 1080.0])); - // A monitor the system did not list keeps to its whole rect. - let other = monitor(5760, 0, 1920, 1080, 1.0).with_work_area(&areas); - assert_eq!(other.docking(None, 1.0).work_area, None); - assert_eq!(monitor(0, 0, 3840, 2160, 2.0).with_work_area(&[]).docking(None, 1.0).work_area, None); - // A work area with no height is left out, so the monitor keeps to its whole rect. - let flat = [WorkArea { monitor: [0, 0, 1920, 1080], work: [0, 1080, 1920, 0] }]; - assert_eq!(monitor(0, 0, 1920, 1080, 1.0).with_work_area(&flat).docking(None, 1.0).work_area, None); - } - - #[test] - fn a_restored_window_keeps_its_title_bar_out_of_a_taskbar_along_the_top() { - // A 1920 × 1080 monitor with a 48-pixel taskbar along its top edge. - let areas = [WorkArea { monitor: [0, 0, 1920, 1080], work: [0, 48, 1920, 1032] }]; - let m = [monitor(0, 0, 1920, 1080, 1.0).with_work_area(&areas)]; - // A window saved at the top edge moves down below the taskbar. - let g = place(saved(Some([100, 0]), [1000.0, 700.0], false), &m, Some(0)); - assert_eq!(g.pos, Some([100, 48])); - // A window that fits below the taskbar keeps its place. - assert_eq!(place(saved(Some([100, 200]), [1000.0, 700.0], false), &m, Some(0)).pos, Some([100, 200])); - // A window taller than the work area is made as tall as the work area and placed in it. - let tall = place(saved(Some([0, 0]), [1900.0, 1060.0], false), &m, Some(0)); - assert_eq!((tall.pos, tall.size), (Some([0, 48]), [1900.0, 1032.0])); - // With a system frame of 16 × 39 pixels the inner size leaves room for it. - let framed = [m[0].less_frame([16, 39])]; - let tall = place(saved(Some([0, 0]), [1900.0, 1060.0], false), &framed, Some(0)); - assert_eq!((tall.pos, tall.size), (Some([0, 48]), [1900.0, 993.0])); - // Without a work area the frame leaves the monitor's rect as it was. - assert_eq!(monitor(0, 0, 1920, 1080, 1.0).less_frame([16, 39]).work, None); - } - - #[test] - fn a_window_fitted_below_the_smallest_size_lowers_the_minimum_to_its_size() { - // 1366 × 768 at 150% with a 48-pixel taskbar along the bottom: a work area 480 points high. - let areas = [WorkArea { monitor: [0, 0, 1366, 768], work: [0, 0, 1366, 720] }]; - let m = [monitor(0, 0, 1366, 768, 1.5).with_work_area(&areas)]; - let g = place(saved(Some([0, 0]), [900.0, 500.0], false), &m, Some(0)); - assert_eq!(g.size, [900.0, 480.0]); - // The minimum height drops to the fitted 480 points; the width keeps the normal minimum. - assert_eq!(min_size(g.size), [800.0, 480.0]); - // A window with room for the smallest size keeps the normal minimum. - let big = [monitor(0, 0, 1920, 1080, 1.0)]; - assert_eq!(min_size(place(saved(Some([0, 0]), [1000.0, 700.0], false), &big, Some(0)).size), MIN_SIZE); - assert_eq!(min_size([1.0, 1.0]), [1.0, 1.0]); - } - - #[test] - fn macos_screen_rects_turn_into_winits_top_left_pixels() { - // A 1512 × 982 point primary screen at 2× with a 37-point menu bar and an 80-point Dock, - // and a 1920 × 1080 screen at 1× above it, its bottom-left 200 points right of the - // primary's top-left. - let primary = 982.0; - assert_eq!(from_bottom_left([0.0, 0.0, 1512.0, 982.0], primary, 2.0), Some([0, 0, 3024, 1964])); - assert_eq!(from_bottom_left([0.0, 80.0, 1512.0, 865.0], primary, 2.0), Some([0, 74, 3024, 1730])); - assert_eq!(from_bottom_left([200.0, 982.0, 1920.0, 1080.0], primary, 1.0), Some([200, -1080, 1920, 1080])); - assert_eq!(from_bottom_left([f64::NAN, 0.0, 1.0, 1.0], primary, 1.0), None); - assert_eq!(from_bottom_left([0.0, 0.0, 1e300, 1.0], primary, 1.0), None); - } - - #[test] - fn monitors_of_different_scales_are_listed_only_on_a_desktop_of_shared_points() { - let named = |m: Monitor, name: &str| (m, Some(name.to_string())); - let same = [named(monitor(0, 0, 1920, 1080, 1.5), "a"), named(monitor(1920, 0, 1920, 1080, 1.5), "b")]; - assert_eq!(docking_list(&same, 1.0, false).len(), 2); - let mixed = [named(monitor(0, 0, 3840, 2160, 2.0), "a"), named(monitor(3840, 0, 1920, 1080, 1.0), "b")]; - assert_eq!(docking_list(&mixed, 1.0, false), Vec::new()); - assert_eq!(docking_list(&mixed, 1.0, true).len(), 2); - assert_eq!(docking_list(&[], 1.0, false), Vec::new()); - } - - #[test] - fn a_name_that_two_monitors_share_is_left_out_of_the_list() { - let list = [ - (monitor(0, 0, 1920, 1080, 1.0), Some("Monitor #1".to_string())), - (monitor(1920, 0, 1920, 1080, 1.0), Some("Monitor #1".to_string())), - (monitor(3840, 0, 1920, 1080, 1.0), Some("Monitor #2".to_string())), - (monitor(5760, 0, 1920, 1080, 1.0), None), - ]; - let names: Vec<_> = docking_list(&list, 1.0, false).into_iter().map(|m| m.name).collect(); - assert_eq!(names, [None, None, Some("Monitor #2".to_string()), None]); - } - - #[test] - fn the_monitor_list_is_read_on_the_first_frame_then_once_a_second_or_on_a_zoom_change() { - assert!(monitors_due(None, 0.0, 1.0)); - assert!(!monitors_due(Some((5.0, 1.0)), 5.0, 1.0)); - assert!(!monitors_due(Some((5.0, 1.0)), 5.5, 1.0)); - assert!(monitors_due(Some((5.0, 1.0)), 6.0, 1.0)); - assert!(monitors_due(Some((5.0, 1.0)), 5.5, 1.25)); - } - - #[test] - fn the_saved_window_comes_back_where_it_was() { - let two = [monitor(0, 0, 2560, 1440, 1.0), monitor(2560, 0, 1920, 1080, 1.0)]; - for g in [saved(Some([100, 80]), [1200.0, 800.0], false), saved(Some([2700, 50]), [1000.0, 700.0], true), saved(None, [1000.0, 700.0], false)] - { - assert_eq!(Some(place(g, &two, Some(0))), g); - } - } - - #[test] - fn a_saved_window_stays_on_a_connected_monitor() { - let laptop = [monitor(0, 0, 1600, 900, 1.0)]; - // Last time on a second monitor that is gone: centred on the remaining one. - let g = place(saved(Some([2700, 50]), [1000.0, 700.0], false), &laptop, Some(0)); - assert_eq!(g, WindowGeometry { pos: Some([300, 100]), size: [1000.0, 700.0], maximized: false }); - // Half off the monitor's right and bottom edges: moved fully onto it. - let g = place(saved(Some([1200, 600]), [1000.0, 700.0], false), &laptop, Some(0)); - assert_eq!(g.pos, Some([600, 200])); - // Bigger than the screen now (it was on a larger one): it fits, and opens maximized. - let g = place(saved(Some([0, 0]), [2400.0, 1300.0], false), &laptop, Some(0)); - assert_eq!(g, WindowGeometry { pos: Some([0, 0]), size: [1536.0, 772.0], maximized: true }); - // A monitor left of the primary one (negative coordinates) still counts. - let left = [monitor(0, 0, 1920, 1080, 1.0), monitor(-1920, 0, 1920, 1080, 1.0)]; - assert_eq!(place(saved(Some([-1800, 40]), [1000.0, 700.0], false), &left, Some(0)).pos, Some([-1800, 40])); - // Nonsense sizes from a damaged preferences file are kept within the screen. - let g = place(saved(Some([i32::MAX, i32::MIN]), [-5.0, f32::MAX], false), &laptop, Some(0)); - assert_eq!(g, WindowGeometry { pos: Some([400, 64]), size: [800.0, 772.0], maximized: true }); - let g = place(saved(Some([5, 5]), [f32::NEG_INFINITY, f32::INFINITY], false), &laptop, Some(0)); - assert_eq!(g, WindowGeometry { pos: Some([400, 64]), size: [800.0, 772.0], maximized: true }); - } - - #[test] - fn the_window_geometry_is_tracked_for_the_next_launch() { - let ctx = egui::Context::default(); - let mut geometry = None; - let mut frame = |info: egui::ViewportInfo| { - let mut input = egui::RawInput::default(); - input.viewports.insert(egui::ViewportId::ROOT, info); - ctx.run_ui(input, |ui| track(ui.ctx(), &mut geometry, None)).textures_delta.clear(); - geometry - }; - let rect = egui::Rect::from_min_size(egui::pos2(20.0, 30.0), egui::vec2(1000.0, 600.0)); - let normal = egui::ViewportInfo { - native_pixels_per_point: Some(1.5), - inner_rect: Some(rect), - outer_rect: Some(rect), - maximized: Some(false), - ..Default::default() - }; - // Position in physical pixels, size in points. - let g = WindowGeometry { pos: Some([30, 45]), size: [1000.0, 600.0], maximized: false }; - assert_eq!(frame(normal.clone()), Some(g)); - // Maximized or minimized: the size to restore stays. - let big = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 700.0)); - let maximized = egui::ViewportInfo { inner_rect: Some(big), outer_rect: Some(big), maximized: Some(true), ..normal.clone() }; - assert_eq!(frame(maximized), Some(WindowGeometry { maximized: true, ..g })); - let minimized = egui::ViewportInfo { inner_rect: None, outer_rect: None, minimized: Some(true), ..normal.clone() }; - assert_eq!(frame(minimized), Some(WindowGeometry { maximized: true, ..g })); - assert_eq!(frame(normal), Some(g)); - // Saved with the preferences; older preference files have no window. - let mut ui = vectorcraft_ui_egui::UiState { window: Some(g), ..Default::default() }; - let back: vectorcraft_ui_egui::UiState = serde_json::from_slice(&serde_json::to_vec(&ui).unwrap()).unwrap(); - assert_eq!(back.window, Some(g)); - ui.window = None; - let json = serde_json::to_value(&ui).unwrap(); - assert!(json.get("window").is_none()); - let back: vectorcraft_ui_egui::UiState = serde_json::from_value(json).unwrap(); - assert_eq!(back.window, None); - } - - #[test] - fn the_host_maximized_flag_is_remembered_when_egui_does_not_report_it() { - let ctx = egui::Context::default(); - let mut geometry = Some(WindowGeometry { pos: Some([10, 20]), size: [800.0, 600.0], maximized: false }); - let rect = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(1920.0, 1080.0)); - let mut input = egui::RawInput::default(); - input.viewports.insert( - egui::ViewportId::ROOT, - egui::ViewportInfo { inner_rect: Some(rect), outer_rect: Some(rect), maximized: None, ..Default::default() }, - ); - let mut out = ctx.run_ui(input, |ui| track(ui.ctx(), &mut geometry, Some(true))); - out.textures_delta.clear(); - assert_eq!(geometry, Some(WindowGeometry { pos: Some([10, 20]), size: [800.0, 600.0], maximized: true })); - } -} diff --git a/apps/vectorcraft/src/windows_screen_color.rs b/apps/vectorcraft/src/windows_screen_color.rs deleted file mode 100644 index 56ea45eb7d..0000000000 --- a/apps/vectorcraft/src/windows_screen_color.rs +++ /dev/null @@ -1,655 +0,0 @@ -//! Windows: Sample Color from Screen (`vectorcraft_ui_egui::screen_color`). Windows has no system -//! color sampler, so a thread of its own copies the virtual screen, the bounding rectangle of all -//! the monitors (), -//! into a bitmap with `BitBlt` from the screen's device context -//! (), then covers -//! the virtual screen with a borderless topmost window that shows that copy under a crosshair -//! cursor. The window has its own message loop on that thread, so the UI keeps drawing. -//! -//! A left click answers the copied pixel under the pointer as sRGB; Escape, a click of any other -//! button, closing the window, and the window losing the keyboard focus or the mouse capture answer -//! `None`. Each -//! click is answered when its button is released, so the release does not reach the window -//! underneath. The color comes from the copy taken before the window was shown, so the window -//! never samples itself, and moving content shows the frame it had when the copy was taken. -//! -//! The pixels are 8-bit GDI colors, read as sRGB: GDI content is taken to be sRGB when the display -//! does not use Advanced Color -//! (). The colors -//! of HDR and wide-gamut displays are not converted. -//! -//! winit makes the process per-monitor DPI aware, so the virtual screen, the pointer and the copy -//! are in physical pixels on every monitor, whatever its scale, and a monitor left of or above the -//! main one has negative coordinates -//! (). -//! -//! The Win32 calls have no safe binding; [`overlay`] allows `unsafe_code`. -#![cfg_attr(not(windows), allow(dead_code))] - -/// The status message for every failure; the details go to the log. -const FAILED: &str = "the screen color sampler failed"; - -/// The largest copy of the virtual screen, in bytes of 32-bit pixels: 1 GiB, eight 7680 × 4320 -/// monitors. VectorCraft's own limit. -const MAX_SNAPSHOT_BYTES: u64 = 1 << 30; - -/// `CLR_INVALID` (`wingdi.h`): what `GetPixel` answers for a pixel it can't read. -const CLR_INVALID: u32 = 0xFFFF_FFFF; - -/// The virtual screen in physical pixels: its top-left corner (negative when a monitor is left of -/// or above the main one) and its size. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct VirtualScreen { - left: i32, - top: i32, - width: i32, - height: i32, -} - -impl VirtualScreen { - /// The virtual screen `GetSystemMetrics` reports, checked before any memory is taken for its - /// copy: an error when it is empty, larger than [`MAX_SNAPSHOT_BYTES`], or reaches past the - /// coordinates Windows can address. - fn new(left: i32, top: i32, width: i32, height: i32) -> Result { - if width <= 0 || height <= 0 { - return Err(format!("the virtual screen is {width} × {height} pixels")); - } - let bytes = u64::from(width.unsigned_abs()).saturating_mul(u64::from(height.unsigned_abs())).saturating_mul(4); - if bytes > MAX_SNAPSHOT_BYTES { - return Err(format!("the virtual screen ({width} × {height} pixels) is larger than the {MAX_SNAPSHOT_BYTES}-byte limit")); - } - if left.checked_add(width).is_none() || top.checked_add(height).is_none() { - return Err(format!("the virtual screen at ({left}, {top}) reaches past the coordinate range")); - } - Ok(Self { left, top, width, height }) - } - - /// The pixel of the copy at the screen point (`x`, `y`), or `None` when the point is outside the - /// virtual screen. - fn pixel(&self, x: i32, y: i32) -> Option<(i32, i32)> { - let (px, py) = (x.checked_sub(self.left)?, y.checked_sub(self.top)?); - ((0..self.width).contains(&px) && (0..self.height).contains(&py)).then_some((px, py)) - } -} - -/// The sRGB components (0 to 1) of a `COLORREF` (`0x00bbggrr`), or `None` for `CLR_INVALID` or any -/// other value with its high byte set. -fn srgb(colorref: u32) -> Option<[f32; 3]> { - if colorref == CLR_INVALID { - return None; - } - let [r, g, b, high] = colorref.to_le_bytes(); - (high == 0).then(|| [r, g, b].map(|v| f32::from(v) / 255.0)) -} - -/// The client point of a mouse message. Its `lParam` holds each coordinate as a signed 16-bit -/// value (`GET_X_LPARAM` and `GET_Y_LPARAM`, -/// ), so a coordinate past -/// 32,767 pixels in a wide virtual screen loses its high bits. Each coordinate becomes the value -/// with the same low 16 bits nearest to `near`, the message's own pointer position (`MSG.pt`, -/// ) in client -/// coordinates. -fn message_point(lparam: isize, near: (i32, i32)) -> (i32, i32) { - let widen = |low: i16, near: i32| near.saturating_add(i32::from(i32::from(low).wrapping_sub(near) as i16)); - (widen(lparam as i16, near.0), widen((lparam >> 16) as i16, near.1)) -} - -/// A mouse button: the left one picks, and any other one cancels. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Button { - Left, - Right, - /// The middle button or a side button. - Other, -} - -/// What the person did in the sampler's window. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Input { - Down(Button), - Up(Button), - Escape, - /// The window became the active window. - Activated, - /// The window stopped being the active window. - Deactivated, - /// Another window took the mouse capture. - CaptureLost, - /// The window was asked to close (Alt+F4). - Closed, -} - -/// What the sampler does next. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Step { - Wait, - Pick, - Cancel, -} - -/// The mouse button last pressed in the window, and whether the window has been active. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -struct Press { - down: Option