Merge remote-tracking branch 'upstream/main' into pin-craft-libs-picker

This commit is contained in:
aiongg committed 2026-11-19 01:57:02 +00:00
commit 9a1308e09e
72 files changed
+2663 -2109

No files matched your search

Generated
+136 -36
View File
@@ -1532,8 +1532,8 @@ name = "craft-crs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb"
dependencies = [
"craft-metadata",
"craft-xml",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"thiserror 2.0.21",
]
@@ -1553,6 +1553,14 @@ dependencies = [
"rayon",
]
[[package]]
name = "craft-dds"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be#7b8c1eccea0c695a495ab279c9523e6efcc9b8be"
dependencies = [
"rayon",
]
[[package]]
name = "craft-dialogs"
version = "0.1.0"
@@ -1615,12 +1623,12 @@ source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e75
dependencies = [
"craft-eps",
"craft-idml",
"craft-image-codecs",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"craft-kra",
"craft-ora",
"craft-pcraft-bundle",
"craft-raw",
"craft-svg",
"craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"craft-zip",
"serde",
"serde_json",
@@ -1751,7 +1759,7 @@ name = "craft-idml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb"
dependencies = [
"craft-xml",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"craft-zip",
"thiserror 2.0.21",
]
@@ -1761,11 +1769,38 @@ name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb"
dependencies = [
"craft-dds",
"craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"craft-heif",
"craft-jpeg",
"craft-metadata",
"craft-tiff",
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"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=7b8c1eccea0c695a495ab279c9523e6efcc9b8be#7b8c1eccea0c695a495ab279c9523e6efcc9b8be"
dependencies = [
"craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)",
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)",
"crc32fast",
"exr",
"flate2",
@@ -1802,6 +1837,11 @@ dependencies = [
"serde_json",
]
[[package]]
name = "craft-ipp"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e7873217287876f76a045550369c90a541693c33#e7873217287876f76a045550369c90a541693c33"
[[package]]
name = "craft-jpeg"
version = "0.1.0"
@@ -1810,6 +1850,14 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be#7b8c1eccea0c695a495ab279c9523e6efcc9b8be"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-keymap"
version = "0.1.0"
@@ -1817,7 +1865,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e75
dependencies = [
"craft-host",
"craft-i18n",
"craft-xml",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"egui",
"serde",
"serde_json",
@@ -1828,7 +1876,7 @@ name = "craft-kra"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb"
dependencies = [
"craft-xml",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"craft-zip",
"thiserror 2.0.21",
]
@@ -1872,7 +1920,19 @@ source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e75
dependencies = [
"brotli-decompressor 6.3.2",
"chrono",
"craft-tiff",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"quick-xml 0.41.0",
"serde",
]
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be#7b8c1eccea0c695a495ab279c9523e6efcc9b8be"
dependencies = [
"brotli-decompressor 6.3.2",
"chrono",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)",
"quick-xml 0.41.0",
"serde",
]
@@ -1882,7 +1942,7 @@ name = "craft-ora"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb"
dependencies = [
"craft-xml",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"craft-zip",
"thiserror 2.0.21",
]
@@ -2030,8 +2090,8 @@ source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e75
dependencies = [
"chrono",
"craft-crw",
"craft-metadata",
"craft-tiff",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"jxl-oxide",
"miniz_oxide 0.9.1",
"rayon",
@@ -2077,10 +2137,29 @@ name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb"
dependencies = [
"craft-image-codecs",
"craft-xml",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"flate2",
"kurbo 0.13.1",
"quick-xml 0.41.0",
"resvg 0.48.1",
"roxmltree 0.21.2",
"thiserror 2.0.21",
"usvg 0.48.1",
"vectorcraft-geom",
"vectorcraft-pathops",
]
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be#7b8c1eccea0c695a495ab279c9523e6efcc9b8be"
dependencies = [
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)",
"data-url",
"flate2",
"gif",
"image-webp",
"kurbo 0.13.1",
"quick-xml 0.41.0",
"resvg 0.48.1",
@@ -2174,6 +2253,15 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be#7b8c1eccea0c695a495ab279c9523e6efcc9b8be"
dependencies = [
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-time"
version = "0.1.0"
@@ -2243,7 +2331,7 @@ dependencies = [
"craft-platform",
"craft-quit",
"craft-settings",
"craft-svg",
"craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"craft-theme",
"craft-ui-macros",
"craft-window",
@@ -2321,7 +2409,7 @@ dependencies = [
"craft-host",
"craft-i18n",
"craft-platform",
"craft-svg",
"craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"craft-theme",
"craft-ui-macros",
"craft-ui-panels",
@@ -2434,6 +2522,16 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be#7b8c1eccea0c695a495ab279c9523e6efcc9b8be"
dependencies = [
"quick-xml 0.41.0",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-zip"
version = "0.1.0"
@@ -6273,10 +6371,10 @@ dependencies = [
"core-graphics2",
"craft",
"craft-cms",
"craft-image-codecs",
"craft-svg",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)",
"craft-update",
"craft-xml",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"eframe",
"egui",
"egui_kittest",
@@ -6320,7 +6418,7 @@ name = "photocraft-algo"
version = "0.23.1"
dependencies = [
"craft",
"craft-metadata",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"criterion",
"photocraft-color",
"photocraft-geom",
@@ -6340,7 +6438,7 @@ dependencies = [
"cap-std",
"clap",
"craft",
"craft-image-codecs",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"craft-psd",
"getrandom 0.3.4",
"photocraft-color",
@@ -6373,7 +6471,7 @@ dependencies = [
"clap_mangen",
"craft",
"craft-cms",
"craft-image-codecs",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"craft-psd",
"photocraft-automation",
"photocraft-doc",
@@ -6437,11 +6535,11 @@ dependencies = [
"craft-affinity",
"craft-cms",
"craft-file-formats",
"craft-image-codecs",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"craft-pcraft-format",
"craft-print",
"craft-psd",
"craft-xml",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"exr",
"flate2",
"photocraft-algo",
@@ -6477,8 +6575,7 @@ name = "photocraft-format"
version = "0.23.1"
dependencies = [
"blake3",
"craft-file-formats",
"craft-image-codecs",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"craft-pcraft-bundle",
"craft-pcraft-format",
"craft-zip",
@@ -6538,16 +6635,16 @@ dependencies = [
"craft-crs",
"craft-docpath",
"craft-file-formats",
"craft-image-codecs",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"craft-kra",
"craft-ora",
"craft-pdf",
"craft-pdn",
"craft-psd",
"craft-svg",
"craft-tiff",
"craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"craft-xcf",
"craft-xml",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"crc32fast",
"flate2",
"kurbo 0.13.1",
@@ -6576,6 +6673,9 @@ dependencies = [
[[package]]
name = "photocraft-ipp"
version = "0.23.1"
dependencies = [
"craft-ipp",
]
[[package]]
name = "photocraft-ops"
@@ -6635,7 +6735,7 @@ dependencies = [
name = "photocraft-raw"
version = "0.23.1"
dependencies = [
"craft-image-codecs",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"craft-raw",
"flate2",
"image",
@@ -6697,7 +6797,7 @@ dependencies = [
"craft",
"craft-file-formats",
"craft-i18n",
"craft-image-codecs",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"craft-print",
"craft-psd",
"eframe",
@@ -6746,7 +6846,7 @@ dependencies = [
name = "photocraft-web"
version = "0.23.1"
dependencies = [
"craft-image-codecs",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)",
"craft-psd",
"eframe",
"egui",
+2 -1
View File
@@ -58,7 +58,8 @@ craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519
craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" }
craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" }
craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb", features = ["tree-render", "tree-render-system-fonts"] }
# Keep the shared embedded-image validation API until the framework revision includes it.
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "7b8c1eccea0c695a495ab279c9523e6efcc9b8be", features = ["tree-render", "tree-render-system-fonts"] }
craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" }
# Camera-field EXIF reader/writer, shared prerequisite craft-libs#1563.
+2 -1
View File
@@ -241,8 +241,9 @@ fn layer_box_blurs_match_direct_convolution_at_any_radius() {
];
let params = [
FilterParams::GaussianBlur { radius: 4.5 },
// 9.3 already reaches past the layer's height with three boxes (edges repeated); a larger radius takes the same
// running sums and only made the direct-convolution oracle slow (#15652).
FilterParams::GaussianBlur { radius: 9.3 },
FilterParams::GaussianBlur { radius: 40.0 },
FilterParams::BoxBlur { radius: 5.0 },
FilterParams::BoxBlur { radius: 70.0 },
];
+6 -11
View File
@@ -102,16 +102,10 @@ fn exact(a: &[f32], b: &[f32], what: &str) {
#[test]
fn offset_fast_path_matches_the_per_channel_oracle() {
let mut layouts: Vec<(ColorMode, usize, bool)> = vec![
(ColorMode::Rgb, 3, false),
(ColorMode::Rgb, 4, true),
(ColorMode::Grayscale, 1, false),
(ColorMode::Grayscale, 2, true),
(ColorMode::Cmyk, 4, false),
(ColorMode::Cmyk, 5, true),
(ColorMode::Lab, 4, true),
];
layouts.extend((1..=MAXC).flat_map(|n| [(ColorMode::Multichannel, n, false), (ColorMode::Multichannel, n, true)]));
// The fast path dispatches on the channel count and alpha (`smart_blur`'s `smart_rows` arms, generic code past
// five); the colour mode reaches it only through the native white and black, which the oracle computes the same
// way. So every count with and without alpha covers every arm, whatever the mode is called (#15652).
let layouts: Vec<(ColorMode, usize, bool)> = (1..=MAXC).flat_map(|n| [(ColorMode::Multichannel, n, false), (ColorMode::Multichannel, n, true)]).collect();
let win = Rect::new(-7, -4, 33, 30);
for (mode, n, alpha) in layouts {
let src = image(win, n, alpha);
@@ -121,7 +115,8 @@ fn offset_fast_path_matches_the_per_channel_oracle() {
// The usual tile (the window less the halo), the whole window, and one sticking out of it.
let inner = Rect::new(win.x0 + ri, win.y0 + ri, win.x1 - ri, win.y1 - ri);
for out in [inner, win, Rect::new(-12, -9, 10, 8), Rect::EMPTY] {
for quality in [BlurQuality::Low, BlurQuality::Medium, BlurQuality::High] {
// Quality only sets the offset stride: Low a coarse one, High every offset at these radii (#15652).
for quality in [BlurQuality::Low, BlurQuality::High] {
for sm in [SmartBlurMode::Normal, SmartBlurMode::EdgeOnly, SmartBlurMode::OverlayEdge] {
for threshold in [8.0, 60.0] {
let what = format!("{mode:?} n={n} alpha={alpha} r={radius} {out:?} {quality:?} {sm:?} t={threshold}");
+14 -5
View File
@@ -361,18 +361,27 @@ fn multiband_matches_the_serial_code() {
assert_eq!(multiband(9, 7, &[], &[], 3).unwrap().0.len(), ref_multiband(9, 7, &[], &[], 3).0.len());
}
/// Batching the bands (#7758) changes when they are built, not the result. Budgets from none
/// (one image per batch) up to everything in steps of a fifth pass through every split of the
/// three images.
/// Batching the bands (#7758) changes when they are built, not the result. The batching adds the
/// next image while the batch's band cost stays within the budget, so its split changes only where
/// the budget crosses the cost of a run of consecutive images: each such sum and one below it, plus
/// none and everything, pass through every split the images can have (#15652; it swept 47 budgets).
#[test]
fn multiband_batches_match_the_serial_code() {
let budgets: Vec<usize> =
std::iter::successors(Some(1024.0f64), |b| Some(b * 1.2)).take_while(|b| *b < 4e6).map(|b| b as usize).chain([0, usize::MAX]).collect();
for (n, &(w, h)) in [(40usize, 30usize), (97, 61), (201, 129)].iter().enumerate() {
for ch in [1usize, 3] {
let (imgs, wts) = rois(w, h, ch, n as u64 * 17 + ch as u64);
for levels in [1usize, 3, 5] {
let want = ref_multiband(w, h, &imgs, &wts, levels);
let costs: Vec<usize> = imgs.iter().map(|im| blend::band_cost(im, w, h, ch, levels)).collect();
let mut budgets = vec![0, usize::MAX];
for start in 0..costs.len() {
for end in start + 1..=costs.len() {
let run: usize = costs[start..end].iter().sum();
budgets.extend([run.saturating_sub(1), run]);
}
}
budgets.sort_unstable();
budgets.dedup();
for &budget in &budgets {
let got = try_multiband_batched(w, h, &imgs, &wts, levels, budget, None).unwrap();
assert_eq!(bits(&got.0), bits(&want.0), "colours {w}x{h}x{ch} levels {levels} budget {budget}");
+9 -4
View File
@@ -195,15 +195,18 @@ fn facet_scratch_rejects_large_or_incomplete_storage() {
#[test]
fn cell_filters_match_scalar_models_edges_and_fractional_cells() {
let bounds = Rect::new(-19, -13, 32, 29);
for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab, ColorMode::Multichannel] {
// The cell filters see the mode only as a channel count, CMYK's ink direction (`subtractive`) and the native
// background, so Lab adds nothing to RGB; cells of 100 and 300 are both past every `out`, and the seed has no
// branch (0 and u32::MAX keep the wrapping ends) (#15652).
for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Multichannel] {
for alpha in [false, true] {
let ctx = Ctx { bounds, mode, alpha };
for pattern in 0..5 {
for halo in [0, 7] {
let src = fixture(bounds.inflate(halo), &ctx, pattern);
for out in [bounds, Rect::new(-23, -15, 37, 31), Rect::new(-7, 2, 18, 13)] {
for cell in [2.0, 3.75, 10.0, 100.0, 300.0] {
for seed in [0, 37, u32::MAX] {
for cell in [2.0, 3.75, 10.0, 300.0] {
for seed in [0, u32::MAX] {
let got = cells::crystallize(&src, out, &ctx, cell, seed).unwrap();
assert_bits(&got, &crystallize_direct(&src, out, &ctx, cell, seed));
for bg in [[1.0; 4], [0.1, 0.8, 0.4, 0.25]] {
@@ -257,7 +260,9 @@ fn cell_filters_tiled_storage_matches_scalar_with_soft_selection() {
crate::mix_selection(&mut expected_data, bounds, &selection, &image, ctx.alpha);
let mut expected = surface.clone();
expected.write_region(bounds, &expected_data);
for tile in [1, 7, 17, 256] {
// Tile 7 has dense edge tiles, sparse inner ones and a partial last one; 17 makes 1-pixel-wide and
// 2-row tiles. Tile 1 sent every edge pixel through the dense fallback (#15652).
for tile in [7, 17, 256] {
let got = apply_tiled(&surface, &params, bounds, bounds, Some(&selection), tile, extent);
assert_bits(&got.read_region(bounds), &expected.read_region(bounds));
}
+7 -7
View File
@@ -113,13 +113,13 @@ fn fft_cancellation_discards_partial_work_and_bounds_scratch() {
#[test]
fn positive_threshold_dispatch_retains_exact_pixel_decisions() {
let area = Rect::new(-3, 2, 253, 258);
for depth in SampleType::ALL {
let s = source(area, PixelFormat::new(ColorMode::Rgb, depth, true));
let p = FilterParams::UnsharpMask { amount: 500.0, radius: 64.0, threshold: 8.0 };
let expected = crate::sharpen::tests::apply_reference(&s, &p, area, area, None, Some(area), 256);
let actual = crate::apply_in(&s, &p, area, area, None, area);
assert_eq!(expected.to_interleaved(area), actual.to_interleaved(area));
}
// The FFT gate has no depth branch; only the positive threshold turns it away here. The exact kernel at every
// depth is `sharpen::tests::exact_tiled_selected_outputs_and_cancellation` (#15652).
let s = source(area, PixelFormat::new(ColorMode::Rgb, SampleType::U8, true));
let p = FilterParams::UnsharpMask { amount: 500.0, radius: 64.0, threshold: 8.0 };
let expected = crate::sharpen::tests::apply_reference(&s, &p, area, area, None, Some(area), 256);
let actual = crate::apply_in(&s, &p, area, area, None, area);
assert_eq!(expected.to_interleaved(area), actual.to_interleaved(area));
}
#[test]
+4 -2
View File
@@ -624,7 +624,8 @@ fn chisel_fields_do_not_depend_on_the_threads() {
for (k, m) in maps.iter().enumerate() {
for reach in [3.0f32, 12.0] {
let one = with_threads(1, || (sharp_edges(m), distance_field_of(m, reach)));
for threads in [2, 5, 16] {
// 2 threads give groups of several units with a short last one, 16 one unit a group: the two ways `par_units` splits work (#15652).
for threads in [2, 16] {
let many = with_threads(threads, || (sharp_edges(m), distance_field_of(m, reach)));
assert_eq!(one.0.slot, many.0.slot, "map {k} sharp slots on {threads} threads");
let edges = |s: &SharpEdges| {
@@ -675,7 +676,8 @@ fn bevel_maps_do_not_depend_on_the_threads() {
}
let run = || bevel_maps(shape, &b, &light, &tex, &PreparedPatterns::new(&pats, PREPARED_PATTERN_BYTES)).0;
let one = with_threads(1, run);
for threads in [2, 5, 16] {
// 2 threads give groups of several units with a short last one, 16 one unit a group: the two ways `par_units` splits work (#15652).
for threads in [2, 16] {
let many = with_threads(threads, run);
assert_eq!(one.len(), many.len());
for (j, (a, m)) in one.iter().zip(&many).enumerate() {
+4
View File
@@ -460,6 +460,10 @@ pub fn custom_shapes(s: &Session) -> &[CustomShape] {
&s.edit_state.custom_shapes
}
/// Serialize tests that intentionally purge or seed the global smart caches.
#[cfg(test)]
pub(crate) static PURGE_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[cfg(test)]
#[path = "edit_menu_cmds/tests.rs"]
mod tests;
@@ -1,8 +1,6 @@
use super::*;
use photocraft_doc::vector::Subpath;
static PURGE_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn session(depth: u32) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 64, "height": 48, "depth": depth, "background": "white"})).unwrap();
@@ -842,9 +842,11 @@ mod tests {
#[test]
fn a_preview_within_the_full_resolution_budget_is_the_plain_solve_bit_for_bit() {
let mut s = textured(300, 300);
s.execute("select.rect", json!({"x": 20, "y": 30, "width": 60, "height": 50})).unwrap();
for p in [json!({"offset": [120, 90]}), json!({"offset": [120, 90], "rotate": 30, "mode": "extend"})] {
// The solves are short on a small canvas and selection; the budget edge is checked on a
// canvas that holds a 256 × 256 selection and its move.
let mut s = textured(110, 90);
s.execute("select.rect", json!({"x": 10, "y": 10, "width": 24, "height": 20})).unwrap();
for p in [json!({"offset": [60, 50]}), json!({"offset": [60, 50], "rotate": 30, "mode": "extend"})] {
let job = preview(&s, &p).unwrap();
assert!(!job.is_coarse());
let (got, damage) = job.run(&JobCtx::new()).unwrap();
@@ -859,6 +861,7 @@ mod tests {
assert!(got.layers[0].surface().unwrap().read_region(b) == want.layers[0].surface().unwrap().read_region(b), "{p}");
}
// 256 × 256 is the largest selection solved at full resolution.
let mut s = textured(300, 300);
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 256, "height": 256})).unwrap();
assert!(!preview(&s, &json!({"offset": [20, 20]})).unwrap().is_coarse());
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 257, "height": 256})).unwrap();
@@ -876,7 +879,14 @@ mod tests {
s.edit("faint selection", |doc, _| {
let mut sel = Surface::new(photocraft_color::PixelFormat::GRAY8);
let r = Rect::new(20, 20, 536, 536);
let data: Vec<f32> = (r.y0..r.y1).flat_map(|y| (r.x0..r.x1).map(move |x| if x % 4 == 0 && y % 4 == 0 { 1.0 / 255.0 } else { 0.0 })).collect();
// Two clusters at opposite corners: the bounds are what scale the preview, and the few
// selected pixels keep the solve short.
let near = |v: i32| v < r.x0 + 40 || v >= r.x1 - 40;
let data: Vec<f32> = (r.y0..r.y1)
.flat_map(|y| {
(r.x0..r.x1).map(move |x| if x % 4 == 0 && y % 4 == 0 && near(x) && near(y) && (x < 300) == (y < 300) { 1.0 / 255.0 } else { 0.0 })
})
.collect();
sel.write_region(r, &data);
doc.selection = Some(sel);
Ok(())
@@ -58,9 +58,11 @@ fn green_doc() -> Session {
s
}
/// The same checker on a horizontal grey ramp, constant across each 10 px column.
/// The same checker on a horizontal grey ramp, constant across each 10 px column. Cropped to what
/// the tests read (the landings end at x 620, y 440): a fill samples the whole canvas, so its
/// cost grows with it.
fn ramp_doc() -> Session {
let mut s = session(800, 600);
let mut s = session(640, 460);
paint(&mut s, |x, y| {
if let Some(v) = checker(x, y) {
[v, v, v]
+10 -4
View File
@@ -1636,12 +1636,16 @@ fn content_aware_move_preview_shows_the_result_without_touching_the_session() {
assert!(content_aware_move_preview(&s, &json!({"offset": [70, 0], "mode": "copy"})).is_err());
}
/// A 30×30 object in the middle of a 400×300 selection (over the 256×256 a preview solves at full
/// resolution) on a 700×400 canvas, dragged by (250, 60).
/// A 30×30 object in a 60×60 selection, with two 8×8 pieces at the corners of a 400×300 bounding
/// box (over the 256×256 a preview solves at full resolution) on a 700×400 canvas, dragged by
/// (250, 60). The selection's bounds decide the preview's scale and placement; its few selected
/// pixels are what the solves work on, which keeps them short.
fn large_move(depth: u64) -> Session {
let mut s = session(700, 400, depth, "rgb");
paint_layer(&mut s, |x, y| if (195..225).contains(&x) && (145..175).contains(&y) { [0.05, 0.1, 0.9, 1.0] } else { texture(x, y) });
s.execute("select.rect", json!({"x": 10, "y": 10, "width": 400, "height": 300})).unwrap();
s.execute("select.rect", json!({"x": 180, "y": 130, "width": 60, "height": 60})).unwrap();
s.execute("select.rect", json!({"x": 10, "y": 10, "width": 8, "height": 8, "mode": "add"})).unwrap();
s.execute("select.rect", json!({"x": 402, "y": 302, "width": 8, "height": 8, "mode": "add"})).unwrap();
s
}
@@ -2298,7 +2302,9 @@ fn live_dab_strokes_commit_their_pixels_and_they_are_the_commands() {
fn live_dab_batches_match_the_accumulating_renderer() {
use photocraft_paint::{GrayTile, StrokeRenderer, TipShape};
for depth in DEPTHS {
// 8 bits (integers, and the measured Smudge mode only 8-bit RGB gets in `dab.rs`) and 32 bits (floats): 16 bits
// differs from 8 only in the raster's shared encode, which the live and the reference renderer both use (#15652).
for depth in [8, 32] {
let mut s = session(200, 90, depth, "rgb");
s.execute("layer.new.layer", json!({})).unwrap();
paint_layer(&mut s, |x, y| {
+9 -4
View File
@@ -70,7 +70,12 @@ pub fn encode_source(doc: &Document) -> Result<Vec<u8>> {
/// Decodes smart-object contents (a `.pcraft` bundle, PSD/PSB, or any flat image format).
pub fn decode_source(file_name: &str, bytes: &[u8]) -> Result<Document> {
if photocraft_io::svg::is_svg(bytes) {
decode_source_classified(file_name, bytes, photocraft_io::svg::is_svg(bytes))
}
/// Reuse the central format decision made by this render operation.
fn decode_source_classified(file_name: &str, bytes: &[u8], svg: bool) -> Result<Document> {
if svg {
// This API has no warning channel. Stack/source caches and contents edits must not
// turn a partial SVG import into silently complete smart-object contents.
return photocraft_io::svg::import_svg_bounded_images_strict(file_name, bytes, 24_000_000)
@@ -197,13 +202,13 @@ pub(crate) use placing::detach_psd;
pub(crate) use placing::{affine_homography, set_placement, shift_smart, transform_placement};
use placing::{convert, reset_transform, shift_layer, via_copy};
pub use placing::{layer_to_smart, layers_to_smart, placement};
#[cfg(test)]
pub(crate) use rendering::DISPLAY_NATIVE_HASH_BYTES;
use rendering::refresh_or_fail;
#[cfg(test)]
pub(crate) use rendering::{DISPLAY_NATIVE_HASH_BYTES, WARNING_SOURCE_DECODES, WARNING_SOURCE_LIMIT};
#[cfg(test)]
use rendering::{NativeDigests, blend_surfaces, place, render_in};
pub(crate) use rendering::{WarningRenderSources, render_with_warnings, render_with_warnings_using, source_box};
pub use rendering::{apply_smart_filters, purge_stack_cache, refresh, refresh_layer, render, render_below_filter, stack_cache_bytes, stack_image};
pub(crate) use rendering::{render_with_warnings, source_box};
#[cfg(test)]
use source::svg_source_image_in;
pub use source::{SourceImage, purge_source_cache, source_bytes, source_cache_bytes, source_decode_count, source_image, svg_source_image};
+6 -3
View File
@@ -1,5 +1,5 @@
use super::rendering::{refresh_or_fail, unapplied_filters};
use super::source::{SourceImage, buffer_to_surface, cache_key, cache_put, source_bytes};
use super::source::{SourceImage, buffer_to_surface, cache_put, source_bytes, source_cache_key};
use super::{
Affine, Arc, BlendMode, Document, EngineError, Homography, Layer, LayerContent, LayerId, PLACED_KEYS, Rect, Result, Session, Size, SmartContentsId,
SmartObject, SmartSource, Surface, Value, encode_source, json, layer_param, other, source_box, translate_surface,
@@ -258,8 +258,11 @@ pub fn layers_to_smart(doc: &Document, name: &str, layers: Vec<Layer>) -> Result
sub.layers.iter_mut().for_each(|l| shift_layer(l, -b.x0, -b.y0));
sub.size = Size::new(b.width(), b.height());
let bytes = encode_source(&sub)?;
// Seed the decode cache with the composite we already have.
cache_put(cache_key(&bytes, fmt), SourceImage { surface: Arc::new(translate_surface(&cache, -b.x0, -b.y0)), bounds: sub.bounds() });
// The encoded native document is non-SVG; match the classified render/bounds path.
cache_put(
source_cache_key(&sub.name, &bytes, fmt, Some(false)),
SourceImage { surface: Arc::new(translate_surface(&cache, -b.x0, -b.y0)), bounds: sub.bounds() },
);
let source = SmartSource::Embedded { file_name: sub.name.clone(), bytes: Arc::new(bytes) };
Ok(Layer::new(name, LayerContent::Smart(SmartObject::new(source, Affine::translate(b.x0 as f64, b.y0 as f64), Some(cache)))))
+182 -41
View File
@@ -1,23 +1,31 @@
use super::filters::smart;
use super::source::{
SourceImage, cache_get, cache_key, cache_put, convert_svg_source, source_bytes, source_image, source_surface_from_buffer, svg_source_image_in, vector_scale,
SourceImage, cache_get, cache_key, cache_put, convert_svg_source, source_bytes, source_surface_from_buffer, svg_source_image_in, vector_scale,
};
use super::{
Affine, Arc, BlendMode, Document, EngineError, Homography, JobCtx, Layer, LayerContent, LayerId, PixelFormat, Rect, Result, SmartFilter, SmartObject,
SmartSource, Stage, StageKey, Surface, Value, affine_homography, decode_source, other, placement, stack_cache,
SmartSource, Stage, StageKey, Surface, Value, affine_homography, other, placement, stack_cache,
};
use std::sync::Mutex;
use std::collections::VecDeque;
use std::sync::{Mutex, Weak};
/// Layer › Smart Objects › Stack Mode: the source's layers (or, when it holds a single group, the
/// group's layers) combined per pixel with `mode`. Cached like [`source_image`], keyed by mode.
/// group's layers) combined per pixel with `mode`. Cached like [`super::source_image`], keyed by mode.
pub fn stack_image(file_name: &str, bytes: &[u8], fmt: PixelFormat, mode: photocraft_doc::StackMode) -> Result<SourceImage> {
stack_image_classified(file_name, bytes, fmt, mode, None)
}
fn stack_image_classified(file_name: &str, bytes: &[u8], fmt: PixelFormat, mode: photocraft_doc::StackMode, svg: Option<bool>) -> Result<SourceImage> {
use photocraft_algo::stack::Stat;
let mut key = cache_key(bytes, fmt);
key.0 = *blake3::hash(&[&key.0[..], b"stack:", mode.id().as_bytes()].concat()).as_bytes();
// Keep the filename in the key because fallback import uses it to choose a format.
// Use a separate domain from entries that predate plain SVG completeness checks.
key.0 = *blake3::hash(&[&key.0[..], b"stack-source-v3:", blake3::hash(file_name.as_bytes()).as_bytes(), mode.id().as_bytes()].concat()).as_bytes();
if let Some(img) = cache_get(&key) {
return Ok(img);
}
let doc = decode_source(file_name, bytes)?;
let svg = svg.unwrap_or_else(|| photocraft_io::svg::is_svg(bytes));
let doc = super::decode_source_classified(file_name, bytes, svg)?;
let layers: &[Layer] = match doc.layers.as_slice() {
[only] if only.is_group() => only.children().unwrap_or_default(),
all => all,
@@ -25,7 +33,7 @@ pub fn stack_image(file_name: &str, bytes: &[u8], fmt: PixelFormat, mode: photoc
let bounds = doc.bounds();
// An SVG opens with one layer per shape, and every visible one gets its own float frame:
// they may take 1 GiB together, the SVG import's own budget, before any is rendered.
if photocraft_io::svg::is_svg(bytes) {
if svg {
let visible = u64::try_from(layers.iter().filter(|l| l.visible).count()).unwrap_or(u64::MAX);
let frame_bytes = doc.size.area().saturating_mul(16);
if visible.saturating_mul(frame_bytes) > 1 << 30 {
@@ -173,16 +181,24 @@ fn apply_smart_filter(f: &SmartFilter, sm: &SmartObject, cur: &Surface, canvas:
if f.blend == BlendMode::Normal && f.opacity >= 1.0 { Ok(out) } else { Ok(blend_surfaces(cur, &out, f.blend, f.opacity.clamp(0.0, 1.0))) }
}
/// The source placed in document pixels, before any smart filter.
/// The source placed in document pixels, before any smart filter (uncached test oracle).
#[cfg(test)]
pub(super) fn place(name: &str, bytes: &[u8], doc: &Document, sm: &SmartObject) -> Result<Surface> {
place_with_svg(name, bytes, doc, sm, &mut |bytes, scale| svg_source_image_in(bytes, doc, scale))
place_with_svg(name, bytes, doc, sm, photocraft_io::svg::is_svg(bytes), &mut |bytes, scale| svg_source_image_in(bytes, doc, scale))
}
fn place_with_svg(name: &str, bytes: &[u8], doc: &Document, sm: &SmartObject, svg: &mut impl FnMut(&[u8], f64) -> Result<SourceImage>) -> Result<Surface> {
fn place_with_svg(
name: &str,
bytes: &[u8],
doc: &Document,
sm: &SmartObject,
is_svg: bool,
svg: &mut impl FnMut(&[u8], f64) -> Result<SourceImage>,
) -> Result<Surface> {
let fmt = doc.pixel_format();
// A vector source is rendered at the placement's scale, and the placement is divided by
// that scale so the rendered pixels land where the source units would.
if sm.stack_mode.is_none() && sm.warp.is_none() && photocraft_io::svg::is_svg(bytes) {
if sm.stack_mode.is_none() && sm.warp.is_none() && is_svg {
let k = vector_scale(sm);
let img = svg(bytes, k)?;
return Ok(match &sm.perspective {
@@ -201,10 +217,10 @@ fn place_with_svg(name: &str, bytes: &[u8], doc: &Document, sm: &SmartObject, sv
});
}
let img = match sm.stack_mode {
Some(mode) if photocraft_io::svg::is_svg(bytes) => convert_svg_source(stack_image(name, bytes, PixelFormat::RGBA32F, mode)?, doc)?,
None if photocraft_io::svg::is_svg(bytes) => svg(bytes, 1.0)?,
Some(mode) => stack_image(name, bytes, fmt, mode)?,
None => source_image(name, bytes, fmt)?,
Some(mode) if is_svg => convert_svg_source(stack_image_classified(name, bytes, PixelFormat::RGBA32F, mode, Some(is_svg))?, doc)?,
None if is_svg => svg(bytes, 1.0)?,
Some(mode) => stack_image_classified(name, bytes, fmt, mode, Some(is_svg))?,
None => super::source::source_image_classified(name, bytes, fmt, is_svg)?,
};
// The placed stage is unclipped: a large enough placement (an image scaled to fill a huge
// frame) would otherwise fill memory before any allocation could fail.
@@ -312,7 +328,7 @@ pub(crate) fn source_box(doc: &Document, sm: &SmartObject) -> Option<[f64; 4]> {
let r = match sm.stack_mode {
None if photocraft_io::svg::is_svg(&bytes) => photocraft_io::svg::bounded_canvas_bounds(&bytes, 24_000_000).ok()?,
Some(mode) => stack_image(&name, &bytes, fmt, mode).ok()?.bounds,
None => source_image(&name, &bytes, fmt).ok()?.bounds,
None => super::source::source_image(&name, &bytes, fmt).ok()?.bounds,
};
Some([f64::from(r.x0), f64::from(r.y0), f64::from(r.x1), f64::from(r.y1)])
}
@@ -324,28 +340,143 @@ pub fn render(doc: &Document, sm: &SmartObject) -> Result<Option<Surface>> {
}
/// Command-only rendering that retains usable SVG artwork and reports omitted embedded images.
/// It deliberately bypasses both source and filter-stage caches: a later warningless render
/// must not accidentally reuse an incomplete surface. Native previews remain strict.
/// Its local source cache never enters the strict process-wide source/filter caches.
pub(crate) fn render_with_warnings(doc: &Document, sm: &SmartObject) -> Result<(Option<Surface>, Vec<String>)> {
let Some((name, bytes)) = source_bytes(&doc.metadata, &sm.source) else { return Ok((None, Vec::new())) };
if !photocraft_io::svg::is_svg(&bytes) || sm.vector_preview.is_some() || sm.stack_mode.is_some() {
render_with_warnings_using(sm, &mut WarningRenderSources::new(doc))
}
struct WarningSource {
source: Weak<Vec<u8>>,
name: [u8; 32],
scale: u64,
image: SourceImage,
warnings: Vec<String>,
bytes: usize,
}
/// One command's bounded source-space renders. Placement, warp, filters and masks
/// are instance-specific and must never be cached here. Weak identity pins only the
/// allocation header; the borrowed document owns encoded bytes throughout the command.
pub(crate) struct WarningRenderSources<'a> {
document: &'a Document,
srgb: Option<bool>,
entries: VecDeque<WarningSource>,
budget: usize,
limit: usize,
bytes: usize,
}
#[cfg(test)]
thread_local! {
pub(crate) static WARNING_SOURCE_DECODES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
pub(crate) static WARNING_SOURCE_LIMIT: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
}
impl<'a> WarningRenderSources<'a> {
pub(crate) fn new(document: &'a Document) -> Self {
#[cfg(test)]
let limit = WARNING_SOURCE_LIMIT.with(|limit| limit.get().unwrap_or(32));
#[cfg(not(test))]
let limit = 32;
Self { document, srgb: None, entries: VecDeque::new(), budget: if cfg!(target_arch = "wasm32") { 128 << 20 } else { 384 << 20 }, limit, bytes: 0 }
}
#[cfg(test)]
pub(crate) fn with_limits(document: &'a Document, budget: usize, limit: usize) -> Self {
Self { budget, limit, ..Self::new(document) }
}
#[cfg(test)]
pub(crate) fn profile_initialized(&self) -> bool {
self.srgb.is_some()
}
fn image(&mut self, bytes: &Arc<Vec<u8>>, scale: f64, name: [u8; 32]) -> Result<(SourceImage, Vec<String>)> {
let doc = self.document;
// Non-SVG and unavailable sources keep their old fast path without
// materializing ICC bytes. This immutable document needs the context once.
let key = scale.to_bits();
if let Some(index) =
self.entries.iter().position(|entry| entry.scale == key && entry.name == name && std::ptr::eq(entry.source.as_ptr(), Arc::as_ptr(bytes)))
&& let Some(entry) = self.entries.remove(index)
{
let result = (entry.image.clone(), entry.warnings.clone());
self.entries.push_back(entry);
return Ok(result);
}
// Only the exact sRGB fast path needs this lazy, immutable document context.
// Pixel format/profile do not belong in each entry's key: the document is borrowed.
let srgb = *self.srgb.get_or_insert_with(|| {
doc.mode == photocraft_color::ColorMode::Rgb
&& crate::color_cmds::document_profile(doc).to_bytes().as_ref() == craft_cms::Builtin::Srgb.profile().to_bytes().as_ref()
});
#[cfg(test)]
WARNING_SOURCE_DECODES.with(|count| count.set(count.get().saturating_add(1)));
let (buf, warnings) = photocraft_io::svg::rasterize_bounded_with_warnings(bytes, scale as f32, 24_000_000)
.map_err(|e| other(format!("can't render the SVG smart object: {e}")))?;
// Charge owned native tiles, entry and warning storage, not borrowed encoded bytes.
// This is a soft memo budget: oversize entries retain the existing uncached path.
let cost = usize::try_from(photocraft_raster::tile_storage_bytes(buf.rect, &doc.pixel_format()))
.unwrap_or(usize::MAX)
.saturating_add(std::mem::size_of::<WarningSource>())
.saturating_add(warnings.capacity().saturating_mul(std::mem::size_of::<String>()))
.saturating_add(warnings.iter().fold(0usize, |total, warning| total.saturating_add(warning.capacity())));
let admitted = self.limit != 0 && cost <= self.budget;
if admitted {
while self.entries.len() >= self.limit || self.bytes > self.budget - cost {
let Some(entry) = self.entries.pop_front() else {
// Recover conservatively if accounting ever outlives an empty queue.
self.bytes = 0;
break;
};
self.bytes = self.bytes.saturating_sub(entry.bytes);
}
}
// Preserve the normal renderer's exact built-in sRGB fast path.
// A full memo is optional. Let the placement proceed uncached if the
// browser cannot afford retaining these tiles along with prior renders.
let admitted = admitted && crate::memory_gate::ensure("retain the SVG source for this update", cost as u64).is_ok();
let image = if srgb {
SourceImage { surface: Arc::new(super::source::buffer_to_surface(&buf, doc.pixel_format())), bounds: buf.rect }
} else {
let source = SourceImage { surface: Arc::new(super::source::buffer_to_surface(&buf, PixelFormat::RGBA32F)), bounds: buf.rect };
convert_svg_source(source, doc)?
};
if admitted && self.entries.try_reserve(1).is_ok() {
self.bytes += cost; // cost was admitted against budget - bytes above.
self.entries.push_back(WarningSource {
source: Arc::downgrade(bytes),
name,
scale: key,
image: image.clone(),
warnings: warnings.clone(),
bytes: cost,
});
}
Ok((image, warnings))
}
}
/// Reuse only warning-aware source pixels during one shared-content update.
pub(crate) fn render_with_warnings_using(sm: &SmartObject, sources: &mut WarningRenderSources<'_>) -> Result<(Option<Surface>, Vec<String>)> {
let doc = sources.document;
if sm.vector_preview.is_some() || sm.stack_mode.is_some() {
return render(doc, sm).map(|surface| (surface, Vec::new()));
}
let Some((name, bytes)) = source_bytes(&doc.metadata, &sm.source) else { return Ok((None, Vec::new())) };
if !photocraft_io::svg::is_svg(&bytes) {
// Keep the same source snapshot for fallback, including authorized linked reads.
return render_in_with_source(doc, sm, &JobCtx::new(), Some((name, bytes))).map(|surface| (surface, Vec::new()));
}
let name_key = *blake3::hash(name.as_bytes()).as_bytes();
if !unapplied_filters(sm).is_empty() {
return Err(other("the smart object has unsupported visible filters"));
}
let mut warnings = Vec::new();
let placed = place_with_svg(&name, &bytes, doc, sm, &mut |bytes, scale| {
let (buf, omitted) = photocraft_io::svg::rasterize_bounded_with_warnings(bytes, scale as f32, 24_000_000)
.map_err(|e| other(format!("can't render the SVG smart object: {e}")))?;
let placed = place_with_svg(&name, &bytes, doc, sm, true, &mut |_, scale| {
let (image, omitted) = sources.image(&bytes, scale, name_key)?;
warnings.extend(omitted);
// Preserve the normal renderer's exact built-in sRGB fast path.
let profile = crate::color_cmds::document_profile(doc);
if doc.mode == photocraft_color::ColorMode::Rgb && profile.to_bytes().as_ref() == craft_cms::Builtin::Srgb.profile().to_bytes().as_ref() {
return Ok(SourceImage { surface: Arc::new(super::source::buffer_to_surface(&buf, doc.pixel_format())), bounds: buf.rect });
}
let source = SourceImage { surface: Arc::new(super::source::buffer_to_surface(&buf, PixelFormat::RGBA32F)), bounds: buf.rect };
convert_svg_source(source, doc)
Ok(image)
})?;
Ok((Some(apply_smart_filters(&placed, sm, doc.bounds())?), warnings))
}
@@ -354,27 +485,33 @@ pub(crate) fn render_with_warnings(doc: &Document, sm: &SmartObject) -> Result<(
/// is cancelled. Gives the same pixels as [`apply_smart_filters`] on the placed source, but
/// starts from the deepest stage of the stack already rendered (see [`stack_cache`]).
pub(super) fn render_in(doc: &Document, sm: &SmartObject, ctx: &JobCtx) -> Result<Option<Surface>> {
// Stored filters can come from a file or another layer. Check before looking up cached
// stages too: a trusted UI render may have populated this process-wide cache earlier.
render_in_with_source(doc, sm, ctx, None)
}
fn render_in_with_source(doc: &Document, sm: &SmartObject, ctx: &JobCtx, snapshot: Option<(String, Arc<Vec<u8>>)>) -> Result<Option<Surface>> {
// A trusted UI render may have populated these stages. Check authority even on a hit.
for filter in sm.smart_filters.iter().filter(|f| sm.filters_enabled && f.visible) {
crate::jobs::authorize_render_command(&filter.command, &filter.params)?;
}
let Some((name, bytes)) = source_bytes(&doc.metadata, &sm.source) else { return Ok(None) };
let bytes = display_source(sm, &bytes);
let Some((name, original)) = snapshot.or_else(|| source_bytes(&doc.metadata, &sm.source)) else { return Ok(None) };
let bytes = display_source(sm, &original);
let (fmt, canvas) = (doc.pixel_format(), doc.bounds());
let mut placed_key = stack_cache::placed_key(&bytes, fmt, sm, canvas);
if photocraft_io::svg::is_svg(&bytes) {
let mut h = blake3::Hasher::new();
h.update(&placed_key);
// Plain SVG uses the original strict vector path. Gzip sources use ordinary
// file import and native-size pixels, as existing saved objects expect.
let is_svg = photocraft_io::svg::is_svg(&bytes);
let mut h = blake3::Hasher::new();
h.update(b"smart-placement-v3:");
h.update(&stack_cache::placed_key(&bytes, fmt, sm, canvas));
h.update(blake3::hash(name.as_bytes()).as_bytes());
if is_svg {
h.update(&crate::color_cmds::document_profile(doc).to_bytes());
placed_key = *h.finalize().as_bytes();
}
let placed_key: StageKey = *h.finalize().as_bytes();
let placed = || -> Result<Stage> {
if let Some(stage) = stack_cache::get(&placed_key) {
return Ok(stage);
}
let surface = place(&name, &bytes, doc, sm)?;
// Edge pixels repeat at the canvas ∪ placed-content edge, as for layer filters.
let surface = place_with_svg(&name, &bytes, doc, sm, is_svg, &mut |bytes, scale| svg_source_image_in(bytes, doc, scale))?;
let stage = Stage { extent: canvas.union(&surface.content_bounds()), surface };
stack_cache::put(placed_key, &stage);
Ok(stage)
@@ -497,3 +634,7 @@ pub(super) fn refresh_or_fail_in(doc: &mut Document, id: LayerId, ctx: &JobCtx)
}
Err(other("the smart object's contents are unavailable (missing linked file?), so it can't be re-rendered"))
}
#[cfg(test)]
#[path = "tests/source_work.rs"]
mod source_work_tests;
+64 -7
View File
@@ -70,7 +70,7 @@ pub struct SourceImage {
pub bounds: Rect,
}
type CacheKey = ([u8; 32], PixelFormat);
pub(super) type CacheKey = ([u8; 32], PixelFormat, Option<[u8; 32]>);
struct CacheEntry {
key: CacheKey,
@@ -100,7 +100,23 @@ fn cache() -> std::sync::MutexGuard<'static, Vec<CacheEntry>> {
}
pub(super) fn cache_key(bytes: &[u8], fmt: PixelFormat) -> CacheKey {
(*blake3::hash(bytes).as_bytes(), fmt)
(*blake3::hash(bytes).as_bytes(), fmt, None)
}
/// Keep automatic recognition and caller-supplied classifications separate. The filename
/// also selects extension-sensitive importers. Neither decision may be bypassed by a hit.
pub(super) fn source_cache_key(file_name: &str, bytes: &[u8], fmt: PixelFormat, svg: Option<bool>) -> CacheKey {
let mut key = cache_key(bytes, fmt);
let mut context = blake3::Hasher::new();
context.update(b"source-decode-context-v1\0");
context.update(&[match svg {
None => 0,
Some(false) => 1,
Some(true) => 2,
}]);
context.update(file_name.as_bytes());
key.2 = Some(*context.finalize().as_bytes());
key
}
pub(super) fn cache_get(key: &CacheKey) -> Option<SourceImage> {
@@ -136,7 +152,7 @@ fn cache_put_within(key: CacheKey, image: SourceImage, limit: usize) {
/// How many times these contents were decoded at this pixel format (0 = never / evicted).
pub fn source_decode_count(bytes: &[u8], fmt: PixelFormat) -> u32 {
let key = cache_key(bytes, fmt);
cache().iter().find(|e| e.key == key).map(|e| e.decodes).unwrap_or(0)
cache().iter().filter(|e| e.key.0 == key.0 && e.key.1 == fmt).fold(0u32, |total, e| total.saturating_add(e.decodes))
}
/// Bytes held by cached source composites.
@@ -291,7 +307,7 @@ pub fn svg_source_image(bytes: &[u8], fmt: PixelFormat, scale: f64) -> Result<So
let mut h = blake3::Hasher::new();
h.update(bytes);
h.update(&scale.to_bits().to_le_bytes());
let key = (*h.finalize().as_bytes(), fmt);
let key = (*h.finalize().as_bytes(), fmt, None);
if let Some(img) = cache_get(&key) {
return Ok(img);
}
@@ -318,7 +334,7 @@ pub(super) fn svg_source_image_in(bytes: &[u8], doc: &Document, scale: f64) -> R
h.update(bytes);
h.update(&scale.to_bits().to_le_bytes());
h.update(&profile.to_bytes());
let key = (*h.finalize().as_bytes(), fmt);
let key = (*h.finalize().as_bytes(), fmt, None);
if let Some(image) = cache_get(&key) {
return Ok(image);
}
@@ -353,12 +369,23 @@ pub(crate) fn vector_scale(sm: &SmartObject) -> f64 {
/// The composited source image of `bytes` in pixel format `fmt` (decoded once, then cached).
pub fn source_image(file_name: &str, bytes: &[u8], fmt: PixelFormat) -> Result<SourceImage> {
let key = cache_key(bytes, fmt);
source_image_inner(file_name, bytes, fmt, None)
}
pub(super) fn source_image_classified(file_name: &str, bytes: &[u8], fmt: PixelFormat, svg: bool) -> Result<SourceImage> {
source_image_inner(file_name, bytes, fmt, Some(svg))
}
fn source_image_inner(file_name: &str, bytes: &[u8], fmt: PixelFormat, svg: Option<bool>) -> Result<SourceImage> {
let key = source_cache_key(file_name, bytes, fmt, svg);
if let Some(img) = cache_get(&key) {
return Ok(img);
}
crate::memory_gate::ensure(&format!("render the smart object \u{201c}{file_name}\u{201d}"), crate::memory_gate::smart_render_need(bytes))?;
let doc = decode_source(file_name, bytes)?;
let doc = match svg {
Some(svg) => super::decode_source_classified(file_name, bytes, svg)?,
None => decode_source(file_name, bytes)?,
};
let img = SourceImage { surface: Arc::new(flattened_source(&doc, fmt)?), bounds: doc.bounds() };
cache_put(key, img.clone());
Ok(img)
@@ -368,6 +395,36 @@ pub fn source_image(file_name: &str, bytes: &[u8], fmt: PixelFormat) -> Result<S
mod tests {
use super::*;
#[test]
fn source_cache_keys_preserve_filename_and_classification() {
let bytes = b"source context regression";
let fmt = PixelFormat::RGBA8;
let keys = [
source_cache_key("source.png", bytes, fmt, None),
source_cache_key("source.dat", bytes, fmt, None),
source_cache_key("source.png", bytes, fmt, Some(false)),
source_cache_key("source.png", bytes, fmt, Some(true)),
cache_key(bytes, fmt),
];
for (i, key) in keys.iter().enumerate() {
for other in &keys[i + 1..] {
assert_ne!(key, other);
}
}
assert_eq!(keys[0], source_cache_key("source.png", bytes, fmt, None));
assert_ne!(keys[0], source_cache_key("source.png", bytes, PixelFormat::RGBA32F, None));
}
#[test]
fn warm_raster_source_cannot_bypass_svg_classification() {
let raster = photocraft_codecs::Image::from_u8(1, 1, photocraft_codecs::ChannelLayout::Rgb, vec![13, 47, 91]).unwrap();
let png = photocraft_codecs::encode(&raster, photocraft_codecs::Format::Png, &Default::default()).unwrap();
let name = "source-classification-regression.png";
let first = source_image_classified(name, &png, PixelFormat::RGBA8, false).unwrap();
assert_eq!(first.bounds, Rect::new(0, 0, 1, 1));
assert!(source_image_classified(name, &png, PixelFormat::RGBA8, true).is_err(), "a warm raster hit must not skip strict SVG decoding");
assert!(source_image(name, &png, PixelFormat::RGBA8).is_ok());
}
fn image(side: i32) -> SourceImage {
let mut s = Surface::new(PixelFormat::RGBA8);
s.fill_rect(Rect::new(0, 0, side, side), &[0.2, 0.4, 0.6, 1.0]);
@@ -5,6 +5,7 @@ mod selection;
mod source_flatten;
mod stack_cache;
mod svg_profile;
mod svg_stack_completeness;
const DEPTHS: [u64; 3] = [8, 16, 32];
const W: i32 = 64;
@@ -0,0 +1,124 @@
use super::*;
use photocraft_color::{ColorMode, SampleType};
use photocraft_geom::Size;
use std::io::Write;
fn drawing(label: &str, omitted: bool) -> Vec<u8> {
let image = if omitted { r#"<image width="1" height="1" href="data:image/png;base64,A"/>"# } else { "" };
format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8"><!--{label}--><rect width="8" height="8" fill="red"/>{image}</svg>"#).into_bytes()
}
fn gzip(bytes: &[u8]) -> Vec<u8> {
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
encoder.write_all(bytes).unwrap();
encoder.finish().unwrap()
}
fn document() -> Document {
Document::new("Source work", Size::new(8, 8), ColorMode::Rgb, SampleType::U8)
}
fn object(name: &str, bytes: Arc<Vec<u8>>) -> SmartObject {
SmartObject::new(SmartSource::Embedded { file_name: name.into(), bytes }, Affine::IDENTITY, None)
}
#[test]
fn saved_svgz_refresh_keeps_native_size_pixels_and_place_reports_omissions() {
// The fractional edge distinguishes native-size import and resampling from
// rasterizing the vector again at the enlarged placement resolution.
let svg = br#"<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8"><rect x=".35" width="5.4" height="8" fill="red"/><image width="1" height="1" href="data:image/png;base64,A"/></svg>"#;
let encoded = gzip(svg);
let name = "saved-refresh.svgz";
let mut session = crate::Session::new();
session.execute("file.new", serde_json::json!({"width":32,"height":32})).unwrap();
let placed = crate::file_cmds::place_bytes(&mut session, name, encoded.clone(), None, &serde_json::json!({"smartObject":true,"scale":175})).unwrap();
let warnings = placed["warnings"].as_array().unwrap();
assert!(warnings.iter().any(|warning| warning.as_str().is_some_and(|warning| warning.contains("embedded image was omitted"))));
let state = session.active().unwrap();
let layer = state.active_layer.unwrap();
let saved = photocraft_format::save_to_bytes(&state.doc, &Default::default()).unwrap();
let mut doc = photocraft_format::load_from_bytes(&saved).unwrap();
let format = doc.pixel_format();
let mut changed = doc.layer(layer).unwrap().clone();
let LayerContent::Smart(sm) = &mut changed.content else { panic!("saved SVGZ smart object") };
sm.transform.m[4] += 1.;
sm.cache = None;
// Independent oracle for the previous route: ordinary file import at source
// size, then the same image placement used for other raster sources.
let source = crate::file_cmds::import(name, &encoded).unwrap();
let bounds = source.bounds();
let source = super::super::source::flattened_source(&source, format).unwrap();
let expected = photocraft_algo::warp::place_source(&source, bounds, &sm.transform, None).unwrap();
assert_eq!(source_box(&doc, sm), Some([0., 0., 8., 8.]));
assert!(refresh_layer(&doc, &mut changed).unwrap());
let LayerContent::Smart(sm) = &mut changed.content else { panic!("refreshed SVGZ smart object") };
assert_eq!(sm.cache.as_ref(), Some(&expected));
sm.smart_filters.push(SmartFilter {
command: "image.adjustments.invert".into(),
params: serde_json::json!({}),
blend: BlendMode::Normal,
opacity: 1.,
visible: true,
});
let filtered = apply_smart_filters(&expected, sm, doc.bounds()).unwrap();
*doc.layer_mut(layer).unwrap() = changed;
assert!(refresh(&mut doc, layer).unwrap());
let LayerContent::Smart(sm) = &doc.layer(layer).unwrap().content else { panic!("filtered SVGZ smart object") };
assert_eq!(sm.cache.as_ref(), Some(&filtered));
let plain = object("saved-refresh.svg", Arc::new(svg.to_vec()));
assert!(render(&doc, &plain).is_err(), "plain SVG refresh still requires complete pixels");
let (pixels, warnings) = render_with_warnings(&doc, &plain).unwrap();
assert!(pixels.is_some());
assert_eq!(warnings.len(), 1);
}
#[test]
fn memo_prices_owned_output_and_does_not_retain_encoded_capacity() {
let doc = document();
let data = drawing("reserved encoded capacity", false);
let mut reserved = Vec::with_capacity(1 << 20);
reserved.extend_from_slice(&data);
let bytes = Arc::new(reserved);
let weak = Arc::downgrade(&bytes);
let sm = object("reserved.svg", bytes);
let tile = photocraft_raster::tile_storage_bytes(doc.bounds(), &doc.pixel_format()) as usize;
let mut memo = WarningRenderSources::with_limits(&doc, tile + 4096, 32);
WARNING_SOURCE_DECODES.with(|value| value.set(0));
let first = render_with_warnings_using(&sm, &mut memo).unwrap();
assert!(first.1.is_empty());
assert_eq!(memo.entries.len(), 1, "encoded spare capacity is borrowed, not retained memo storage");
assert!(memo.bytes <= tile + 4096);
assert_eq!(render_with_warnings_using(&sm, &mut memo).unwrap(), first);
assert_eq!(WARNING_SOURCE_DECODES.with(std::cell::Cell::get), 1);
assert_eq!(weak.strong_count(), 1, "only the caller owns its source allocation");
drop(sm);
assert!(weak.upgrade().is_none(), "the memo must not pin an encoded body after its owner drops it");
}
#[test]
fn empty_memo_with_stale_accounting_recovers_without_panicking() {
let doc = document();
let data = Arc::new(drawing("empty accounting", false));
let mut memo = WarningRenderSources::new(&doc);
memo.bytes = memo.budget;
let (image, warnings) = memo.image(&data, 1., *blake3::hash(b"empty.svg").as_bytes()).unwrap();
assert!(warnings.is_empty());
assert_eq!(image.surface.rgba(3, 3), [1., 0., 0., 1.]);
assert_eq!(memo.entries.len(), 1);
assert!(memo.bytes <= memo.budget);
}
#[test]
fn raster_named_svg_keeps_the_ordinary_import_path() {
let image = photocraft_codecs::Image::from_u8(1, 1, photocraft_codecs::ChannelLayout::Rgb, vec![0, 255, 0]).unwrap();
let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap();
let doc = document();
let sm = object("renamed.svg", Arc::new(png));
let rendered = render(&doc, &sm).unwrap().unwrap();
assert_eq!(rendered.rgba(0, 0), [0., 1., 0., 1.]);
let (reported, warnings) = render_with_warnings_using(&sm, &mut WarningRenderSources::new(&doc)).unwrap();
assert_eq!(reported.unwrap(), rendered);
assert!(warnings.is_empty());
}
@@ -92,16 +92,23 @@ fn convert_to_layers_unpacks_full_canvas_shapes_in_a_4k_document() {
/// and renders the rest of the drawing, as it did before the bounded render.
#[test]
fn svg_with_an_unreadable_embedded_image_still_places() {
let svg = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"8\" height=\"8\"><image width=\"4\" height=\"4\" href=\"data:image/x-foo,abc\"/><rect x=\"4\" width=\"4\" height=\"8\" fill=\"#ff0000\"/></svg>";
let mut s = Session::new();
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
let placed = crate::file_cmds::place_bytes(&mut s, "Logo.svg", svg.as_bytes().to_vec(), None, &json!({"smartObject": true})).unwrap();
assert!(placed["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("embedded image was omitted")));
let doc = &s.active().unwrap().doc;
let LayerContent::Smart(sm) = &doc.layer(LayerId(placed["layer"].as_u64().unwrap())).unwrap().content else { panic!("smart") };
assert_eq!(sm.cache.as_ref().unwrap().rgba(6, 4), [1.0, 0.0, 0.0, 1.0]);
// A warning-bearing command must not poison the strict source/filter caches.
assert!(render(doc, sm).is_err());
for href in ["data:image/x-foo,abc", "data:image/png;base64,A"] {
let svg = format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"8\" height=\"8\"><image width=\"4\" height=\"4\" href=\"{href}\"/><rect x=\"4\" width=\"4\" height=\"8\" fill=\"#ff0000\"/></svg>"
);
let mut s = Session::new();
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
let placed = crate::file_cmds::place_bytes(&mut s, "Logo.svg", svg.as_bytes().to_vec(), None, &json!({"smartObject": true})).unwrap();
let warnings = placed["warnings"].as_array().unwrap();
assert_eq!(warnings.len(), 1, "{href}: {warnings:?}");
assert!(warnings[0].as_str().unwrap().contains("embedded image was omitted"));
let doc = &s.active().unwrap().doc;
let LayerContent::Smart(sm) = &doc.layer(LayerId(placed["layer"].as_u64().unwrap())).unwrap().content else { panic!("smart") };
assert_eq!(sm.cache.as_ref().unwrap().rgba(6, 4), [1.0, 0.0, 0.0, 1.0]);
assert!(matches!(&sm.source, SmartSource::Embedded { file_name, bytes } if file_name == "Logo.svg" && bytes.as_slice() == svg.as_bytes()));
// The warning render must neither repair the original bytes nor populate strict caches.
assert!(render(doc, sm).is_err(), "{href}");
}
}
/// Warp setup needs only the source frame, found with the bounded parse and the exact canvas
@@ -0,0 +1,133 @@
use super::super::{source, stack_cache};
use super::*;
fn incomplete_svg() -> Vec<u8> {
let image = photocraft_codecs::Image::from_u8(1, 1, photocraft_codecs::ChannelLayout::Rgba, vec![0, 255, 0, 255]).unwrap();
let mut png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap();
let idat = png.windows(4).position(|bytes| bytes == b"IDAT").unwrap();
// Keep the complete IHDR and dimensions, but damage actual compressed pixels.
*png.get_mut(idat + 4).unwrap() ^= 0xff;
assert_eq!(photocraft_codecs::probe_allocation_size(&png).unwrap(), (1, 1));
let data = png.iter().map(|byte| format!("%{byte:02X}")).collect::<String>();
format!("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"2\" height=\"2\"><!--stack-completeness-review--><rect width=\"2\" height=\"2\" fill=\"red\"/><image width=\"2\" height=\"2\" href=\"data:image/png,{data}\"/></svg>").into_bytes()
}
fn smart_svg(bytes: Vec<u8>) -> SmartObject {
SmartObject::new(SmartSource::Embedded { file_name: "Stack completeness.svg".into(), bytes: Arc::new(bytes) }, Affine::IDENTITY, None)
}
fn old_stack_key(bytes: &[u8], fmt: PixelFormat, mode: photocraft_doc::StackMode) -> source::CacheKey {
let mut key = source::cache_key(bytes, fmt);
key.0 = *blake3::hash(&[&key.0[..], b"stack:", mode.id().as_bytes()].concat()).as_bytes();
key
}
fn old_placed_key(bytes: &[u8], doc: &Document, smart: &SmartObject) -> StageKey {
let key = stack_cache::placed_key(bytes, doc.pixel_format(), smart, doc.bounds());
let mut hash = blake3::Hasher::new();
hash.update(&key);
hash.update(&crate::color_cmds::document_profile(doc).to_bytes());
*hash.finalize().as_bytes()
}
#[test]
fn gzipped_svg_stack_retains_ordinary_import_for_misnamed_sources() {
use std::io::Write;
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
encoder.write_all(&incomplete_svg()).unwrap();
let bytes = Arc::new(encoder.finish().unwrap());
let session = session(8);
let doc = &session.active().unwrap().doc;
for name in ["logo.gz", "without-extension"] {
let mut smart = SmartObject::new(SmartSource::Embedded { file_name: name.into(), bytes: bytes.clone() }, Affine::IDENTITY, None);
assert!(decode_source(name, &bytes).is_ok());
smart.stack_mode = Some(photocraft_doc::StackMode::Mean);
let rendered = render(doc, &smart).unwrap().unwrap();
assert_eq!(rendered.rgba(1, 1), [1., 0., 0., 1.]);
assert_eq!(source_box(doc, &smart), Some([0., 0., 2., 2.]));
}
}
#[test]
fn svg_stack_rejects_incomplete_pixels_repeatedly_but_ordinary_placement_keeps_warnings() {
let session = session(8);
let doc = &session.active().unwrap().doc;
let bytes = incomplete_svg();
let mut smart = smart_svg(bytes.clone());
let (ordinary, warnings) = render_with_warnings(doc, &smart).unwrap();
assert_eq!(ordinary.unwrap().rgba(1, 1), [1., 0., 0., 1.]);
assert_eq!(warnings.len(), 1);
assert!(warnings[0].contains("embedded image was omitted"));
smart.stack_mode = Some(photocraft_doc::StackMode::Mean);
for _ in 0..2 {
assert!(stack_image("Stack completeness.svg", &bytes, PixelFormat::RGBA32F, photocraft_doc::StackMode::Mean).is_err());
assert!(render(doc, &smart).is_err());
assert!(render_with_warnings(doc, &smart).is_err());
assert_eq!(source_box(doc, &smart), None);
assert!(smart.cache.is_none());
}
}
#[test]
fn svg_stack_does_not_reuse_incomplete_legacy_source_or_filter_stages() {
let _cache = crate::edit_menu_cmds::PURGE_TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let session = session(8);
let doc = &session.active().unwrap().doc;
let bytes = incomplete_svg();
let mut smart = smart_svg(bytes.clone());
smart.stack_mode = Some(photocraft_doc::StackMode::Mean);
let mut poisoned = Surface::new(PixelFormat::RGBA32F);
poisoned.fill_rect(Rect::new(0, 0, 2, 2), &[0., 1., 0., 1.]);
let key = old_stack_key(&bytes, PixelFormat::RGBA32F, photocraft_doc::StackMode::Mean);
source::cache_put(key, source::SourceImage { surface: Arc::new(poisoned), bounds: Rect::new(0, 0, 2, 2) });
assert!(stack_image("Stack completeness.svg", &bytes, PixelFormat::RGBA32F, photocraft_doc::StackMode::Mean).is_err());
let mut poisoned = Surface::new(doc.pixel_format());
poisoned.fill_rect(Rect::new(0, 0, 2, 2), &[0., 1., 0., 1.]);
let stage = Stage { surface: poisoned, extent: doc.bounds() };
let placed = old_placed_key(&bytes, doc, &smart);
stack_cache::put(placed, &stage);
assert!(render(doc, &smart).is_err(), "old placed pixels must not bypass strict decoding");
smart.smart_filters.push(SmartFilter {
command: "filter.blur.gaussianBlur".into(),
params: json!({"radius": 1}),
blend: BlendMode::Normal,
opacity: 1.,
visible: true,
});
let filtered = stack_cache::filter_key(&placed, &smart.smart_filters[0], None);
stack_cache::put(filtered, &stage);
assert!(render(doc, &smart).is_err(), "old deepest filter stages must not bypass strict decoding");
assert!(render_with_warnings(doc, &smart).is_err());
}
#[test]
fn complete_svg_stack_keeps_mean_pixels_across_source_stage_and_warning_render_caches() {
let bytes = br#"<svg xmlns="http://www.w3.org/2000/svg" width="2" height="2"><!--complete-stack-review--><rect width="2" height="2" fill="red"/><rect width="2" height="2" fill="blue"/></svg>"#;
let session = session(32);
let mut doc = (*session.active().unwrap().doc).clone();
doc.icc_profile = Some(craft_cms::Builtin::Srgb.profile().to_bytes());
let mut smart = smart_svg(bytes.to_vec());
smart.stack_mode = Some(photocraft_doc::StackMode::Mean);
// The red/blue Mean is 0.5 in the SVG's U8 encoding. Existing source
// conversion rounds it to 128/255 before widening and decoding the sRGB
// transfer for F32. The explicit sRGB destination keeps the rendered result
// within ICC roundoff of that value (the matrix path is not bit-exact).
let expected = photocraft_color::convert::srgb_to_linear(128.0 / 255.0);
let check_mean = |pixel: [f32; 4]| {
assert!((pixel[0] - expected).abs() < 3e-5, "red Mean: {pixel:?}");
assert!(pixel[1].abs() < 1e-6, "green Mean: {pixel:?}");
assert!((pixel[2] - expected).abs() < 3e-5, "blue Mean: {pixel:?}");
assert_eq!(pixel[3], 1.0);
};
for _ in 0..2 {
let source = stack_image("Complete.svg", bytes, PixelFormat::RGBA32F, photocraft_doc::StackMode::Mean).unwrap();
check_mean(source.surface.rgba(1, 1));
let strict = render(&doc, &smart).unwrap().unwrap();
check_mean(strict.rgba(1, 1));
let (reported, warnings) = render_with_warnings(&doc, &smart).unwrap();
assert_eq!(reported.unwrap(), strict);
assert!(warnings.is_empty());
assert_eq!(source_box(&doc, &smart), Some([0., 0., 2., 2.]));
}
}
+5 -1
View File
@@ -385,6 +385,7 @@ fn update_contents_with_frame_budget(s: &mut Session, p: &Value, native: bool, f
replacements.push(replacement);
}
// Finish every fallible render before committing any document state.
let mut sources = crate::smart_cmds::WarningRenderSources::new(doc);
for replacement in &mut replacements {
if let Some(preview) = vector_preview.as_ref() {
// This exact SVG was fully validated above. Render only a disposable display
@@ -402,7 +403,7 @@ fn update_contents_with_frame_budget(s: &mut Session, p: &Value, native: bool, f
sm.cache = rendered.cache;
} else {
let LayerContent::Smart(sm) = &mut replacement.content else { return Err(EngineError::NoLayer(replacement.id)) };
let (surface, omitted) = crate::smart_cmds::render_with_warnings(doc, sm)?;
let (surface, omitted) = crate::smart_cmds::render_with_warnings_using(sm, &mut sources)?;
sm.cache = Some(surface.ok_or_else(|| bad(UPDATE, "SVG contents could not be rendered"))?);
for warning in omitted {
if !warnings.contains(&warning) {
@@ -412,6 +413,7 @@ fn update_contents_with_frame_budget(s: &mut Session, p: &Value, native: bool, f
}
crate::smart_cmds::detach_psd(replacement);
}
drop(sources);
s.edit(if native { "Update Vector Contents" } else { "Update SVG Contents" }, |doc, _| {
for replacement in replacements {
let id = replacement.id;
@@ -459,5 +461,7 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
#[cfg(test)]
mod source_cache_tests;
#[cfg(test)]
mod tests;
@@ -0,0 +1,306 @@
use super::*;
use crate::smart_cmds::{WARNING_SOURCE_DECODES, WARNING_SOURCE_LIMIT, WarningRenderSources, render_with_warnings_using};
use photocraft_color::{ColorMode, PixelFormat, SampleType};
use photocraft_doc::SmartFilter;
use photocraft_geom::Affine;
fn artwork(width: u32, height: u32) -> String {
let image = photocraft_codecs::Image::from_u8(width, height, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat((width * height) as usize)).unwrap();
let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap();
let encoded = base64::engine::general_purpose::STANDARD.encode(png);
format!(
r##"<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><image width="8" height="16" preserveAspectRatio="none" href="data:image/png;base64,{encoded}"/><rect x="8" width="8" height="16" fill="#808080"/><image width="1" height="1" href="data:image/png;base64,A"/></svg>"##
)
}
fn object(svg: &str) -> SmartObject {
SmartObject::new(SmartSource::Embedded { file_name: "Memo.svg".into(), bytes: Arc::new(svg.as_bytes().to_vec()) }, Affine::IDENTITY, None)
}
fn count() -> usize {
WARNING_SOURCE_DECODES.with(std::cell::Cell::get)
}
fn reset() {
WARNING_SOURCE_DECODES.with(|count| count.set(0));
}
fn assert_update_warnings(result: &Value) {
let warnings = result["warnings"].as_array().unwrap();
let omitted = "SVG: 1 embedded image was omitted";
assert_eq!(warnings.iter().filter(|warning| warning.as_str().unwrap().starts_with(omitted)).count(), 1);
assert!(warnings.len() <= 2, "at most one omission and one image-layer information notice: {warnings:?}");
assert!(warnings.iter().all(|warning| {
let warning = warning.as_str().unwrap();
warning.starts_with(omitted) || warning == "SVG: embedded images are pixel layers"
}));
}
fn draw(sources: &mut WarningRenderSources<'_>, sm: &SmartObject) -> photocraft_raster::Surface {
let (surface, warnings) = render_with_warnings_using(sm, sources).unwrap();
assert_eq!(warnings.len(), 1);
surface.unwrap()
}
fn shared_session(instances: usize) -> (Session, LayerId) {
let mut s = Session::new();
s.execute("file.new", json!({"width":32,"height":32})).unwrap();
let original = br#"<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><rect width="16" height="16" fill="red"/></svg>"#;
let placed = crate::file_cmds::place_bytes(&mut s, "Shared.svg", original.to_vec(), None, &json!({"smartObject":true})).unwrap();
let id = LayerId(placed["layer"].as_u64().unwrap());
let first = s.active().unwrap().doc.layer(id).unwrap().clone();
let doc = Arc::make_mut(&mut s.active_mut().unwrap().doc);
for index in 1..instances {
let mut layer = first.duplicate();
let LayerContent::Smart(sm) = &mut layer.content else { panic!("smart") };
sm.transform = Affine::translate((index % 4) as f64, (index % 3) as f64);
layer.opacity = 0.5;
doc.layers.push(layer);
}
(s, id)
}
fn request(s: &mut Session, id: LayerId, svg: &str) -> Value {
let handoff = s.execute(EXPORT, json!({"layer":id.0})).unwrap();
json!({"document":handoff["document"],"layer":id.0,"contentsId":handoff["contentsId"],"fingerprint":handoff["fingerprint"],"svg":svg})
}
#[test]
fn warning_source_profile_context_stays_lazy_for_non_svg_and_missing_sources() {
let doc = Document::new("Raster", Size::new(8, 8), ColorMode::Rgb, SampleType::U8);
let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat(4)).unwrap();
let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap();
let sm = SmartObject::new(SmartSource::Embedded { file_name: "Raster.png".into(), bytes: Arc::new(png) }, Affine::IDENTITY, None);
let expected = crate::smart_cmds::render(&doc, &sm).unwrap();
let mut sources = WarningRenderSources::new(&doc);
assert!(!sources.profile_initialized());
reset();
let (surface, warnings) = render_with_warnings_using(&sm, &mut sources).unwrap();
assert_eq!(surface, expected);
assert!(warnings.is_empty());
assert!(!sources.profile_initialized(), "a strict non-SVG cache hit needs no SVG color context");
let missing = SmartObject::new(SmartSource::Linked { path: String::new() }, Affine::IDENTITY, None);
let (surface, warnings) = render_with_warnings_using(&missing, &mut sources).unwrap();
assert!(surface.is_none());
assert!(warnings.is_empty());
assert!(!sources.profile_initialized());
assert_eq!(count(), 0);
draw(&mut sources, &object(&artwork(4, 4)));
assert!(sources.profile_initialized());
assert_eq!(count(), 1);
}
#[test]
fn shared_svg_update_decodes_one_source_for_equal_scale_and_keeps_warning_caches_private() {
let (mut s, id) = shared_session(100);
let before = s.active().unwrap().doc.clone();
let svg = artwork(8, 8);
let params = request(&mut s, id, &svg);
reset();
let result = s.execute(UPDATE, params).unwrap();
assert_eq!(count(), 1, "each placement must reuse the update's source-space render");
assert_update_warnings(&result);
let doc = &s.active().unwrap().doc;
let instances: Vec<_> = doc.layers.iter().filter(|layer| matches!(&layer.content, LayerContent::Smart(_))).collect();
assert_eq!(instances.len(), 100);
for layer in instances {
let sm = smart(doc, layer.id).unwrap();
let previous = before.layer(layer.id).unwrap();
assert_eq!(layer.opacity, previous.opacity);
assert_eq!(sm.transform, smart(&before, layer.id).unwrap().transform);
assert_eq!(embedded(doc, sm).unwrap().1, svg.as_bytes());
let x = sm.transform.m[4] as i32;
let y = sm.transform.m[5] as i32;
assert_eq!(sm.cache.as_ref().unwrap().rgba(x + 3, y + 3), [0., 1., 0., 1.]);
}
let sm = smart(doc, id).unwrap();
assert!(crate::smart_cmds::render(doc, sm).is_err(), "strict global cache must remain unpoisoned");
let mut stack = sm.clone();
stack.stack_mode = Some(photocraft_doc::StackMode::Mean);
assert!(crate::smart_cmds::render(doc, &stack).is_err(), "Stack Mode still requires complete artwork");
assert!(s.undo());
assert_eq!(s.active().unwrap().doc, before);
assert!(s.redo());
assert_eq!(embedded(&s.active().unwrap().doc, smart(&s.active().unwrap().doc, id).unwrap()).unwrap().1, svg.as_bytes());
}
#[test]
fn local_svg_sources_separate_scale_and_profile_but_keep_instance_filters_and_placement() {
let mut doc = Document::new("Profile", Size::new(64, 64), ColorMode::Rgb, SampleType::F32);
doc.icc_profile = Some(craft_cms::Builtin::Srgb.profile().to_bytes());
let mut linear = doc.clone();
linear.icc_profile = Some(craft_cms::Builtin::LinearSrgb.profile().to_bytes());
let first = object(&artwork(4, 4));
let mut moved = first.clone();
moved.transform = Affine::translate(20., 0.);
moved.smart_filters.push(SmartFilter {
command: "image.adjustments.invert".into(),
params: json!({}),
blend: photocraft_color::BlendMode::Normal,
opacity: 0.5,
visible: true,
});
let mut sources = WarningRenderSources::new(&doc);
reset();
let a = draw(&mut sources, &first);
let b = draw(&mut sources, &moved);
assert_eq!(count(), 1);
assert_eq!(a.rgba(3, 3), [0., 1., 0., 1.]);
assert_eq!(b.rgba(3, 3), [0.; 4]);
assert!(b.rgba(23, 3).iter().take(3).all(|value| (*value - 0.5).abs() < 0.01));
let mut scaled = first.clone();
scaled.transform = Affine { m: [2., 0., 0., 2., 0., 0.] };
draw(&mut sources, &scaled);
assert_eq!(count(), 2, "different raster scales require different source renders");
let corrected = draw(&mut WarningRenderSources::new(&linear), &first);
assert_eq!(count(), 3, "a different document interpretation cannot reuse the earlier source");
assert!((a.rgba(12, 3)[0] - 0.502).abs() < 0.01);
assert!((corrected.rgba(12, 3)[0] - 0.216).abs() < 0.01);
assert_eq!(draw(&mut sources, &first), a);
assert_eq!(count(), 3);
}
#[test]
fn local_svg_source_memo_evicts_and_oversize_entries_render_without_retention() {
let mut doc = Document::new("Budget", Size::new(64, 64), ColorMode::Rgb, SampleType::U8);
doc.icc_profile = Some(craft_cms::Builtin::Srgb.profile().to_bytes());
let first = object(&artwork(4, 4));
let mut scaled = first.clone();
scaled.transform = Affine { m: [2., 0., 0., 2., 0., 0.] };
let tile = photocraft_raster::tile_storage_bytes(Rect::new(0, 0, 32, 32), &PixelFormat::RGBA8) as usize;
for (budget, limit) in [(tile + 4096, 32), (usize::MAX, 1)] {
let mut sources = WarningRenderSources::with_limits(&doc, budget, limit);
reset();
let expected = draw(&mut sources, &first);
draw(&mut sources, &scaled);
assert_eq!(draw(&mut sources, &first), expected);
assert_eq!(count(), 3, "byte and entry limits both evict the old scale");
}
let huge_source = artwork(4, 4).replace("</svg>", &format!("<!--{}--></svg>", " ".repeat(tile + 8192)));
let encoded = object(&huge_source);
let mut sources = WarningRenderSources::with_limits(&doc, tile + 4096, 32);
reset();
let expected = draw(&mut sources, &encoded);
assert_eq!(draw(&mut sources, &encoded), expected);
assert_eq!(count(), 1, "the immutable document owns encoded bytes; only rendered output belongs to the memo budget");
let mut output_too_large = WarningRenderSources::with_limits(&doc, tile - 1, 32);
reset();
let expected = draw(&mut output_too_large, &first);
assert_eq!(draw(&mut output_too_large, &first), expected);
assert_eq!(count(), 2, "oversize rendered output remains an uncached success");
let mut disabled = WarningRenderSources::with_limits(&doc, 0, 0);
assert_eq!(draw(&mut disabled, &first), draw(&mut WarningRenderSources::new(&doc), &first));
}
#[test]
fn shared_svg_update_render_failure_and_cancelled_authorization_preserve_document_history() {
for cancel in [false, true] {
let (mut s, id) = shared_session(2);
let doc = Arc::make_mut(&mut s.active_mut().unwrap().doc);
let LayerContent::Smart(sm) = &mut doc.layers.last_mut().unwrap().content else { panic!("smart") };
sm.smart_filters.push(SmartFilter {
command: if cancel { "image.adjustments.invert" } else { "unsupported.persisted.filter" }.into(),
params: json!({}),
blend: photocraft_color::BlendMode::Normal,
opacity: 1.,
visible: true,
});
if cancel {
s.authorize = Some(|command, _| if command == "image.adjustments.invert" { Err(EngineError::Cancelled) } else { Ok(()) });
}
let before = s.active().unwrap().doc.clone();
let history = s.active().unwrap().history.entries();
let revision = s.active().unwrap().revision;
let params = request(&mut s, id, &artwork(4, 4));
reset();
let error = s.execute(UPDATE, params).unwrap_err();
if cancel {
assert!(matches!(error, EngineError::Cancelled), "expected the authority cancellation, got {error}");
} else {
assert!(error.to_string().contains("unsupported visible filters"), "{error}");
}
assert_eq!(s.active().unwrap().doc, before);
assert_eq!(s.active().unwrap().history.entries(), history);
assert_eq!(s.active().unwrap().revision, revision);
assert_eq!(count(), if cancel { 0 } else { 1 });
}
}
#[test]
fn shared_svg_update_keeps_the_existing_placed_pixel_budget_atomic() {
let (mut s, id) = shared_session(2);
let LayerContent::Smart(sm) = &mut Arc::make_mut(&mut s.active_mut().unwrap().doc).layers.last_mut().unwrap().content else { panic!("smart") };
sm.transform = Affine { m: [1000., 0., 0., 1000., 0., 0.] };
let before = s.active().unwrap().doc.clone();
let history = s.active().unwrap().history.entries();
let revision = s.active().unwrap().revision;
let params = request(&mut s, id, &artwork(4, 4));
reset();
assert!(s.execute(UPDATE, params).is_err());
assert_eq!(count(), 0, "placed-frame admission precedes source rendering");
assert_eq!(s.active().unwrap().doc, before);
assert_eq!(s.active().unwrap().history.entries(), history);
assert_eq!(s.active().unwrap().revision, revision);
}
#[test]
#[ignore = "24MP embedded PNG / 100 shared instances; run once in release for performance qualification"]
fn shared_svg_update_24mp_source_timing() {
struct MemoLimit(Option<usize>);
impl MemoLimit {
fn set(limit: usize) -> Self {
Self(WARNING_SOURCE_LIMIT.with(|current| current.replace(Some(limit))))
}
}
impl Drop for MemoLimit {
fn drop(&mut self) {
WARNING_SOURCE_LIMIT.with(|current| current.set(self.0));
}
}
let previous_limit = WARNING_SOURCE_LIMIT.with(std::cell::Cell::get);
// Encode once. Each pass builds the same initial document and handoff outside
// the clock; UPDATE includes its normal import and all instance rendering.
let svg = artwork(6000, 4000);
let mut expected = None;
let mut timings = Vec::new();
for (label, limit, decodes) in [("optimized-before", 32, 1), ("memo-off", 0, 100), ("optimized-after", 32, 1)] {
let (mut s, id) = shared_session(100);
let params = request(&mut s, id, &svg);
let _restore = MemoLimit::set(limit);
reset();
let start = std::time::Instant::now();
let result = s.execute(UPDATE, params).unwrap();
let elapsed = start.elapsed().as_secs_f64() * 1000.;
assert_eq!(count(), decodes, "{label}");
assert_update_warnings(&result);
let doc = &s.active().unwrap().doc;
let mut pixels = blake3::Hasher::new();
let mut sources = blake3::Hasher::new();
let mut samples = Vec::new();
for layer in doc.layers.iter().filter(|layer| matches!(&layer.content, LayerContent::Smart(_))) {
let sm = smart(doc, layer.id).unwrap();
let source = embedded(doc, sm).unwrap().1;
assert_eq!(source, svg.as_bytes());
sources.update(blake3::hash(source).as_bytes());
let cache = sm.cache.as_ref().unwrap();
for value in cache.read_region(doc.bounds()) {
pixels.update(&value.to_bits().to_le_bytes());
}
let (x, y) = (sm.transform.m[4] as i32, sm.transform.m[5] as i32);
let sample = cache.rgba(x + 3, y + 3);
assert_eq!(sample, [0., 1., 0., 1.]);
samples.push(sample);
}
assert_eq!(samples.len(), 100);
let signature = (*pixels.finalize().as_bytes(), *sources.finalize().as_bytes(), samples, result["warnings"].clone());
if let Some(expected) = &expected {
assert_eq!(&signature, expected, "pixels, samples, encoded sources and warnings must match: {label}");
} else {
expected = Some(signature);
}
eprintln!("24MP PNG / 16x16 SVG / 100 shared instances: {label}: {elapsed:.3} ms, {decodes} source renders");
timings.push(elapsed);
}
eprintln!("optimized median of two: {:.3} ms; memo-off: {:.3} ms", (timings[0] + timings[2]) / 2., timings[1]);
assert_eq!(WARNING_SOURCE_LIMIT.with(std::cell::Cell::get), previous_limit, "test override restored");
}
+18 -7
View File
@@ -419,13 +419,24 @@ fn original_vector_formats_save_atomically_and_survive_undo_and_persistence() {
/// is accepted with that image left out, as placing the same SVG is.
#[test]
fn saved_svg_with_an_unreadable_embedded_image_still_updates() {
let (mut s, id) = session(8);
let edited = r#"<svg xmlns="http://www.w3.org/2000/svg" width="8" height="6"><image width="4" height="6" href="data:image/bmp,BM"/><rect x="4" width="4" height="6" fill="blue"/></svg>"#;
let params = request(&mut s, id, edited);
let result = s.execute(UPDATE, params).unwrap();
assert_eq!(result["updated"], true);
assert!(result["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("embedded image was omitted")));
assert_eq!(source(&s, id), edited.as_bytes());
for href in ["data:image/bmp,BM", "data:image/png;base64,A"] {
let (mut s, id) = session(8);
let edited = format!(
r#"<svg xmlns="http://www.w3.org/2000/svg" width="8" height="6"><image width="4" height="6" href="{href}"/><rect x="4" width="4" height="6" fill="blue"/></svg>"#
);
let params = request(&mut s, id, &edited);
let result = s.execute(UPDATE, params).unwrap();
assert_eq!(result["updated"], true);
let warnings = result["warnings"].as_array().unwrap();
assert_eq!(warnings.len(), 1, "{href}: {warnings:?}");
assert!(warnings[0].as_str().unwrap().contains("embedded image was omitted"));
assert_eq!(source(&s, id), edited.as_bytes());
let doc = &s.active().unwrap().doc;
let sm = smart(doc, id).unwrap();
assert_eq!(sm.cache.as_ref().unwrap().rgba(18, 11), [0.0, 0.0, 1.0, 1.0]);
assert!(crate::smart_cmds::render(doc, sm).is_err(), "warning-bearing save must not populate strict caches: {href}");
assert_eq!(source(&s, id), edited.as_bytes(), "strict refusal must leave the unrepaired source intact");
}
}
/// updateSvg replaces SVG contents only: it never turns an AI, PDF or EPS source into SVG.
+2 -1
View File
@@ -267,7 +267,8 @@ mod tests {
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
let fmt = PixelFormat::new(mode, sample, true);
let mut source = Surface::with_default(fmt, &vec![0.3; fmt.channels()]);
let bounds = Rect::from_xywh(-128, -128, 512, 256);
// 256 x 256 is exactly the U16 table's area threshold (`use_table`), so the table path still runs (#15652).
let bounds = Rect::from_xywh(-128, -128, 256, 256);
let data: Vec<_> = (0..32 * 24 * fmt.channels())
.map(|i| {
let v = (i * 37 % 257) as f32 / 256.0;
+1 -1
View File
@@ -343,7 +343,7 @@ pub struct Interface {
/// The theme id of the light slot.
#[serde(deserialize_with = "theme_ids::theme")]
pub light_theme: String,
/// Theme ids shown in the appearance button's context menu.
/// Theme ids starred in Preferences › Interface; #13581 decides where they show.
#[serde(deserialize_with = "theme_ids::themes")]
pub favorite_themes: Vec<String>,
/// Pasteboard colour in standard screen mode (`canvasCustomColor` when "custom").
@@ -31,15 +31,14 @@ fn raster(d: &Document, name: &str, bounds: Rect, color: [f32; 4]) -> Layer {
layer
}
/// Keeps the measured straight geometry and fits turned controls under the 1 MiB transform limit
/// that the preference test can set process-wide.
fn scene_divisor(turned: bool) -> i32 {
if turned { 2 } else { 1 }
}
/// The scene is the measured 800 × 500 one at half size: the fills' cost grows with the canvas, and
/// turned controls must fit under the 1 MiB transform limit that the preference test can set
/// process-wide.
const DIVISOR: i32 = 2;
/// The measured scene, with a deliberately different crop extension colour.
fn scene(turned: bool) -> (Session, Layers) {
let divisor = scene_divisor(turned);
fn scene() -> (Session, Layers) {
let divisor = DIVISOR;
let rect = |x0, y0, x1, y1| Rect::new(x0 / divisor, y0 / divisor, x1 / divisor, y1 / divisor);
let mut s = Session::new();
s.execute("file.new", json!({"width":800/divisor,"height":500/divisor,"depth":8,"background":"white"})).unwrap();
@@ -72,14 +71,13 @@ fn select(s: &mut Session, id: LayerId) {
/// Extends the frame to the right by one eighth of the original width.
fn frame(turned: bool) -> Value {
let divisor = scene_divisor(turned);
let divisor = DIVISOR;
json!({"x":0,"y":0,"width":900/divisor,"height":500/divisor,"angle":if turned { 10 } else { 0 },"deleteCroppedPixels":true})
}
/// Samples the same relative point inside the new strip in both fixture sizes.
fn extension_sample(turned: bool) -> (i32, i32) {
let divisor = scene_divisor(turned);
(850 / divisor, 400 / divisor)
fn extension_sample() -> (i32, i32) {
(850 / DIVISOR, 400 / DIVISOR)
}
fn crop(s: &mut Session, mut p: Value, aware: bool) {
@@ -133,11 +131,11 @@ fn undo_redo(s: &mut Session, before: &Document) {
assert_eq!(s.active().unwrap().history.undo_label(), Some("Content-aware Crop"));
}
/// Matches the three measured rows at their original size, bounds and sample points.
/// Matches the three measured rows: bounds and sample points, at half the measured size.
#[test]
fn measured_straight_rows_fill_background_and_only_the_active_raster() {
for row in 0..3 {
let (mut s, ids) = scene(false);
let (mut s, ids) = scene();
let active = if row == 1 { ids.edge } else { ids.quads };
if row == 2 {
s.edit("Layer 0", |d, _| {
@@ -155,22 +153,22 @@ fn measured_straight_rows_fill_background_and_only_the_active_raster() {
let past = s.active().unwrap().history.past_len();
crop(&mut s, p, true);
let d = doc(&s);
assert_eq!((d.size.width, d.size.height), (900, 500));
assert_eq!((d.size.width, d.size.height), (900 / DIVISOR as u32, 500 / DIVISOR as u32));
let mut untouched = vec![ids.small, ids.hidden, ids.text];
untouched.push(if row == 1 { ids.quads } else { ids.edge });
if row == 2 {
assert!(d.background().is_none());
untouched.push(ids.background);
} else {
assert_eq!(d.layer(ids.background).unwrap().surface().unwrap().content_bounds(), Rect::new(0, 0, 900, 500));
pixel(d, ids.background, 850, 400, WHITE);
assert_eq!(d.layer(ids.background).unwrap().surface().unwrap().content_bounds(), Rect::new(0, 0, 900 / DIVISOR, 500 / DIVISOR));
pixel(d, ids.background, 850 / DIVISOR, 400 / DIVISOR, WHITE);
}
let bounds = if row == 1 { Rect::new(600, 0, 900, 500) } else { Rect::new(0, 0, 900, 500) };
let bounds = if row == 1 { Rect::new(600 / DIVISOR, 0, 900 / DIVISOR, 500 / DIVISOR) } else { Rect::new(0, 0, 900 / DIVISOR, 500 / DIVISOR) };
assert_eq!(d.layer(active).unwrap().surface().unwrap().content_bounds(), bounds);
pixel(d, active, 850, if row == 1 { 400 } else { 125 }, if row == 1 { BLUE } else { GREEN });
pixel(d, active, 850 / DIVISOR, if row == 1 { 400 / DIVISOR } else { 125 / DIVISOR }, if row == 1 { BLUE } else { GREEN });
// The fill adds pixels only where the crop uncovered the canvas: the active layer's own
// pixels inside the old canvas are the plain crop's.
covered_as_plain(d, &plain, active, Rect::new(0, 0, 800, 500));
covered_as_plain(d, &plain, active, Rect::new(0, 0, 800 / DIVISOR, 500 / DIVISOR));
unchanged(d, &plain, &untouched);
named_one_step(&s, past, "Content-aware Crop");
undo_redo(&mut s, &before);
@@ -180,9 +178,9 @@ fn measured_straight_rows_fill_background_and_only_the_active_raster() {
/// Checks own-layer donors and exact non-target parity after rotation.
#[test]
fn turned_rows_sample_each_target_and_leave_other_layers_at_plain_crop() {
let (x, y) = extension_sample(true);
let (x, y) = extension_sample();
for row in 0..3 {
let (mut s, ids) = scene(true);
let (mut s, ids) = scene();
// Uniform donors isolate target selection from the existing turned-fill sampling policy.
s.edit("Uniform Quads", |d, _| {
let fmt = d.pixel_format();
@@ -222,8 +220,8 @@ fn turned_rows_sample_each_target_and_leave_other_layers_at_plain_crop() {
#[test]
fn background_active_is_not_a_second_target() {
for turned in [false, true] {
let (x, y) = extension_sample(turned);
let (mut s, ids) = scene(turned);
let (x, y) = extension_sample();
let (mut s, ids) = scene();
select(&mut s, ids.background);
let p = frame(turned);
let plain = plain_control(&mut s, &p);
@@ -244,9 +242,9 @@ fn background_active_is_not_a_second_target() {
#[test]
fn unmeasured_active_targets_and_delete_off_keep_the_legacy_target() {
for turned in [false, true] {
let (x, y) = extension_sample(turned);
let (x, y) = extension_sample();
for (text, locked_group, delete) in [(true, false, true), (false, true, true), (false, false, false)] {
let (mut s, ids) = scene(turned);
let (mut s, ids) = scene();
let active = if text { ids.text } else { ids.quads };
if locked_group {
s.edit("Group active", |d, _| {
@@ -273,13 +271,13 @@ fn unmeasured_active_targets_and_delete_off_keep_the_legacy_target() {
/// Checks the plain history name for interior crops and crops with synthesis disabled.
#[test]
fn no_fill_or_content_aware_off_keeps_the_crop_history_name() {
for (p, aware, turned) in [
(json!({"x":20,"y":20,"width":40,"height":30}), true, false),
(json!({"x":20,"y":20,"width":40,"height":30,"angle":10}), true, true),
(frame(false), false, false),
(frame(true), false, true),
for (p, aware) in [
(json!({"x":20,"y":20,"width":40,"height":30}), true),
(json!({"x":20,"y":20,"width":40,"height":30,"angle":10}), true),
(frame(false), false),
(frame(true), false),
] {
let (mut s, ids) = scene(turned);
let (mut s, ids) = scene();
select(&mut s, ids.quads);
let past = s.active().unwrap().history.past_len();
crop(&mut s, p, aware);
@@ -332,8 +330,8 @@ fn turned_hidden_overhang_coverage_belongs_to_each_layer() {
#[test]
fn donorless_added_target_keeps_the_background_fill() {
for turned in [false, true] {
let (x, y) = extension_sample(turned);
let (mut s, ids) = scene(turned);
let (x, y) = extension_sample();
let (mut s, ids) = scene();
let empty = s
.edit("Empty target", |d, active| {
let layer = Layer::raster("Empty", d.pixel_format());
@@ -381,3 +381,56 @@ fn review_picker_reads_the_addressed_mask_layer() {
}
}
}
/// A Smart Filter mask is a gray target like a layer mask: the picker reads the stored mask, or the implicit Reveal
/// All before anything is stored, without materializing it, and the commit edits only the filter mask, in every
/// colour mode and native depth. (The UI's tone dialogs test only that their pick reaches this target, #15648.)
#[test]
fn filter_mask_picker_samples_and_edits_only_the_filter_mask() {
for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] {
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
for stored in [false, true] {
for kind in ["levels", "curves"] {
let case = format!("{mode:?} {depth:?} stored={stored} {kind}");
let mut s = session(mode, depth);
// A Smart Filter needs the composite selected, not one colour channel, and no Quick Mask (the filter
// would edit the Quick Mask instead).
s.edit("No Quick Mask", |doc, _| {
doc.quick_mask = None;
Ok(())
})
.unwrap();
s.active_mut().unwrap().channel_view.target = ChannelTarget::Composite;
s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();
s.execute("filter.blur.gaussianBlur", json!({"radius": 1})).unwrap();
if stored {
s.execute("edit.fill", json!({"target": "filterMask", "contents": "color", "color": "#404040"})).unwrap();
}
let id = s.active().unwrap().active_layer.unwrap();
let before = s.active().unwrap().doc.clone();
let p = json!({"target": "filterMask", "eyedropper": {"point": "white", "at": [8, 8]}});
let picked = adjust_params::destructive_eyedropper(&s, kind, &p).unwrap().unwrap();
assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc), "sampling is read-only: {case}");
let white = if stored { 64.0 } else { 255.0 };
let sampled = if kind == "levels" {
adjust_params::to_params(&picked)["inWhite"].as_f64().unwrap()
} else {
adjust_params::to_params(&picked)["points"].as_array().unwrap().last().unwrap()[0].as_f64().unwrap()
};
assert!((sampled - white).abs() < 1.0, "{case}: sampled {sampled}, want {white}");
s.execute(&format!("image.adjustments.{kind}"), p).unwrap();
let doc = &s.active().unwrap().doc;
let (LayerContent::Smart(old), LayerContent::Smart(new)) = (&before.layer(id).unwrap().content, &doc.layer(id).unwrap().content) else {
panic!("{case}: not a smart object")
};
assert!(new.filter_mask.as_ref().unwrap().surface.sample_channel(8, 8, 0) > 0.99, "{case}");
assert_eq!(new.smart_filters, old.smart_filters, "{case}: the adjustment edits the mask, adds no filter");
assert_eq!(new.source, old.source, "{case}");
assert_eq!(doc.layer(id).unwrap().mask, before.layer(id).unwrap().mask, "{case}: the layer mask");
assert_eq!(doc.channels, before.channels, "{case}");
assert_eq!(doc.quick_mask, before.quick_mask, "{case}");
}
}
}
}
}
-1
View File
@@ -15,7 +15,6 @@ photocraft-color = { workspace = true }
photocraft-raster = { workspace = true }
photocraft-doc = { workspace = true }
photocraft-codecs = { workspace = true }
photocraft-formats = { workspace = true }
craft-pcraft-format = { workspace = true }
craft-pcraft-bundle = { workspace = true }
craft-zip = { workspace = true }
+9 -9
View File
@@ -382,15 +382,15 @@ zip_cases! {
#[test]
fn directory_bundle_roundtrip_all_modes() {
for mode in MODES {
for depth in SampleType::ALL {
let doc = rich_doc(mode, depth);
let dir = temp_dir("dir");
PcraftWriter::new().save_dir(&doc, &dir, &SaveOptions::default()).unwrap();
assert!(dir.join("manifest.json").is_file());
assert_eq!(load_path(&dir).unwrap(), doc, "{mode:?} {depth:?}");
std::fs::remove_dir_all(dir).unwrap();
}
// The directory bundle runs the zip save's `prepare` and object encoding and differs only in the container, which
// does not depend on mode or depth: every mode x depth is `zip_cases!` above (#15652).
for (mode, depth) in [(ColorMode::Rgb, SampleType::U8), (ColorMode::Lab, SampleType::F32)] {
let doc = rich_doc(mode, depth);
let dir = temp_dir("dir");
PcraftWriter::new().save_dir(&doc, &dir, &SaveOptions::default()).unwrap();
assert!(dir.join("manifest.json").is_file());
assert_eq!(load_path(&dir).unwrap(), doc, "{mode:?} {depth:?}");
std::fs::remove_dir_all(dir).unwrap();
}
}
+10 -7
View File
@@ -486,12 +486,13 @@ fn shadows_and_highlights_with_per_pixel_stages() {
cr! { shadows: 30.0, highlights: -30.0, whites: 40.0, blacks: -30.0, encoding_gamma: 1.8},
],
);
// At the dialog's proxy size, at one depth: the depth only changes how the input is
// At the dialog's proxy width, at one depth: the depth only changes how the input is
// quantized (8 and 16 bits both develop with `float = false`), and every depth already ran
// above at 171×113. The size is what matters here (subsampled pyramid levels).
// above at 171×113. The long side is what matters here (subsampled pyramid levels); the short
// one only needs to keep several levels, so the frame is a strip.
let Some(mut g) = gpu() else { return };
let d = compare_at(&mut g, &all, Depth::Sixteen, (858, 572));
eprintln!("shadows/highlights + per pixel 858x572: max |GPU - CPU| = {d:.2e}");
let d = compare_at(&mut g, &all, Depth::Sixteen, (858, 120));
eprintln!("shadows/highlights + per pixel 858x120: max |GPU - CPU| = {d:.2e}");
}
/// Asserts that each of `sets` moves some pixel of the test image by over 2 %, so a comparison
@@ -564,10 +565,12 @@ fn clarity_texture_and_dehaze_with_shadows_highlights_and_per_pixel_stages() {
];
check("clarity/texture/dehaze + shadows/highlights + per pixel", &sets);
let Some(mut g) = gpu() else { return };
// At the dialog's proxy size (Dehaze and Clarity on a copy subsampled twice), and wider (three
// At the dialog's proxy width (Dehaze and Clarity on a copy subsampled twice), and wider (three
// times). One depth per size: the depth only changes how the input is quantized (8 and 16
// bits both develop with `float = false`), and every depth already ran above at 171×113.
for (size, depth) in [((858, 572), Depth::Eight), ((1600, 900), Depth::Float)] {
// bits both develop with `float = false`), and every depth already ran above at 171×113. The
// long side sets the subsampling; the short one only needs to keep several pyramid levels, so
// the frames are strips.
for (size, depth) in [((858, 120), Depth::Eight), ((1600, 120), Depth::Float)] {
let d = compare_at(&mut g, &all, depth, size);
eprintln!("everything {size:?} {depth:?}: max |GPU - CPU| = {d:.2e}");
}
+67 -193
View File
@@ -10,7 +10,6 @@
//! stops and direction in the layer's own gradient fill, with a warning that the exact geometry
//! is not kept.
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, OnceLock, PoisonError};
use craft_svg::tree::draw::{self, tiny_skia};
@@ -25,6 +24,9 @@ use photocraft_raster::Surface;
use crate::{ImportResult, IoError};
#[cfg(test)]
mod xml_reuse_tests;
/// Hard caps on the memory resvg needs to draw a subtree, checked before it draws: craft-svg's
/// `tree::draw`, within this crate's peak pixel budget.
#[cfg(test)]
@@ -300,18 +302,25 @@ fn fallback_face(c: char, used: &[usvg::fontdb::ID], db: &usvg::fontdb::Database
.map(|f| f.id)
}
/// usvg's font choice, with the chosen faces read from memory ([`in_memory`]).
fn font_resolver() -> usvg::FontResolver<'static> {
/// Load the same fonts for top-level and embedded text. usvg requests them only
/// when it shapes text, including text hidden inside an encoded image URL.
fn font_resolver(loaded: &OnceLock<Arc<usvg::fontdb::Database>>, load: fn() -> Arc<usvg::fontdb::Database>) -> usvg::FontResolver<'_> {
let mut resolver = usvg::FontResolver::default();
let select = resolver.select_font;
resolver.select_font = Box::new(move |font, db| {
if db.faces().next().is_none() {
*db = Arc::clone(loaded.get_or_init(load));
}
let id = select(font, db)?;
#[cfg(not(target_arch = "wasm32"))]
let id = in_memory(id, db);
Some(id)
});
#[cfg(not(target_arch = "wasm32"))]
{
let select = usvg::FontResolver::default_font_selector();
usvg::FontResolver {
select_font: Box::new(move |font, db| select(font, db).map(|id| in_memory(id, db))),
select_fallback: Box::new(|c, used, db| fallback_face(c, used, db).map(|id| in_memory(id, db))),
}
resolver.select_fallback = Box::new(|c, used, db| fallback_face(c, used, db).map(|id| in_memory(id, db)));
}
#[cfg(target_arch = "wasm32")]
usvg::FontResolver::default()
resolver
}
#[cfg(not(target_arch = "wasm32"))]
@@ -361,17 +370,17 @@ impl From<ParseFailure> for IoError {
/// Native parsing always reuses the complete-operation worker, including private probes.
/// WASM has no worker stack, so shared outer/embedded XML depth is guarded inline.
fn parse_at_depth<T: Send>(depth: usize, isolated: bool, parse: impl FnOnce(bool) -> Result<T, IoError> + Send) -> Result<T, ParseFailure> {
fn parse_at_depth<T: Send>(depth: usize, parse: impl FnOnce() -> Result<T, IoError> + Send) -> Result<T, ParseFailure> {
#[cfg(not(target_arch = "wasm32"))]
{
let _ = (depth, isolated);
let _ = depth;
// The nested Result distinguishes a worker failure from a normal parser error.
on_svg_stack(|| Ok(parse(true))).map_err(ParseFailure::Isolation)?.map_err(ParseFailure::Decode)
on_svg_stack(|| Ok(parse())).map_err(ParseFailure::Isolation)?.map_err(ParseFailure::Decode)
}
#[cfg(target_arch = "wasm32")]
{
if isolated || depth <= INLINE_XML_DEPTH {
return parse(isolated).map_err(ParseFailure::Decode);
if depth <= INLINE_XML_DEPTH {
return parse().map_err(ParseFailure::Decode);
}
Err(ParseFailure::Isolation(IoError::Svg(format!(
"SVG parsing deeper than {INLINE_XML_DEPTH} levels requires the native app's isolated parser; simplify the drawing or open it in PhotoCraft desktop"
@@ -379,24 +388,19 @@ fn parse_at_depth<T: Send>(depth: usize, isolated: bool, parse: impl FnOnce(bool
}
}
/// Supplies bounded parsing options to direct resolver tests without changing their existing interface.
#[cfg(test)]
fn options(fontdb: Arc<usvg::fontdb::Database>, depth_left: usize) -> usvg::Options<'static> {
options_with_isolation(fontdb, depth_left, false, Arc::new(craft_svg::tree::ImageResolver::new(tree_limits(depth_left, MAX_RASTER_PIXELS))))
}
/// Parse options for an untrusted drawing. `<image href>` resolves only `data:` URLs: a file path
/// or relative href is never read, so opening an SVG cannot pull local files (`/etc/...`,
/// `~/.ssh/...`) into the document. Embedded SVG images get no `<image>` resolution at all
/// (`usvg` already blanks it for sub-SVGs). An embedded SVG may nest `depth_left` levels: it is
/// parsed on top of the drawing's own recursion, so the two depths share [`MAX_XML_DEPTH`].
fn options_with_isolation(
fontdb: Arc<usvg::fontdb::Database>,
_depth_left: usize,
_isolated: bool,
image_resolver: Arc<craft_svg::tree::ImageResolver>,
) -> usvg::Options<'static> {
usvg::Options { resources_dir: None, image_href_resolver: image_resolver.resolver(), fontdb, font_resolver: font_resolver(), ..usvg::Options::default() }
/// Font and resource options for untrusted drawings. The shared validated context
/// installs its own bounded data-only image resolver during conversion.
fn parse_checked_svg(
text: &str,
resolver: &craft_svg::tree::ValidatedImageResolver,
load_fonts: fn() -> Arc<usvg::fontdb::Database>,
) -> Result<(usvg::Tree, bool), IoError> {
let checked = craft_svg::tree::preflight(text, &resolver.limits()).map_err(svg_parse_error)?;
let loaded = OnceLock::new();
let options = usvg::Options { resources_dir: None, font_resolver: font_resolver(&loaded, load_fonts), ..usvg::Options::default() };
let tree = resolver.parse_preflight(checked, options).map_err(svg_parse_error)?;
let fontless_text = loaded.get().is_some_and(|db| db.faces().next().is_none());
Ok((tree, fontless_text))
}
/// A parsed drawing.
@@ -414,8 +418,8 @@ struct Parsed {
/// Parses a drawing, `.svgz` included. The XML is inflated and checked here, before the parser
/// sees it: deeper nesting than [`MAX_XML_DEPTH`] is an error, not a stack overflow. The font
/// database (and its one-off scan of the system fonts) is only loaded when the drawing may
/// contain text.
/// database (and its one-off scan of the system fonts) is loaded only when the drawing requests
/// a text font.
fn parse(bytes: &[u8]) -> Result<Parsed, IoError> {
parse_with(bytes, fonts)
}
@@ -426,10 +430,14 @@ fn tree_limits(depth: usize, raster_pixels: u64) -> craft_svg::tree::Limits {
// PhotoCraft's stack guard counts open tags; the shared SVG preflight counts every
// element, including a self-closing leaf. Allow that leaf at the same guarded depth.
depth: depth.saturating_add(1),
// The shared default is intentionally conservative for general consumers. PhotoCraft
// already guards XML nesting and reference expansion against its 512-level parser
// budget, so pass that same explicit limit through instead of inheriting 256.
tree_depth: depth.saturating_add(1),
// Expanded references consume parser stack even when the source XML is
// shallow. Native parsing owns the larger worker; WASM must keep both
// reference expansion and lexical nesting within its inline allowance.
tree_depth: {
#[cfg(target_arch = "wasm32")]
let depth = depth.min(INLINE_XML_DEPTH);
depth.saturating_add(1)
},
embedded_bytes: usize::try_from(MAX_BOUNDED_SVG_BYTES).unwrap_or(usize::MAX),
embedded_depth: MAX_EMBEDDED_SVG_DEPTH,
embedded_raster_pixels: raster_pixels.min(MAX_RASTER_PIXELS),
@@ -448,23 +456,16 @@ fn parse_with_image_limit(bytes: &[u8], fonts: fn() -> Arc<usvg::fontdb::Databas
if depth > MAX_XML_DEPTH {
return Err(IoError::Svg(format!("elements are nested more than {MAX_XML_DEPTH} levels deep")));
}
let has_text = xml.windows(4).any(|w| w == b"text");
let fontdb = if has_text { fonts() } else { Arc::new(usvg::fontdb::Database::new()) };
let fontless_text = has_text && fontdb.faces().next().is_none();
// Parse the already-bounded-and-decoded text with from_str, not from_data: from_data
// Convert the already-bounded-and-decoded text through checked XML, never from_data:
// re-checks the gzip magic and would decompress a second time without our size limit if
// the inflated content happened to start with a nested gzip stream.
let text = std::str::from_utf8(&xml).map_err(|_| IoError::Svg("the SVG is not valid UTF-8".into()))?;
let image_resolver = Arc::new(craft_svg::tree::ImageResolver::new(tree_limits(MAX_XML_DEPTH, max_image_pixels)));
image_resolver.set_document_depth(depth);
parse_at_depth(depth, false, |isolated| {
image_resolver.check_document(text).map_err(svg_parse_error)?;
let opt = options_with_isolation(fontdb, MAX_XML_DEPTH.saturating_sub(depth), isolated, Arc::clone(&image_resolver));
let tree = guarded_parse(|| craft_svg::tree::parse_text(text, &tree_limits(MAX_XML_DEPTH, max_image_pixels), &opt))?;
let tree = tree.map_err(svg_parse_error)?;
// The resolver already rejects each over-budget optional image before decode.
// Ordinary Open keeps the usable outer drawing, as before the shared-parser
// migration; strict stored previews enforce completeness in their separate path.
let limits = tree_limits(MAX_XML_DEPTH, max_image_pixels);
let image_resolver = craft_svg::tree::ValidatedImageResolver::new(limits);
parse_at_depth(depth, || {
let (tree, fontless_text) = guarded_parse(|| parse_checked_svg(text, &image_resolver, fonts))??;
// Ordinary Open retains usable artwork and discloses optional omissions.
// Strict stored previews enforce completeness in their separate path.
Ok(Parsed { tree, fontless_text, image_usage: image_resolver.usage() })
})
.map_err(IoError::from)
@@ -513,7 +514,7 @@ struct ImageBudget {
/// stored display preview must draw completely, or it isn't used.
strict: bool,
error: Option<String>,
resolver: Arc<craft_svg::tree::ImageResolver>,
resolver: Arc<craft_svg::tree::ValidatedImageResolver>,
}
/// Record the first budget or decoding failure seen while usvg resolves images. Resolver
@@ -526,13 +527,7 @@ fn image_error(budget: &Mutex<ImageBudget>, error: impl Into<String>) {
}
/// Parse one bounded SVG with the shared tree parser and its format-neutral image resolver.
fn parse_image_bounded_with(
bytes: &[u8],
budget: Arc<Mutex<ImageBudget>>,
xml_left: usize,
fonts: fn() -> Arc<usvg::fontdb::Database>,
isolated: bool,
) -> Result<usvg::Tree, IoError> {
fn parse_image_bounded_with(bytes: &[u8], budget: Arc<Mutex<ImageBudget>>, fonts: fn() -> Arc<usvg::fontdb::Database>) -> Result<usvg::Tree, IoError> {
let overrun = |error: IoError| {
image_error(&budget, error.to_string());
error
@@ -541,28 +536,17 @@ fn parse_image_bounded_with(
return Err(overrun(IoError::Svg("embedded SVG source exceeds the 16 MiB byte limit".into())));
}
let xml = inflate_with_limit(bytes, MAX_BOUNDED_SVG_BYTES).map_err(overrun)?;
let nesting = nesting_depth(&xml, xml_left)?;
if nesting > xml_left {
return Err(IoError::Svg(format!("elements are nested more than {xml_left} levels deep")));
let depth = nesting_depth(&xml, MAX_XML_DEPTH)?;
if depth > MAX_XML_DEPTH {
return Err(IoError::Svg(format!("elements are nested more than {MAX_XML_DEPTH} levels deep")));
}
let shared_depth = MAX_XML_DEPTH.saturating_sub(xml_left).saturating_add(nesting);
budget.lock().unwrap_or_else(PoisonError::into_inner).resolver.set_document_depth(nesting);
parse_at_depth(shared_depth, isolated, |isolated| {
let has_text = xml.windows(4).any(|w| w == b"text");
let fontdb = if has_text { fonts() } else { Arc::new(usvg::fontdb::Database::new()) };
if has_text && fontdb.faces().next().is_none() {
budget.lock().unwrap_or_else(PoisonError::into_inner).fontless_text = true;
}
parse_at_depth(depth, || {
let resolver = Arc::clone(&budget.lock().unwrap_or_else(PoisonError::into_inner).resolver);
let text = std::str::from_utf8(&xml).map_err(|_| IoError::Svg("the SVG is not valid UTF-8".into()))?;
resolver.check_document(text).map_err(svg_parse_error)?;
let refusals = Arc::new(SvgRefusals::default());
let mut opt = options_with_isolation(fontdb, xml_left, isolated, Arc::clone(&resolver));
opt.image_href_resolver = noting_refusals(opt.image_href_resolver, resolver, Arc::clone(&refusals));
let limits = tree_limits(xml_left, MAX_RASTER_PIXELS);
let tree = guarded_parse(|| craft_svg::tree::parse_text(text, &limits, &opt))?;
let tree = tree.map_err(svg_parse_error)?;
let (tree, fontless_text) =
guarded_parse(|| parse_checked_svg(text, &resolver, fonts)).inspect_err(|error| image_error(&budget, error.to_string()))??;
let mut counter = budget.lock().unwrap_or_else(PoisonError::into_inner);
counter.fontless_text |= fontless_text;
let usage = counter.resolver.usage();
counter.pixels = counter.pixels.saturating_sub(usage.raster_pixels);
counter.xml_bytes = counter.xml_bytes.saturating_sub(u64::try_from(usage.embedded_svg_bytes).unwrap_or(u64::MAX));
@@ -571,8 +555,8 @@ fn parse_image_bounded_with(
// Resource overruns fail bounded renders; non-strict renders may omit a child
// whose XML depth exceeds the allowance left by the outer drawing.
if usage.raster_limit_images > 0 {
counter.error.get_or_insert_with(|| "embedded SVG raster images exceed the decoded pixel budget".into());
} else if usage.svg_limit_images > 0 && (counter.strict || refusals.over_budget.load(Ordering::Relaxed)) {
counter.error.get_or_insert_with(|| "embedded SVG raster images exceed the encoded byte or decoded pixel budget".into());
} else if usage.svg_resource_limit_images > 0 || (counter.strict && usage.svg_limit_images > 0) {
counter.error.get_or_insert_with(|| "embedded SVG images exceed the byte or nesting budget".into());
} else if counter.strict && (usage.invalid_raster_images > 0 || usage.invalid_svg_images > 0) {
counter.error.get_or_insert_with(|| "can't parse an embedded SVG image".into());
@@ -598,116 +582,6 @@ fn parse_image_bounded_with(
})
}
/// Why craft-svg left embedded SVG images out of one bounded parse. Its usage counts every
/// refused SVG image together, but an image past [`MAX_EMBEDDED_SVG_DEPTH`] or the byte budget
/// fails even a non-strict parse, as the bounded path did before craft-svg, while one nested
/// too deeply in XML or that can't be unpacked (gzip inside gzip, a damaged stream, an unknown
/// encoding) only leaves itself out.
#[derive(Default)]
struct SvgRefusals {
/// Embedded SVG images being resolved around the current one.
depth: AtomicUsize,
/// An image was refused for the chain depth or the byte budget.
over_budget: AtomicBool,
/// Bytes craft-svg charged images that couldn't be unpacked: it charges such an image
/// everything the byte budget had left, and so does a readable image that fits the budget
/// only without those charges. Neither is the drawing's content.
unread_charges: AtomicUsize,
/// Bytes unpacked again to tell those images apart, at most one byte budget per drawing.
rechecked: AtomicUsize,
/// Source bytes decoded during refusal rechecks, at most one byte budget per drawing.
text_rechecked: AtomicUsize,
}
/// Note in `refusals` what craft-svg will do with an embedded SVG's `data` when its images have
/// `used` bytes of the budget: it unpacks the data within what is left, accepts it and charges
/// its text (decoded Latin-1 can be longer), or refuses it and charges everything left. Refused
/// for size after unreadable images were charged, the data is unpacked once more within the
/// budget less only the drawing's content; past that, or past what may be unpacked again, the
/// drawing is over budget.
fn note_byte_refusal(data: &[u8], used: usize, refusals: &SvgRefusals) {
let budget = usize::try_from(MAX_BOUNDED_SVG_BYTES).unwrap_or(usize::MAX);
let left = budget.saturating_sub(used);
let unread = refusals.unread_charges.load(Ordering::Relaxed);
match craft_svg::svgz::text(data, left) {
Ok(text) if text.len() > left => refusals.over_budget.store(true, Ordering::Relaxed),
Ok(_) => {}
Err(craft_svg::svgz::Error::TooLarge(_)) if unread == 0 => refusals.over_budget.store(true, Ordering::Relaxed),
Err(craft_svg::svgz::Error::TooLarge(_)) => {
let content_left = budget.saturating_sub(used.saturating_sub(unread));
// Rechecks may inflate or allocate text for a legacy encoding.
let compressed = data.starts_with(&[0x1f, 0x8b]);
let limit = if compressed { content_left.min(budget.saturating_sub(refusals.rechecked.load(Ordering::Relaxed))) } else { content_left };
// Bound inflation and text-conversion work independently from content size.
let (unpacked, too_large) = match craft_svg::svgz::inflate(data, limit) {
Ok(xml) => {
// Inflation and text conversion have separate work allowances: a fitting
// Latin-1 document must not spend its UTF-8 size against inflation bytes.
// Charge source bytes before decoding, including invalid encodings. The
// supported encodings expand by at most 2x, so conversion work stays bounded
// even for plain children that do not require inflation.
let text_left = budget.saturating_sub(refusals.text_rechecked.load(Ordering::Relaxed));
let too_large = if xml.len() > text_left {
true
} else {
refusals.text_rechecked.fetch_add(xml.len(), Ordering::Relaxed);
craft_svg::svgz::decode(&xml).is_ok_and(|text| text.len() > content_left)
};
(if compressed { xml.len() } else { 0 }, too_large)
}
Err(craft_svg::svgz::Error::Nested(len)) => (len, false),
Err(craft_svg::svgz::Error::TooLarge(_)) => (if compressed { limit } else { 0 }, true),
Err(_) => (limit, false),
};
refusals.rechecked.fetch_add(unpacked, Ordering::Relaxed);
if too_large {
refusals.over_budget.store(true, Ordering::Relaxed);
} else {
refusals.unread_charges.fetch_add(left, Ordering::Relaxed);
}
}
Err(_) => {
refusals.unread_charges.fetch_add(left, Ordering::Relaxed);
}
}
}
/// `resolve`, also noting in `refusals` why craft-svg is about to refuse each embedded SVG. It
/// repeats craft-svg's first two checks in their order: the chain depth, then unpacking within
/// what the byte budget has left (`text/plain` data is an SVG unless it is a raster craft-svg
/// draws).
fn noting_refusals(
resolve: usvg::ImageHrefResolver<'static>,
resolver: Arc<craft_svg::tree::ImageResolver>,
refusals: Arc<SvgRefusals>,
) -> usvg::ImageHrefResolver<'static> {
let usvg::ImageHrefResolver { resolve_data, resolve_string } = resolve;
usvg::ImageHrefResolver {
resolve_data: Box::new(move |mime, data, options| {
let raster = matches!(
photocraft_codecs::detect(&data),
Some(photocraft_codecs::Format::Png | photocraft_codecs::Format::Jpeg | photocraft_codecs::Format::Gif | photocraft_codecs::Format::WebP)
);
if !(mime == "image/svg+xml" || (mime == "text/plain" && !raster)) {
return resolve_data(mime, data, options);
}
// Once over budget the drawing fails whatever follows, so nothing more is unpacked.
if !refusals.over_budget.load(Ordering::Relaxed) {
if refusals.depth.load(Ordering::Relaxed) >= MAX_EMBEDDED_SVG_DEPTH {
refusals.over_budget.store(true, Ordering::Relaxed);
} else {
note_byte_refusal(&data, resolver.usage().embedded_svg_bytes, &refusals);
}
}
refusals.depth.fetch_add(1, Ordering::Relaxed);
let image = resolve_data(mime, data, options);
refusals.depth.fetch_sub(1, Ordering::Relaxed);
image
}),
resolve_string,
}
}
/// Used paint/effect resources can decode an image once per use. Ordinary paths, gradients,
/// clipping paths and blur filters without image references do not multiply unrelated photos.
fn repeatable_image_resources(tree: &usvg::Tree) -> (bool, bool) {
@@ -809,9 +683,9 @@ fn parse_bounded_work_with(bytes: &[u8], max_pixels: u64, strict: bool, fonts: f
fontless_text: false,
strict,
error: None,
resolver: Arc::new(craft_svg::tree::ImageResolver::new(tree_limits(MAX_XML_DEPTH, max_pixels.min(MAX_RASTER_PIXELS)))),
resolver: Arc::new(craft_svg::tree::ValidatedImageResolver::new(tree_limits(MAX_XML_DEPTH, max_pixels.min(MAX_RASTER_PIXELS)))),
}));
let tree = parse_image_bounded_with(bytes, budget.clone(), MAX_XML_DEPTH, fonts, false)?;
let tree = parse_image_bounded_with(bytes, budget.clone(), fonts)?;
let counter = budget.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let decoded = max_pixels.min(MAX_RASTER_PIXELS).saturating_sub(counter.pixels);
Ok(ParsedWork {
@@ -1,6 +1,254 @@
use super::*;
use std::io::Write;
fn assert_incomplete_image_is_disclosed(text: &str) {
for bytes in [text.as_bytes().to_vec(), gzip(text.as_bytes())] {
let imported = crate::import("damaged.svg", &bytes).unwrap();
assert_omission_warning(&imported, 1);
assert_eq!(photocraft_compose::flatten(&imported.document).get(1, 1), [1., 0., 0., 1.]);
let bounded = import_svg_bounded_images("damaged.svg", &bytes, MAX_RASTER_PIXELS).unwrap();
assert_omission_warning(&bounded, 1);
assert!(import_svg_preview_with_work("damaged.svg", &bytes, MAX_RASTER_PIXELS).is_err());
assert!(import_svg_bounded_images_strict("damaged.svg", &bytes, MAX_RASTER_PIXELS).is_err());
assert!(rasterize(&bytes, 1.).is_err());
assert!(rasterize_bounded(&bytes, 1., MAX_RASTER_PIXELS).is_err());
let (pixels, warnings) = rasterize_bounded_with_warnings(&bytes, 1., MAX_RASTER_PIXELS).unwrap();
assert_eq!(pixels.get(1, 1), [1., 0., 0., 1.]);
assert_eq!(warnings.len(), 1);
assert!(warnings[0].starts_with("SVG: 1 embedded "));
assert!(warnings[0].len() < 256);
assert!(!warnings[0].contains("data:"));
// A warning-aware parse cannot make a later strict render accept an omission.
assert!(rasterize_bounded(&bytes, 1., MAX_RASTER_PIXELS).is_err());
assert!(rasterize_rgba8(&bytes).is_err());
}
}
#[test]
fn valid_twelve_bit_jpeg_rejected_by_the_svg_renderer_is_disclosed() {
// ISO/IEC 10918-1 marker syntax: one 8x8, 12-bit gray DCT block.
// Unit quantization, zero DC difference and EOB yield a constant mid-gray.
// This is generated data, not a camera or third-party binary fixture.
fn segment(out: &mut Vec<u8>, marker: u8, payload: &[u8]) {
out.extend_from_slice(&[0xff, marker]);
out.extend_from_slice(&u16::try_from(payload.len() + 2).unwrap().to_be_bytes());
out.extend_from_slice(payload);
}
let mut jpeg = vec![0xff, 0xd8];
let mut quantization = vec![0];
quantization.extend_from_slice(&[1; 64]);
segment(&mut jpeg, 0xdb, &quantization);
segment(&mut jpeg, 0xc1, &[12, 0, 8, 0, 8, 1, 1, 0x11, 0]);
let mut tables = Vec::new();
for class in [0x00, 0x10] {
tables.extend_from_slice(&[class, 1]);
tables.extend_from_slice(&[0; 15]);
tables.push(0); // One one-bit code: DC category zero / AC end-of-block.
}
segment(&mut jpeg, 0xc4, &tables);
segment(&mut jpeg, 0xda, &[1, 1, 0, 0, 63, 0]);
jpeg.extend_from_slice(&[0x3f, 0xff, 0xd9]); // DC=0, EOB=0, then six pad bits.
let decoded = photocraft_codecs::decode(&jpeg).expect("valid extended sequential JPEG");
assert_eq!(decoded.dimensions(), (8, 8));
// Match resvg's actual JPEG backend/output policy, rather than the broader
// shared codec which also supports valid 12-bit and arithmetic JPEG files.
let kind = usvg::ImageKind::JPEG(Arc::new(jpeg.clone()));
let mut pixels_left = MAX_RASTER_PIXELS;
assert_eq!(
draw::validate_raster(&kind, MAX_RASTER_PIXELS, &mut pixels_left),
Err(draw::RasterValidationFailure::Invalid),
"fixture must exercise the shared renderer capability gap"
);
for mime in ["image/jpeg", "text/plain"] {
let direct = drawing(&url(mime, &jpeg));
assert_incomplete_image_is_disclosed(&direct);
for child in [direct.as_bytes().to_vec(), gzip(direct.as_bytes())] {
assert_incomplete_image_is_disclosed(&drawing(&url("image/svg+xml", &child)));
}
}
}
#[test]
fn corrupt_png_pixels_with_valid_dimensions_are_disclosed_before_rasterization() {
let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat(4)).unwrap();
let mut png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap();
let mut at = 8;
loop {
let length = u32::from_be_bytes(png[at..at + 4].try_into().unwrap()) as usize;
if &png[at + 4..at + 8] == b"IDAT" {
assert!(length >= 2);
png[at + 8..at + 10].fill(0); // Invalid zlib header, with an honest chunk CRC.
let checksum = crc32fast::hash(&png[at + 4..at + 8 + length]);
png[at + 8 + length..at + 12 + length].copy_from_slice(&checksum.to_be_bytes());
break;
}
at += length + 12;
}
assert_eq!(photocraft_codecs::probe_allocation_size(&png).unwrap(), (2, 2));
assert!(tiny_skia::Pixmap::decode_png(&png).is_err());
let direct = drawing(&url("image/png", &png));
assert_incomplete_image_is_disclosed(&direct);
for child in [direct.as_bytes().to_vec(), gzip(direct.as_bytes())] {
assert_incomplete_image_is_disclosed(&drawing(&url("image/svg+xml", &child)));
}
}
#[test]
fn malformed_data_image_hrefs_are_disclosed_before_the_parser_discards_them() {
let direct = drawing("data:image/png;base64,A");
assert_incomplete_image_is_disclosed(&direct);
assert_incomplete_image_is_disclosed(&direct.replace("href=", "xmlns:xlink=\"http://www.w3.org/1999/xlink\" xlink:href="));
assert_incomplete_image_is_disclosed(&direct.replace("base64,A", "base64,&#65;"));
for child in [direct.as_bytes().to_vec(), gzip(direct.as_bytes())] {
assert_incomplete_image_is_disclosed(&drawing(&url("image/svg+xml", &child)));
}
}
fn assert_no_omission_or_unexpected_import_warning(imported: &ImportResult) {
assert!(omission_warnings(imported).is_empty(), "{:?}", imported.warnings);
assert!(
imported.warnings.iter().all(|warning| warning == "SVG: embedded images are pixel layers"),
"only the existing pixel-layer information is expected: {:?}",
imported.warnings
);
}
fn assert_ignored_data_image_stays_quiet(text: &str) {
for bytes in [text.as_bytes().to_vec(), gzip(text.as_bytes())] {
let imported = crate::import("ignored.svg", &bytes).unwrap();
assert_no_omission_or_unexpected_import_warning(&imported);
assert_eq!(photocraft_compose::flatten(&imported.document).get(1, 1), [1., 0., 0., 1.]);
let strict = import_svg_bounded_images_strict("ignored.svg", &bytes, MAX_RASTER_PIXELS).unwrap();
assert_no_omission_or_unexpected_import_warning(&strict);
import_svg_preview_with_work("ignored.svg", &bytes, MAX_RASTER_PIXELS).unwrap();
let (pixels, warnings) = rasterize_bounded_with_warnings(&bytes, 1., MAX_RASTER_PIXELS).unwrap();
assert!(warnings.is_empty());
assert_eq!(pixels.get(1, 1), [1., 0., 0., 1.]);
assert_eq!(rasterize_bounded(&bytes, 1., MAX_RASTER_PIXELS).unwrap().get(1, 1), [1., 0., 0., 1.]);
assert_eq!(rasterize(&bytes, 1.).unwrap().get(1, 1), [1., 0., 0., 1.]);
}
}
#[test]
fn malformed_non_image_data_hrefs_stay_ignored_in_open_and_strict_rendering() {
for href in [
"data:application/octet-stream;base64,A",
"data:application/octet-stream;base64",
"data:APPLICATION/OCTET-STREAM;BASE64,A",
"data:text/css;base64,A",
"data:application/octet-stream;base64#fragment,not-the-delimiter",
] {
let text = drawing(href);
assert_ignored_data_image_stays_quiet(&text);
assert_ignored_data_image_stays_quiet(&text.replace("href=", "xmlns:x='http://www.w3.org/1999/xlink' x:href="));
for child in [text.as_bytes().to_vec(), gzip(text.as_bytes())] {
assert_ignored_data_image_stays_quiet(&drawing(&url("image/svg+xml", &child)));
}
}
}
#[test]
fn default_and_explicit_plain_data_failures_keep_image_omission_policy() {
for href in ["data:text/plain;base64,A", "data:;base64,A", "data:;base64", "data:image/png;base64"] {
assert_incomplete_image_is_disclosed(&drawing(href));
}
}
#[test]
fn ignored_non_image_repair_preserves_hidden_foreign_and_valid_image_controls() {
for content in [
"<image display='none' width='2' height='2' href='data:application/octet-stream;base64'/>",
"<foreign:image xmlns:foreign='urn:unrelated' width='2' height='2' href='data:application/octet-stream;base64,A'/>",
"<image width='2' height='2' xmlns:x='http://www.w3.org/1999/xlink' x:href='data:image/png;base64,A' href='data:application/octet-stream;base64,A'/>",
] {
let text = format!("<svg xmlns='http://www.w3.org/2000/svg' width='2' height='2'><rect width='2' height='2' fill='red'/>{content}</svg>");
assert_ignored_data_image_stays_quiet(&text);
}
let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat(4)).unwrap();
let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap();
let text = format!(
"<svg xmlns='http://www.w3.org/2000/svg' width='2' height='2'><image width='2' height='2' href='{}'/><image width='2' height='2' href='data:application/octet-stream;base64,A'/></svg>",
url("image/png", &png)
);
let imported = crate::import("mixed.svg", text.as_bytes()).unwrap();
assert_eq!(imported.warnings, vec!["SVG: embedded images are pixel layers"]);
assert_eq!(photocraft_compose::flatten(&imported.document).get(1, 1), [0., 1., 0., 1.]);
let strict = import_svg_bounded_images_strict("mixed.svg", text.as_bytes(), MAX_RASTER_PIXELS).unwrap();
assert_eq!(strict.warnings, vec!["SVG: embedded images are pixel layers"]);
assert_eq!(rasterize_bounded(text.as_bytes(), 1., MAX_RASTER_PIXELS).unwrap().get(1, 1), [0., 1., 0., 1.]);
}
#[test]
fn malformed_nested_declarations_are_not_removed_into_valid_images() {
let child = b"<?xml bogus?><svg xmlns='http://www.w3.org/2000/svg' width='2' height='2'><rect width='2' height='2' fill='green'/></svg>";
for bytes in [child.to_vec(), gzip(child)] {
assert_incomplete_image_is_disclosed(&drawing(&url("image/svg+xml", &bytes)));
}
}
#[test]
fn used_data_images_with_mismatched_image_mime_are_disclosed() {
let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat(4)).unwrap();
let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap();
assert_eq!(photocraft_codecs::decode(&png).unwrap().dimensions(), (2, 2));
for mime in ["image/jpeg", "image/jpg"] {
let direct = drawing(&url(mime, &png));
assert_incomplete_image_is_disclosed(&direct);
for child in [direct.as_bytes().to_vec(), gzip(direct.as_bytes())] {
assert_incomplete_image_is_disclosed(&drawing(&url("image/svg+xml", &child)));
}
}
}
#[test]
fn complete_renderer_raster_formats_and_plain_text_sniffing_stay_usable() {
let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat(4)).unwrap();
for (format, mime) in [
(photocraft_codecs::Format::Png, "image/png"),
(photocraft_codecs::Format::Jpeg, "image/jpeg"),
(photocraft_codecs::Format::Gif, "image/gif"),
(photocraft_codecs::Format::WebP, "image/webp"),
] {
let encoded = photocraft_codecs::encode(&image, format, &Default::default()).unwrap();
for mime in [mime, "text/plain"] {
let text = drawing(&url(mime, &encoded));
let imported = crate::import("complete.svg", text.as_bytes()).unwrap();
assert!(omission_warnings(&imported).is_empty(), "{format:?}: {:?}", imported.warnings);
let pixel = rasterize_bounded(text.as_bytes(), 1., MAX_RASTER_PIXELS).unwrap().get(1, 1);
assert!(pixel[1] > 0.8 && pixel[0] < 0.2 && pixel[2] < 0.2 && pixel[3] == 1., "{format:?}: {pixel:?}");
}
}
}
#[test]
fn unused_hidden_and_unselected_href_failures_do_not_acquire_warnings() {
for content in [
"<defs><image id='unused' width='2' height='2' href='data:image/png;base64,A'/></defs>",
"<image display='none' width='2' height='2' href='data:image/png;base64,A'/>",
"<image width='2' height='2' xmlns:x='http://www.w3.org/1999/xlink' x:href='data:image/png;base64,A' href='application-ignored'/>",
"<foreign:image xmlns:foreign='urn:unrelated' width='2' height='2' href='data:image/png;base64,A'/>",
] {
let text = format!("<svg xmlns='http://www.w3.org/2000/svg' width='2' height='2'><rect width='2' height='2' fill='red'/>{content}</svg>");
for source_text in [text.clone(), drawing(&url("image/svg+xml", text.as_bytes())), drawing(&url("image/svg+xml", &gzip(text.as_bytes())))] {
for bytes in [source_text.as_bytes().to_vec(), gzip(source_text.as_bytes())] {
let imported = crate::import("unused.svg", &bytes).unwrap();
assert!(omission_warnings(&imported).is_empty(), "{content}: {:?}", imported.warnings);
assert_eq!(photocraft_compose::flatten(&imported.document).get(1, 1), [1., 0., 0., 1.]);
let imported = import_svg_bounded_images("unused.svg", &bytes, MAX_RASTER_PIXELS).unwrap();
assert!(omission_warnings(&imported).is_empty());
let (pixels, warnings) = rasterize_bounded_with_warnings(&bytes, 1., MAX_RASTER_PIXELS).unwrap();
assert!(warnings.is_empty(), "{content}: {warnings:?}");
assert_eq!(pixels.get(1, 1), [1., 0., 0., 1.]);
assert_eq!(rasterize_bounded(&bytes, 1., MAX_RASTER_PIXELS).unwrap().get(1, 1), [1., 0., 0., 1.]);
assert_eq!(rasterize(&bytes, 1.).unwrap().get(1, 1), [1., 0., 0., 1.]);
rasterize_rgba8(&bytes).unwrap();
import_svg_preview_with_work("unused.svg", &bytes, MAX_RASTER_PIXELS).unwrap();
import_svg_bounded_images_strict("unused.svg", &bytes, MAX_RASTER_PIXELS).unwrap();
}
}
}
}
fn url(mime: &str, bytes: &[u8]) -> String {
let mut value = format!("data:{mime},");
for byte in bytes {
@@ -9,6 +257,23 @@ fn url(mime: &str, bytes: &[u8]) -> String {
value
}
#[test]
fn svgz_content_detection_and_parser_agree_on_later_gzip_members() {
let xml = b"<svg xmlns='http://www.w3.org/2000/svg' width='2' height='2'><rect width='2' height='2'/></svg>";
// The first member alone looks like SVG. Detection must validate the
// following member as well, even when there is no filename extension.
let split = xml.len() - b"</svg>".len();
let mut compressed = gzip(&xml[..split]);
compressed.extend(gzip(&xml[split..]));
assert!(crate::is_svg_input("untitled", &compressed));
assert!(rasterize_bounded(&compressed, 1., 16).is_ok());
let crc = compressed.len() - 8;
compressed[crc] ^= 1;
assert!(!crate::is_svg_input("untitled", &compressed));
assert!(rasterize_bounded(&compressed, 1., 16).is_err());
}
fn gzip(bytes: &[u8]) -> Vec<u8> {
let mut writer = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
writer.write_all(bytes).unwrap();
@@ -215,3 +480,70 @@ fn malformed_data_urls_and_broken_pixel_payloads_are_disclosed_before_rendering(
assert!(import_svg_preview_with_work("strict.svg", text.as_bytes(), MAX_RASTER_PIXELS).is_err());
}
}
#[test]
fn excessive_mime_parameters_preserve_valid_images_and_disclose_only_real_failures() {
fn assert_complete_green_image(text: &str) {
for bytes in [text.as_bytes().to_vec(), gzip(text.as_bytes())] {
let imported = crate::import("valid.svg", &bytes).unwrap();
assert_no_omission_or_unexpected_import_warning(&imported);
assert_eq!(photocraft_compose::flatten(&imported.document).get(1, 1), [0., 1., 0., 1.]);
let strict = import_svg_bounded_images_strict("valid.svg", &bytes, MAX_RASTER_PIXELS).unwrap();
assert_no_omission_or_unexpected_import_warning(&strict);
assert_eq!(photocraft_compose::flatten(&strict.document).get(1, 1), [0., 1., 0., 1.]);
import_svg_preview_with_work("valid.svg", &bytes, MAX_RASTER_PIXELS).unwrap();
let (pixels, warnings) = rasterize_bounded_with_warnings(&bytes, 1., MAX_RASTER_PIXELS).unwrap();
assert!(warnings.is_empty());
assert_eq!(pixels.get(1, 1), [0., 1., 0., 1.]);
assert_eq!(rasterize_bounded(&bytes, 1., MAX_RASTER_PIXELS).unwrap().get(1, 1), [0., 1., 0., 1.]);
assert_eq!(rasterize(&bytes, 1.).unwrap().get(1, 1), [0., 1., 0., 1.]);
let (width, height, pixels) = rasterize_rgba8(&bytes).unwrap();
assert_eq!((width, height), (2, 2));
assert_eq!(pixels, [0, 255, 0, 255].repeat(4));
}
}
let parameters = (0..65).map(|index| format!(";p{index}=x")).collect::<String>();
let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat(4)).unwrap();
let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap();
for essence in ["image/png", "text/plain", ""] {
let href = url(&format!("{essence}{parameters}"), &png);
let text = drawing(&href);
assert_complete_green_image(&text);
for child in [text.as_bytes().to_vec(), gzip(text.as_bytes())] {
assert_complete_green_image(&drawing(&url("image/svg+xml", &child)));
}
// Header compaction cannot turn a malformed base64 body or a missing
// delimiter into a valid image, including default text/plain MIME.
for href in [format!("data:{essence}{parameters};base64,A"), format!("data:{essence}{parameters};base64")] {
assert_incomplete_image_is_disclosed(&drawing(&href));
}
}
assert_incomplete_image_is_disclosed(&drawing(&url(&format!("image/unsupported{parameters}"), &png)));
let href = format!("data:application/octet-stream{parameters};base64,AA==");
assert_ignored_data_image_stays_quiet(&drawing(&href));
let image = url(&format!("image/png{parameters}"), &png);
for content in [
format!("<defs><image id='unused' href='{image}'/></defs>"),
format!("<image display='none' width='2' height='2' href='{image}'/>"),
format!("<foreign:image xmlns:foreign='urn:unrelated' width='2' height='2' href='{image}'/>"),
format!("<image width='2' height='2' xmlns:x='http://www.w3.org/1999/xlink' x:href='{image}' href='{href}'/>"),
] {
let text = format!("<svg xmlns='http://www.w3.org/2000/svg' width='2' height='2'><rect width='2' height='2' fill='red'/>{content}</svg>");
assert_ignored_data_image_stays_quiet(&text);
}
}
#[test]
fn valid_image_at_the_mime_parameter_boundary_keeps_its_pixels() {
let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat(4)).unwrap();
let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap();
// This helper percent-encodes the payload; 64 parameters hit the separator boundary.
let parameters = (0..64).map(|index| format!(";p{index}=x")).collect::<String>();
let text = drawing(&url(&format!("image/png{parameters}"), &png));
for bytes in [text.as_bytes().to_vec(), gzip(text.as_bytes())] {
let imported = crate::import("valid.svg", &bytes).unwrap();
assert_eq!(imported.warnings, vec!["SVG: embedded images are pixel layers"]);
assert_eq!(photocraft_compose::flatten(&imported.document).get(1, 1), [0., 1., 0., 1.]);
assert_eq!(rasterize(&bytes, 1.).unwrap().get(1, 1), [0., 1., 0., 1.]);
}
}
+155 -64
View File
@@ -5,13 +5,11 @@ use super::*;
/// Require shallow, deep and nested private SVG probes to reuse the single native parser worker.
fn private_svg_parsing_uses_the_same_worker_at_every_depth() {
for depth in [2, 200] {
parse_at_depth(depth, false, |isolated| {
assert!(isolated);
parse_at_depth(depth, || {
assert!(SVG_WORKER.with(std::cell::Cell::get));
assert_eq!(std::thread::current().name(), Some("photocraft-svg"));
let worker = std::thread::current().id();
parse_at_depth(200, isolated, |nested| {
assert!(nested);
parse_at_depth(200, || {
assert_eq!(std::thread::current().id(), worker);
Ok(())
})
@@ -40,17 +38,48 @@ fn non_strict_embedded_svg_records_isolation_failure_but_omits_invalid_images()
fontless_text: false,
strict: false,
error: None,
resolver: Arc::new(craft_svg::tree::ImageResolver::new(tree_limits(MAX_XML_DEPTH, MAX_RASTER_PIXELS))),
resolver: Arc::new(craft_svg::tree::ValidatedImageResolver::new(tree_limits(MAX_XML_DEPTH, MAX_RASTER_PIXELS))),
}));
let invalid = image_svg(&embedded_image("image/svg+xml", b"<not-svg/>"));
parse_image_bounded_with(invalid.as_bytes(), budget.clone(), MAX_XML_DEPTH, inter_only, false).unwrap();
parse_image_bounded_with(invalid.as_bytes(), budget.clone(), inter_only).unwrap();
assert!(budget.lock().unwrap().error.is_none(), "ordinary invalid images are still omitted");
let svg = image_svg("<text>x</text>");
let error = parse_image_bounded_with(svg.as_bytes(), budget.clone(), 2, panic_fonts, false).unwrap_err();
let error = parse_image_bounded_with(svg.as_bytes(), budget.clone(), panic_fonts).unwrap_err();
assert!(error.to_string().contains("bounded SVG worker failed"));
assert_eq!(budget.lock().unwrap().error.as_deref(), Some(error.to_string().as_str()));
}
/// Shallow declarations can expand to a much deeper parser walk through references.
fn reference_chain_svg(links: usize) -> String {
let mut source = String::from("<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'><defs>");
for index in 0..links {
source.push_str(&format!("<g id='n{index}'><use href='#n{}'/></g>", index + 1));
}
source.push_str(&format!("<g id='n{links}'><rect width='1' height='1'/></g></defs><use href='#n0'/></svg>"));
source
}
#[test]
fn bounded_render_rejects_expanded_references_that_exceed_the_app_limit() {
let depth = tree_limits(MAX_XML_DEPTH, MAX_RASTER_PIXELS).tree_depth;
let source = reference_chain_svg(depth + 2);
assert!(nesting_depth(source.as_bytes(), depth).unwrap() <= depth, "the lexical guard alone admits this source");
let error = rasterize_bounded(source.as_bytes(), 1., 16).unwrap_err();
assert!(error.to_string().contains("layers are nested too deeply"), "{error}");
}
#[cfg(target_arch = "wasm32")]
#[test]
fn wasm_inline_allowance_bounds_shallow_expanded_references_before_conversion() {
let limits = tree_limits(MAX_XML_DEPTH, MAX_RASTER_PIXELS);
assert_eq!(limits.tree_depth, INLINE_XML_DEPTH + 1);
let shallow = reference_chain_svg(INLINE_XML_DEPTH / 4);
assert!(craft_svg::tree::preflight(&shallow, &limits).is_ok());
let expanded = reference_chain_svg(INLINE_XML_DEPTH + 2);
assert!(nesting_depth(expanded.as_bytes(), INLINE_XML_DEPTH).unwrap() <= INLINE_XML_DEPTH);
assert!(matches!(craft_svg::tree::preflight(&expanded, &limits), Err(craft_svg::tree::Error::TooDeep(_))));
}
fn embedded_image(mime: &str, bytes: &[u8]) -> String {
let data = bytes.iter().map(|byte| format!("%{byte:02X}")).collect::<String>();
format!("<image width=\"1\" height=\"1\" href=\"data:{mime},{data}\"/>")
@@ -60,7 +89,7 @@ fn image_svg(images: &str) -> String {
format!("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"1\" height=\"1\">{images}</svg>")
}
fn base64(bytes: &[u8]) -> String {
pub(super) fn base64(bytes: &[u8]) -> String {
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::new();
for chunk in bytes.chunks(3) {
@@ -427,6 +456,46 @@ fn inter_only() -> Arc<usvg::fontdb::Database> {
Arc::new(db)
}
#[test]
fn percent_encoded_svg_child_text_renders_without_outer_text() {
let child = br#"<svg xmlns="http://www.w3.org/2000/svg" width="80" height="40"><text x="5" y="32" font-family="Inter" font-size="30">HI</text></svg>"#;
let data = child.iter().map(|byte| format!("%{byte:02X}")).collect::<String>();
let outer =
format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="80" height="40"><image width="80" height="40" href="data:image/svg+xml,{data}"/></svg>"#);
assert!(!outer.contains("text"), "the encoded child is the only text source");
let has_glyph_ink = |pixels: &photocraft_compose::Buffer| pixels.px.iter().any(|pixel| pixel[3] > 0.5);
let ink = on_svg_stack(|| {
let parsed = parse_with(outer.as_bytes(), inter_only)?;
let imported = import_parsed("child.svg", parsed, MAX_GROUP_DEPTH, None, false)?;
let (parsed, chain) = parse_bounded_inner_with(outer.as_bytes(), MAX_RASTER_PIXELS, inter_only)?;
assert_eq!(chain, 1);
let pixels = rasterize_tree(&complete_raster_tree(parsed)?, 1.0)?;
Ok([has_glyph_ink(&photocraft_compose::flatten(&imported.document)), has_glyph_ink(&pixels)])
})
.unwrap();
assert_eq!(ink, [true, true], "glyph ink through ordinary import and bounded rendering");
}
#[test]
fn svg_without_text_does_not_load_fonts() {
fn unexpected_fonts() -> Arc<usvg::fontdb::Database> {
panic!("a text-free drawing should never load fonts");
}
let child = image_svg(r#"<rect width="1" height="1" fill="red"/>"#);
let outer = image_svg(&embedded_image("image/svg+xml", child.as_bytes()));
on_svg_stack(|| {
let ordinary = parse_with(outer.as_bytes(), unexpected_fonts)?;
let (bounded, _) = parse_bounded_inner_with(outer.as_bytes(), MAX_RASTER_PIXELS, unexpected_fonts)?;
for parsed in [ordinary, bounded] {
assert!(!parsed.fontless_text);
assert_eq!(rasterize_tree(&parsed.tree, 1.0)?.get(0, 0), [1., 0., 0., 1.]);
}
Ok(())
})
.unwrap();
}
/// Text asking for fonts that aren't installed (`Arial, Helvetica, sans-serif` on a Linux
/// without them) is set in an installed font, as a browser does, instead of being dropped.
#[test]
@@ -851,24 +920,29 @@ fn missing_svg_font_uses_an_available_generic_instead_of_dropping_text() {
}
#[test]
fn resolve_data_rejects_oversized_and_malformed_embedded_png_and_webp() {
let opt = options(Arc::new(usvg::fontdb::Database::new()), MAX_XML_DEPTH);
let resolve = &opt.image_href_resolver.resolve_data;
fn embedded_png_and_webp_validation_preserves_public_warning_and_strict_contracts() {
let img = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, vec![255; 12]).unwrap();
let valid_png = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap();
assert!(resolve("image/png", Arc::new(valid_png.clone()), &opt).is_some());
assert!(resolve("text/plain", Arc::new(valid_png.clone()), &opt).is_some());
let mut huge_png = valid_png;
huge_png[16..20].copy_from_slice(&40_000u32.to_be_bytes());
huge_png[20..24].copy_from_slice(&40_000u32.to_be_bytes());
assert!(resolve("image/png", Arc::new(huge_png.clone()), &opt).is_none(), "oversized PNG rejected before decode");
assert!(resolve("text/plain", Arc::new(huge_png), &opt).is_none(), "oversized mime-less PNG rejected before decode");
// Malformed WebP header under image/webp or text/plain must be rejected at the probe step.
let bad_webp = b"RIFF\x10\x00\x00\x00WEBPVP8 ".to_vec();
assert!(resolve("image/webp", Arc::new(bad_webp.clone()), &opt).is_none());
assert!(resolve("text/plain", Arc::new(bad_webp), &opt).is_none());
for mime in ["image/png", "text/plain"] {
let svg = image_svg(&embedded_image(mime, &valid_png));
let output = rasterize_bounded(svg.as_bytes(), 1.0, 64).unwrap();
assert_eq!((output.rect.width(), output.rect.height()), (1, 1));
assert_eq!(output.get(0, 0), [1.; 4]);
let mut huge = valid_png.clone();
huge[16..20].copy_from_slice(&40_000u32.to_be_bytes());
huge[20..24].copy_from_slice(&40_000u32.to_be_bytes());
let svg = image_svg(&embedded_image(mime, &huge));
assert!(parse_bounded(svg.as_bytes(), 64).is_err(), "oversized PNG refused before decode: {mime}");
assert!(rasterize_bounded(svg.as_bytes(), 1.0, 64).is_err());
}
for mime in ["image/webp", "text/plain"] {
let svg = image_svg(&embedded_image(mime, b"RIFF\x10\x00\x00\x00WEBPVP8 "));
let parsed = parse_bounded(svg.as_bytes(), 64).unwrap();
assert_eq!(omitted_image_count(parsed.image_usage), 1);
assert!(rasterize_bounded(svg.as_bytes(), 1.0, 64).is_err());
let imported = import_svg_bounded("invalid.webp.svg", svg.as_bytes(), 64).unwrap();
assert!(imported.warnings.iter().any(|warning| warning.contains("omitted")));
}
}
#[test]
@@ -884,11 +958,12 @@ fn jpeg_allocation_probe_uses_the_frame_header_and_oversized_jpegs_are_refused()
assert_eq!(photocraft_codecs::probe_allocation_size(&jpeg(400, 300)).unwrap(), (300, 400));
assert!(photocraft_codecs::probe_allocation_size(&[0xFF, 0xD8, 0xFF, 0xDA, 0, 2]).is_err());
assert!(photocraft_codecs::probe_allocation_size(&[0xFF, 0xD8]).is_err());
let opt = options(Arc::new(usvg::fontdb::Database::new()), MAX_XML_DEPTH);
let resolve = &opt.image_href_resolver.resolve_data;
// 1.2 billion pixels would be 4.8 GB of RGBA before resvg scaled anything down.
assert!(resolve("image/jpeg", Arc::new(jpeg(40_000, 30_000)), &opt).is_none());
assert!(resolve("text/plain", Arc::new(jpeg(40_000, 30_000)), &opt).is_none());
for mime in ["image/jpeg", "text/plain"] {
// 1.2 billion pixels would require 4.8 GB before scaling.
let svg = image_svg(&embedded_image(mime, &jpeg(40_000, 30_000)));
assert!(parse_bounded(svg.as_bytes(), 64).is_err());
assert!(rasterize_bounded(svg.as_bytes(), 1.0, 64).is_err());
}
}
#[test]
@@ -899,17 +974,21 @@ fn resolve_data_rejects_nested_gzip_and_handles_text_plain_svgz() {
e.write_all(bytes).unwrap();
e.finish().unwrap()
}
let opt = options(Arc::new(usvg::fontdb::Database::new()), MAX_XML_DEPTH);
let resolve = &opt.image_href_resolver.resolve_data;
let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"4\" height=\"4\"><rect width=\"4\" height=\"4\"/></svg>";
let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"4\" height=\"4\"><rect width=\"4\" height=\"4\" fill=\"#ff0000\"/></svg>";
let once = gz(svg);
assert!(resolve("image/svg+xml", Arc::new(once.clone()), &opt).is_some());
assert!(resolve("text/plain", Arc::new(once.clone()), &opt).is_some());
// Doubly gzip-compressed payload must be rejected rather than decompressed a second time by usvg.
let twice = gz(&once);
assert!(resolve("image/svg+xml", Arc::new(twice.clone()), &opt).is_none());
assert!(resolve("text/plain", Arc::new(twice), &opt).is_none());
for mime in ["image/svg+xml", "text/plain"] {
let single = image_svg(&embedded_image(mime, &once));
let output = rasterize_bounded(single.as_bytes(), 1.0, 64).unwrap();
assert_eq!((output.rect.width(), output.rect.height()), (1, 1));
assert_eq!(output.get(0, 0), [1., 0., 0., 1.]);
let nested = image_svg(&embedded_image(mime, &twice));
let parsed = parse_bounded(nested.as_bytes(), 64).unwrap();
assert_eq!(omitted_image_count(parsed.image_usage), 1);
assert!(rasterize_bounded(nested.as_bytes(), 1.0, 64).is_err());
let imported = import_svg_bounded("nested.svg", nested.as_bytes(), 64).unwrap();
assert!(imported.warnings.iter().any(|warning| warning.contains("omitted")));
}
}
/// The outer gzip is size-limited by PhotoCraft. Its result must be XML, never another
@@ -1191,10 +1270,24 @@ fn fitting_latin1_retry_keeps_inflation_and_content_budgets_separate() {
let decoded = craft_svg::svgz::decode(&latin1).unwrap();
assert!(latin1.len() < budget / 2);
assert!(decoded.len() > budget / 2 && decoded.len() < budget);
let refusals = SvgRefusals { unread_charges: AtomicUsize::new(budget), rechecked: AtomicUsize::new(budget / 2), ..SvgRefusals::default() };
note_byte_refusal(&gzip(&latin1), budget, &refusals);
assert!(!refusals.over_budget.load(Ordering::Relaxed));
assert_eq!(refusals.rechecked.load(Ordering::Relaxed), budget / 2 + latin1.len());
let valid = gzip(b"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"1\" height=\"1\"/>");
let damaged = embedded_image("image/svg+xml", &valid[..valid.len() / 2]);
let mut primer = b"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"1\" height=\"1\"><!--".to_vec();
let close = b"--></svg>";
primer.resize(budget / 2 - close.len(), b' ');
primer.extend_from_slice(close);
assert_eq!(primer.len(), budget / 2);
let primer = embedded_image("image/svg+xml", &gzip(&primer));
let fitting = embedded_image("image/svg+xml", &gzip(&latin1));
let source = image_svg(&format!("{damaged}{primer}{fitting}"));
let parsed = parse_bounded(source.as_bytes(), MAX_RASTER_PIXELS).unwrap();
assert_eq!(parsed.image_usage.svg_resource_limit_images, 0, "decoded content fits its independent original allowance");
assert_eq!(parsed.image_usage.svg_limit_images, 2, "both fitting retries remain omitted");
assert_eq!(parsed.image_usage.invalid_svg_images, 1, "the original corrupt source stays unreadable");
assert_eq!(parsed.image_usage.embedded_svg_bytes, budget, "retry classification never refunds failed admission work");
assert!(rasterize_bounded(source.as_bytes(), 1.0, MAX_RASTER_PIXELS).is_err(), "warningless pixels must remain strict");
let imported = import_svg_bounded("legacy-retry.svg", source.as_bytes(), MAX_RASTER_PIXELS).unwrap();
assert!(imported.warnings.iter().any(|warning| warning.contains("omitted")));
}
/// After a damaged image spent the budget, images refused for bytes are unpacked again to tell
/// whether they are too large themselves, but at most one budget's worth in all: past that the
@@ -1213,8 +1306,9 @@ fn images_after_a_damaged_svgz_are_unpacked_again_within_one_budget() {
assert!(error.to_string().contains("byte or nesting budget"), "{error}");
}
/// Each image unpacked again is charged at least what was unpacked, refused ones included, so
/// however many follow a damaged image the unpacking adds up to one budget, not one each.
/// Classification after damaged data has one separate allowance for the entire drawing.
/// Exercise the real wrapped resolver: failed work stays charged and later references cannot
/// acquire another classification allowance after the first oversized source exhausts it.
#[test]
fn unpacking_images_again_adds_up_to_one_budget_however_many_there_are() {
let budget = usize::try_from(MAX_BOUNDED_SVG_BYTES).unwrap();
@@ -1222,12 +1316,23 @@ fn unpacking_images_again_adds_up_to_one_budget_however_many_there_are() {
huge.resize(budget * 2, b' ');
huge.extend_from_slice(b"</svg>");
let huge = gzip(&huge);
// A damaged image was charged the whole budget; every later image is refused for size.
let refusals = SvgRefusals { unread_charges: AtomicUsize::new(budget), ..SvgRefusals::default() };
for _ in 0..64 {
note_byte_refusal(&huge, budget, &refusals);
assert!(refusals.over_budget.load(Ordering::Relaxed), "too large without the charges");
assert_eq!(refusals.rechecked.load(Ordering::Relaxed), budget);
let valid = gzip(b"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"1\" height=\"1\"/>");
let damaged = embedded_image("image/svg+xml", &valid[..valid.len() / 2]);
let parsed = parse_bounded(image_svg(&damaged).as_bytes(), MAX_RASTER_PIXELS).unwrap();
assert_eq!(parsed.image_usage.invalid_svg_images, 1);
assert_eq!(parsed.image_usage.embedded_svg_bytes, budget, "failed work retains its original charge");
assert_eq!(parsed.image_usage.svg_resource_limit_images, 0, "corruption alone is not a resource overrun");
for count in [1, 64] {
let mut children = damaged.clone();
for index in 0..count {
let mut source = huge.clone();
source.push(index);
children.push_str(&embedded_image("image/svg+xml", &source));
}
let source = image_svg(&children);
let error = parse_bounded(source.as_bytes(), MAX_RASTER_PIXELS).unwrap_err();
assert!(error.to_string().contains("byte or nesting budget"), "{error}");
assert!(rasterize_bounded(source.as_bytes(), 1.0, MAX_RASTER_PIXELS).is_err());
}
}
@@ -1609,17 +1714,3 @@ fn every_raster_refusal_reason_is_reported_once() {
assert_eq!(dropped("rasterising limit"), 1, "{:?}", result.warnings);
assert_eq!(dropped("too much memory"), 1, "{:?}", result.warnings);
}
#[test]
fn plain_legacy_encoding_rechecks_have_a_separate_bounded_work_allowance() {
let budget = usize::try_from(MAX_BOUNDED_SVG_BYTES).unwrap();
let xml = b"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><svg><!--\xe9--></svg>";
let refusals = SvgRefusals { unread_charges: AtomicUsize::new(budget), text_rechecked: AtomicUsize::new(budget - xml.len()), ..SvgRefusals::default() };
note_byte_refusal(xml, budget, &refusals);
assert!(!refusals.over_budget.load(Ordering::Relaxed));
assert_eq!(refusals.text_rechecked.load(Ordering::Relaxed), budget);
assert_eq!(refusals.rechecked.load(Ordering::Relaxed), 0);
note_byte_refusal(xml, budget, &refusals);
assert!(refusals.over_budget.load(Ordering::Relaxed));
assert_eq!(refusals.text_rechecked.load(Ordering::Relaxed), budget);
}
+148
View File
@@ -0,0 +1,148 @@
//! App-visible XML validation, rendering and omission contracts. Detailed repair
//! source projection and parse-count tests live with the shared SVG implementation.
use super as svg;
use super::tests::base64;
use super::tiny_skia;
use crate::IoError;
use std::sync::Arc;
const SVG_NS: &str = "http://www.w3.org/2000/svg";
const XLINK_NS: &str = "http://www.w3.org/1999/xlink";
fn empty_fonts() -> Arc<svg::usvg::fontdb::Database> {
Arc::new(svg::usvg::fontdb::Database::new())
}
#[test]
fn unchanged_xml_keeps_ordinary_and_bounded_rendering() {
let text = "<?xml version='1.0'?><svg xmlns='http://www.w3.org/2000/svg' width='4' height='4'><a href='#shape'/><rect id='shape' width='4' height='4' fill='red'/></svg>";
let parsed = svg::parse_with(text.as_bytes(), empty_fonts).unwrap();
assert_eq!(svg::omitted_image_count(parsed.image_usage), 0);
let pixels = svg::render(&parsed.tree, 1.).unwrap();
assert_eq!(pixels.pixel(1, 1).unwrap().red(), 255);
svg::parse_bounded_inner_with(text.as_bytes(), 16, empty_fonts).unwrap();
}
#[test]
fn repaired_xml_keeps_warning_and_strict_contracts() {
for text in [
"<?xml version='1.0'?><svg xmlns='http://www.w3.org/2000/svg' width='4' height='4'><rect width='4' height='4' fill='red'/><image width='1' height='1' href='data:image/png;base64,A'/></svg>",
"<!DOCTYPE svg [<!ENTITY a 'data:image/png;base64,A'>]><svg xmlns='http://www.w3.org/2000/svg' width='4' height='4'><rect width='4' height='4' fill='red'/><image width='1' height='1' href='&a;'/></svg>",
] {
let parsed = svg::parse_with(text.as_bytes(), empty_fonts).unwrap();
assert_eq!(parsed.image_usage.invalid_raster_images, 1);
assert_eq!(svg::render(&parsed.tree, 1.).unwrap().pixel(2, 2).unwrap().red(), 255);
let (pixels, warnings) = svg::rasterize_bounded_with_warnings(text.as_bytes(), 1., 16).unwrap();
assert_eq!(pixels.get(2, 2), [1., 0., 0., 1.]);
assert_eq!(warnings.len(), 1);
assert!(svg::rasterize_bounded(text.as_bytes(), 1., 16).is_err());
}
}
#[test]
fn original_xml_guards_run_before_repair_or_conversion() {
let opening = "<svg xmlns='http://www.w3.org/2000/svg' width='4' height='4'>";
let image = "<image width='1' height='1' href='data:image/png;base64,A'/>";
let mut attributes = String::new();
for index in 0..=svg::tree_limits(svg::MAX_XML_DEPTH, 16).attributes {
use std::fmt::Write;
write!(attributes, " a{index}='x'").unwrap();
}
let rejected = format!("{opening}<g{attributes}>{image}</g></svg>");
let Err(error) = svg::parse_with(rejected.as_bytes(), empty_fonts) else {
panic!("original attribute limits must apply before URL repair");
};
assert!(error.to_string().contains("attribute"), "{error}");
let accepted = format!(
"<!DOCTYPE svg [<!ENTITY a 'data:image/png;base64,A'>]>{opening}<image width='1' height='1' href='&a;'/><rect width='4' height='4' fill='red'/></svg>"
);
let (pixels, warnings) = svg::rasterize_bounded_with_warnings(accepted.as_bytes(), 1., 16).unwrap();
assert_eq!(pixels.get(2, 2), [1., 0., 0., 1.]);
assert_eq!(warnings.len(), 1);
}
#[test]
fn checked_xml_conversion_panic_is_an_isolation_failure() {
let result: Result<(), IoError> = svg::guarded_parse(|| panic!("injected XML conversion panic"));
assert!(matches!(result, Err(IoError::Svg(message)) if message.contains("bounded SVG worker failed")));
}
#[test]
fn long_attribute_spacing_preserves_artwork_and_discloses_only_used_images() {
for spacing in [" ".repeat(300), " \t\n\r".repeat(300)] {
for attribute in ["href", "x:href"] {
let text = format!(
"<svg xmlns='{SVG_NS}' xmlns:x='{XLINK_NS}' width='4' height='4'><rect width='4' height='4' fill='red'/><image width='1' height='1' {attribute}{spacing}={spacing}'data:image/png;base64,A'/></svg>"
);
let (pixels, warnings) = svg::rasterize_bounded_with_warnings(text.as_bytes(), 1., 16).unwrap();
assert_eq!(pixels.get(2, 2), [1., 0., 0., 1.]);
assert_eq!(warnings.len(), 1);
assert!(svg::rasterize_bounded(text.as_bytes(), 1., 16).is_err());
let hidden = text.replace("<image ", "<image display='none' ");
let (_, warnings) = svg::rasterize_bounded_with_warnings(hidden.as_bytes(), 1., 16).unwrap();
assert!(warnings.is_empty());
}
}
}
#[test]
fn many_mime_parameters_preserve_valid_pixels_and_invalid_image_omissions() {
let mut image = tiny_skia::Pixmap::new(1, 1).unwrap();
image.fill(tiny_skia::Color::from_rgba8(0, 255, 0, 255));
let body = base64(&image.encode_png().unwrap());
let parameters = ";p=x".repeat(100);
let drawing = |body: &str| {
format!(
"<svg xmlns='{SVG_NS}' width='4' height='4'><rect width='4' height='4' fill='red'/><image width='1' height='1' href='data:image/png{parameters};base64,{body}'/></svg>"
)
};
let text = drawing(&body);
let (pixels, warnings) = svg::rasterize_bounded_with_warnings(text.as_bytes(), 1., 16).unwrap();
assert!(warnings.is_empty());
assert_eq!(pixels.get(0, 0), [0., 1., 0., 1.]);
assert_eq!(pixels.get(2, 2), [1., 0., 0., 1.]);
assert!(svg::rasterize_bounded(text.as_bytes(), 1., 16).is_ok());
let text = drawing("A");
let (pixels, warnings) = svg::rasterize_bounded_with_warnings(text.as_bytes(), 1., 16).unwrap();
assert_eq!(pixels.get(2, 2), [1., 0., 0., 1.]);
assert_eq!(warnings.len(), 1);
assert!(svg::rasterize_bounded(text.as_bytes(), 1., 16).is_err());
}
#[test]
fn repeated_use_reports_encoded_byte_exhaustion_at_small_pixel_counts() {
let mut png = tiny_skia::Pixmap::new(1, 1).unwrap();
png.fill(tiny_skia::Color::from_rgba8(0, 255, 0, 255));
let png = png.encode_png().unwrap();
let references = "<use href='#i'/>".repeat(64);
let body = base64(&png);
let source = format!(
"<svg xmlns='{SVG_NS}' width='4' height='4'><defs><image id='i' width='1' height='1' href='data:image/png;base64,{body}'/></defs>{references}</svg>"
);
// Keep the test small while using the real resolver and PhotoCraft error
// adapter. The repeated callbacks exhaust encoded bytes before raster pixels.
let mut limits = svg::tree_limits(svg::MAX_XML_DEPTH, 1024);
limits.bytes = source.len();
limits.embedded_bytes = 0;
assert!(64 * png.len() > limits.bytes);
let resolver = Arc::new(craft_svg::tree::ValidatedImageResolver::new(limits));
let budget = Arc::new(std::sync::Mutex::new(svg::ImageBudget {
pixels: 1024,
xml_bytes: svg::MAX_BOUNDED_SVG_BYTES,
svg_images: 0,
svg_chain: 0,
draw_nodes: 0,
repeatable_raster: false,
repeatable_svg: false,
fontless_text: false,
strict: false,
error: None,
resolver: resolver.clone(),
}));
let error = svg::parse_image_bounded_with(source.as_bytes(), budget, empty_fonts).unwrap_err();
assert!(error.to_string().contains("encoded byte or decoded pixel budget"), "{error}");
let usage = resolver.usage();
assert!(usage.raster_limit_images > 0);
assert!(usage.raster_pixels > 0 && usage.raster_pixels < 64, "{usage:?}");
}
+6
View File
@@ -403,6 +403,12 @@ fn deeply_nested_embedded_svg_is_dropped_not_a_stack_overflow() {
// drawing still renders (its rect is black).
let r = open(&embed(&base64_data_url("image/svg+xml", nested(svg::MAX_XML_DEPTH - 2).as_bytes())));
assert!(close(px(&r.document, 4, 4), [0.0, 0.0, 0.0, 1.0]), "{:?}", px(&r.document, 4, 4));
// One more child level fits in isolation, but exceeds the shared
// allowance once the outer drawing's ancestor is included.
let beyond = nested(svg::MAX_XML_DEPTH - 1);
let r = open(&embed(&base64_data_url("image/svg+xml", beyond.as_bytes())));
assert!(close(px(&r.document, 4, 4), [0.0; 4]), "over-limit child must remain transparent: {:?}", px(&r.document, 4, 4));
assert!(r.warnings.iter().any(|warning| warning.contains("omitted")), "over-limit child must be disclosed: {:?}", r.warnings);
})
.unwrap()
.join()
+1
View File
@@ -7,6 +7,7 @@ license.workspace = true
rust-version.workspace = true
[dependencies]
craft-ipp = { git = "https://github.com/storytold/craft-libs", rev = "e7873217287876f76a045550369c90a541693c33" }
[lints]
workspace = true
+2 -697
View File
@@ -1,701 +1,6 @@
//! `photocraft-ipp`: a small IPP client for CUPS, in pure Rust with no dependencies.
//!
//! Talks to the local print server the way `lp` does, but in-process: over the CUPS domain
//! socket (`/run/cups/cups.sock`, or `CUPS_SERVER` when it names a path) or TCP (`localhost:631`,
//! or `CUPS_SERVER` as `host[:port]`). Three operations, from RFC 8010 / 8011 and CUPS's own
//! extensions: list the printers, read the default, and submit a PDF as a job.
//!
//! Never panics: every read is bounded and every malformed reply is an error. Works on any Unix
//! and on Windows for TCP (CUPS rarely runs there; the Windows print path is separate).
//! Re-exports [`craft_ipp`] for backward compatibility with `photocraft-ipp`.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpStream, ToSocketAddrs};
use std::path::PathBuf;
use std::time::Duration;
/// Where the print server listens.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Endpoint {
/// A Unix domain socket (CUPS's default, also what a Flatpak sees with `--socket=cups`).
Unix(PathBuf),
/// A TCP host and port.
Tcp(String, u16),
}
/// Why a request failed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
/// No server could be reached.
Unreachable(String),
/// The HTTP or IPP reply could not be read.
Protocol(String),
/// The server answered with an IPP error status (the code and its message).
Status(u16, String),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::Unreachable(m) => write!(f, "no print server: {m}"),
Error::Protocol(m) => write!(f, "print server reply: {m}"),
Error::Status(code, m) => write!(f, "print server refused ({code:#06x}): {m}"),
}
}
}
impl std::error::Error for Error {}
type Result<T> = std::result::Result<T, Error>;
/// A printer the server knows.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Printer {
pub name: String,
/// `printer-info`, the human description.
pub info: String,
/// `printer-state`: 3 idle, 4 printing, 5 stopped.
pub state: u32,
pub accepting_jobs: bool,
pub is_default: bool,
/// A CUPS class (a pool of printers) rather than one printer.
pub is_class: bool,
}
/// Timeouts: connecting, and each request (a Print-Job carries the whole PDF).
const CONNECT: Duration = Duration::from_secs(3);
const REQUEST: Duration = Duration::from_secs(60);
/// The whole reply, however it trickles in: the timeouts above only cover each read.
const REPLY_DEADLINE: Duration = Duration::from_secs(120);
/// Largest reply read.
const MAX_REPLY: usize = 16 << 20;
/// Largest number of attributes taken from a reply.
const MAX_ATTRIBUTES: usize = 100_000;
pub const OP_PRINT_JOB: u16 = 0x0002;
pub const OP_CUPS_GET_DEFAULT: u16 = 0x4001;
pub const OP_CUPS_GET_PRINTERS: u16 = 0x4002;
pub const OP_CUPS_GET_CLASSES: u16 = 0x4005;
pub const TAG_OPERATION_GROUP: u8 = 0x01;
pub const TAG_JOB_GROUP: u8 = 0x02;
pub const TAG_END: u8 = 0x03;
pub const TAG_PRINTER_GROUP: u8 = 0x04;
pub const TAG_INTEGER: u8 = 0x21;
pub const TAG_BOOLEAN: u8 = 0x22;
pub const TAG_ENUM: u8 = 0x23;
pub const TAG_TEXT: u8 = 0x41;
pub const TAG_NAME: u8 = 0x42;
pub const TAG_KEYWORD: u8 = 0x44;
pub const TAG_URI: u8 = 0x45;
pub const TAG_CHARSET: u8 = 0x47;
pub const TAG_LANGUAGE: u8 = 0x48;
pub const TAG_MIME: u8 = 0x49;
impl Endpoint {
/// The server this machine uses: `CUPS_SERVER` (a socket path, or `host[:port]`), else the
/// CUPS socket, else `localhost:631`. `None` when nothing answers.
pub fn detect() -> Option<Endpoint> {
if let Some(server) = std::env::var_os("CUPS_SERVER").filter(|v| !v.is_empty()) {
let ep = Endpoint::parse(&server.to_string_lossy());
return ep.reachable().then_some(ep);
}
[
Endpoint::Unix(PathBuf::from("/run/cups/cups.sock")),
Endpoint::Unix(PathBuf::from("/var/run/cups/cups.sock")),
// macOS
Endpoint::Unix(PathBuf::from("/private/var/run/cupsd")),
Endpoint::Tcp("localhost".into(), 631),
]
.into_iter()
.find(Endpoint::reachable)
}
/// `server` as a socket path (starts with `/`) or `host[:port]` (port 631 by default). An IPv6
/// server is `[address]` or `[address]:port`; written bare (more than one `:`) it keeps the
/// default port, because its last `:` cannot be told apart from a port separator. Anything else
/// after the bracket (`[::1]:abc`) stays the host, so a mistyped endpoint cannot resolve rather
/// than quietly becoming the default one.
pub fn parse(server: &str) -> Endpoint {
if server.starts_with('/') {
return Endpoint::Unix(PathBuf::from(server));
}
// `[IPv6]:port` - the brackets tell the address from the port, and are not part of the host.
if let Some(rest) = server.strip_prefix('[')
&& let Some((host, tail)) = rest.split_once(']')
{
// Nothing after the bracket, or a real `:port`, is understood. Anything else (`[::1]:abc`,
// `[::1]:70000`, `[::1]junk`) keeps the whole string as the host, so the mistyped endpoint
// stays unresolvable instead of quietly becoming the default one.
let port = if tail.is_empty() {
631
} else if let Some(port) = tail.strip_prefix(':').and_then(|p| p.parse().ok()) {
port
} else {
return Endpoint::Tcp(server.to_string(), 631);
};
return Endpoint::Tcp(host.to_string(), port);
}
// A bare IPv6 literal has more than one ':', so splitting on the last one would cut the
// address in half: it is the host, and the port stays the default. A zone id (`fe80::1%eth0`)
// carries no ':', so there a port can still follow the address.
let host_port = if server.matches(':').count() > 1 && !server.contains('%') { None } else { server.rsplit_once(':') };
let (host, port) = host_port.and_then(|(h, p)| p.parse().ok().map(|p| (h.to_string(), p))).unwrap_or((server.to_string(), 631));
Endpoint::Tcp(host, port)
}
/// Whether a connection opens.
pub fn reachable(&self) -> bool {
self.connect().is_ok()
}
fn connect(&self) -> Result<Stream> {
match self {
#[cfg(unix)]
Endpoint::Unix(path) => {
if !path.exists() {
return Err(Error::Unreachable(format!("{} does not exist", path.display())));
}
let s = std::os::unix::net::UnixStream::connect(path).map_err(|e| Error::Unreachable(format!("{}: {e}", path.display())))?;
let _ = s.set_read_timeout(Some(REQUEST));
let _ = s.set_write_timeout(Some(REQUEST));
Ok(Stream::Unix(s))
}
#[cfg(not(unix))]
Endpoint::Unix(path) => Err(Error::Unreachable(format!("{}: Unix sockets are not available here", path.display()))),
Endpoint::Tcp(host, port) => {
let addr = (host.as_str(), *port).to_socket_addrs().map_err(|e| Error::Unreachable(format!("{host}:{port}: {e}")))?.next();
let addr = addr.ok_or_else(|| Error::Unreachable(format!("{host}:{port}: no address")))?;
open_tcp(host, *port, addr, |addr| TcpStream::connect_timeout(&addr, CONNECT))
}
}
}
/// The endpoint as an HTTP authority: an IPv6 host is bracketed, or its last colon reads as the
/// port separator and the request carries a host CUPS has never heard of. A scoped address keeps
/// its zone id and writes it escaped as "%25": "%" is not valid inside an authority (RFC 3986
/// section 3.2.2 reserves it for escaping), and the escaped form is what CUPS, curl and the
/// ipp:// URIs CUPS writes use for a zone. RFC 9844 (Aug 2025) obsoleted RFC 6874, which had made
/// that form URI syntax, so this is interop rather than a standard; dropping the zone instead
/// would name a different host on the wire than the socket was opened to. The socket still gets
/// the raw address%zone, which is the form a resolver understands.
fn host(&self) -> String {
match self {
Endpoint::Unix(_) => "localhost".into(),
Endpoint::Tcp(host, port) if host.contains(':') => format!("[{}]:{port}", host.replace('%', "%25")),
Endpoint::Tcp(host, port) => format!("{host}:{port}"),
}
}
}
impl std::fmt::Display for Endpoint {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Endpoint::Unix(p) => write!(f, "{}", p.display()),
Endpoint::Tcp(h, p) if h.contains(':') => write!(f, "[{h}]:{p}"),
Endpoint::Tcp(h, p) => write!(f, "{h}:{p}"),
}
}
}
/// Open one address and put the request timeouts on it. The connect call is a parameter so the
/// refusal path can be tested at all: no port is guaranteed to stay free between picking one and
/// using it, and what a refused connect reported is what the caller is supposed to hear.
fn open_tcp(host: &str, port: u16, addr: SocketAddr, open: impl FnOnce(SocketAddr) -> std::io::Result<TcpStream>) -> Result<Stream> {
let s = open(addr).map_err(|e| Error::Unreachable(format!("{host}:{port}: {e}")))?;
let _ = s.set_read_timeout(Some(REQUEST));
let _ = s.set_write_timeout(Some(REQUEST));
Ok(Stream::Tcp(s))
}
enum Stream {
#[cfg(unix)]
Unix(std::os::unix::net::UnixStream),
Tcp(TcpStream),
}
impl Read for Stream {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
match self {
#[cfg(unix)]
Stream::Unix(s) => s.read(buf),
Stream::Tcp(s) => s.read(buf),
}
}
}
impl Write for Stream {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
match self {
#[cfg(unix)]
Stream::Unix(s) => s.write(buf),
Stream::Tcp(s) => s.write(buf),
}
}
fn flush(&mut self) -> std::io::Result<()> {
match self {
#[cfg(unix)]
Stream::Unix(s) => s.flush(),
Stream::Tcp(s) => s.flush(),
}
}
}
/// Builds an IPP request body.
pub struct Request {
buf: Vec<u8>,
}
impl Request {
pub fn new(op: u16, id: u32) -> Self {
let mut buf = vec![2, 0];
buf.extend_from_slice(&op.to_be_bytes());
buf.extend_from_slice(&id.to_be_bytes());
buf.push(TAG_OPERATION_GROUP);
let mut r = Request { buf };
r.attr(TAG_CHARSET, "attributes-charset", b"utf-8");
r.attr(TAG_LANGUAGE, "attributes-natural-language", b"en");
r
}
/// Appends an attribute to the current group.
pub fn attr(&mut self, tag: u8, name: &str, value: &[u8]) {
// IPP lengths are 16-bit; longer names and values are cut, both the length and the bytes.
let name = name.as_bytes().get(..name.len().min(0xffff)).unwrap_or_default();
let value = value.get(..value.len().min(0xffff)).unwrap_or_default();
self.buf.push(tag);
self.buf.extend_from_slice(&(name.len() as u16).to_be_bytes());
self.buf.extend_from_slice(name);
self.buf.extend_from_slice(&(value.len() as u16).to_be_bytes());
self.buf.extend_from_slice(value);
}
/// An attribute with several values (the extra ones carry an empty name).
pub fn attr_many(&mut self, tag: u8, name: &str, values: &[&str]) {
for (i, v) in values.iter().enumerate() {
self.attr(tag, if i == 0 { name } else { "" }, v.as_bytes());
}
}
pub fn integer(&mut self, name: &str, v: i32) {
self.attr(TAG_INTEGER, name, &v.to_be_bytes());
}
/// Starts a new attribute group.
pub fn group(&mut self, tag: u8) {
self.buf.push(tag);
}
/// The message with its end tag.
pub fn end(mut self) -> Vec<u8> {
self.buf.push(TAG_END);
self.buf
}
}
/// One attribute of a reply: the group it sits in, its tag, name and values.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Attribute {
pub group: u8,
pub tag: u8,
pub name: String,
pub values: Vec<Vec<u8>>,
}
impl Attribute {
/// The first value as text.
pub fn text(&self) -> String {
self.values.first().map(|v| String::from_utf8_lossy(v).into_owned()).unwrap_or_default()
}
/// The first value as a big-endian integer.
pub fn int(&self) -> Option<i32> {
self.values.first().and_then(|v| <[u8; 4]>::try_from(v.as_slice()).ok()).map(i32::from_be_bytes)
}
}
/// A decoded reply.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Reply {
pub status: u16,
pub request_id: u32,
pub attributes: Vec<Attribute>,
}
/// The attribute range for one group delimiter in a parsed message. Ranges are half-open and
/// include empty groups, so repeated group tags remain distinct.
#[derive(Debug, Clone, Copy)]
struct GroupRange {
tag: u8,
start: usize,
end: usize,
}
/// Parsed message details kept private so the public flat `Reply` API stays source-compatible.
struct ParsedMessage {
reply: Reply,
end: usize,
groups: Vec<GroupRange>,
}
impl Reply {
/// Parses an IPP message (RFC 8010 §3): header, then groups of attributes until the end tag.
pub fn parse(b: &[u8]) -> Result<Reply> {
parse_message(b).map(|parsed| parsed.reply)
}
/// Parses a message and returns where its attributes end (document data may follow).
fn parse_at(b: &[u8]) -> Result<(Reply, usize)> {
parse_message(b).map(|parsed| (parsed.reply, parsed.end))
}
/// The server's own message for an error status, or a name for the code.
fn status_message(&self) -> String {
self.attributes.iter().find(|a| a.name == "status-message").map(Attribute::text).filter(|m| !m.is_empty()).unwrap_or_else(|| {
match self.status {
0x0400 => "bad request",
0x0401 => "forbidden",
0x0402 => "not authenticated",
0x0403 => "not authorized",
0x0406 => "not found",
0x0409 => "unsupported document format",
0x0500 => "internal server error",
0x0506 => "the printer is not accepting jobs",
_ => "error",
}
.to_string()
})
}
}
/// Parses one IPP message while preserving each group instance for private consumers that need
/// object boundaries. The public reply remains a flat list of attributes.
fn parse_message(b: &[u8]) -> Result<ParsedMessage> {
let bad = |m: &str| Error::Protocol(m.to_string());
if b.len() < 9 {
return Err(bad("reply shorter than an IPP header"));
}
let status = u16::from_be_bytes([b[2], b[3]]);
let request_id = u32::from_be_bytes([b[4], b[5], b[6], b[7]]);
let mut pos = 8;
let mut group = 0u8;
let mut active_group = None;
let mut last_attribute_group = None;
let mut attributes: Vec<Attribute> = Vec::new();
let mut groups: Vec<GroupRange> = Vec::new();
loop {
let tag = *b.get(pos).ok_or_else(|| bad("reply ends before the end-of-attributes tag"))?;
pos += 1;
if tag == TAG_END {
if let Some(last) = groups.last_mut() {
last.end = attributes.len();
}
return Ok(ParsedMessage { reply: Reply { status, request_id, attributes }, end: pos, groups });
}
if tag < 0x10 {
if let Some(last) = groups.last_mut() {
last.end = attributes.len();
}
if groups.len() >= MAX_ATTRIBUTES {
return Err(bad("too many attribute groups"));
}
group = tag;
let group_index = groups.len();
groups.push(GroupRange { tag, start: attributes.len(), end: attributes.len() });
active_group = Some(group_index);
continue;
}
let name_len =
usize::from(u16::from_be_bytes([*b.get(pos).ok_or_else(|| bad("cut attribute"))?, *b.get(pos + 1).ok_or_else(|| bad("cut attribute"))?]));
pos += 2;
let name = b.get(pos..pos + name_len).ok_or_else(|| bad("cut attribute name"))?;
pos += name_len;
let value_len =
usize::from(u16::from_be_bytes([*b.get(pos).ok_or_else(|| bad("cut attribute"))?, *b.get(pos + 1).ok_or_else(|| bad("cut attribute"))?]));
pos += 2;
let value = b.get(pos..pos + value_len).ok_or_else(|| bad("cut attribute value"))?.to_vec();
pos += value_len;
if name_len == 0 {
// Additional values can continue an attribute only within this exact group instance.
match attributes.last_mut() {
Some(last) if last_attribute_group == active_group => last.values.push(value),
_ => return Err(bad("an additional value with no attribute before it")),
}
} else {
attributes.push(Attribute { group, tag, name: String::from_utf8_lossy(name).into_owned(), values: vec![value] });
last_attribute_group = active_group;
}
if attributes.len() > MAX_ATTRIBUTES {
return Err(bad("too many attributes"));
}
}
}
/// POSTs `body` (IPP, with any document data after it) to `path` and returns the parsed reply with
/// its private group boundaries.
fn post(endpoint: &Endpoint, path: &str, body: &[u8]) -> Result<ParsedMessage> {
let mut stream = endpoint.connect()?;
let head = format!(
"POST {path} HTTP/1.1\r\nHost: {}\r\nContent-Type: application/ipp\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
endpoint.host(),
body.len()
);
stream
.write_all(head.as_bytes())
.and_then(|()| stream.write_all(body))
.and_then(|()| stream.flush())
.map_err(|e| Error::Protocol(format!("sending: {e}")))?;
let raw = read_response(&mut stream)?;
let (status, headers, body) = http_response(&raw)?;
if status != 200 {
return Err(Error::Protocol(match status {
401 => "the print server asks for authentication (HTTP 401)".to_string(),
403 => "the print server forbids this request (HTTP 403)".to_string(),
s => format!("HTTP {s}"),
}));
}
let body = if headers.iter().any(|(k, v)| k == "transfer-encoding" && v.contains("chunked")) { dechunk(body)? } else { body.to_vec() };
let reply = parse_message(&body)?;
if reply.reply.status >= 0x0400 {
return Err(Error::Status(reply.reply.status, reply.reply.status_message()));
}
Ok(reply)
}
/// Lowercase HTTP headers.
type Headers = Vec<(String, String)>;
/// Reads one HTTP response: the headers, then as much body as `Content-Length` says, or up to
/// the last chunk, or to the end of the stream when the server says neither. A server that keeps
/// the connection open would otherwise hold the reply until the read times out.
fn read_response(stream: &mut Stream) -> Result<Vec<u8>> {
let mut raw = Vec::new();
let mut buf = [0u8; 16 * 1024];
let mut body_at = None;
let mut expected: Option<usize> = None;
let mut chunked = false;
// Where the chunk walk resumes, so each read costs its own bytes, not the whole body again.
let mut chunk_at = 0usize;
// Where the header-end search resumes (three bytes back, for a marker split across reads).
let mut head_at = 0usize;
let started = std::time::Instant::now();
loop {
if started.elapsed() > REPLY_DEADLINE {
return Err(Error::Protocol("the print server took too long to reply".into()));
}
let n = stream.read(&mut buf).map_err(|e| Error::Protocol(format!("reading: {e}")))?;
if n == 0 {
return Ok(raw);
}
raw.extend_from_slice(buf.get(..n).unwrap_or_default());
if raw.len() > MAX_REPLY {
return Err(Error::Protocol("the reply is larger than 16 MiB".into()));
}
if body_at.is_none()
&& let Some(end) = raw.get(head_at..).and_then(|r| r.windows(4).position(|w| w == b"\r\n\r\n")).map(|p| head_at + p)
{
body_at = Some(end + 4);
let (_, headers, _) = http_response(&raw)?;
expected = headers.iter().find(|(k, _)| k == "content-length").and_then(|(_, v)| v.parse().ok());
chunked = headers.iter().any(|(k, v)| k == "transfer-encoding" && v.contains("chunked"));
}
let Some(at) = body_at else {
head_at = raw.len().saturating_sub(3);
continue;
};
let body = raw.get(at..).unwrap_or_default();
let complete = match expected {
Some(len) if !chunked => body.len() >= len,
_ if chunked => chunked_complete(body, &mut chunk_at),
_ => false,
};
if complete {
if let Some(len) = expected.filter(|_| !chunked) {
raw.truncate(at + len);
}
return Ok(raw);
}
}
}
/// Splits an HTTP/1.1 response into status, lowercase headers and body.
fn http_response(raw: &[u8]) -> Result<(u16, Headers, &[u8])> {
let end = raw.windows(4).position(|w| w == b"\r\n\r\n").ok_or_else(|| Error::Protocol("no HTTP header".into()))?;
let head = String::from_utf8_lossy(raw.get(..end).unwrap_or(&[]));
let mut lines = head.split("\r\n");
let status_line = lines.next().unwrap_or_default();
let status: u16 =
status_line.split_whitespace().nth(1).and_then(|s| s.parse().ok()).ok_or_else(|| Error::Protocol(format!("bad status line `{status_line}`")))?;
let headers = lines.filter_map(|l| l.split_once(':')).map(|(k, v)| (k.trim().to_ascii_lowercase(), v.trim().to_ascii_lowercase())).collect();
Ok((status, headers, raw.get(end + 4..).unwrap_or(&[])))
}
/// Whether a chunked body has reached its last (zero-size) chunk, walking the chunk sizes so a
/// `0\r\n\r\n` inside a chunk's payload (an attribute value can hold it) does not count. A
/// malformed or impossible size counts as complete, so [`dechunk`] reports it instead of
/// waiting for more.
fn chunked_complete(body: &[u8], resume: &mut usize) -> bool {
let mut b = body.get(*resume..).unwrap_or_default();
loop {
// Chunks already walked are not walked again: `resume` marks the start of this one.
*resume = body.len() - b.len();
let Some(line_end) = b.windows(2).position(|w| w == b"\r\n") else { return false };
let size_str = String::from_utf8_lossy(b.get(..line_end).unwrap_or(&[]));
let Ok(size) = usize::from_str_radix(size_str.split(';').next().unwrap_or_default().trim(), 16) else { return true };
b = b.get(line_end + 2..).unwrap_or(&[]);
if size == 0 {
return true;
}
// A size past the reply cap can never be satisfied: complete, so `dechunk` rejects it
// (checked, so `ffffffffffffffff` cannot overflow the slice arithmetic).
let Some(end) = size.checked_add(2).filter(|_| size <= MAX_REPLY) else { return true };
let Some(rest) = b.get(end..) else { return false };
b = rest;
}
}
/// Joins the chunks of a chunked transfer encoding.
fn dechunk(mut b: &[u8]) -> Result<Vec<u8>> {
let mut out = Vec::new();
loop {
let line_end = b.windows(2).position(|w| w == b"\r\n").ok_or_else(|| Error::Protocol("cut chunk size".into()))?;
let size_str = String::from_utf8_lossy(b.get(..line_end).unwrap_or(&[]));
let size = usize::from_str_radix(size_str.split(';').next().unwrap_or_default().trim(), 16).map_err(|_| Error::Protocol("bad chunk size".into()))?;
b = b.get(line_end + 2..).unwrap_or(&[]);
if size == 0 {
return Ok(out);
}
let chunk = b.get(..size).ok_or_else(|| Error::Protocol("cut chunk".into()))?;
out.extend_from_slice(chunk);
if out.len() > MAX_REPLY {
return Err(Error::Protocol("the reply is larger than 16 MiB".into()));
}
b = b.get(size + 2..).ok_or_else(|| Error::Protocol("cut chunk end".into()))?;
}
}
/// Where `/path` lands on the server: `/printers/<name>` or `/classes/<name>`.
fn queue_path(name: &str, is_class: bool) -> Result<String> {
if name.is_empty() || name.bytes().any(|b| b < 0x20 || b == 0x7f) {
return Err(Error::Protocol("printer name contains an invalid control character".into()));
}
let mut encoded = String::with_capacity(name.len());
for &b in name.as_bytes() {
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
encoded.push(char::from(b));
} else {
encoded.push_str(&format!("%{b:02X}"));
}
}
Ok(format!("/{}/{encoded}", if is_class { "classes" } else { "printers" }))
}
/// The printers the server knows (CUPS-Get-Printers), then its classes (CUPS-Get-Classes, which
/// `lp -d` accepts just the same), the default one flagged.
pub fn printers(endpoint: &Endpoint) -> Result<Vec<Printer>> {
let mut out = queues(endpoint, OP_CUPS_GET_PRINTERS, false)?;
// A server without classes answers "not found"; an older server may not know the operation.
out.extend(queues(endpoint, OP_CUPS_GET_CLASSES, true).unwrap_or_default());
let default = default_printer(endpoint).unwrap_or(None);
for p in &mut out {
p.is_default = default.as_deref() == Some(p.name.as_str());
}
Ok(out)
}
fn queues(endpoint: &Endpoint, op: u16, is_class: bool) -> Result<Vec<Printer>> {
let mut r = Request::new(op, 1);
r.attr_many(TAG_KEYWORD, "requested-attributes", &["printer-name", "printer-info", "printer-state", "printer-is-accepting-jobs"]);
let parsed = match post(endpoint, "/", &r.end()) {
Ok(reply) => reply,
// CUPS answers "not found" ("No destinations added.") when no printer is set up.
Err(Error::Status(0x0406, _)) => return Ok(Vec::new()),
Err(e) => return Err(e),
};
let mut out = Vec::new();
let attributes = &parsed.reply.attributes;
for group in parsed.groups.iter().filter(|group| group.tag == TAG_PRINTER_GROUP) {
let Some(group_attributes) = attributes.get(group.start..group.end) else {
return Err(Error::Protocol("invalid printer attribute group range".into()));
};
let mut name = None;
let mut info = String::new();
let mut state = 3;
let mut accepting_jobs = true;
for a in group_attributes {
match a.name.as_str() {
"printer-name" if name.is_none() => name = Some(a.text()),
"printer-info" => info = a.text(),
"printer-state" => state = a.int().unwrap_or(3).clamp(0, 5) as u32,
"printer-is-accepting-jobs" => accepting_jobs = a.values.first().is_none_or(|v| v.first() != Some(&0)),
_ => {}
}
}
if let Some(name) = name.filter(|name| !name.is_empty()) {
out.push(Printer { name, info, state, accepting_jobs, is_default: false, is_class });
}
}
Ok(out)
}
/// The server's default printer (CUPS-Get-Default), `None` when there is none.
pub fn default_printer(endpoint: &Endpoint) -> Result<Option<String>> {
let mut r = Request::new(OP_CUPS_GET_DEFAULT, 2);
r.attr_many(TAG_KEYWORD, "requested-attributes", &["printer-name"]);
match post(endpoint, "/", &r.end()) {
Ok(reply) => Ok(reply.reply.attributes.iter().find(|a| a.name == "printer-name").map(Attribute::text).filter(|n| !n.is_empty())),
// CUPS answers "not found" when no default is set.
Err(Error::Status(0x0406, _)) => Ok(None),
Err(e) => Err(e),
}
}
/// What to print.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Job<'a> {
pub printer: &'a str,
/// `printer` names a class.
pub is_class: bool,
/// Shown in the queue.
pub title: &'a str,
pub user: &'a str,
pub copies: u32,
/// The document, as `format` (`application/pdf`).
pub document: &'a [u8],
pub format: &'a str,
}
/// Submits `job` (Print-Job) and returns the job id.
pub fn print_job(endpoint: &Endpoint, job: &Job<'_>) -> Result<u32> {
let mut r = Request::new(OP_PRINT_JOB, 3);
let path = queue_path(job.printer, job.is_class)?;
r.attr(TAG_URI, "printer-uri", format!("ipp://{}{path}", endpoint.host()).as_bytes());
r.attr(TAG_NAME, "requesting-user-name", job.user.as_bytes());
r.attr(TAG_NAME, "job-name", job.title.as_bytes());
r.attr(TAG_MIME, "document-format", job.format.as_bytes());
if job.copies > 1 {
r.buf.push(TAG_JOB_GROUP);
r.integer("copies", job.copies.clamp(1, 999) as i32);
}
let mut body = r.end();
body.extend_from_slice(job.document);
let reply = post(endpoint, &path, &body)?.reply;
reply
.attributes
.iter()
.find(|a| a.name == "job-id")
.and_then(Attribute::int)
.map(|id| id.max(0) as u32)
.ok_or_else(|| Error::Protocol("no job id in the reply".into()))
}
/// A request as a server sees it: the operation (the request's status field), its attributes
/// and the document data after the end tag. For fakes in tests and tools.
pub fn parse_request(b: &[u8]) -> Result<(u16, Vec<Attribute>, Vec<u8>)> {
let (reply, end) = Reply::parse_at(b)?;
Ok((reply.status, reply.attributes, b.get(end..).unwrap_or(&[]).to_vec()))
}
#[cfg(test)]
mod tests;
pub use craft_ipp::*;
-673
View File
@@ -1,673 +0,0 @@
//! The client against an in-process fake CUPS: TCP and Unix socket, content-length and chunked
//! replies, every operation, error statuses and broken replies.
use super::*;
use std::io::{BufRead, BufReader};
use std::sync::mpsc;
/// What the fake received: op, attributes, document.
type Seen = (u16, Vec<Attribute>, Vec<u8>);
/// A fake server answering one request with `reply_body` (IPP bytes), chunked or not, under an
/// HTTP status. Returns the endpoint and a channel with what it received.
fn fake(reply: Vec<u8>, chunked: bool, http_status: u16) -> (Endpoint, mpsc::Receiver<Seen>) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let (tx, rx) = mpsc::channel();
std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
serve(Stream::Tcp(stream), reply, chunked, http_status, &tx);
});
(Endpoint::Tcp("127.0.0.1".into(), port), rx)
}
fn serve(stream: Stream, reply: Vec<u8>, chunked: bool, http_status: u16, tx: &mpsc::Sender<Seen>) {
let mut reader = BufReader::new(stream);
let mut line = String::new();
let mut content_length = 0usize;
let mut first = String::new();
loop {
line.clear();
reader.read_line(&mut line).unwrap();
if first.is_empty() {
first = line.clone();
}
if line == "\r\n" || line.is_empty() {
break;
}
if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") {
content_length = v.trim().parse().unwrap();
}
}
if first.is_empty() {
return; // a reachability probe: connect and close
}
assert!(first.starts_with("POST "), "{first}");
let mut body = vec![0u8; content_length];
reader.read_exact(&mut body).unwrap();
let _ = tx.send(parse_request(&body).unwrap());
let mut out = reader.into_inner();
let status_text = if http_status == 200 { "OK" } else { "Nope" };
if chunked {
let mut resp = format!("HTTP/1.1 {http_status} {status_text}\r\nContent-Type: application/ipp\r\nTransfer-Encoding: chunked\r\n\r\n").into_bytes();
for chunk in reply.chunks(7) {
resp.extend_from_slice(format!("{:x}\r\n", chunk.len()).as_bytes());
resp.extend_from_slice(chunk);
resp.extend_from_slice(b"\r\n");
}
resp.extend_from_slice(b"0\r\n\r\n");
out.write_all(&resp).unwrap();
} else {
out.write_all(format!("HTTP/1.1 {http_status} {status_text}\r\nContent-Type: application/ipp\r\nContent-Length: {}\r\n\r\n", reply.len()).as_bytes())
.unwrap();
out.write_all(&reply).unwrap();
}
out.flush().unwrap();
}
/// An attribute to write: tag, name, values.
type Attr<'a> = (u8, &'a str, &'a [&'a [u8]]);
/// A group to write: tag and attributes.
type Group<'a> = (u8, &'a [Attr<'a>]);
/// An IPP reply body.
fn ipp(status: u16, groups: &[Group<'_>]) -> Vec<u8> {
let mut b = vec![2, 0];
b.extend_from_slice(&status.to_be_bytes());
b.extend_from_slice(&1u32.to_be_bytes());
for (group, attrs) in groups {
b.push(*group);
for (tag, name, values) in *attrs {
for (i, v) in values.iter().enumerate() {
b.push(*tag);
let n = if i == 0 { name.as_bytes() } else { b"" };
b.extend_from_slice(&(n.len() as u16).to_be_bytes());
b.extend_from_slice(n);
b.extend_from_slice(&(v.len() as u16).to_be_bytes());
b.extend_from_slice(v);
}
}
}
b.push(TAG_END);
b
}
fn ok_header() -> Group<'static> {
(TAG_OPERATION_GROUP, &[(TAG_CHARSET, "attributes-charset", &[b"utf-8"]), (TAG_LANGUAGE, "attributes-natural-language", &[b"en"])])
}
#[test]
fn printers_are_listed_with_state_and_default() {
let three = ipp(
0,
&[
ok_header(),
(
TAG_PRINTER_GROUP,
&[
(TAG_NAME, "printer-name", &[b"Office"]),
(TAG_TEXT, "printer-info", &[b"HP in the office"]),
(TAG_ENUM, "printer-state", &[&3u32.to_be_bytes()]),
(TAG_BOOLEAN, "printer-is-accepting-jobs", &[&[1]]),
],
),
(
TAG_PRINTER_GROUP,
&[
(TAG_NAME, "printer-name", &[b"Stopped"]),
(TAG_ENUM, "printer-state", &[&5u32.to_be_bytes()]),
(TAG_BOOLEAN, "printer-is-accepting-jobs", &[&[0]]),
],
),
],
);
for chunked in [false, true] {
let (ep, rx) = fake(three.clone(), chunked, 200);
// `printers` asks for the default too; that second request reaches a server that has
// closed, so the default is simply unknown here.
let list = printers(&ep).unwrap();
let (op, attrs, doc) = rx.recv().unwrap();
assert_eq!(op, OP_CUPS_GET_PRINTERS);
assert!(attrs.iter().any(|a| a.name == "requested-attributes" && a.values.len() == 4 && a.tag == TAG_KEYWORD));
assert!(doc.is_empty());
assert_eq!(list.len(), 2, "chunked {chunked}");
assert_eq!((list[0].name.as_str(), list[0].info.as_str(), list[0].state, list[0].accepting_jobs), ("Office", "HP in the office", 3, true));
assert_eq!((list[1].name.as_str(), list[1].state, list[1].accepting_jobs), ("Stopped", 5, false));
assert!(!list[0].is_default && !list[1].is_default);
}
}
#[test]
fn printer_attributes_before_name_are_preserved() {
let state = 5u32.to_be_bytes();
let base: [Attr<'_>; 4] = [
(TAG_TEXT, "printer-info", &[b"Studio Printer"]),
(TAG_ENUM, "printer-state", &[&state]),
(TAG_BOOLEAN, "printer-is-accepting-jobs", &[b"\0"]),
(TAG_NAME, "printer-name", &[b"studio"]),
];
let body = ipp(0, &[ok_header(), (TAG_PRINTER_GROUP, &base)]);
for chunked in [false, true] {
let (ep, _) = fake(body.clone(), chunked, 200);
let list = printers(&ep).unwrap();
assert_eq!(list.len(), 1, "chunked {chunked}");
assert_eq!((list[0].name.as_str(), list[0].info.as_str(), list[0].state, list[0].accepting_jobs), ("studio", "Studio Printer", 5, false));
assert!(!list[0].is_class);
}
}
#[test]
fn printer_groups_do_not_share_metadata() {
let state_a = 4u32.to_be_bytes();
let state_b = 5u32.to_be_bytes();
let body = ipp(
0,
&[
ok_header(),
(
TAG_PRINTER_GROUP,
&[(TAG_NAME, "printer-name", &[b"first"]), (TAG_TEXT, "printer-info", &[b"First printer"]), (TAG_ENUM, "printer-state", &[&state_a])],
),
(
TAG_PRINTER_GROUP,
&[(TAG_TEXT, "printer-info", &[b"Second printer"]), (TAG_ENUM, "printer-state", &[&state_b]), (TAG_NAME, "printer-name", &[b"second"])],
),
],
);
let (ep, _) = fake(body, false, 200);
let list = queues(&ep, OP_CUPS_GET_PRINTERS, false).unwrap();
assert_eq!(list.len(), 2);
assert_eq!((list[0].name.as_str(), list[0].info.as_str(), list[0].state), ("first", "First printer", 4));
assert_eq!((list[1].name.as_str(), list[1].info.as_str(), list[1].state), ("second", "Second printer", 5));
}
#[test]
fn printer_attribute_order_does_not_change_results() {
let state = 5u32.to_be_bytes();
let fields: [Attr<'_>; 4] = [
(TAG_TEXT, "printer-info", &[b"Studio Printer"]),
(TAG_ENUM, "printer-state", &[&state]),
(TAG_BOOLEAN, "printer-is-accepting-jobs", &[b"\0"]),
(TAG_NAME, "printer-name", &[b"studio"]),
];
let expected = Printer { name: "studio".into(), info: "Studio Printer".into(), state: 5, accepting_jobs: false, is_default: false, is_class: false };
let mut permutations = 0;
for first in 0..4 {
for second in 0..4 {
for third in 0..4 {
for fourth in 0..4 {
let order = [first, second, third, fourth];
if order[0] == order[1]
|| order[0] == order[2]
|| order[0] == order[3]
|| order[1] == order[2]
|| order[1] == order[3]
|| order[2] == order[3]
{
continue;
}
permutations += 1;
let ordered = order.iter().map(|index| fields[*index]).collect::<Vec<_>>();
let body = ipp(0, &[ok_header(), (TAG_PRINTER_GROUP, &ordered)]);
let (ep, _) = fake(body, false, 200);
assert_eq!(queues(&ep, OP_CUPS_GET_PRINTERS, false).unwrap(), vec![expected.clone()], "order {order:?}");
}
}
}
}
assert_eq!(permutations, 24);
}
#[test]
fn class_attributes_before_name_are_preserved() {
let state = 5u32.to_be_bytes();
let body = ipp(
0,
&[
ok_header(),
(
TAG_PRINTER_GROUP,
&[
(TAG_BOOLEAN, "printer-is-accepting-jobs", &[b"\0"]),
(TAG_TEXT, "printer-info", &[b"Shared studio"]),
(TAG_ENUM, "printer-state", &[&state]),
(TAG_NAME, "printer-name", &[b"studio-class"]),
],
),
],
);
let (ep, rx) = fake(body, true, 200);
let classes = queues(&ep, OP_CUPS_GET_CLASSES, true).unwrap();
assert_eq!(rx.recv().unwrap().0, OP_CUPS_GET_CLASSES);
assert_eq!(classes.len(), 1);
assert_eq!(
(classes[0].name.as_str(), classes[0].info.as_str(), classes[0].state, classes[0].accepting_jobs, classes[0].is_class),
("studio-class", "Shared studio", 5, false, true)
);
}
#[test]
fn empty_or_unnamed_groups_do_not_leak_metadata() {
let body = ipp(
0,
&[
ok_header(),
(TAG_PRINTER_GROUP, &[(TAG_NAME, "printer-name", &[b"named"])]),
(TAG_PRINTER_GROUP, &[]),
(TAG_PRINTER_GROUP, &[(TAG_TEXT, "printer-info", &[b"orphan metadata"])]),
(TAG_PRINTER_GROUP, &[(TAG_NAME, "printer-name", &[b"next"]), (TAG_ENUM, "printer-state", &[&3u32.to_be_bytes()])]),
],
);
let (ep, _) = fake(body, false, 200);
let list = queues(&ep, OP_CUPS_GET_PRINTERS, false).unwrap();
assert_eq!(list.len(), 2);
assert_eq!((list[0].name.as_str(), list[0].info.as_str()), ("named", ""));
assert_eq!((list[1].name.as_str(), list[1].info.as_str()), ("next", ""));
}
#[test]
fn additional_values_do_not_cross_group_boundaries() {
let valid = ipp(0, &[ok_header(), (TAG_PRINTER_GROUP, &[(TAG_KEYWORD, "supported", &[b"one", b"two"])])]);
let reply = Reply::parse(&valid).unwrap();
assert_eq!(reply.attributes.iter().find(|a| a.name == "supported").map(|a| a.values.as_slice()), Some(&[b"one".to_vec(), b"two".to_vec()][..]));
let mut body = vec![2, 0, 0, 0, 0, 0, 0, 1, TAG_PRINTER_GROUP];
body.extend_from_slice(&[TAG_NAME, 0, 12]);
body.extend_from_slice(b"printer-name");
body.extend_from_slice(&[0, 5]);
body.extend_from_slice(b"first");
body.extend_from_slice(&[TAG_TEXT, 0, 12]);
body.extend_from_slice(b"printer-info");
body.extend_from_slice(&[0, 6]);
body.extend_from_slice(b"before");
body.push(TAG_PRINTER_GROUP);
body.extend_from_slice(&[TAG_TEXT, 0, 0, 0, 5]);
body.extend_from_slice(b"after");
body.extend_from_slice(&[TAG_NAME, 0, 12]);
body.extend_from_slice(b"printer-name");
body.extend_from_slice(&[0, 6]);
body.extend_from_slice(b"second");
body.push(TAG_END);
let (ep, _) = fake(body, true, 200);
assert!(matches!(queues(&ep, OP_CUPS_GET_PRINTERS, false), Err(Error::Protocol(_))));
}
#[test]
fn default_printer_is_read_and_absence_is_not_an_error() {
let (ep, rx) = fake(ipp(0, &[ok_header(), (TAG_PRINTER_GROUP, &[(TAG_NAME, "printer-name", &[b"Office"])])]), false, 200);
assert_eq!(default_printer(&ep).unwrap(), Some("Office".into()));
assert_eq!(rx.recv().unwrap().0, OP_CUPS_GET_DEFAULT);
let (ep, _rx) = fake(ipp(0x0406, &[ok_header(), (TAG_OPERATION_GROUP, &[(TAG_TEXT, "status-message", &[b"No default printer"])])]), false, 200);
assert_eq!(default_printer(&ep).unwrap(), None);
}
#[test]
fn a_print_job_carries_the_document_and_returns_its_id() {
let (ep, rx) = fake(ipp(0, &[ok_header(), (TAG_JOB_GROUP, &[(TAG_INTEGER, "job-id", &[&42u32.to_be_bytes()])])]), true, 200);
let pdf = b"%PDF-1.4 fake".to_vec();
let id =
print_job(&ep, &Job { printer: "Office", is_class: false, title: "photo.psd", user: "diego", copies: 2, document: &pdf, format: "application/pdf" })
.unwrap();
assert_eq!(id, 42);
let (op, attrs, doc) = rx.recv().unwrap();
assert_eq!(op, OP_PRINT_JOB);
assert_eq!(doc, pdf);
let get = |n: &str| attrs.iter().find(|a| a.name == n).cloned().unwrap_or_else(|| panic!("{n}"));
let uri = String::from_utf8(get("printer-uri").values[0].clone()).unwrap();
// Spelled out here rather than echoed back from host(), so the printer-uri the server receives is
// pinned down even when the authority is an IP literal.
assert!(uri.starts_with("ipp://127.0.0.1:") && uri.ends_with("/printers/Office"), "{uri}");
assert_eq!(get("job-name").values[0], b"photo.psd");
assert_eq!(get("requesting-user-name").values[0], b"diego");
assert_eq!(get("document-format").values[0], b"application/pdf");
let copies = get("copies");
assert_eq!((copies.group, copies.tag, copies.int()), (TAG_JOB_GROUP, TAG_INTEGER, Some(2)));
// One copy: no job attributes group at all.
let (ep, rx) = fake(ipp(0, &[ok_header(), (TAG_JOB_GROUP, &[(TAG_INTEGER, "job-id", &[&7u32.to_be_bytes()])])]), false, 200);
print_job(&ep, &Job { printer: "P", is_class: false, title: "t", user: "u", copies: 1, document: b"x", format: "application/pdf" }).unwrap();
assert!(!rx.recv().unwrap().1.iter().any(|a| a.name == "copies"));
}
#[test]
fn error_statuses_and_broken_replies_are_errors() {
let (ep, _rx) = fake(ipp(0x0506, &[ok_header(), (TAG_OPERATION_GROUP, &[(TAG_TEXT, "status-message", &[b"Printer is not accepting jobs"])])]), false, 200);
let e = print_job(&ep, &Job { printer: "P", is_class: false, title: "t", user: "u", copies: 1, document: b"x", format: "application/pdf" }).unwrap_err();
assert_eq!(e, Error::Status(0x0506, "Printer is not accepting jobs".into()));
assert!(e.to_string().contains("0x0506"));
// A CUPS with no printer at all answers "not found": that is an empty list, not an error.
let (ep, _rx) = fake(ipp(0x0406, &[ok_header(), (TAG_OPERATION_GROUP, &[(TAG_TEXT, "status-message", &[b"No destinations added."])])]), false, 200);
assert_eq!(printers(&ep).unwrap(), Vec::<Printer>::new());
// HTTP 401, a reply cut short, garbage.
let (ep, _rx) = fake(ipp(0, &[ok_header()]), false, 401);
assert!(matches!(printers(&ep), Err(Error::Protocol(m)) if m.contains("401")));
let (ep, _rx) = fake(vec![2, 0, 0, 0, 0, 0, 0, 1, TAG_OPERATION_GROUP, TAG_NAME, 0, 5], true, 200);
assert!(matches!(printers(&ep), Err(Error::Protocol(_))));
let (ep, _rx) = fake(b"not ipp at all".to_vec(), false, 200);
assert!(matches!(printers(&ep), Err(Error::Protocol(_))));
// Nobody reachable. A port is never guaranteed to be free, let alone to stay free: that is what
// made the old port-1 case fail on a FreeBSD CI VM. A name that can never resolve (RFC 2606)
// reaches the same exit without owning or releasing anything.
let e = printers(&Endpoint::Tcp("printer.invalid".into(), 631)).unwrap_err();
assert!(matches!(e, Error::Unreachable(_)), "{e}");
assert!(e.to_string().contains("printer.invalid"), "{e} does not name the server it tried");
}
#[test]
fn a_refused_connection_is_unreachable_and_keeps_why() {
// The refused-connect path, with the machine no longer deciding what is closed: the connect call
// is a parameter, so this test cannot race for an ephemeral port with anything.
let addr: SocketAddr = "192.0.2.9:631".parse().unwrap();
let asked_for = std::cell::RefCell::new(None);
let open = |seen: SocketAddr| -> std::io::Result<TcpStream> {
*asked_for.borrow_mut() = Some(seen);
Err(std::io::Error::new(std::io::ErrorKind::ConnectionRefused, "nobody is listening on this port"))
};
let e = match open_tcp("printserver", 631, addr, open) {
Ok(_) => panic!("nothing opens {addr}"),
Err(e) => e,
};
assert_eq!(*asked_for.borrow(), Some(addr), "the connector is handed the resolved address");
match &e {
Error::Unreachable(m) => {
assert!(m.contains("printserver:631"), "{e} does not name the endpoint");
assert!(m.contains("nobody is listening on this port"), "{e} loses why the connect failed");
}
other => panic!("expected Unreachable, got {other}"),
}
}
#[test]
fn reply_parsing_is_bounded() {
assert!(Reply::parse(&[]).is_err());
assert!(Reply::parse(&[2, 0, 0, 0, 0, 0, 0, 1]).is_err(), "no end tag");
let mut many = vec![2, 0, 0, 0, 0, 0, 0, 1, TAG_OPERATION_GROUP];
for _ in 0..MAX_ATTRIBUTES + 1 {
many.extend_from_slice(&[TAG_NAME, 0, 1, b'a', 0, 0]);
}
many.push(TAG_END);
assert!(matches!(Reply::parse(&many), Err(Error::Protocol(m)) if m.contains("too many")));
// An additional value before any attribute.
assert!(Reply::parse(&[2, 0, 0, 0, 0, 0, 0, 1, TAG_OPERATION_GROUP, TAG_NAME, 0, 0, 0, 1, b'x', TAG_END]).is_err());
assert!(dechunk(b"zz\r\n").is_err() && dechunk(b"5\r\nab").is_err());
assert_eq!(dechunk(b"3\r\nabc\r\n0\r\n\r\n").unwrap(), b"abc");
}
#[cfg(unix)]
#[test]
fn the_unix_socket_endpoint_works_and_detect_honours_cups_server() {
let dir = std::env::temp_dir().join(format!("pc-ipp-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let sock = dir.join("cups.sock");
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let (tx, rx) = mpsc::channel();
let reply = ipp(0, &[ok_header(), (TAG_PRINTER_GROUP, &[(TAG_NAME, "printer-name", &[b"Sock"])])]);
std::thread::spawn(move || {
for _ in 0..3 {
let (stream, _) = listener.accept().unwrap();
serve(Stream::Unix(stream), reply.clone(), false, 200, &tx);
}
});
let ep = Endpoint::Unix(sock.clone());
assert!(ep.reachable());
assert_eq!(default_printer(&ep).unwrap(), Some("Sock".into()));
assert_eq!(rx.recv().unwrap().0, OP_CUPS_GET_DEFAULT);
assert!(!Endpoint::Unix(dir.join("missing.sock")).reachable());
assert_eq!(ep.to_string(), sock.display().to_string());
let _ = std::fs::remove_dir_all(&dir);
}
/// An IPv6 print server is not a `host:port` split: a bare address has more than one ':', and the
/// brackets of `[address]:port` must not end up inside the host, where no resolver can read them.
#[test]
fn an_ipv6_print_server_is_parsed_as_a_host_not_as_host_port() {
assert_eq!(Endpoint::parse("::1"), Endpoint::Tcp("::1".into(), 631));
assert_eq!(Endpoint::parse("fe80::1"), Endpoint::Tcp("fe80::1".into(), 631));
assert_eq!(Endpoint::parse("2001:db8::1"), Endpoint::Tcp("2001:db8::1".into(), 631));
assert_eq!(Endpoint::parse("[::1]"), Endpoint::Tcp("::1".into(), 631));
assert_eq!(Endpoint::parse("[::1]:631"), Endpoint::Tcp("::1".into(), 631));
assert_eq!(Endpoint::parse("[fe80::1]:6310"), Endpoint::Tcp("fe80::1".into(), 6310));
// A zone id carries no ':', so a port can still follow it without brackets.
assert_eq!(Endpoint::parse("fe80::1%eth0:631"), Endpoint::Tcp("fe80::1%eth0".into(), 631));
// What already worked is unchanged.
assert_eq!(Endpoint::parse("cups.example"), Endpoint::Tcp("cups.example".into(), 631));
assert_eq!(Endpoint::parse("cups.example:6310"), Endpoint::Tcp("cups.example".into(), 6310));
assert_eq!(Endpoint::parse("127.0.0.1:6310"), Endpoint::Tcp("127.0.0.1".into(), 6310));
assert_eq!(Endpoint::parse("/var/run/cups/cups.sock"), Endpoint::Unix("/var/run/cups/cups.sock".into()));
// A mistyped bracketed endpoint is not quietly the default one: the whole string stays the host,
// so nothing can resolve it and detect() reports the endpoint unreachable.
assert_eq!(Endpoint::parse("[::1]:abc"), Endpoint::Tcp("[::1]:abc".into(), 631));
assert_eq!(Endpoint::parse("[::1]:70000"), Endpoint::Tcp("[::1]:70000".into(), 631));
assert_eq!(Endpoint::parse("[::1]junk"), Endpoint::Tcp("[::1]junk".into(), 631));
assert!(!Endpoint::parse("[::1]:abc").reachable());
}
/// The authority a request carries (the `Host:` header and the `ipp://` printer-uri) has to bracket an
/// IPv6 host, or its last colon reads as the port separator and CUPS sees a nonsense host.
#[test]
fn an_ipv6_endpoint_writes_its_authority_in_brackets() {
assert_eq!(Endpoint::parse("::1").host(), "[::1]:631");
assert_eq!(Endpoint::parse("[::1]:631").host(), "[::1]:631");
assert_eq!(Endpoint::parse("[fe80::1]:6310").host(), "[fe80::1]:6310");
assert_eq!(Endpoint::parse("cups.example").host(), "cups.example:631");
assert_eq!(Endpoint::parse("cups.example:6310").host(), "cups.example:6310");
assert_eq!(Endpoint::parse("127.0.0.1:6310").host(), "127.0.0.1:6310");
// A scoped address keeps its zone id, but the authority writes it "%25"-escaped: a bare "%" is
// not valid inside an authority, and the escaped form is what CUPS and curl-style ipp:// URIs
// use. The host itself stays raw, because that is what the resolver gets.
assert_eq!(Endpoint::parse("fe80::1%3:631").host(), "[fe80::1%253]:631");
assert_eq!(Endpoint::parse("[fe80::1%3]:6310").host(), "[fe80::1%253]:6310");
assert_eq!(Endpoint::parse("fe80::1%eth0:631").host(), "[fe80::1%25eth0]:631");
assert_eq!(Endpoint::parse("fe80::1%3:631"), Endpoint::Tcp("fe80::1%3".into(), 631));
// What the user is shown is written the same way, with the zone exactly as it was typed.
assert_eq!(Endpoint::parse("::1").to_string(), "[::1]:631");
assert_eq!(Endpoint::parse("cups.example:6310").to_string(), "cups.example:6310");
assert_eq!(Endpoint::parse("fe80::1%3:631").to_string(), "[fe80::1%3]:631");
}
#[test]
fn requests_start_with_the_mandatory_attributes() {
let r = Request::new(OP_PRINT_JOB, 9).end();
let (op, attrs, doc) = parse_request(&r).unwrap();
assert_eq!(op, OP_PRINT_JOB);
assert_eq!(Reply::parse(&r).unwrap().request_id, 9);
assert_eq!(attrs[0].name, "attributes-charset");
assert_eq!(attrs[1].name, "attributes-natural-language");
assert!(doc.is_empty());
}
/// A server that keeps the connection open after its reply (a printer reached directly, a proxy)
/// must not hold the client until the read times out: the reply ends at Content-Length, or at
/// the last chunk.
#[test]
fn replies_end_at_content_length_or_the_last_chunk_without_waiting_for_close() {
for chunked in [false, true] {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let one = ipp(0, &[ok_header(), (TAG_PRINTER_GROUP, &[(TAG_NAME, "printer-name", &[b"Office"])])]);
let none = ipp(0x0406, &[ok_header()]);
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(stream) = stream else { return };
let mut reader = BufReader::new(stream);
let (mut line, mut len) = (String::new(), 0usize);
loop {
line.clear();
if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" {
break;
}
if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") {
len = v.trim().parse().unwrap_or(0);
}
}
if len == 0 {
continue;
}
let mut body = vec![0u8; len];
if reader.read_exact(&mut body).is_err() {
continue;
}
let op = parse_request(&body).map(|r| r.0).unwrap_or(0);
let reply = if op == OP_CUPS_GET_PRINTERS { one.clone() } else { none.clone() };
let mut out = reader.into_inner();
let mut resp = Vec::new();
if chunked {
resp.extend_from_slice(b"HTTP/1.1 200 OK\r\nContent-Type: application/ipp\r\nTransfer-Encoding: chunked\r\n\r\n");
for chunk in reply.chunks(5) {
resp.extend_from_slice(format!("{:x}\r\n", chunk.len()).as_bytes());
resp.extend_from_slice(chunk);
resp.extend_from_slice(b"\r\n");
}
resp.extend_from_slice(b"0\r\n\r\n");
} else {
resp.extend_from_slice(format!("HTTP/1.1 200 OK\r\nContent-Type: application/ipp\r\nContent-Length: {}\r\n\r\n", reply.len()).as_bytes());
resp.extend_from_slice(&reply);
}
if out.write_all(&resp).and_then(|()| out.flush()).is_err() {
continue;
}
// Keep this connection open for a while, on its own thread, and go on serving.
std::thread::spawn(move || {
std::thread::sleep(Duration::from_secs(10));
drop(out);
});
}
});
let ep = Endpoint::Tcp("127.0.0.1".into(), port);
let started = std::time::Instant::now();
let list = printers(&ep).unwrap();
assert_eq!(list.len(), 1, "chunked {chunked}");
assert!(started.elapsed() < Duration::from_secs(5), "waited for the server to close (chunked {chunked}): {:?}", started.elapsed());
}
}
/// A chunked reply whose payload contains the bytes of a last chunk (`\r\n0\r\n\r\n`, here inside
/// a printer name) and arrives split right after them: the reader must wait for the real last
/// chunk instead of returning a cut reply.
#[test]
fn a_last_chunk_pattern_inside_a_value_does_not_end_the_reply() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let reply = ipp(0, &[ok_header(), (TAG_PRINTER_GROUP, &[(TAG_NAME, "printer-name", &[b"Of\r\n0\r\n\r\nfice"])])]);
let cut = reply.windows(7).position(|w| w == b"\r\n0\r\n\r\n").unwrap() + 7;
std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let mut reader = BufReader::new(stream);
let (mut line, mut len) = (String::new(), 0usize);
loop {
line.clear();
if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" {
break;
}
if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") {
len = v.trim().parse().unwrap_or(0);
}
}
let mut body = vec![0u8; len];
reader.read_exact(&mut body).unwrap();
let mut out = reader.into_inner();
let (first, second) = reply.split_at(cut);
// Part one ends exactly on the pattern, inside the first chunk's payload.
let mut a = b"HTTP/1.1 200 OK\r\nContent-Type: application/ipp\r\nTransfer-Encoding: chunked\r\n\r\n".to_vec();
a.extend_from_slice(format!("{:x}\r\n", first.len()).as_bytes());
a.extend_from_slice(first);
out.write_all(&a).and_then(|()| out.flush()).unwrap();
std::thread::sleep(Duration::from_millis(400));
let mut b = b"\r\n".to_vec();
b.extend_from_slice(format!("{:x}\r\n", second.len()).as_bytes());
b.extend_from_slice(second);
b.extend_from_slice(b"\r\n0\r\n\r\n");
out.write_all(&b).and_then(|()| out.flush()).unwrap();
});
let ep = Endpoint::Tcp("127.0.0.1".into(), port);
let list = printers(&ep).unwrap();
assert_eq!(list.len(), 1);
assert_eq!(list[0].name, "Of\r\n0\r\n\r\nfice");
// The boundary walk itself: complete only at a zero-size chunk, never on payload bytes.
assert!(!complete(b"5\r\nab\r\n0"));
assert!(!complete(b"7\r\n\r\n0\r\n\r\nx\r\n"));
assert!(complete(b"7\r\n\r\n0\r\n\r\nx\r\n0\r\n\r\n"));
assert!(complete(b"zz\r\n") && dechunk(b"zz\r\n").is_err());
}
/// [`chunked_complete`] on a whole body at once.
fn complete(body: &[u8]) -> bool {
chunked_complete(body, &mut 0)
}
/// Fed a byte at a time, as a server dripping the reply would, the walk resumes where it stopped
/// and agrees with the one-shot answer at every length.
#[test]
fn the_chunk_walk_resumes_instead_of_starting_over() {
let body = b"3\r\nabc\r\n10\r\n0123456789abcdef\r\n0\r\n\r\n";
let mut at = 0;
for len in 0..=body.len() {
let prefix = &body[..len];
assert_eq!(chunked_complete(prefix, &mut at), complete(prefix), "{len}");
assert!(at <= len);
}
assert!(at > 0, "it moved past the chunks already walked");
}
/// A chunk size that cannot be satisfied (`usize::MAX`, `usize::MAX - 1`, anything past the
/// reply cap) is a protocol error, through the real reader, never an overflow panic.
#[test]
fn an_impossible_chunk_size_is_a_protocol_error_not_a_panic() {
for size_line in ["ffffffffffffffff", "fffffffffffffffe", "1000001"] {
assert!(complete(format!("{size_line}\r\n").as_bytes()));
assert!(dechunk(format!("{size_line}\r\nab\r\n").as_bytes()).is_err());
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let line = size_line.to_string();
std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let mut reader = BufReader::new(stream);
let (mut l, mut len) = (String::new(), 0usize);
loop {
l.clear();
if reader.read_line(&mut l).unwrap_or(0) == 0 || l == "\r\n" {
break;
}
if let Some(v) = l.to_ascii_lowercase().strip_prefix("content-length:") {
len = v.trim().parse().unwrap_or(0);
}
}
let mut body = vec![0u8; len];
reader.read_exact(&mut body).unwrap();
let mut out = reader.into_inner();
let resp = format!("HTTP/1.1 200 OK\r\nContent-Type: application/ipp\r\nTransfer-Encoding: chunked\r\n\r\n{line}\r\n");
let _ = out.write_all(resp.as_bytes()).and_then(|()| out.flush());
});
let ep = Endpoint::Tcp("127.0.0.1".into(), port);
match printers(&ep) {
Err(Error::Protocol(_)) => {}
other => panic!("{size_line}: expected a protocol error, got {other:?}"),
}
}
}
#[test]
fn printer_names_are_encoded_as_one_request_target_segment() {
assert_eq!(queue_path("office printer/1", false).unwrap(), "/printers/office%20printer%2F1");
assert!(queue_path("printer\r\nX-Injected: yes", false).is_err());
}
/// A reply arriving a byte at a time, its blank line split across reads, is still found: the
/// header search resumes where it stopped instead of rescanning everything read so far.
#[test]
fn a_header_trickled_a_byte_at_a_time_is_found() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let server = std::thread::spawn(move || {
let (mut s, _) = listener.accept().unwrap();
s.set_nodelay(true).unwrap();
for b in b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nokEXTRA" {
s.write_all(&[*b]).unwrap();
std::thread::sleep(std::time::Duration::from_millis(1));
}
});
let mut stream = Stream::Tcp(TcpStream::connect(addr).unwrap());
let raw = read_response(&mut stream).unwrap();
assert!(raw.ends_with(b"\r\n\r\nok"), "{:?}", String::from_utf8_lossy(&raw));
server.join().unwrap();
}
+5 -2
View File
@@ -319,9 +319,12 @@ mod tests {
#[test]
fn a_large_selection_shows_a_coarse_result_then_the_exact_one() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 600, "height": 400})).unwrap();
// The selection is just past the engine's full-resolution preview budget (256 x 256 pixels), the one condition
// for the coarse stage; the solve's cost grows with the selection and the canvas, so both stay as small as the
// move to x 250..507 allows (#15652).
app.run("file.new", json!({"width": 520, "height": 280})).unwrap();
app.run("paint.pencil", json!({"points": [[150, 160], [170, 160]], "size": 12, "color": "#0000ff"})).unwrap();
app.run("select.rect", json!({"x": 10, "y": 10, "width": 300, "height": 300})).unwrap();
app.run("select.rect", json!({"x": 10, "y": 10, "width": 257, "height": 256})).unwrap();
app.ui.tool = Tool::ContentAwareMove;
app.ui.tool_options.cam_transform_on_drop = false;
let m = egui::Modifiers::NONE;
+3 -2
View File
@@ -1028,8 +1028,9 @@ fn a_floating_document_follows_navigator_and_status_bar_zoom() {
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text(typed.into()));
h.key_press(egui::Key::Enter);
h.run_steps(2);
h.run_steps(58);
// The harness steps 1/4 s a frame, so 10 frames after Enter are 2.5 s: well past the 150 ms zoom ease, with
// frames after it in which the window could write its view back (60 frames, 15 s, before #15652).
h.run_steps(10);
assert!(h.state().ui.window_views.is_empty(), "the window keeps no copy of the view");
assert!(
(h.state().ui.views[0].zoom - want).abs() < 1e-3,
+3 -1
View File
@@ -275,7 +275,9 @@ mod gpu_tests {
#[test]
fn per_pixel_settings_develop_on_the_gpu_like_the_cpu_and_the_rest_stays_on_the_cpu() {
let _gpu = photocraft_testkit::gpu_lock();
for depth in [8, 16, 32] {
// 8 and 32 bits: the dialog hands the develop only `float` (32-bit or not, `camera_raw_ui/convert.rs`), so 16
// bits takes 8 bits' path; every depth's develop is the gpu crate's `tests/it/camera_raw.rs` (#15652).
for depth in [8, 32] {
let Some(mut app) = gpu_app(depth) else { return };
force_pass(&app);
open_raw(&mut app);
+27 -26
View File
@@ -375,32 +375,33 @@ mod tests {
#[test]
fn native_component_wide_angle_previews_and_commit_keep_unselected_samples() {
for mode in ["rgb", "cmyk", "lab"] {
for depth in [8, 16, 32] {
for alpha in [true, false] {
let fixture = crate::distort_ui::component_tests::app(mode, depth);
let mut app = if alpha { fixture } else { crate::distort_ui::component_tests::without_alpha(fixture) };
let ctx = app.ctx().clone();
open(&mut app, &ctx).unwrap();
ui(&mut app, json!({"set": {"model": "fisheye", "focalLength": 10.0}})).unwrap();
ui(&mut app, json!({"add": {"a": [8, 8], "b": [56, 16], "orientation": "horizontal"}})).unwrap();
let layer = app.wide_angle.as_ref().unwrap().layer;
let source = source_of(&app);
let session = session_of(&app);
let before = source.proxy.as_ref().clone();
let pf = source.geometry.proxy_rect;
let (preview, _) =
preview_surface(&before, &proxy_params(&session, source.geometry.frame, source.geometry.scale), pf, &source.target, None).unwrap();
source.state().run(&session).unwrap();
crate::distort_ui::component_tests::protected(&before, &preview, pf);
assert_ne!(preview.read_region(pf), before.read_region(pf));
app.run("channel.target", json!({"channel":{"color":1}})).unwrap();
ui(&mut app, json!({"commit": true})).unwrap();
take(&mut app, &ctx);
let after = app.session.active().unwrap().doc.layer(layer).unwrap().surface().unwrap();
crate::distort_ui::component_tests::protected(&before, after, pf);
assert_ne!(after.read_region(pf), before.read_region(pf));
}
// One depth per mode, each with and without alpha: the preview and commit have no branch on mode or depth, and
// `restrict_surface_impl` is generic over the sample width; alpha decides whether the warped layout differs
// from the original, so it stays a full axis (#15652).
for (mode, depth) in [("rgb", 8), ("cmyk", 16), ("lab", 32)] {
for alpha in [true, false] {
let fixture = crate::distort_ui::component_tests::app(mode, depth);
let mut app = if alpha { fixture } else { crate::distort_ui::component_tests::without_alpha(fixture) };
let ctx = app.ctx().clone();
open(&mut app, &ctx).unwrap();
ui(&mut app, json!({"set": {"model": "fisheye", "focalLength": 10.0}})).unwrap();
ui(&mut app, json!({"add": {"a": [8, 8], "b": [56, 16], "orientation": "horizontal"}})).unwrap();
let layer = app.wide_angle.as_ref().unwrap().layer;
let source = source_of(&app);
let session = session_of(&app);
let before = source.proxy.as_ref().clone();
let pf = source.geometry.proxy_rect;
let (preview, _) =
preview_surface(&before, &proxy_params(&session, source.geometry.frame, source.geometry.scale), pf, &source.target, None).unwrap();
source.state().run(&session).unwrap();
crate::distort_ui::component_tests::protected(&before, &preview, pf);
assert_ne!(preview.read_region(pf), before.read_region(pf));
app.run("channel.target", json!({"channel":{"color":1}})).unwrap();
ui(&mut app, json!({"commit": true})).unwrap();
take(&mut app, &ctx);
let after = app.session.active().unwrap().doc.layer(layer).unwrap().surface().unwrap();
crate::distort_ui::component_tests::protected(&before, after, pf);
assert_ne!(after.read_region(pf), before.read_region(pf));
}
}
}
+25 -18
View File
@@ -350,9 +350,13 @@ fn cmd_gives_the_move_tool_only_where_the_tool_does_not_take_cmd() {
// The Eraser is left out: it is in the Brush's family (`canvas::tools::family`), which refuses a ⌘ press the same
// way for every tool (`PaintTool::takes`); the Elliptical Marquee is the Rectangular one's marquee pass with
// another shape (`selection.rs`, `MarqueeKind`).
// One app per group, with the tool switched between cases and a fresh layer for each: starting
// the whole app dominates the cost of a case.
let moves = [Tool::Brush, Tool::Gradient, Tool::CloneStamp, Tool::Eyedropper, Tool::Move, Tool::RectMarquee, Tool::Lasso];
let mut h = harness(moves[0]);
for tool in moves {
let mut h = harness(tool);
h.state_mut().ui.tool = tool;
h.run_steps(1);
let id = with_layer(&mut h);
let steps = h.state().session.active().unwrap().history.past_len();
drag_with(&mut h, Modifiers::COMMAND, 130.0, 130.0, 170.0, 150.0);
@@ -362,28 +366,31 @@ fn cmd_gives_the_move_tool_only_where_the_tool_does_not_take_cmd() {
assert_eq!(st.history.past_len(), steps + 1, "{tool:?}: one step, nothing painted");
assert_eq!(h.state().ui.tool, tool, "{tool:?}: the tool is back");
}
// The Crop and Rotate View tools go last, in an app of their own: they leave a pending crop and
// a turned view behind.
let keeps = [
Tool::Hand,
Tool::RotateView,
Tool::Zoom,
Tool::Pen,
Tool::Rectangle,
Tool::Type,
Tool::VerticalType,
Tool::Crop,
Tool::PathSelection,
Tool::DirectSelection,
vec![Tool::Hand, Tool::Zoom, Tool::Pen, Tool::Rectangle, Tool::Type, Tool::VerticalType, Tool::PathSelection, Tool::DirectSelection],
vec![Tool::Crop, Tool::RotateView],
];
for tool in keeps {
let mut h = harness(tool);
let id = with_layer(&mut h);
drag_with(&mut h, Modifiers::COMMAND, 130.0, 130.0, 170.0, 150.0);
assert_eq!(bounds(&h, id), Rect::new(100, 100, 160, 160), "{tool:?}: the layer stays");
assert_ne!(h.state().session.active().unwrap().history.undo_label(), Some("Move"), "{tool:?}");
assert_eq!(h.state().ui.tool, tool);
for group in keeps {
let mut h = harness(group[0]);
for tool in group {
h.state_mut().ui.tool = tool;
h.run_steps(1);
keeps_the_layer(&mut h, tool);
}
}
}
/// A ⌘-drag with `tool`, one that keeps ⌘ for itself, leaves a fresh layer where it is.
fn keeps_the_layer(h: &mut Harness<'static, Box<PhotocraftApp>>, tool: Tool) {
let id = with_layer(h);
drag_with(h, Modifiers::COMMAND, 130.0, 130.0, 170.0, 150.0);
assert_eq!(bounds(h, id), Rect::new(100, 100, 160, 160), "{tool:?}: the layer stays");
assert_ne!(h.state().session.active().unwrap().history.undo_label(), Some("Move"), "{tool:?}");
assert_eq!(h.state().ui.tool, tool);
}
/// ⌘⌥-drag duplicates the layer first and moves the copy, as the Move tool's ⌥-drag does. Off
/// the Mac the same keys are Ctrl+Alt, which the Brush keeps for its on-canvas resize
/// (`brush_resize`, Alt+right-drag there too), so Ctrl+Alt duplicates with the tools that have no
@@ -146,9 +146,17 @@ pub(crate) const RUNTIME_COMMANDS: &[(&str, Bridged)] = &[
("view.screenMode.cycleBack", Bridged::ScreenMode(ScreenModeCommands::CycleBack)),
];
/// The framework command of every row of [`RUNTIME_COMMANDS`], built once. `Bridged::command` allocates the
/// command's id, and the menu bar asks [`bridge_of`] for each of its items on every frame (the command gate's
/// [`screen_mode_row`]): building every row's command there cost about a tenth of the UI pass (#15493).
fn bridged_commands() -> &'static [(CommandRef, &'static str, Bridged)] {
static TABLE: std::sync::OnceLock<Vec<(CommandRef, &'static str, Bridged)>> = std::sync::OnceLock::new();
TABLE.get_or_init(|| RUNTIME_COMMANDS.iter().map(|(id, bridged)| (bridged.command(), *id, *bridged)).collect())
}
/// The PhotoCraft id and bridge row of a framework command, if a row bridges it.
fn bridge_of(command: &CommandRef) -> Option<(&'static str, Bridged)> {
RUNTIME_COMMANDS.iter().find(|(_, bridged)| bridged.command() == *command).map(|(id, bridged)| (*id, *bridged))
bridged_commands().iter().find(|(bridged, _, _)| bridged == command).map(|(_, id, bridged)| (*id, *bridged))
}
/// Whether the runtime defines command `id` (a row of [`RUNTIME_COMMANDS`]).
@@ -720,3 +720,18 @@ fn a_second_pass_in_one_frame_runs_no_command_twice() {
crate::app::framework::keys_pass(&mut app, &ctx, egui::RawInput::default(), |_| {});
assert_eq!(count(&app), n + 1, "one press, one duplicate");
}
/// `bridge_of` answers from the table built once (#15493) exactly as a scan that builds every row's command does:
/// for every row's framework command, and none for a command no row bridges.
#[test]
fn bridge_of_finds_the_row_a_fresh_scan_finds() {
use super::{CommandRef, RUNTIME_COMMANDS, bridge_of};
let scan = |command: &CommandRef| RUNTIME_COMMANDS.iter().find(|(_, bridged)| bridged.command() == *command).map(|(id, bridged)| (*id, *bridged));
for (_, bridged) in RUNTIME_COMMANDS {
let command = bridged.command();
assert_eq!(bridge_of(&command), scan(&command), "{command:?}");
assert!(bridge_of(&command).is_some(), "{command:?} is bridged");
}
let unknown = CommandRef::new("photocraft.noSuchCommand");
assert_eq!(bridge_of(&unknown), None);
}
+9 -3
View File
@@ -434,10 +434,16 @@ mod tests {
let mut checked = 0;
for sel in selections {
for copied in [false, true] {
// `is_enabled` only reads the app, so one app per world answers for every command; each command then
// runs on a world of its own. A copied style is read by Paste Layer Style alone (the engine's
// `style_clipboard`), so the other commands run without it only (#15652).
let app = crate::PhotocraftApp::new(world(sel, copied), crate::Services::default());
for (cmd, must_change) in commands {
let app = crate::PhotocraftApp::new(world(sel, copied), crate::Services::default());
if copied && cmd != "layer.layerStyle.pasteLayerStyle" {
continue;
}
let enabled = crate::menus::is_enabled(&app, cmd);
let mut s = app.session;
let mut s = world(sel, copied);
let before = fingerprint(&s);
let r = s.execute(cmd, json!({}));
let changed = fingerprint(&s) != before;
@@ -457,7 +463,7 @@ mod tests {
}
}
}
assert_eq!(checked, selections.len() * 2 * commands.len());
assert_eq!(checked, selections.len() * (commands.len() + 1));
}
/// #13293: on a lone Background, Group from Layers… and Load Selection… are greyed, as in the
+4
View File
@@ -98,6 +98,10 @@ pub(crate) fn state_hash(app: &PhotocraftApp, input: Option<u64>) -> u64 {
(&ui.recent_files, &app.workspaces.set.current, app.ui.palette.open, ui.transform.is_some(), ui.text_edit.is_some(), app.dialog_count()).hash(&mut h);
// Cut and Copy are enabled while the typed text has a selection.
ui.text_edit.as_ref().map(|e| e.anchor != e.caret).hash(&mut h);
// The Window bars' ticks; the Contextual Task Bar's Hide bar and `ui.set` change them without a menu click (#15489).
// Not the task bar's place, which moves every frame of a drag.
let p = &ui.panels;
(p.options_bar, p.status_bar, p.menu_bar, p.context_task_bar).hash(&mut h);
(app.discard.is_some(), crate::distort_ui::modal_workspace(app)).hash(&mut h);
crate::prefs_ui::recording(app).hash(&mut h);
// The rows show the keymap's chords; the keymap follows these from the frame they change.
@@ -219,3 +219,21 @@ fn opening_or_closing_a_workspace_without_input_rebuilds_the_menus() {
app.framework.dialogs.cancel_by_id(&ctx, id);
assert_eq!(state_hash(&app, None), closed, "and come back when it is cancelled");
}
/// The Contextual Task Bar's tick follows the bar when its Hide bar or `ui.set` turns it off without a menu click
/// (#15489).
#[test]
fn the_task_bar_tick_follows_the_bar_hidden_without_a_menu_click() {
let (mut h, synced, _) = harness(true);
let ticked = |synced: &Synced| {
let bar = synced.borrow().last().cloned().expect("menus synced");
bar.find(&CommandRef::new("window.panel.contextualTaskBar")).and_then(|it| it.kind.checked())
};
assert_eq!(ticked(&synced), Some(true));
h.state_mut().ui.panels.context_task_bar = false;
h.run_steps(2);
assert_eq!(ticked(&synced), Some(false), "unticked once the bar is hidden");
h.state_mut().ui.panels.context_task_bar = true;
h.run_steps(2);
assert_eq!(ticked(&synced), Some(true), "ticked again once it shows");
}
+1 -12
View File
@@ -10,7 +10,7 @@ use craft::keymap::{CommandRef, Mods};
use craft::ui::contract::{Bind, CommandSet as _};
use craft::ui::dialog::DialogResult;
use craft::ui::docking::{WorkspaceAsk, WorkspaceCommands, run_workspace, workspace_states};
use craft::ui::patterns::dock::{HostedDeleteWorkspace, HostedNewWorkspace, NewWorkspace, WorkspaceSwitcher};
use craft::ui::patterns::dock::{HostedDeleteWorkspace, HostedNewWorkspace, NewWorkspace};
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind, ParamLayout, ParamResult};
use craft::ui::runtime::commands::CommandState;
use craft::ui::value_drag::SliderScale;
@@ -315,17 +315,6 @@ pub fn take(app: &mut PhotocraftApp, _ctx: &egui::Context) {
}
}
/// The workspace switcher of the title bar.
pub fn switcher(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let out = WorkspaceSwitcher::new(&app.workspaces.set).show(ui);
if let Some(id) = out.switched
&& let Err(message) = select(app, &id)
{
app.ui.status = message;
app.ui.status_error = true;
}
}
/// The state of each workspace command, for the command source.
pub fn states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandState)> {
workspace_states(&app.workspaces.set).into_iter().map(|(command, state)| (CommandRef::from(command), state)).collect()
@@ -431,8 +431,13 @@ fn editing_the_options_bar_amount_reenables_smoothing() {
#[test]
fn every_section_draws_without_issuing_commands() {
for (panel, view) in [("brushSettings", None), ("brushes", Some(PresetView::List)), ("brushes", Some(PresetView::Grid))] {
for section in 0..SECTIONS.len() {
// Brush Settings draws the selected section's controls, but only up to `CHECKBOX_ONLY_START`: a later section is
// reset to 0 before drawing (`brush_settings.rs`, tested by `checkbox_only_rows_cannot_restore_an_empty_properties_pane`).
// The Brushes panel does not read the section at all, so one run per view covers it (#15652).
for (panel, view, sections) in
[("brushSettings", None, 0..CHECKBOX_ONLY_START), ("brushes", Some(PresetView::List), 0..1), ("brushes", Some(PresetView::Grid), 0..1)]
{
for section in sections {
let mut h = harness(panel, section);
if let Some(view) = view {
h.state_mut().ui.brushes_panel.view = view;
+6 -2
View File
@@ -8,7 +8,7 @@
use craft::behavior::dock::{Action, DockEdge, DockPlacement, Layout, Node, PanelPlace, PanelState, Permissions, SplitSize, Target};
use craft::behavior::overlay::Side;
use craft::behavior::{DockSide, EditEvent, EditEvents, IconId};
use craft::ui::contract::{Bind, BodyCx, SizeLimits};
use craft::ui::contract::{Bind, BodyCx, Lazy, SizeLimits};
use craft::ui::docking::{
DockCommands, DockConfig, DockEvent, DockPanels, DockScene, DockSizes, DockTo, DragUnit, FloatSpace, GroupAt, HidePanels, PanelSpec, actions, move_actions,
request_actions,
@@ -202,7 +202,11 @@ impl DockPanels<String> for Panels<'_> {
return Some(match at {
GroupAt::Measure(width) => super::toolbar::measure(self.app, ui, width),
GroupAt::Show(rect) => {
super::toolbar::toolbar(self.app, ui);
// The rail settles as a panel body does: while nothing it shows changed and no input reaches it,
// the frame repaints its last run instead of running every tool button again (#15493).
let version = super::region_versions::toolbar_drawn(self.app, ui);
let app = &mut *self.app;
Lazy::new("toolbar", 0.0).settles(true).content(version).show(ui, |ui| super::toolbar::toolbar(app, ui));
rect.height()
}
});
+42 -3
View File
@@ -9,9 +9,10 @@ use std::hash::{Hash, Hasher};
use super::{PhotocraftApp, chrome_ui};
use crate::color_picker_ui::PickWindow;
/// The version of the options bar: the Zoom tool's members show the active view.
/// The version of the options bar: the Zoom tool's members show the active view, and an open Free Transform shows
/// its own members in place of the tool's (Escape ends it without a command, #15547).
pub(crate) fn options_bar(app: &PhotocraftApp) -> u64 {
version(app, view(app))
version(app, (view(app), app.ui.transform.is_some()))
}
/// The version of the status bar: the zoom readout of the active view, the status message and the item it shows, the
@@ -42,10 +43,21 @@ pub(crate) fn panel(app: &PhotocraftApp, id: &str) -> u64 {
/// Edit Toolbar drawer, the side its flyouts open on, Quick Mask and the screen mode. The active tool and the colours
/// are in every version.
pub(crate) fn toolbar(app: &PhotocraftApp) -> u64 {
toolbar_with(app, 0)
}
/// [`toolbar`] for the rail as drawn in `ui` (#15493): also the resolved tokens it was drawn with (they change with the
/// theme, the UI font size and the UI scale), so a theme change redraws it even without a command.
pub(crate) fn toolbar_drawn(app: &PhotocraftApp, ui: &egui::Ui) -> u64 {
toolbar_with(app, std::sync::Arc::as_ptr(&craft::ui::runtime::env::Env::of(ui).tokens) as usize)
}
/// [`toolbar`] with the tokens it was drawn with named by `tokens`.
fn toolbar_with(app: &PhotocraftApp, tokens: usize) -> u64 {
let quick_mask = app.session.active().is_some_and(|st| st.doc.quick_mask.is_some());
let opens_start = crate::panel_docking::toolbar_opens(app) == craft::behavior::overlay::Side::Start;
let screen_mode = format!("{:?}", app.ui.view.screen_mode);
version(app, (app.session.prefs.rev(), &app.ui.group_tools, app.ui.toolbar_drawer, opens_start, quick_mask, screen_mode))
version(app, (app.session.prefs.rev(), &app.ui.group_tools, app.ui.toolbar_drawer, opens_start, quick_mask, screen_mode, tokens))
}
/// What every region may show, joined with `extra`: the commands run (any of them may change anything), the active
@@ -71,3 +83,30 @@ fn view(app: &PhotocraftApp) -> Option<[u64; 5]> {
crate::canvas::active_view(app)
.map(|view| [view.zoom.to_bits(), view.center.x.to_bits(), view.center.y.to_bits(), view.rotation.to_bits(), u64::from(view.flip_x)])
}
#[cfg(test)]
mod tests {
use super::*;
use crate::state::Tool;
/// Everything the settled toolbar shows moves its version (#15493): a version that missed one would replay a stale
/// rail. The same state gives the same version, so the rail settles.
#[test]
fn the_toolbar_version_moves_with_what_the_rail_shows() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
let base = toolbar_with(&app, 1);
assert_eq!(toolbar_with(&app, 1), base, "the same state settles");
assert_ne!(toolbar_with(&app, 2), base, "other tokens (theme, UI font size or scale)");
let changed = |name: &str, change: &dyn Fn(&mut PhotocraftApp), app: &mut PhotocraftApp| {
let before = toolbar_with(app, 1);
change(app);
assert_ne!(toolbar_with(app, 1), before, "{name} moves the version");
};
changed("the tool", &|app| app.ui.tool = Tool::Brush, &mut app);
changed("a slot's remembered tool", &|app| app.ui.group_tools.insert(0, Tool::EllipseMarquee), &mut app);
changed("the Edit Toolbar drawer", &|app| app.ui.toolbar_drawer = !app.ui.toolbar_drawer, &mut app);
changed("the toolbar layout", &|app| app.session.prefs.edit(|prefs| prefs.toolbar.hidden.push("Brush".to_string())), &mut app);
changed("the colours", &|app| app.session.tools.foreground[0] = 0.25, &mut app);
}
}
+6 -24
View File
@@ -1,50 +1,32 @@
use std::cell::RefCell;
use craft::behavior::IconId;
use craft::ui::buttons::IconButton;
use craft::ui::contract::{Props as _, Show as _, TooltipSpec};
use craft::ui::contract::Show as _;
use craft::ui::shell::{Title, TitleBar};
use super::{PhotocraftApp, brand};
// ----------------------------------------------------------------------------- title bar
/// The app's top bar, in the shell's title slot: brand mark, menus, the document title and the workspace controls.
/// The app's top bar, in the shell's title slot: brand mark, menus and the document title. Nothing else sits at its
/// far end, as in the reference application: the workspace switcher, command search and appearance mode live in
/// Window › Workspace, Edit › Search and Window › Appearance (#13577).
/// The framework `TitleBar` follows the window's frame: with the app's own frame (Windows and Linux) it is also the
/// window's title bar and the caption buttons take its ends; with the system's frame it shows the content and no title.
pub fn title_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let title = title_text(app);
// The bar runs `leading` in its body and `trailing` in its end region, one after the other, so the two borrows
// of the app never overlap.
let app = RefCell::new(app);
let out = TitleBar::new().show_titled(
ui,
Title::new(title),
|ui, _| {
let mut guard = app.borrow_mut();
let app = &mut **guard;
brand::mark().show(ui);
// With the macOS menu bar the menus are at the top of the screen instead.
if app.services.native_menu.is_none() {
crate::menus::menu_bar(app, ui);
}
},
|ui, _| {
let mut guard = app.borrow_mut();
let app = &mut **guard;
crate::prefs_ui::appearance_button(app, ui);
let tip = crate::shortcuts::tip_label(app, "Search commands", "edit.search");
let search = IconButton::new(IconId::new("search")).label(tip.clone()).tooltip(TooltipSpec::new(tip)).selected(app.ui.palette.open).show(ui);
if search.clicked() {
app.ui.palette.open = !app.ui.palette.open;
}
crate::workspace_ui::switcher(app, ui);
},
|_, _| {},
);
// The bar never closes the window: File › Exit asks about unsaved work first.
if out.close_requested {
let mut guard = app.borrow_mut();
let _ = crate::menus::invoke(&mut guard, ui.ctx(), "file.exit", serde_json::json!({}));
let _ = crate::menus::invoke(app, ui.ctx(), "file.exit", serde_json::json!({}));
}
}
@@ -82,3 +82,16 @@ fn the_menu_bar_follows_its_panel_flag() {
assert!(h.query_all_by_label("Layers").next().is_some(), "the dock itself stays (menu bar {menu_bar})");
}
}
/// The top bar holds the brand mark, the menus, the title and the caption buttons, and nothing at its far end, as in
/// the reference application: no appearance button, no command search and no workspace switcher (#13577). Each of
/// them stays in a menu: Window › Appearance, Edit › Search and Window › Workspace.
#[test]
fn the_top_bar_has_no_appearance_search_or_workspace_controls() {
let h = integrated_app(|_| {});
assert!(h.query_by_label("File").is_some(), "the menus are drawn");
assert!(h.query_by_label("Close").is_some(), "the caption buttons are drawn");
assert!(h.query_by_label("Appearance").is_none(), "no appearance button");
assert!(h.query_by_label_contains("Search commands").is_none(), "no command search button");
assert!(h.query_by_label("Choose a workspace").is_none(), "no workspace switcher");
}
+60
View File
@@ -18,6 +18,10 @@ use super::tool_commands;
#[path = "toolbar_tab_reveal_tests.rs"]
mod toolbar_tab_reveal_tests;
#[cfg(test)]
#[path = "toolbar_measure_tests.rs"]
mod toolbar_measure_tests;
// ----------------------------------------------------------------------------- toolbar
/// Tool groups separated by hairlines, Photoshop order.
@@ -179,8 +183,64 @@ fn footer(app: &mut PhotocraftApp, ui: &mut egui::Ui, rail: RailFooter) {
});
}
/// What the rail's measured height depends on: the width and room it is laid out in, the slots (the same `Arc` while
/// the preferences are the same), where its flyouts open, the Edit Toolbar drawer, and the scale, direction and resolved
/// tokens (theme, density, text size) it is drawn with. The current and remembered tools change which icon a button
/// shows, not its size, and the footer's buttons keep their sizes whatever they show.
#[derive(Clone)]
struct MeasureKey {
width: u32,
room: [u32; 2],
slots: std::sync::Arc<[ToolSlot<Tool>]>,
opens: Side,
editing: bool,
pixels_per_point: u32,
rtl: bool,
tokens: std::sync::Arc<craft::ui::style::UiTokens>,
}
impl PartialEq for MeasureKey {
fn eq(&self, other: &Self) -> bool {
(self.width, self.room, self.opens, self.editing, self.pixels_per_point, self.rtl)
== (other.width, other.room, other.opens, other.editing, other.pixels_per_point, other.rtl)
&& std::sync::Arc::ptr_eq(&self.slots, &other.slots)
&& std::sync::Arc::ptr_eq(&self.tokens, &other.tokens)
}
}
/// The height of the toolbar's rail laid out `width` wide: as many tool columns as `width` holds, with the footer.
///
/// The dock asks for it on every frame before it shows the rail, and a measuring run of the rail (every tool button
/// and the footer, each resolving its command) was the largest part of the UI pass (#15493). The last height is kept
/// with what it depends on ([`MeasureKey`]) and measured again only when one of them changes.
pub(crate) fn measure(app: &mut PhotocraftApp, ui: &egui::Ui, width: f32) -> f32 {
thread_local! {
static LAST: std::cell::RefCell<Option<(MeasureKey, f32)>> = const { std::cell::RefCell::new(None) };
}
let slots = app.toolbar_slots.get(&app.session.prefs);
let (opens, editing) = (crate::panel_docking::toolbar_opens(app), app.ui.toolbar_drawer);
let env = craft::ui::runtime::env::Env::of(ui);
let room = ui.available_size();
let key = MeasureKey {
width: width.to_bits(),
room: [room.x.to_bits(), room.y.to_bits()],
slots: std::sync::Arc::clone(&slots),
opens,
editing,
pixels_per_point: ui.ctx().pixels_per_point().to_bits(),
rtl: env.direction.is_rtl(),
tokens: std::sync::Arc::clone(&env.tokens),
};
if let Some(height) = LAST.with(|last| last.borrow().as_ref().filter(|(kept, _)| *kept == key).map(|(_, height)| *height)) {
return height;
}
let height = measure_now(app, ui, width);
LAST.with(|last| *last.borrow_mut() = Some((key, height)));
height
}
/// [`measure`] without the kept height: a measuring run of the rail.
fn measure_now(app: &mut PhotocraftApp, ui: &egui::Ui, width: f32) -> f32 {
let slots = app.toolbar_slots.get(&app.session.prefs);
let remembered = last_used(&slots, &app.ui.group_tools);
let current = app.ui.tool;
@@ -0,0 +1,65 @@
//! The kept height of the toolbar's rail (#15493): `measure` answers as a measuring run does, and measures again
//! when the width or the toolbar layout changes.
use super::*;
use crate::app::framework::BuildApp;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
/// What one pass measured: the width, the kept height and a fresh measuring run's.
type Seen = Rc<RefCell<Vec<(f32, f32, f32)>>>;
/// A harness that measures the rail `width` wide on every pass, through `measure` and through a fresh run.
fn harness(width: Rc<Cell<f32>>, seen: Seen) -> egui_kittest::Harness<'static, Box<PhotocraftApp>> {
let mut ready = false;
let app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
let mut harness = egui_kittest::Harness::builder().with_context(app.ctx().clone()).with_size(vec2(400.0, 900.0)).build_app(
move |ui, app: &mut PhotocraftApp| {
if !ready {
egui_extras::install_image_loaders(ui.ctx());
crate::theme::install_fonts(ui.ctx());
crate::theme::apply(ui.ctx(), &crate::theme::AppTheme::pro());
ready = true;
return;
}
let w = width.get();
let kept = measure(app, ui, w);
let fresh = measure_now(app, ui, w);
seen.borrow_mut().push((w, kept, fresh));
},
app,
);
harness.run_steps(4);
harness
}
fn last(seen: &Seen) -> (f32, f32, f32) {
*seen.borrow().last().expect("a pass measured the rail")
}
#[test]
fn the_kept_height_follows_the_width_and_the_toolbar_layout() {
let width = Rc::new(Cell::new(40.0));
let seen: Seen = Rc::default();
let mut harness = harness(Rc::clone(&width), Rc::clone(&seen));
let (_, one_column, fresh) = last(&seen);
assert_eq!(one_column, fresh, "one column: the kept height is the measured one");
harness.run_steps(2);
assert_eq!(last(&seen).1, one_column, "the same inputs keep the height");
width.set(120.0);
harness.run_steps(2);
let (_, wide, fresh) = last(&seen);
assert_eq!(wide, fresh, "a wider rail is measured again");
assert!(wide < one_column, "more columns make a shorter rail: {wide} against {one_column}");
// Hide most tools: the layout changes, and with it the slots.
harness.state_mut().session.prefs.edit(|prefs| {
prefs.toolbar.hidden = Tool::ALL.iter().skip(4).map(|tool| format!("{tool:?}")).collect();
});
harness.run_steps(2);
let (_, fewer, fresh) = last(&seen);
assert_eq!(fewer, fresh, "a changed layout is measured again");
assert!(fewer < wide, "fewer tools make a shorter rail: {fewer} against {wide}");
}
+2 -2
View File
@@ -57,9 +57,9 @@ mod save;
pub(crate) mod shortcuts;
mod startup;
// PLAN: assumed top-w18's appearance file keeps `display_scale` and `selected_theme` and exports `appearance_button` and `theme_menu`.
pub(crate) use appearance::{appearance_button, cycle_appearance, interface_zoom, show_selected_theme, step_brightness, sync_appearance, theme_menu};
// PLAN: assumed top-w18's appearance file keeps `display_scale` and `selected_theme` and exports `theme_menu`.
pub use appearance::{canvas_style, pasteboard_color};
pub(crate) use appearance::{cycle_appearance, interface_zoom, show_selected_theme, step_brightness, sync_appearance, theme_menu};
#[cfg(test)]
pub(crate) use dialogs::set_draft;
pub use dialogs::{apply_window, invoke, open_preferences, window_open};
@@ -1,12 +1,7 @@
use super::{AppearanceMode, Color32, PhotocraftApp, json, prefs};
use crate::theme::AppTheme;
use craft::keymap::CommandRef;
use craft::menu::{ThemeChoice, ThemeLabels, ThemeMenu, ThemeRow};
use craft::menu::{ThemeChoice, ThemeMenu, ThemeRow};
use craft::theme::{Mode, ThemeId};
use craft::ui::buttons::IconButton;
use craft::ui::contract::{Props as _, Show as _, ShowContainer as _};
use craft::ui::menu::Menu;
use craft::ui::primitives::IconSpec;
use craft::ui::runtime::env::system_appearance;
/// The GPU canvas's gamut warning colours from Preferences › Transparency & Gamut.
@@ -98,26 +93,6 @@ pub fn theme_menu(app: &PhotocraftApp) -> ThemeMenu {
ThemeMenu::new(rows, current).favorites(&favorites)
}
/// The title bar's appearance button: the icon of the mode, a click that cycles Auto → Light → Dark, and a context
/// menu with the settings row and the favourite themes.
pub(crate) fn appearance_button(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let (icon, name) = match app.session.prefs().interface.appearance_mode {
AppearanceMode::Auto => ("monitor", tl!("Auto")),
AppearanceMode::Dark => ("moon", tl!("Dark")),
AppearanceMode::Light => ("sun", tl!("Light")),
};
// PLAN: assumed `IconButton::label`, `.tooltip(..)` and the output's `clicked()` / `response()`.
let out = IconButton::new(IconSpec::svg(craft::behavior::IconId::new(icon)))
.label(tl!("Appearance"))
.tooltip(crate::i18n::fmt(tl!("Appearance Mode: {mode}"), &[("mode", name)]))
.show(ui);
if out.clicked() {
cycle_appearance(app, ui.ctx());
}
let nodes = theme_menu(app).favorite_items(&ThemeLabels::default(), CommandRef::new("edit.preferences.interface"));
Menu::context(tl!("Appearance"), &out.response).show(ui, |ui, _| craft::menu::context::rows(ui, &nodes));
}
/// The OS's light or dark mode, `None` where it gives no answer.
pub(super) fn system_theme(_app: &PhotocraftApp, ctx: &egui::Context) -> Option<egui::Theme> {
system_appearance(ctx).appearance.mode.map(|mode| match mode {
+1 -1
View File
@@ -246,7 +246,7 @@ fn auto_uses_native_system_theme_when_egui_does_not_report_one() {
}
#[test]
fn appearance_button_cycles_modes_without_losing_theme_choices() {
fn next_appearance_mode_cycles_modes_without_losing_theme_choices() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
let ctx = app.ctx().clone();
app.run("prefs.set", json!({"values": {"interface.darkTheme": "studio", "interface.lightTheme": "classic"}})).unwrap();
+1 -1
View File
@@ -479,7 +479,7 @@ pub(crate) fn poll(app: &mut PhotocraftApp, ctx: &egui::Context) {
Ok(result) => {
if let Some(fingerprint) = result.get("fingerprint").filter(|v| !v.is_null()) {
edit.target.fingerprint = fingerprint.clone();
crate::notices::io_result_warnings(app, &result, "SVG");
crate::notices::io_result_warnings(app, &result, if native { "Vector" } else { "SVG" });
} else {
report(app, "The SVG update did not return its fingerprint; syncing stopped".into());
continue;
+44 -3
View File
@@ -20,13 +20,13 @@ impl ExternalSvgSession for TestSession {
}
}
struct NativeTestSession(Saves);
struct NativeTestSession(Saves, &'static str);
impl ExternalSvgSession for NativeTestSession {
fn poll(&mut self) -> Option<Result<Vec<u8>, String>> {
self.0.borrow_mut().pop_front()
}
fn poll_vector(&mut self) -> Option<Result<crate::ExternalVectorSave, String>> {
self.poll().map(|r| r.map(|bytes| crate::ExternalVectorSave { bytes, preview_svg: Some(SVG.as_bytes().to_vec()) }))
self.poll().map(|r| r.map(|bytes| crate::ExternalVectorSave { bytes, preview_svg: Some(self.1.as_bytes().to_vec()) }))
}
}
@@ -571,14 +571,23 @@ fn embedded_ai_link_table_handoff_preserves_source_until_saved_and_undo_restores
assert_eq!(editor, ExternalSvgEditor::VectorCraft);
assert_eq!(*source.bytes, original);
assert_eq!(source.extension, "ai");
Ok(Box::new(NativeTestSession(queue.clone())))
// An empty, same-size preview is admissible and yields a real
// "nothing to draw" warning from the native update command.
let empty_preview = r#"<svg xmlns="http://www.w3.org/2000/svg" width="12" height="8"/>"#;
Ok(Box::new(NativeTestSession(queue.clone(), empty_preview)))
}));
open(&mut app);
assert!(calls.borrow().is_empty());
confirm(&mut app).unwrap();
assert_eq!(app.session.active().unwrap().doc, before);
app.ui.notices.clear();
saves.borrow_mut().push_back(Ok(b"%PDF-1.6\nedited native AI".to_vec()));
poll(&mut app, &egui::Context::default());
assert_eq!(app.ui.notices.len(), 1);
let notice = &app.ui.notices[0];
assert!(notice.title.contains("Vector"), "{notice:?}");
assert_eq!(notice.tone, craft::theme::variant::Tone::Neutral);
assert!(notice.lines.iter().any(|line| line.contains("nothing to draw")));
let layer = app.session.active().unwrap().doc.layer(id).unwrap();
assert!(
matches!(&layer.content,LayerContent::Smart(sm) if matches!(&sm.source,SmartSource::Embedded {file_name,bytes} if file_name=="Logo.ai" && bytes.as_slice()==b"%PDF-1.6\nedited native AI"))
@@ -653,6 +662,38 @@ fn finished_session_retains_final_save_until_target_is_safe() {
assert!(app.smart_svg.editing.is_empty());
}
#[test]
fn external_svg_save_back_reports_omissions_once_and_keeps_silent_updates_quiet() {
for omitted in [false, true] {
let (mut app, saves, _) = fixture();
open(&mut app);
app.smart_svg.pending.as_mut().unwrap().editor = Editor::Illustrator;
confirm(&mut app).unwrap();
app.ui.notices.clear();
let before = app.session.active().unwrap().doc.clone();
let child = if omitted { "<image width='2' height='2' href='data:image/png,%00'/>" } else { "" };
let svg = SVG.replace("red", "blue").replace("</svg>", &format!("{child}</svg>"));
saves.borrow_mut().push_back(Ok(svg.into_bytes()));
let ctx = egui::Context::default();
poll(&mut app, &ctx);
assert_ne!(app.session.active().unwrap().doc, before);
assert_eq!(app.smart_svg.editing.len(), 1, "the session keeps the successful new fingerprint");
if omitted {
assert_eq!(app.ui.notices.len(), 1);
assert!(app.ui.notices[0].title.contains("SVG"));
assert!(app.ui.notices[0].lines.iter().any(|line| line.contains("embedded") && line.contains("omitted")));
assert_eq!(app.ui.notices[0].tone, craft::theme::variant::Tone::Neutral);
} else {
assert!(app.ui.notices.is_empty(), "{:?}", app.ui.notices);
}
let notices = app.ui.notices.clone();
poll(&mut app, &ctx);
assert_eq!(app.ui.notices, notices, "polling the same completed save cannot duplicate a warning");
app.session.execute("edit.undo", json!({})).unwrap();
assert_eq!(app.session.active().unwrap().doc, before);
}
}
#[test]
fn svg_save_back_displays_omitted_image_warning() {
let (mut app, saves, _) = fixture();
@@ -2181,3 +2181,24 @@ fn a_waiting_new_layer_click_keeps_the_layer_it_was_made_on() {
assert_eq!(at(new), at(placed) + 1, "the new layer sits right above the layer selected at the click: {order:?}");
assert_eq!(st.active_layer, Some(new));
}
/// #15547: once Escape or Enter ends Free Transform, the options bar shows the active tool's members again in the
/// next frame, not the transform fields.
#[test]
fn ending_the_transform_brings_back_the_tools_options_bar() {
use egui_kittest::kittest::Queryable as _;
for key in [egui::Key::Escape, egui::Key::Enter] {
let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24));
app.ui.tool = Tool::Gradient;
let mut h = harness(app, egui::vec2(1400.0, 900.0));
h.run_steps(4);
let ctx = h.ctx.clone();
crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap();
h.run_steps(2);
assert!(h.query_by_label("Reverse").is_none(), "the transform fields replace the Gradient members");
h.key_press(key);
h.run_steps(2);
assert!(h.state().ui.transform.is_none(), "{key:?} ended the transform");
assert!(h.query_by_label("Reverse").is_some(), "after {key:?} the Gradient members are back");
}
}
+4 -1
View File
@@ -308,6 +308,9 @@ fn edit_draft(app: &mut PhotocraftApp, edit: EditEvent<EditSubpath>) -> bool {
fn set_draft(app: &mut PhotocraftApp, value: EditSubpath) {
let n = value.knots.len();
let selection_on_draft = app.ui.direct_selection.target == Some(PathRef::Pen);
// A refused draft whose document changed since takes no press, only Delete and Backspace: it stays refused, or
// `cancel_stale_pen` would drop all of it on the next pass instead of the one anchor (#15488).
let stale = app.ui.pen.as_ref().and_then(|p| p.owner.as_ref()).is_some_and(|o| !o.valid(app));
let Some(pen) = ensure_draft(app) else { return };
if pen.draft == value {
return;
@@ -325,7 +328,7 @@ fn set_draft(app: &mut PhotocraftApp, value: EditSubpath) {
}
}
pen.draft = value;
pen.commit_failed = false;
pen.commit_failed &= stale;
if selection_on_draft {
let ds = &mut app.ui.direct_selection;
if grew {
@@ -735,3 +735,38 @@ fn freeform_selection_does_not_claim_a_failed_pen_or_curvature_draft() {
}
}
}
/// A refused Pen draft is kept (#15488): under another tool, Delete is that tool's (the active layer goes); back under
/// the Pen that drew it, Delete takes back one anchor at a time, as while drawing, and only the last anchor drops the
/// draft.
#[test]
fn a_kept_pen_draft_takes_delete_only_under_its_own_tool() {
for tool in [Tool::Pen, Tool::CurvaturePen] {
let mut app = app();
app.run("layer.new.layer", json!({})).unwrap();
app.ui.tool = tool;
app.ui.tool_options.vector_mode = craft::draw::ui::shape::VectorMode::Path;
three_anchors(&mut app);
app.session.authorize = Some(|id, _| if id == "path.set" { Err(photocraft_engine::EngineError::Other("refused path fixture".into())) } else { Ok(()) });
assert!(!pen_commit(&mut app, false), "the fixture must actually refuse the commit");
app.session.authorize = None;
assert_eq!(app.ui.pen.as_ref().unwrap().draft.knots.len(), 3);
let layers = app.session.active().unwrap().doc.layers.len();
let kept = app.ui.pen.as_ref().unwrap().draft.clone();
switch_tool(&mut app, Tool::AddAnchorPoint);
press(&mut app, egui::Key::Delete, egui::Modifiers::NONE);
assert_eq!(app.session.active().unwrap().doc.layers.len(), layers - 1, "{tool:?}: Delete is the other tool's: the layer goes");
assert_eq!(app.ui.pen.as_ref().map(|p| &p.draft), Some(&kept), "{tool:?}: the kept draft is untouched");
switch_tool(&mut app, tool);
for left in [2, 1] {
press(&mut app, egui::Key::Delete, egui::Modifiers::NONE);
assert_eq!(app.ui.pen.as_ref().map(|p| p.draft.knots.len()), Some(left), "{tool:?}: Delete takes back one anchor ({})", app.ui.status);
}
assert_eq!(app.session.active().unwrap().doc.layers.len(), layers - 1, "{tool:?}: no other layer went");
press(&mut app, egui::Key::Delete, egui::Modifiers::NONE);
assert!(app.ui.pen.is_none(), "{tool:?}: the last anchor drops the draft");
assert_eq!(app.session.active().unwrap().doc.layers.len(), layers - 1, "{tool:?}: the last Delete is the drawing tool's too");
}
}
+38 -17
View File
@@ -177,9 +177,20 @@ impl Screen {
/// Renders the app with `doc` open after `setup` commands (saving the PNG as `name` in the temp
/// dir), or None when the GPU can't be used.
fn screen(doc: Document, setup: &[(&str, serde_json::Value)], name: &str) -> Option<Screen> {
screens(vec![(doc, setup, name)]).and_then(|mut shown| shown.pop())
}
/// A document to show, the commands that set it up, and the file name of its screenshot.
type ScreenCase<'a> = (Document, &'a [(&'a str, serde_json::Value)], &'a str);
/// [`screen`] for several documents in one app, opened and rendered in turn: one harness, so one GPU device and one
/// compositor build (#15439) instead of one per document (#15652). Each document's setup commands run while it is
/// the active one; View › 32-bit Preview Options is kept per document.
fn screens(cases: Vec<ScreenCase<'_>>) -> Option<Vec<Screen>> {
let mut cases = cases.into_iter();
let (doc, setup, name) = cases.next()?;
let ok = Arc::new(AtomicBool::new(false));
let ok2 = ok.clone();
let setup: Vec<(String, serde_json::Value)> = setup.iter().map(|(a, b)| (a.to_string(), b.clone())).collect();
let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
egui_kittest::Harness::builder()
.with_size(egui::vec2(1000.0, 700.0))
@@ -205,17 +216,27 @@ fn screen(doc: Document, setup: &[(&str, serde_json::Value)], name: &str) -> Opt
eprintln!("skipping: adapter can't render/filter Rgba16Float");
return None;
}
// Outside the catch_unwind: a failing setup command fails the test instead of reading as
// "no GPU adapter" (#760).
for (id, p) in setup {
harness.state_mut().run(&id, p).unwrap_or_else(|e| panic!("setup command {id}: {e}"));
let mut shown = Vec::new();
let mut case = Some((setup, name));
while let Some((setup, name)) = case.take() {
// Outside the catch_unwind: a failing setup command fails the test instead of reading as
// "no GPU adapter" (#760).
for (id, p) in setup {
harness.state_mut().run(id, p.clone()).unwrap_or_else(|e| panic!("setup command {id}: {e}"));
}
harness.run_steps(6);
let img = harness.render().expect("render");
let out = std::env::temp_dir().join(name);
let _ = img.save(&out);
eprintln!("screen: {}", out.display());
shown.push(Screen { w: img.width(), h: img.height(), px: img.into_raw() });
if let Some((doc, setup, name)) = cases.next() {
harness.state_mut().session.open_document(doc, None);
harness.state_mut().sync_views();
case = Some((setup, name));
}
}
harness.run_steps(6);
let img = harness.render().expect("render");
let out = std::env::temp_dir().join(name);
let _ = img.save(&out);
eprintln!("screen: {}", out.display());
Some(Screen { w: img.width(), h: img.height(), px: img.into_raw() })
Some(shown)
}
/// Distinct gray levels along a screen row inside `x0..x1`, and the largest step between
@@ -242,20 +263,20 @@ fn thirty_two_bit_preview_exposes_values_above_one() {
// A dark 32-bit ramp brightened +4 stops by View › 32-bit Preview Options: with an 8-bit
// canvas texture its 0..1/16 range has 16 codes (banding); the float texture keeps it smooth.
let doc = gradient(SampleType::F32, 2048, 1024, 0.0, 1.0 / 16.0);
let Some(img) = screen(doc, &[("view.thirtyTwoBitPreviewOptions", json!({"exposure": 4.0, "gamma": 1.0}))], "photocraft-canvas-16f-hdr-ramp.png") else {
return;
};
let (n, _) = screen_levels(&img, img.h / 2, 150, 600);
assert!(n > 40, "{n} levels: banded");
// Values above 1.0 are brought into range by a negative exposure instead of clipped: 2.0
// at −3 stops shows as sRGB(lin(2.0) / 8) rather than sRGB(lin(1.0) / 8).
let mut flat = Document::new("hdr", Size::new(512, 512), ColorMode::Rgb, SampleType::F32);
let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::F32, true));
s.fill_rect(Rect::new(0, 0, 512, 512), &[2.0, 2.0, 2.0, 1.0]);
flat.layers.push(Layer::new("bright", LayerContent::Raster(s)));
let Some(img) = screen(flat, &[("view.thirtyTwoBitPreviewOptions", json!({"exposure": -3.0, "gamma": 1.0}))], "photocraft-canvas-16f-hdr-flat.png") else {
let brighten = [("view.thirtyTwoBitPreviewOptions", json!({"exposure": 4.0, "gamma": 1.0}))];
let darken = [("view.thirtyTwoBitPreviewOptions", json!({"exposure": -3.0, "gamma": 1.0}))];
let Some(shown) = screens(vec![(doc, &brighten, "photocraft-canvas-16f-hdr-ramp.png"), (flat, &darken, "photocraft-canvas-16f-hdr-flat.png")]) else {
return;
};
let [ramp, img] = &shown[..] else { panic!("two screens, got {}", shown.len()) };
let (n, _) = screen_levels(ramp, ramp.h / 2, 150, 600);
assert!(n > 40, "{n} levels: banded");
let got = img.green(img.w * 2 / 5, img.h / 2) as f32;
let dec = |v: f32| if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) };
let enc = |v: f32| if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 };
@@ -29,14 +29,17 @@ fn harness() -> Option<Harness> {
}
}
/// The colour on screen at document point `at` (which may lie past the document).
fn sample(h: &mut Harness, at: [f32; 2]) -> [u8; 3] {
/// The colours on screen at document points `at` (which may lie past the document), read from one settled frame:
/// the points of one state share a render instead of settling and rendering the same frame again (#15652).
fn samples<const N: usize>(h: &mut Harness, at: [[f32; 2]; N]) -> [[u8; 3]; N] {
h.run_steps(6);
let xf = photocraft_ui_egui::canvas::active_view(h.state()).expect("canvas view");
let p = xf.to_screen(craft::behavior::kurbo::Point::new(f64::from(at[0]), f64::from(at[1])));
let img = h.render().expect("render");
let px = img.get_pixel(p.x.round() as u32, p.y.round() as u32);
[px[0], px[1], px[2]]
at.map(|at| {
let p = xf.to_screen(craft::behavior::kurbo::Point::new(f64::from(at[0]), f64::from(at[1])));
let px = img.get_pixel(p.x.round() as u32, p.y.round() as u32);
[px[0], px[1], px[2]]
})
}
/// View › Pattern Preview, as the menu runs it.
@@ -77,17 +80,15 @@ fn pattern_preview_repeats_the_document_on_gpu_and_cpu_canvases() {
let path = if flip { "CPU" } else { "GPU" };
h.state_mut().ui.view.flip_horizontal = flip;
h.state_mut().ui.view.pattern_preview = false;
let off = sample(&mut h, right);
let [off, band] = samples(&mut h, [right, [10.0, 50.0]]);
assert!(!near(off, red) && !near(off, blue), "{path}: pasteboard without Pattern Preview, got {off:?}");
assert!(near(sample(&mut h, [10.0, 50.0]), red), "{path}: the document's own band");
assert!(near(band, red), "{path}: the document's own band");
toggle(&mut h);
assert!(h.state().ui.view.pattern_preview);
let got = sample(&mut h, right);
let [got, under, diag] = samples(&mut h, [right, below, diagonal]);
assert!(near(got, red), "{path}: copy to the right shows the left edge, got {got:?}");
let got = sample(&mut h, below);
assert!(near(got, blue), "{path}: copy below, got {got:?}");
let got = sample(&mut h, diagonal);
assert!(near(got, blue), "{path}: diagonal copy, got {got:?}");
assert!(near(under, blue), "{path}: copy below, got {under:?}");
assert!(near(diag, blue), "{path}: diagonal copy, got {diag:?}");
toggle(&mut h);
assert!(!h.state().ui.view.pattern_preview);
}
@@ -86,7 +86,11 @@ fn assert_document_size_is_physical(gpu: bool) {
let Some(mut h) = harness(gpu) else { return };
h.run_steps(4);
const DOC: u32 = 60;
for ui_scale in ["100", "125", "150", "200"] {
// A fractional and an integer UI scale: the canvas sees the scale only as `pixels_per_point` (device px per doc px
// = zoom x ppp), and its sampling branches on that product being below 1, whole (or 2 and up) or fractional
// (`gpu_canvas::callback::filter_mode`). 125% gives 1.25 and 2.5 at the two zooms, as 150% would; 200% gives 2 and
// 4, covering 100%'s 1 and 2, where a dropped ppp could not show anyway (#15652).
for ui_scale in ["125", "200"] {
{
let app = h.state_mut();
while app.session.active().is_some() {
+1
View File
@@ -24,6 +24,7 @@ mod interactive_bench_reporting;
mod layout_perf;
mod magnetic_lasso_right_click;
mod paint_bucket_all_layers;
mod pending_remove_pointer;
mod radial_blur_center;
mod save_memory_gate;
mod system_locale;
@@ -0,0 +1,149 @@
//! #7366: a background Remove on a Red-only target keeps G/B/alpha intact when a Type click
//! selects another layer while the job is pending. The engine regression covers both target
//! cases; this complementary fixture proves the real control-input route is reachable before
//! result application, independently of the full app's wall-clock progress-modal policy.
use photocraft_doc::LayerId;
use photocraft_engine::Session;
use photocraft_engine::jobs::Started;
use photocraft_ui_egui::{PhotocraftApp, Services, control};
const REMOVE: &str = r#"{"points":[[12,10],[16,12]],"size":6}"#;
// Drive the real control-input hook and canvas while holding job-result application until
// after selection. The full app's progress modal intentionally blocks canvas input on slow
// hosts, and its logic tick may collect the result before the click, so it is not this
// pending-result regression's fixture.
struct CanvasApp(Box<PhotocraftApp>);
impl std::ops::Deref for CanvasApp {
type Target = PhotocraftApp;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for CanvasApp {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl eframe::App for CanvasApp {
fn raw_input_hook(&mut self, ctx: &egui::Context, input: &mut egui::RawInput) {
eframe::App::raw_input_hook(&mut self.0, ctx, input);
}
fn logic(&mut self, _ctx: &egui::Context, _frame: &mut eframe::Frame) {
self.sync_views();
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
egui::CentralPanel::default().show(ui, |ui| photocraft_ui_egui::canvas::document_area(&mut self.0, ui));
}
}
type Harness = egui_kittest::Harness<'static, CanvasApp>;
fn run(s: &mut Session, id: &str, p: &str) {
s.execute(id, p.parse().unwrap()).unwrap();
}
/// Context for assertion messages: who is active, whether a text edit is open, and whether the job is done.
fn state_line(app: &PhotocraftApp, job: photocraft_engine::jobs::JobId) -> String {
format!(
"active layer {:?}, text-edit session open {}, job finished {}",
app.session.active().and_then(|d| d.active_layer),
app.ui.text_edit.is_some(),
app.session.job(job).is_none()
)
}
fn pixels(s: &Session, doc: usize, id: LayerId) -> Vec<f32> {
let d = &s.documents()[doc].doc;
d.layer(id).unwrap().surface().unwrap().read_region(d.bounds())
}
#[test]
fn control_pointer_selects_text_before_remove_result_application() {
let mut a = Session::new();
run(&mut a, "file.new", r#"{"name":"A","width":32,"height":24,"background":"transparent"}"#);
run(&mut a, "type.create", r#"{"text":"X","x":2,"y":18,"size":14}"#);
let text = a.active().unwrap().active_layer.unwrap();
run(&mut a, "layer.new.layer", r#"{"name":"Target"}"#);
let target = a.active().unwrap().active_layer.unwrap();
a.edit("fixture", |d, l| {
let q = d.layer_mut(l.unwrap()).unwrap().surface_mut().unwrap();
for y in 0..24 {
for x in 0..32 {
q.write_pixel(x, y, &[((x * 7 + y * 13) % 31) as f32 / 30., (x % 5) as f32 / 4., (y % 7) as f32 / 6., 1.]);
}
}
Ok(())
})
.unwrap();
run(&mut a, "file.new", r##"{"name":"B","width":32,"height":24,"background":"#6a219c"}"##);
a.set_active(0);
run(&mut a, "channel.target", r#"{"channel":"red"}"#);
let b = a.documents()[1].doc.clone();
let text_before = a.documents()[0].doc.layer(text).unwrap().clone();
// The inline Red-only Remove is the oracle.
let mut inline = Session::new();
inline.add_document(a.documents()[0].doc.as_ref().clone(), None);
inline.select_layer(target).unwrap();
run(&mut inline, "channel.target", r#"{"channel":"red"}"#);
run(&mut inline, "paint.remove", REMOVE);
let expected = pixels(&inline, 0, target);
// The app runs in a harness so the canvas takes the control channel's pointer input on the
// frames after the call.
let mut h = Harness::builder().with_size(egui::vec2(1100.0, 720.0)).with_max_steps(64).build_eframe(move |cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
// The app shares the harness's context, which is where the control channel's pointer input arrives.
CanvasApp(PhotocraftApp::with_context(cc.egui_ctx.clone(), a, Services::default()))
});
h.run_steps(4);
let job = match h.state_mut().session.start("paint.remove", REMOVE.parse().unwrap()).unwrap() {
Started::Job(id) => id,
v => panic!("must start a background job: {v:?}"),
};
assert!(h.state().session.job(job).is_some(), "the result is pending before selection");
let ctx = h.ctx.clone();
let (req, _rx) = control::ControlRequest::new("ui.pointer", r#"{"tool":"type","events":[{"kind":"down","x":4,"y":14}]}"#.parse().unwrap());
match control::handle(h.state_mut(), &ctx, &req) {
control::Reply::Done(reply) => assert_eq!(reply["ok"], true, "the pointer request is accepted: {reply}"),
_ => panic!("ui.pointer must reply immediately"),
}
// The control channel queues input for the canvas; wait for delivery rather than
// assuming two passes suffice on every host.
let host = craft::ui::runtime::windows::WindowHost::of(&ctx);
for _ in 0..8 {
if host.injected_idle() {
break;
}
h.run_steps(1);
}
let state = state_line(h.state(), job);
assert!(host.injected_idle(), "the canvas consumed the queued pointer input; {state}");
// `injected_idle` is also true when the step was withdrawn (focus change before its
// pass) instead of delivered, so delivery is asserted separately.
assert!(!host.take_injected_withdrawn(), "the injected press was delivered, not withdrawn; {state}");
let selected = text;
assert_eq!(h.state().session.active().unwrap().active_layer, Some(selected), "the input selects the text layer; {}", state_line(h.state(), job));
assert!(h.state().session.job(job).is_some(), "selection happened before result application");
let a = h.state_mut();
a.session.set_active(1);
a.session.wait_job(job).unwrap();
assert_eq!(a.session.documents()[1].doc, b, "B is unchanged");
let st = &a.session.documents()[0];
assert_eq!(st.doc.layer(text).unwrap(), &text_before, "the text layer is unchanged");
assert_eq!(st.active_layer, Some(selected), "the user's selection survives the job");
let actual = pixels(&a.session, 0, target);
let wrong = expected.as_chunks::<4>().0.iter().zip(actual.as_chunks::<4>().0).filter(|(e, r)| e[1..] != r[1..]).count();
assert_eq!(wrong, 0, "pixels with G/B/alpha changed outside the Red target");
assert_eq!(actual, expected);
}
+133 -114
View File
@@ -20,14 +20,15 @@ const MODES: [ColorMode; 3] = [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab];
const GRAY_TARGET_MODES: [ColorMode; 4] = [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab, ColorMode::Grayscale];
const DEPTHS: [SampleType; 3] = [SampleType::U8, SampleType::U16, SampleType::F32];
const TARGETS: [ChannelTarget; 3] = [ChannelTarget::Alpha(0), ChannelTarget::LayerMask, ChannelTarget::Composite];
/// Every mode and every depth once, for the whole-app tests. The planes they edit are single-channel
/// gray whatever the document mode (the mode only changes the colour layer, which each case asserts
/// stays untouched), and the depth does not interact with the mode, so the full cross product reaches
/// no new code and ran a single test past nextest's 600 s limit on Windows (#15636).
const MODE_DEPTHS: [(ColorMode, SampleType); 3] = [(ColorMode::Rgb, SampleType::U8), (ColorMode::Cmyk, SampleType::U16), (ColorMode::Lab, SampleType::F32)];
/// [`MODE_DEPTHS`] plus a grayscale document, for the tests that also cover gray documents.
const GRAY_MODE_DEPTHS: [(ColorMode, SampleType); 4] =
[(ColorMode::Rgb, SampleType::U8), (ColorMode::Cmyk, SampleType::U16), (ColorMode::Lab, SampleType::F32), (ColorMode::Grayscale, SampleType::U16)];
/// The whole-app picker tests check what the UI adds to the engine's gray picker: the canvas press reaches the
/// armed dialog (`canvas/tools/dialog.rs` -> `canvas_input::pick_tone`), and `adjust_dialog::pick` puts the
/// dialog's target into the parameters and writes the result back into the dialog. That code branches on the
/// dialog kind, the target and on RGB / gray / other documents (`picker.supported`), never on the bit depth, so
/// these tests run every kind and target on [`RGB_8`] and visit the other modes once. Sampling the right plane at
/// every colour mode x native depth is `destructive_eyedropper`'s, tested without the app in the engine's
/// `tone_target_picker.rs` (#15648). The full cross product ran a single test past nextest's 600 s limit on
/// Windows (#15636).
const RGB_8: (ColorMode, SampleType) = (ColorMode::Rgb, SampleType::U8);
/// The keys the hosted adjustment dialog lists beside its engine parameters.
const DIALOG_STATE: [&str; 4] = ["preview", "picker", "channel", "clipping"];
@@ -468,43 +469,49 @@ fn levels_auto_uses_the_selected_colour_channels_histogram() {
}
}
/// Black/white picker controls sample the gray plane and update the visible neutral curve.
/// Black/white picker controls sample the gray plane and update the visible neutral curve: every dialog and target
/// on an RGB document, then a grayscale, a CMYK and a Lab document once each (see [`RGB_8`]).
#[test]
fn grayscale_picker_controls_sample_the_plane_and_change_the_visible_curve() {
let mut h = bench();
let mut cases = Vec::new();
for kind in ["curves", "levels"] {
for (mode, depth) in GRAY_MODE_DEPTHS {
for target in TARGETS {
next_case(&mut h, &fixture_session(mode, depth, target), None);
open_here(&mut h, kind);
assert!(h.get_by_label("Set Neutral Gray Point").accesskit_node().is_disabled());
assert!(!h.get_by_label("Set White Point").accesskit_node().is_disabled());
h.get_by_label("Set White Point").click();
h.run_steps(2);
assert!(picker_armed(&h));
let before = params(&h);
let original = h.state().session.active().unwrap().doc.clone();
sample_at(&mut h, 4.0, 4.0);
let after = params(&h);
let key = if kind == "curves" { "points" } else { "inWhite" };
assert_ne!(before[key], after[key], "{kind} {mode:?} {depth:?} {target:?}");
let sampled_level = if kind == "curves" {
after["points"].as_array().unwrap().last().unwrap()[0].as_f64().unwrap()
} else {
after["inWhite"].as_f64().unwrap()
};
assert!((sampled_level - 63.75).abs() < 0.3, "sample the plane's 25% gray, not the colour layer: {after}");
for key in ["red", "green", "blue"] {
assert_eq!(before[key], after[key], "hidden {key} must not change");
}
assert!(std::sync::Arc::ptr_eq(&original, &h.state().session.active().unwrap().doc));
let id = top(&h);
confirm(&mut h, id).unwrap();
assert!(value(h.state(), target) > 0.99, "{kind} {mode:?} {depth:?} {target:?}");
assert_eq!(h.state().session.active().unwrap().doc.layers[0].content, original.layers[0].content);
}
for target in TARGETS {
cases.push((kind, RGB_8.0, RGB_8.1, target));
}
}
cases.extend([
("curves", ColorMode::Grayscale, SampleType::U16, ChannelTarget::LayerMask),
("levels", ColorMode::Grayscale, SampleType::F32, ChannelTarget::Composite),
("levels", ColorMode::Cmyk, SampleType::U16, ChannelTarget::Alpha(0)),
("curves", ColorMode::Lab, SampleType::F32, ChannelTarget::Alpha(0)),
]);
for (kind, mode, depth, target) in cases {
next_case(&mut h, &fixture_session(mode, depth, target), None);
open_here(&mut h, kind);
assert!(h.get_by_label("Set Neutral Gray Point").accesskit_node().is_disabled());
assert!(!h.get_by_label("Set White Point").accesskit_node().is_disabled());
h.get_by_label("Set White Point").click();
h.run_steps(2);
assert!(picker_armed(&h));
let before = params(&h);
let original = h.state().session.active().unwrap().doc.clone();
sample_at(&mut h, 4.0, 4.0);
let after = params(&h);
let key = if kind == "curves" { "points" } else { "inWhite" };
assert_ne!(before[key], after[key], "{kind} {mode:?} {depth:?} {target:?}");
let sampled_level =
if kind == "curves" { after["points"].as_array().unwrap().last().unwrap()[0].as_f64().unwrap() } else { after["inWhite"].as_f64().unwrap() };
assert!((sampled_level - 63.75).abs() < 0.3, "sample the plane's 25% gray, not the colour layer: {after}");
for key in ["red", "green", "blue"] {
assert_eq!(before[key], after[key], "hidden {key} must not change");
}
assert!(std::sync::Arc::ptr_eq(&original, &h.state().session.active().unwrap().doc));
let id = top(&h);
confirm(&mut h, id).unwrap();
assert!(value(h.state(), target) > 0.99, "{kind} {mode:?} {depth:?} {target:?}");
assert_eq!(h.state().session.active().unwrap().doc.layers[0].content, original.layers[0].content);
}
}
/// Replay a recorded tone step with its dialog enabled while a different channel is selected; `on_canvas` runs the
@@ -960,44 +967,52 @@ fn filter_mask_session(mode: ColorMode, depth: SampleType, stored: bool) -> (Ses
(session, id)
}
/// New upstream filter masks use the same scalar controls, picker and preserved targeting in every document space.
/// New upstream filter masks use the same scalar controls, picker and preserved targeting: both dialogs with a stored
/// and an implicit mask on an RGB document, and a grayscale document once. Every mode and depth is the engine's
/// `filter_mask_picker_samples_and_edits_only_the_filter_mask` (see [`RGB_8`]).
#[test]
fn filter_mask_tone_dialogs_preserve_the_target_and_sample_its_own_levels() {
let mut h = bench();
for (mode, depth) in GRAY_MODE_DEPTHS {
for kind in ["levels", "curves"] {
for stored in [false, true] {
let (session, id) = filter_mask_session(mode, depth, stored);
next_case(&mut h, &session, Some(id.0));
let st = h.state().session.active().unwrap();
let layer = st.active_layer.unwrap();
let expected_name = format!("{} Filter Mask", st.doc.layer(layer).unwrap().name);
let before = st.doc.clone();
open_here(&mut h, kind);
assert_eq!(names(&h), [expected_name], "{mode:?} {depth:?} {kind}");
assert_eq!(params(&h)["target"], "filterMask");
let id = top(&h);
arm(&mut h, "white");
sample_at(&mut h, 4.0, 4.0);
assert!(picker_armed(&h), "the picker stays armed on {mode:?} {depth:?} stored={stored}");
assert!(std::sync::Arc::ptr_eq(&before, &h.state().session.active().unwrap().doc), "sampling is read-only");
assert_eq!(params(&h)["target"], "filterMask");
if kind == "levels" {
let expected = if stored { 64.0 } else { 255.0 };
assert!((params(&h)["inWhite"].as_f64().unwrap() - expected).abs() < 1.0);
}
confirm(&mut h, id).unwrap();
let after = &h.state().session.active().unwrap().doc;
let LayerContent::Smart(old) = &before.layer(layer).unwrap().content else { panic!("smart fixture") };
let LayerContent::Smart(new) = &after.layer(layer).unwrap().content else { panic!("smart result") };
assert_eq!(new.smart_filters, old.smart_filters, "the adjustment edits the mask rather than adding a filter");
assert_eq!(new.source, old.source);
assert_eq!(after.channels, before.channels);
assert_eq!(after.layer(layer).unwrap().mask, before.layer(layer).unwrap().mask);
assert!(new.filter_mask.as_ref().unwrap().surface.sample_channel(8, 8, 0) > 0.99);
}
let mut cases = Vec::new();
for kind in ["levels", "curves"] {
for stored in [false, true] {
cases.push((RGB_8, kind, stored));
}
}
cases.push(((ColorMode::Grayscale, SampleType::U16), "levels", true));
for ((mode, depth), kind, stored) in cases {
let (session, id) = filter_mask_session(mode, depth, stored);
next_case(&mut h, &session, Some(id.0));
let st = h.state().session.active().unwrap();
let layer = st.active_layer.unwrap();
let expected_name = format!("{} Filter Mask", st.doc.layer(layer).unwrap().name);
let before = st.doc.clone();
open_here(&mut h, kind);
assert_eq!(names(&h), [expected_name], "{mode:?} {depth:?} {kind}");
assert_eq!(params(&h)["target"], "filterMask");
let id = top(&h);
arm(&mut h, "white");
sample_at(&mut h, 4.0, 4.0);
assert!(picker_armed(&h), "the picker stays armed on {mode:?} {depth:?} stored={stored}");
assert!(std::sync::Arc::ptr_eq(&before, &h.state().session.active().unwrap().doc), "sampling is read-only");
assert_eq!(params(&h)["target"], "filterMask");
let white = if stored { 64.0 } else { 255.0 };
let sampled = if kind == "levels" {
params(&h)["inWhite"].as_f64().unwrap()
} else {
params(&h)["points"].as_array().unwrap().last().unwrap()[0].as_f64().unwrap()
};
assert!((sampled - white).abs() < 1.0, "{mode:?} {depth:?} {kind} stored={stored}: sampled {sampled}, want {white}");
confirm(&mut h, id).unwrap();
let after = &h.state().session.active().unwrap().doc;
let LayerContent::Smart(old) = &before.layer(layer).unwrap().content else { panic!("smart fixture") };
let LayerContent::Smart(new) = &after.layer(layer).unwrap().content else { panic!("smart result") };
assert_eq!(new.smart_filters, old.smart_filters, "the adjustment edits the mask rather than adding a filter");
assert_eq!(new.source, old.source);
assert_eq!(after.channels, before.channels);
assert_eq!(after.layer(layer).unwrap().mask, before.layer(layer).unwrap().mask);
assert!(new.filter_mask.as_ref().unwrap().surface.sample_channel(8, 8, 0) > 0.99);
}
}
/// A recorded alpha address takes precedence over the currently selected filter mask.
@@ -1189,48 +1204,52 @@ fn addressed_mask_session(mode: ColorMode, depth: SampleType, filter: bool) -> (
#[test]
fn review_mask_action_context_matches_the_addressed_layer() {
let mut h = bench();
for (pair, (mode, depth)) in MODE_DEPTHS.into_iter().enumerate() {
for kind in ["levels", "curves"] {
for filter in [false, true] {
let (source, layer) = addressed_mask_session(mode, depth, filter);
// Resolving the address does not depend on the mode or depth: every selector form on the first pair.
let selectors = [json!(layer.0), json!("Receiver"), json!({"name":"Receiver"})];
for selector in selectors.into_iter().take(if pair == 0 { 3 } else { 1 }) {
next_case(&mut h, &source, None);
let command = format!("image.adjustments.{kind}");
let target = if filter { "filterMask" } else { "mask" };
let raw = json!({"layer":selector,"target":target});
add_action(h.state_mut(), "Other mask", command.clone(), raw, true);
let original = h.state().session.active().unwrap().doc.clone();
let active = h.state().session.active().unwrap().active_layer;
let expected =
photocraft_engine::mask_view_cmds::viewed_mask(original.layer(layer).unwrap(), filter).unwrap().surface.sample_channel(8, 8, 0);
play(&mut h, "Other mask");
assert_eq!(names(&h), [if filter { "Receiver Filter Mask" } else { "Receiver Mask" }]);
let id = top(&h);
arm(&mut h, "white");
sample_at(&mut h, 4.0, 4.0);
let p = params(&h);
let want = photocraft_engine::adjust_params::adjustment_eyedropper(
kind,
&json!({}),
photocraft_engine::adjust_params::CurvesEyedropper::White,
[expected; 3],
ColorMode::Grayscale,
)
.unwrap();
let got = photocraft_engine::adjust_params::from_params(kind, &p, None, ColorMode::Grayscale).unwrap();
assert_eq!(got, want, "{mode:?} {depth:?} {kind} {target}");
let preview = filter_dialog::preview_document(&original, active, &command, &p, 1).unwrap();
confirm(&mut h, id).unwrap();
let doc = &h.state().session.active().unwrap().doc;
assert_eq!(doc.layers, preview.layers);
assert_eq!(doc.layers[0], original.layers[0]);
assert_eq!(doc.channels, original.channels);
assert!(photocraft_engine::mask_view_cmds::viewed_mask(doc.layer(layer).unwrap(), filter).unwrap().surface.sample_channel(8, 8, 0) > 0.99);
assert_eq!(h.state().session.active().unwrap().active_layer, active);
}
}
// Both dialogs with both mask kinds on an RGB document, and a CMYK and a Lab document once. Resolving the address is
// the engine's (`review_picker_reads_the_addressed_mask_layer` runs every selector form in every mode and depth);
// here every form runs on the first layer-mask and filter-mask cases, the name form on the rest.
let mut cases = Vec::new();
for kind in ["levels", "curves"] {
for filter in [false, true] {
cases.push((RGB_8, kind, filter));
}
}
cases.extend([((ColorMode::Cmyk, SampleType::U16), "curves", true), ((ColorMode::Lab, SampleType::F32), "levels", false)]);
for (case, ((mode, depth), kind, filter)) in cases.into_iter().enumerate() {
let (source, layer) = addressed_mask_session(mode, depth, filter);
let selectors = [json!("Receiver"), json!(layer.0), json!({"name":"Receiver"})];
for selector in selectors.into_iter().take(if case < 2 { 3 } else { 1 }) {
next_case(&mut h, &source, None);
let command = format!("image.adjustments.{kind}");
let target = if filter { "filterMask" } else { "mask" };
let raw = json!({"layer":selector,"target":target});
add_action(h.state_mut(), "Other mask", command.clone(), raw, true);
let original = h.state().session.active().unwrap().doc.clone();
let active = h.state().session.active().unwrap().active_layer;
let expected = photocraft_engine::mask_view_cmds::viewed_mask(original.layer(layer).unwrap(), filter).unwrap().surface.sample_channel(8, 8, 0);
play(&mut h, "Other mask");
assert_eq!(names(&h), [if filter { "Receiver Filter Mask" } else { "Receiver Mask" }]);
let id = top(&h);
arm(&mut h, "white");
sample_at(&mut h, 4.0, 4.0);
let p = params(&h);
let want = photocraft_engine::adjust_params::adjustment_eyedropper(
kind,
&json!({}),
photocraft_engine::adjust_params::CurvesEyedropper::White,
[expected; 3],
ColorMode::Grayscale,
)
.unwrap();
let got = photocraft_engine::adjust_params::from_params(kind, &p, None, ColorMode::Grayscale).unwrap();
assert_eq!(got, want, "{mode:?} {depth:?} {kind} {target}");
let preview = filter_dialog::preview_document(&original, active, &command, &p, 1).unwrap();
confirm(&mut h, id).unwrap();
let doc = &h.state().session.active().unwrap().doc;
assert_eq!(doc.layers, preview.layers);
assert_eq!(doc.layers[0], original.layers[0]);
assert_eq!(doc.channels, original.channels);
assert!(photocraft_engine::mask_view_cmds::viewed_mask(doc.layer(layer).unwrap(), filter).unwrap().surface.sample_channel(8, 8, 0) > 0.99);
assert_eq!(h.state().session.active().unwrap().active_layer, active);
}
}
}
+3 -4
View File
@@ -19,7 +19,7 @@
Both Breeze themes are our own values close to Plasma's (not a copy of its colour schemes) and put text readability first: every text colour holds 4.5:1 on every surface and on hovered, pressed and selected states (`theme.rs` tests), so their secondary text, accent and status colours are darker (Light) or lighter (Dark) than Breeze's own, and the primary button is a deeper blue with white text.
Edit → Preferences → Interface shows an Appearance Mode selector (Sync with system, Dark, Light) above separate light and dark theme cards with PhotoCraft editor previews and radio choices. Auto is opt-in and follows the operating system while the app is running. On Linux it reads the desktop portal once and then listens for its `SettingChanged` signal (no polling, and the UI repaints only when the value changes); `gsettings` runs at most once at start-up, by absolute path, when the portal gives no answer. A missing system appearance falls back to Dark. New installs keep Photoshop's default: Dark mode with Pro Medium (Pro Light is the saved light theme). Existing saved single-theme preferences migrate to a fixed Dark or Light mode with their chosen theme. The header appearance button cycles Auto → Light → Dark; its icon shows a monitor, moon or sun for the selected mode. Window → Theme and `ui.set {"theme":"classic"}` select a theme and fix the mode to its light or dark family.
Edit → Preferences → Interface shows an Appearance Mode selector (Sync with system, Dark, Light) above separate light and dark theme cards with PhotoCraft editor previews and radio choices. Auto is opt-in and follows the operating system while the app is running. On Linux it reads the desktop portal once and then listens for its `SettingChanged` signal (no polling, and the UI repaints only when the value changes); `gsettings` runs at most once at start-up, by absolute path, when the portal gives no answer. A missing system appearance falls back to Dark. New installs keep Photoshop's default: Dark mode with Pro Medium (Pro Light is the saved light theme). Existing saved single-theme preferences migrate to a fixed Dark or Light mode with their chosen theme. Window → Appearance → Next Mode cycles Auto → Light → Dark. Window → Theme and `ui.set {"theme":"classic"}` select a theme and fix the mode to its light or dark family.
Window → Theme and macOS PhotoCraft → Appearance also offer Sync with system. Its checkmark follows the saved Auto mode rather than the displayed palette; choosing a manual theme selects its fixed appearance mode.
@@ -100,11 +100,10 @@ missing-glyph boxes. Check every new panel with the offscreen snapshot tool (`do
## Title bar
The app's top bar (`panels::title_bar`) starts with the brand mark (the app icon, `brand.rs`), then the menus, the document title and the workspace controls, like Photoshop's Ps tile and menu row.
The app's top bar (`panels::title_bar`) starts with the brand mark (the app icon, `brand.rs`), then the menus and the document title, like Photoshop's Ps tile and menu row. Nothing else sits at its far end: the workspace switcher, command search and appearance mode live in Window › Workspace, Edit › Search and Window › Appearance.
- **Windows and Linux:** the window has no OS decorations, so there is one bar, not two stacked. The top bar is the title bar (`titlebar.rs`): Minimize, Maximize/Restore and Close (red on hover, `caption_close` tokens) sit flush in the window's top-right corner, the free gap between the menus and the controls drags the window and a double-click there maximizes it, and invisible 5 pt edges (12 pt corners) resize it. Close runs File › Exit, so unsaved documents are asked about first.
- **Windows and Linux:** the window has no OS decorations, so there is one bar, not two stacked. The top bar is the title bar (`titlebar.rs`): Minimize, Maximize/Restore and Close (red on hover, `caption_close` tokens) sit flush in the window's top-right corner, the free gap between the menus and the caption buttons drags the window and a double-click there maximizes it, and invisible 5 pt edges (12 pt corners) resize it. Close runs File › Exit, so unsaved documents are asked about first.
- **macOS:** the traffic lights sit over the integrated title strip (`integrated_titlebar`).
- **Narrow windows** drop controls that are also in a menu before anything overlaps: the theme toggle (Preferences), then search (Edit › Search), then the workspace switcher narrows (Window › Workspace).
## Compact tool controls