diff --git a/Cargo.lock b/Cargo.lock index 54cc8089fd..dd620e2629 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5808,6 +5808,7 @@ version = "0.23.1" dependencies = [ "memory-stats", "serde_json", + "wgpu", ] [[package]] diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs index e1b87e55c9..f42e2d49b8 100644 --- a/crates/format/src/store.rs +++ b/crates/format/src/store.rs @@ -155,8 +155,7 @@ impl ByteSource for ZipSource<'_> { fn bundle_error(error: craft_pcraft_bundle::Error) -> FormatError { match error { craft_pcraft_bundle::Error::LimitExceeded { entry, limit } => FormatError::LimitExceeded(format!("`{entry}` exceeds {limit} bytes")), - craft_pcraft_bundle::Error::Zip(error) if error.is_limit() => FormatError::LimitExceeded(error.to_string()), - craft_pcraft_bundle::Error::Io(message) => FormatError::Io(std::io::Error::other(message)), + craft_pcraft_bundle::Error::Zip(error) => crate::zip::map_read_error(error), other => FormatError::corrupt(other.to_string()), } } @@ -166,8 +165,8 @@ mod bundle_error_tests { use super::*; #[test] - fn shared_io_errors_keep_the_native_io_type_and_message() { - let error = bundle_error(craft_pcraft_bundle::Error::Io("manifest publication failed".into())); + fn shared_save_io_errors_keep_the_native_io_type_and_message() { + let error = save_error(craft_pcraft_bundle::Error::Io("manifest publication failed".into())); let FormatError::Io(error) = error else { panic!("I/O failure must remain typed") }; assert_eq!(error.kind(), std::io::ErrorKind::Other); assert_eq!(error.to_string(), "manifest publication failed"); @@ -183,7 +182,7 @@ mod bundle_error_tests { craft_zip::Error::EntryTooLarge { name: "manifest.json".into(), limit: 16 }, craft_zip::Error::BudgetSpent { name: "manifest.json".into(), limit: 16 }, ] { - let message = error.to_string(); + let message = format!("zip: {error}"); assert!(matches!(bundle_error(craft_pcraft_bundle::Error::Zip(error)), FormatError::LimitExceeded(found) if found == message)); } } @@ -191,18 +190,30 @@ mod bundle_error_tests { #[test] fn malformed_paths_archives_and_hashes_remain_corrupt() { for error in [ + craft_pcraft_bundle::Error::Io("invalid compressed frame".into()), craft_pcraft_bundle::Error::InvalidPath("../manifest.json".into()), craft_pcraft_bundle::Error::InvalidBundle("missing manifest".into()), craft_pcraft_bundle::Error::HashMismatch("tiles/object.zst".into()), craft_pcraft_bundle::Error::Zip(craft_zip::Error::NotZip("truncated".into())), craft_pcraft_bundle::Error::Zip(craft_zip::Error::Entry { name: "manifest.json".into(), msg: "checksum".into() }), ] { - let message = error.to_string(); + let message = match &error { + craft_pcraft_bundle::Error::Zip(e) => format!("zip: {e}"), + _ => error.to_string(), + }; assert!(matches!(bundle_error(error), FormatError::Corrupt(found) if found == message)); } } } +/// Save failures are I/O errors; read-time decompression errors remain corrupt data. +fn save_error(error: craft_pcraft_bundle::Error) -> FormatError { + match error { + craft_pcraft_bundle::Error::Io(message) => FormatError::Io(std::io::Error::other(message)), + other => bundle_error(other), + } +} + pub(crate) struct DirSource { bundle: craft_pcraft_bundle::DirectoryBundle, } @@ -733,7 +744,6 @@ fn path_signature(path: &Path) -> Result> { } } -#[cfg(test)] fn unsafe_bundle_entry(path: &Path) -> FormatError { FormatError::Io(std::io::Error::new( std::io::ErrorKind::InvalidData, @@ -743,7 +753,6 @@ fn unsafe_bundle_entry(path: &Path) -> FormatError { /// The generic atomic writer intentionally follows a destination symlink. Directory bundles /// must reject one instead: all of their managed entries stay below the bundle root. -#[cfg(all(test, windows))] fn plain_file_or_missing(path: &Path) -> Result<()> { match std::fs::symlink_metadata(path) { Ok(metadata) if metadata.is_file() => Ok(()), @@ -1244,7 +1253,10 @@ impl PcraftWriter { } } scratch_ok(doc, generation)?; - let directory_stats = self.directory.save_directory(dir, writer).map_err(bundle_error)?; + // craft-pcraft-bundle refuses a symlinked manifest only when it publishes it, after the + // objects are written. Refusing it first leaves the folder as it was. + plain_file_or_missing(&dir.join(MANIFEST))?; + let directory_stats = self.directory.save_directory(dir, writer).map_err(save_error)?; let mut stats = prepared.stats; stats.objects_removed = directory_stats.removed; for path in &directory_stats.written_objects { diff --git a/crates/format/src/zip.rs b/crates/format/src/zip.rs index d3ded4bb9b..20443a1cbf 100644 --- a/crates/format/src/zip.rs +++ b/crates/format/src/zip.rs @@ -24,7 +24,7 @@ pub struct ZipReader<'a> { by_name: HashMap, } -fn map_read_error(error: craft_zip::Error) -> FormatError { +pub(crate) fn map_read_error(error: craft_zip::Error) -> FormatError { match error { craft_zip::Error::TooManyEntries { .. } | craft_zip::Error::TooManyEndRecords(_) diff --git a/crates/format/tests/it/directory_symlinks.rs b/crates/format/tests/it/directory_symlinks.rs index 7061b8d516..802717f134 100644 --- a/crates/format/tests/it/directory_symlinks.rs +++ b/crates/format/tests/it/directory_symlinks.rs @@ -19,8 +19,7 @@ fn directory_cleanup_preserves_unrelated_zst_files() { let mut writer = PcraftWriter::new(); writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap(); - // An empty shared bundle creates object directories only when it writes objects. - // These directories belong to the fixture that plants the files below. + // An empty document writes no objects, so a save creates neither folder. std::fs::create_dir_all(bundle.join("tiles")).unwrap(); std::fs::create_dir_all(bundle.join("blobs")).unwrap(); let unrelated = bundle.join("tiles/personal-notes.zst"); @@ -62,13 +61,21 @@ mod permissions { } } + /// An empty document's save makes none of the object and preview folders; these tests + /// restrict or fill them, so they make them first. + fn make_dirs(bundle: &Path) { + for dir in ["tiles", "blobs", "composite"] { + std::fs::create_dir_all(bundle.join(dir)).unwrap(); + } + } + #[test] fn directory_save_without_previews_does_not_require_composite_read_permission() { let root = temp_dir("composite-search-only"); let bundle = root.join("project.pcraft"); let mut writer = PcraftWriter::new(); writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap(); - std::fs::create_dir_all(bundle.join("composite")).unwrap(); + make_dirs(&bundle); let restricted = RestoreMode::set(&bundle.join("composite"), 0o300); let mut changed = empty_doc(); changed.name = "saved without previews".into(); @@ -86,8 +93,7 @@ mod permissions { let link = root.join("linked.pcraft"); let mut writer = PcraftWriter::new(); writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap(); - std::fs::create_dir_all(bundle.join("composite")).unwrap(); - std::fs::create_dir_all(bundle.join("blobs")).unwrap(); + make_dirs(&bundle); symlink(&bundle, &link).unwrap(); std::fs::write(bundle.join("thumb.png"), b"stale thumbnail").unwrap(); std::fs::write(bundle.join("composite/preview.png"), b"stale composite").unwrap(); @@ -115,7 +121,7 @@ mod permissions { let bundle = root.join("project.pcraft"); let mut writer = PcraftWriter::new(); writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap(); - std::fs::create_dir_all(bundle.join("composite")).unwrap(); + make_dirs(&bundle); let restricted = RestoreMode::set(&bundle.join("composite"), 0o300); let mut changed = empty_doc(); changed.name = "saved with preview".into(); @@ -135,7 +141,7 @@ mod permissions { let mut writer = PcraftWriter::new(); let original = empty_doc(); writer.save_dir(&original, &bundle, &SaveOptions::default()).unwrap(); - std::fs::create_dir_all(bundle.join("composite")).unwrap(); + make_dirs(&bundle); let preview = bundle.join("composite/preview.png"); std::fs::write(&preview, b"stale composite").unwrap(); let restricted = RestoreMode::set(&bundle.join("composite"), 0o500); @@ -165,7 +171,7 @@ mod permissions { let bundle = root.join("project.pcraft"); let mut writer = PcraftWriter::new(); writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap(); - std::fs::create_dir_all(bundle.join("tiles")).unwrap(); + make_dirs(&bundle); let orphan = bundle.join("tiles").join(format!("{}.zst", "d".repeat(64))); std::fs::write(&orphan, b"unreferenced object").unwrap(); let restricted = RestoreMode::set(&bundle.join("tiles"), 0o500); diff --git a/crates/format/tests/it/roundtrip.rs b/crates/format/tests/it/roundtrip.rs index 0cb4b1589e..a311a17671 100644 --- a/crates/format/tests/it/roundtrip.rs +++ b/crates/format/tests/it/roundtrip.rs @@ -698,7 +698,8 @@ fn directory_save_rejects_manifest_symlink_without_overwriting_target() { assert!(PcraftWriter::new().save_dir(&doc, &dir, &SaveOptions::default()).is_err()); assert_eq!(std::fs::read(&external_manifest).unwrap(), b"keep manifest"); - assert_eq!(std::fs::read_dir(dir.join("tiles")).unwrap().count(), 0); + // Refused before any object is written: `tiles/` is missing or empty. + assert_eq!(std::fs::read_dir(dir.join("tiles")).map_or(0, |entries| entries.count()), 0); std::fs::remove_dir_all(dir).unwrap(); std::fs::remove_dir_all(outside).unwrap(); @@ -808,7 +809,8 @@ fn bundles_without_the_full_composite_still_open() { } let older = z.finish().unwrap(); assert_eq!(read_full_composite(&older).unwrap(), None); - // The shared manifest reader refuses a noncanonical full-composite reference. + // A member that names any other entry is refused, and so is the bundle: craft-pcraft-format + // treats it like a `thumbnail` or `composite` that names another entry. No writer does that. manifest["full_composite"] = serde_json::Value::from("thumb.png"); let mut z = zip::ZipWriter::new(); z.add("manifest.json", &serde_json::to_vec_pretty(&manifest).unwrap()).unwrap(); diff --git a/crates/gpu/tests/it/bounded_readback.rs b/crates/gpu/tests/it/bounded_readback.rs index c723a68c3f..8b99c78054 100644 --- a/crates/gpu/tests/it/bounded_readback.rs +++ b/crates/gpu/tests/it/bounded_readback.rs @@ -12,6 +12,9 @@ use crate::GPU_LOCK; fn test_gpu() -> Option<(NativeContext, Compositor, std::sync::MutexGuard<'static, ()>)> { let lock = GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + // `NativeContext::request` makes and drops an instance of its own; the kept one keeps the + // Vulkan loader from being torn down when it goes. + let _kept = crate::instance(); let ctx = match NativeContext::request(&NativeContextOptions::default()) { Ok(c) => c, Err(e) => { diff --git a/crates/gpu/tests/it/camera_raw.rs b/crates/gpu/tests/it/camera_raw.rs index 754b3e82be..5ef4c6e7c0 100644 --- a/crates/gpu/tests/it/camera_raw.rs +++ b/crates/gpu/tests/it/camera_raw.rs @@ -25,7 +25,7 @@ fn gpu() -> Option { let lock = crate::GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let required = std::env::var_os("WGPU_BACKEND").is_some(); // `WGPU_BACKEND` picks the backend; `PHOTOCRAFT_TEST_FALLBACK_ADAPTER=1` the software one (WARP). - let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); + let instance = crate::instance(); let fallback = std::env::var_os("PHOTOCRAFT_TEST_FALLBACK_ADAPTER").is_some(); let options = wgpu::RequestAdapterOptions { force_fallback_adapter: fallback, ..Default::default() }; let adapter = match pollster::block_on(instance.request_adapter(&options)) { diff --git a/crates/gpu/tests/it/device_loss.rs b/crates/gpu/tests/it/device_loss.rs index 2e8839de12..a4e691d52e 100644 --- a/crates/gpu/tests/it/device_loss.rs +++ b/crates/gpu/tests/it/device_loss.rs @@ -12,7 +12,7 @@ use photocraft_raster::Surface; use crate::GPU_LOCK; fn device() -> Option<(wgpu::Adapter, wgpu::Device, wgpu::Queue)> { - let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); + let instance = crate::instance(); let adapter = match pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) { Ok(a) => a, Err(e) => { diff --git a/crates/gpu/tests/it/main.rs b/crates/gpu/tests/it/main.rs index 077f4acb4c..46a812417f 100644 --- a/crates/gpu/tests/it/main.rs +++ b/crates/gpu/tests/it/main.rs @@ -4,6 +4,33 @@ /// creates a device takes this lock and holds it until the device is dropped. static GPU_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); +/// The wgpu instance every test uses (`WGPU_BACKEND` picks its backends), kept for the whole +/// run: the last instance going away tears the Vulkan loader down, and an instance made while +/// that happens can crash in libvulkan. +pub(crate) fn instance() -> wgpu::Instance { + static KEPT: std::sync::OnceLock = std::sync::OnceLock::new(); + KEPT.get_or_init(|| { + INSTANCES_MADE.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()) + }) + .clone() +} + +/// How many instances [`instance`] has made: one for the whole run. +static INSTANCES_MADE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// [`instance`] makes its instance once, however many tests and threads ask for it: a fresh one +/// per test could crash in libvulkan while another goes away. +#[test] +fn the_instance_is_made_once() { + let threads: Vec<_> = (0..4).map(|_| std::thread::spawn(|| drop(instance()))).collect(); + for t in threads { + assert!(t.join().is_ok()); + } + drop(instance()); + assert_eq!(INSTANCES_MADE.load(std::sync::atomic::Ordering::SeqCst), 1); +} + mod bounded_readback; mod camera_raw; mod device_loss; diff --git a/crates/gpu/tests/it/parity.rs b/crates/gpu/tests/it/parity.rs index 4b3a1447dd..386f8d03eb 100644 --- a/crates/gpu/tests/it/parity.rs +++ b/crates/gpu/tests/it/parity.rs @@ -101,7 +101,7 @@ fn timed(what: &str, run: impl FnOnce() -> T) -> T { fn gpu() -> Option { let lock = GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let required = std::env::var_os("WGPU_BACKEND").is_some(); - let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); + let instance = crate::instance(); let adapter = match pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) { Ok(a) => a, Err(e) => { @@ -145,10 +145,7 @@ fn gpu() -> Option { /// The returned guard holds [`GPU_LOCK`] until the device is dropped. fn any_device() -> Option<(wgpu::Adapter, wgpu::Device, wgpu::Queue, std::sync::MutexGuard<'static, ()>)> { let lock = GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let adapter = pollster::block_on( - wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()).request_adapter(&wgpu::RequestAdapterOptions::default()), - ) - .ok()?; + let adapter = pollster::block_on(crate::instance().request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?; let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).ok()?; Some((adapter, device, queue, lock)) } diff --git a/crates/gpu/tests/it/pipeline_errors.rs b/crates/gpu/tests/it/pipeline_errors.rs index fc1cd43828..e4cd97c52b 100644 --- a/crates/gpu/tests/it/pipeline_errors.rs +++ b/crates/gpu/tests/it/pipeline_errors.rs @@ -12,7 +12,7 @@ use photocraft_gpu::{Compositor, render_to_vec}; use crate::GPU_LOCK; fn device() -> Option<(wgpu::Adapter, wgpu::Device, wgpu::Queue)> { - let instance = wgpu::Instance::default(); + let instance = crate::instance(); let Ok(adapter) = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) else { eprintln!("skipping: no adapter"); return None; @@ -67,7 +67,7 @@ fn parallel_compositor_builds_leave_the_shader_cache_intact() { let var = |name: &str, default: u32| std::env::var(name).ok().and_then(|v| v.parse::().ok()).filter(|&n| n > 0).unwrap_or(default); let (rounds, builds) = (var("PC_BUILD_ROUNDS", 4), var("PC_BUILDS_PER_DEVICE", 8)); for round in 0..rounds { - let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); + let instance = crate::instance(); let Ok(adapter) = pollster::block_on(wgpu::util::initialize_adapter_from_env_or_default(&instance, None)) else { eprintln!("skipping: no adapter"); return; diff --git a/crates/gpu/tests/it/timing.rs b/crates/gpu/tests/it/timing.rs index e0b11db0c4..c38fa25409 100644 --- a/crates/gpu/tests/it/timing.rs +++ b/crates/gpu/tests/it/timing.rs @@ -38,7 +38,7 @@ fn block_on(f: F) -> F::Output { /// A real GPU with timestamp queries, or `None` with the reason printed. fn gpu() -> Option<(wgpu::Device, wgpu::Queue, Compositor)> { let options = wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }; - let Ok(adapter) = block_on(wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()).request_adapter(&options)) else { + let Ok(adapter) = block_on(crate::instance().request_adapter(&options)) else { eprintln!("SKIP gpu timing: no adapter"); return None; }; diff --git a/crates/gpu/tests/it/uniform_limits.rs b/crates/gpu/tests/it/uniform_limits.rs index e562a8ca9d..0916a8bdab 100644 --- a/crates/gpu/tests/it/uniform_limits.rs +++ b/crates/gpu/tests/it/uniform_limits.rs @@ -20,7 +20,7 @@ fn fills_size(count: usize, size: Size) -> Document { } fn constrained_device() -> Option<(wgpu::Adapter, wgpu::Device, wgpu::Queue)> { - let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); + let instance = crate::instance(); let adapter = match pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) { Ok(adapter) => adapter, Err(error) => { diff --git a/crates/gpu/tests/it/vector_mask.rs b/crates/gpu/tests/it/vector_mask.rs index feb8597b8e..7135d72a8d 100644 --- a/crates/gpu/tests/it/vector_mask.rs +++ b/crates/gpu/tests/it/vector_mask.rs @@ -6,7 +6,7 @@ use photocraft_doc::{Adjustment, Document, Effect, Layer, LayerContent, LayerMas use photocraft_geom::Rect; fn gpu() -> Option<(wgpu::Device, wgpu::Queue, photocraft_gpu::Compositor)> { - let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); + let instance = crate::instance(); let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?; let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).ok()?; // Exact comparison needs 32-bit float targets (see parity.rs); skip on adapters without them. diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index e28779baef..3c3bc3fd86 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -10,6 +10,7 @@ //! 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}; @@ -550,7 +551,9 @@ fn parse_image_bounded_with( 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 opt = options_with_isolation(fontdb, xml_left, isolated, resolver); + 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)?; @@ -564,7 +567,7 @@ fn parse_image_bounded_with( // 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_resource_limit_images > 0 || (counter.strict && usage.svg_limit_images > 0) { + } else if usage.svg_limit_images > 0 && (counter.strict || refusals.over_budget.load(Ordering::Relaxed)) { 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()); @@ -590,6 +593,102 @@ 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, +} + +/// 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)); + // Plain data is only measured; compressed data is unpacked again. + 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 }; + // Every unpack is charged at least what it unpacked, so together they stay within one + // budget; plain data is only measured. + let (unpacked, too_large) = match craft_svg::svgz::inflate(data, limit) { + Ok(std::borrow::Cow::Borrowed(_)) => (0, false), + Ok(std::borrow::Cow::Owned(xml)) => (xml.len(), false), + 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, + refusals: Arc, +) -> 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) { diff --git a/crates/io/src/svg/tests.rs b/crates/io/src/svg/tests.rs index a8149bfb48..1cf2f6cc6f 100644 --- a/crates/io/src/svg/tests.rs +++ b/crates/io/src/svg/tests.rs @@ -60,6 +60,18 @@ fn image_svg(images: &str) -> String { format!("{images}") } +fn base64(bytes: &[u8]) -> String { + const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::new(); + for chunk in bytes.chunks(3) { + let n = chunk.iter().enumerate().fold(0u32, |n, (i, b)| n | u32::from(*b) << (16 - 8 * i)); + for i in 0..4 { + out.push(if i <= chunk.len() { T[(n >> (18 - 6 * i) & 63) as usize] as char } else { '=' }); + } + } + out +} + fn png_dimensions(width: u32, height: u32) -> Vec { let mut bytes = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec(); bytes.extend_from_slice(&width.to_be_bytes()); @@ -1032,17 +1044,6 @@ fn bounded_embedded_svg_gets_only_the_nesting_depth_the_drawing_left() { /// main-thread size); deeper ones are refused. #[test] fn the_deepest_chain_of_embedded_svg_images_fits_a_small_stack() { - fn base64(bytes: &[u8]) -> String { - const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - let mut out = String::new(); - for chunk in bytes.chunks(3) { - let n = chunk.iter().enumerate().fold(0u32, |n, (i, b)| n | u32::from(*b) << (16 - 8 * i)); - for i in 0..4 { - out.push(if i <= chunk.len() { T[(n >> (18 - 6 * i) & 63) as usize] as char } else { '=' }); - } - } - out - } let chain = |levels: usize| { let mut svg = "".to_string(); for _ in 0..levels { @@ -1080,6 +1081,131 @@ fn the_deepest_chain_of_embedded_svg_images_fits_a_small_stack() { .unwrap(); } +fn gzip(bytes: &[u8]) -> Vec { + use std::io::Write; + let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best()); + encoder.write_all(bytes).unwrap(); + encoder.finish().unwrap() +} + +/// An `` holding an 8 × 8 rect inside `levels` SVG images, each gzipped: small at any +/// depth, so the byte budget never ends the chain. +fn gzipped_chain_image(levels: usize) -> String { + let mut svg = "".to_string(); + for level in 0..levels { + let image = format!("", base64(&gzip(svg.as_bytes()))); + if level + 1 == levels { + return image; + } + svg = format!("{image}"); + } + String::new() +} + +fn chain_svg(images: &str) -> String { + format!("{images}") +} + +/// One image past [`MAX_EMBEDDED_SVG_DEPTH`] is refused, not parsed with the innermost left out. +/// (Drawing such a chain is refused past craft-svg's own, lower limit of 24.) +#[test] +fn a_chain_of_svg_images_past_the_nesting_cap_is_refused() { + let deepest = chain_svg(&gzipped_chain_image(MAX_EMBEDDED_SVG_DEPTH)); + assert!(deepest.len() < 1 << 20, "far below the byte budget: {} bytes", deepest.len()); + let (_, chain_length) = parse_bounded_inner(deepest.as_bytes(), MAX_RASTER_PIXELS).unwrap(); + assert_eq!(chain_length, MAX_EMBEDDED_SVG_DEPTH as u64, "every level parses"); + let error = parse_bounded(chain_svg(&gzipped_chain_image(MAX_EMBEDDED_SVG_DEPTH + 1)).as_bytes(), MAX_RASTER_PIXELS).unwrap_err(); + assert!(error.to_string().contains("byte or nesting budget"), "{error}"); +} + +/// A chain that fits the cap beside an image only nested too deeply in XML: that image is left +/// out, as on its own, and the chain still parses. +#[test] +fn a_chain_at_the_nesting_cap_beside_an_image_too_deep_in_xml_still_parses() { + let deep = format!( + "{}{}", + "".repeat(MAX_XML_DEPTH - 1), + "".repeat(MAX_XML_DEPTH - 1) + ); + let too_deep = embedded_image("image/svg+xml", deep.as_bytes()); + assert!(parse_bounded(image_svg(&too_deep).as_bytes(), MAX_RASTER_PIXELS).is_ok(), "on its own it is left out"); + let svg = chain_svg(&format!("{}{too_deep}", gzipped_chain_image(MAX_EMBEDDED_SVG_DEPTH))); + let (_, chain_length) = parse_bounded_inner(svg.as_bytes(), MAX_RASTER_PIXELS).unwrap(); + assert_eq!(chain_length, MAX_EMBEDDED_SVG_DEPTH as u64); +} + +/// An embedded SVGZ whose gzip stream is cut short is left out like any unreadable image, though +/// craft-svg charges it the rest of the byte budget. A small image refused for bytes after it is +/// left out too; one past the whole budget on its own still fails the drawing. +#[test] +fn a_damaged_embedded_svgz_is_left_out() { + let svg = ""; + let compressed = gzip(svg.as_bytes()); + let damaged = embedded_image("image/svg+xml", &compressed[..compressed.len() / 2]); + let after = embedded_image("image/svg+xml", svg.as_bytes()); + let parsed = parse_bounded(image_svg(&format!("{damaged}{after}")).as_bytes(), MAX_RASTER_PIXELS).unwrap(); + assert!(!parsed.tree.root().has_children(), "both images are left out"); + let mut huge = b"".to_vec(); + huge.resize(usize::try_from(MAX_BOUNDED_SVG_BYTES).unwrap() + 1024, b' '); + huge.extend_from_slice(b""); + let huge = embedded_image("image/svg+xml", &gzip(&huge)); + let error = parse_bounded(image_svg(&format!("{damaged}{huge}")).as_bytes(), MAX_RASTER_PIXELS).unwrap_err(); + assert!(error.to_string().contains("byte or nesting budget"), "{error}"); + // A stored preview must draw completely, so it is still refused there. + assert!(parse_bounded_work_with(image_svg(&damaged).as_bytes(), MAX_RASTER_PIXELS, true, fonts).is_err()); +} + +/// Latin-1 bytes may fit while their decoded UTF-8 text exceeds the shared budget. +/// Refuse the drawing even when this is its only child, rather than silently omitting it. +#[test] +fn a_latin1_embedded_svg_that_decodes_past_the_budget_is_refused() { + let budget = usize::try_from(MAX_BOUNDED_SVG_BYTES).unwrap(); + let mut latin1 = b""); + let wide = embedded_image("image/svg+xml", &gzip(&latin1)); + let small = embedded_image("image/svg+xml", b""); + let error = parse_bounded(image_svg(&wide).as_bytes(), MAX_RASTER_PIXELS).unwrap_err(); + assert!(error.to_string().contains("byte or nesting budget"), "{error}"); + let error = parse_bounded(image_svg(&format!("{wide}{small}")).as_bytes(), MAX_RASTER_PIXELS).unwrap_err(); + assert!(error.to_string().contains("byte or nesting budget"), "{error}"); +} + +/// 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 +/// drawing is refused rather than unpacking each one. +#[test] +fn images_after_a_damaged_svgz_are_unpacked_again_within_one_budget() { + let svg = ""; + let compressed = gzip(svg.as_bytes()); + let damaged = embedded_image("image/svg+xml", &compressed[..compressed.len() / 2]); + let mut large = b"".to_vec(); + large.resize(usize::try_from(MAX_BOUNDED_SVG_BYTES).unwrap() * 5 / 8, b' '); + large.extend_from_slice(b""); + let large = embedded_image("image/svg+xml", &gzip(&large)); + assert!(parse_bounded(image_svg(&format!("{damaged}{large}")).as_bytes(), MAX_RASTER_PIXELS).is_ok(), "one is left out"); + let error = parse_bounded(image_svg(&format!("{damaged}{large}{large}")).as_bytes(), MAX_RASTER_PIXELS).unwrap_err(); + 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. +#[test] +fn unpacking_images_again_adds_up_to_one_budget_however_many_there_are() { + let budget = usize::try_from(MAX_BOUNDED_SVG_BYTES).unwrap(); + let mut huge = b"".to_vec(); + huge.resize(budget * 2, b' '); + huge.extend_from_slice(b""); + 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); + } +} + /// Only a stored display preview is strict about an embedded image it can't read; an edited SVG /// saved back from an external editor leaves it out, as placement does. #[test] diff --git a/crates/raw/src/shared.rs b/crates/raw/src/shared.rs index bc0f185449..29eb14c2dc 100644 --- a/crates/raw/src/shared.rs +++ b/crates/raw/src/shared.rs @@ -99,6 +99,9 @@ fn warnings(image: &craft_raw::RawImage) -> Vec { out.push("raw white level not recorded in a documented tag; assumed full sample range".into()); } } + if image.notices.gain_table_omitted { + out.push("the raw camera profile's invalid gain table map was omitted".to_string()); + } for op in image.opcodes.list1.iter().chain(&image.opcodes.list2).chain(&image.opcodes.list3) { if !matches!(op, craft_raw::Opcode::GainMap { .. } | craft_raw::Opcode::MapPolynomial { .. }) { out.push("some raw correction opcodes are not applied by PhotoCraft".to_string()); diff --git a/crates/raw/src/testgen/canon.rs b/crates/raw/src/testgen/canon.rs index 41a0229f1a..498b12dfd5 100644 --- a/crates/raw/src/testgen/canon.rs +++ b/crates/raw/src/testgen/canon.rs @@ -26,6 +26,11 @@ pub struct Cr2Spec { impl Cr2Spec { pub fn build(&self) -> Vec { + self.build_with_cfa_tag(None) + } + + /// Write the raw IFD's Canon CR2CFAPattern tag; absent by default for fallback tests. + pub fn build_with_cfa_tag(&self, cfa_tag: Option) -> Vec { let (w, h) = (self.width, self.height); // Slice the sensor data into the JPEG sample order. let widths: Vec = if self.slices.is_empty() { vec![w] } else { self.slices.clone() }; @@ -44,6 +49,9 @@ impl Cr2Spec { let mut t = TiffBuilder::default(); let jb = t.blob(jpeg.clone()); let mut raw = vec![(259, Val::Short(vec![6])), (273, Val::Blobs(vec![jb])), (279, Val::Long(vec![jpeg.len() as u32]))]; + if let Some(code) = cfa_tag { + raw.push((0xc5e0, Val::Long(vec![code]))); + } if !self.slices.is_empty() { let n = widths.len() - 1; raw.push((50752, Val::Short(vec![n as u16, widths[0] as u16, widths[n] as u16]))); diff --git a/crates/raw/tests/it/dng.rs b/crates/raw/tests/it/dng.rs index 616fd346e6..b3343ef266 100644 --- a/crates/raw/tests/it/dng.rs +++ b/crates/raw/tests/it/dng.rs @@ -13,10 +13,12 @@ fn floats(s: &Sensor) -> &[f32] { s.float_data.as_deref().expect("floating-point samples") } +/// `data` as the 0..=1 floats a JPEG XL codestream of those 16-bit values decodes to. fn unit(data: &[u16]) -> Vec { data.iter().map(|&v| f32::from(v) / 65535.0).collect() } +/// Whether `got` equals `want` to within float rounding. fn near(got: &[f32], want: &[f32]) -> bool { got.len() == want.len() && got.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-6) } @@ -200,6 +202,7 @@ fn broken_monochrome_linear_raw_errors() { let first: Vec = spec.data[..4].iter().flat_map(|v| v.to_le_bytes()).collect(); let strip = b.windows(first.len()).position(|win| win == first.as_slice()).expect("strip data"); assert!(decode(&b[..strip + w], &Limits::default()).is_err(), "truncated strip"); + assert!(decode(&b[..strip + 2], &Limits::default()).is_err(), "short truncated strip"); // Two samples per pixel is no LinearRaw layout. let two = DngSpec { samples: 2, data: ramp(2 * w, h, 100, 4000), ..spec.clone() }; let err = decode(&two.build(), &Limits::default()).unwrap_err().to_string(); @@ -266,6 +269,7 @@ fn metadata_is_read() { assert_eq!((d.width, d.height), (20, 16)); } +/// An unrepresentable DefaultCropOrigin is refused; the whole active area is kept with a notice. #[test] fn enormous_double_crop_origin_keeps_the_whole_active_area_with_warning() { let (w, h) = (16, 12); @@ -282,6 +286,7 @@ fn enormous_double_crop_origin_keeps_the_whole_active_area_with_warning() { } } +/// craft-raw clips a crop that reaches past the active area and reports the adjustment. #[test] fn out_of_range_default_crop_uses_checked_intersection_with_warning() { let (w, h) = (16, 12); @@ -567,6 +572,7 @@ fn deflate_strips_round_trip() { for (name, bits, storage, be) in [ ("deflate 16-bit", 16, DngStorage::DeflateStrips { rows: 16, predictor: 1 }, false), ("deflate 16-bit predictor 2", 16, DngStorage::DeflateStrips { rows: 16, predictor: 2 }, false), + ("deflate 12-bit", 12, DngStorage::DeflateStrips { rows: 12, predictor: 1 }, false), ("deflate 12-bit predictor 2", 12, DngStorage::DeflateStrips { rows: 12, predictor: 2 }, false), ("deflate 16-bit predictor 2 BE", 16, DngStorage::DeflateStrips { rows: 16, predictor: 2 }, true), ("deflate LinearRaw predictor 2", 16, DngStorage::DeflateStrips { rows: 40, predictor: 2 }, false), @@ -601,17 +607,17 @@ fn deflate_hostile_fails_cleanly() { assert!(decode(cut, &Limits::default()).is_err(), "a cut zlib stream must not decode"); } -/// Predictor 2 on 8-bit samples wraps at 8 bits, and 12-bit samples bit-packed inside the zlib -/// stream (not in 16-bit containers) decode too. +/// Predictor 2 on 8-bit samples wraps at 8 bits, and 12-bit samples are bit-packed inside the zlib +/// stream (not in 16-bit containers), as the testgen writes them. #[test] fn deflate_8_bit_predictor_and_packed_12_bit() { use std::io::Write as _; - let (w, h) = (16usize, 4usize); let zlib = |bytes: &[u8]| { let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); e.write_all(bytes).unwrap(); e.finish().unwrap() }; + let (w, h) = (16usize, 4usize); // 8-bit, predictor 2: a row falling from 250 to 10 has deltas that wrap mod 256. let data8: Vec = (0..w * h).map(|i| if i % w < w / 2 { 250 } else { 10 }).collect(); let mut spec = DngSpec::cfa(w, h, data8.clone()); @@ -758,6 +764,7 @@ fn floating_point_jpeg_xl_linear_raw_decodes() { assert_eq!(float.rgb, develop(&ints.build(), &DevelopOptions::default()).unwrap().rgb); } +/// Uncompressed floating-point strips (16-bit half floats here) decode too: craft-raw reads them as floats. #[test] fn uncompressed_float_raw_preserves_known_half_values_including_signed_hdr() { let (w, h) = (8, 4); @@ -773,8 +780,7 @@ fn uncompressed_float_raw_preserves_known_half_values_including_signed_hdr() { assert_eq!(s.white, [1.0; 3]); } -/// WhiteLevel has one value per sample plane: the floats are scaled by the highest, so a plane -/// with a higher white level than the first keeps its highlights. +/// WhiteLevel has one value per sample plane, kept per plane next to the unscaled floats. #[test] fn floating_point_white_levels_per_plane_scale_from_the_highest() { let (w, h) = (24, 16); @@ -811,7 +817,8 @@ fn assert_polynomial_development(actual: &Sensor, normalized: Vec) { } /// #8125: a lossy DNG's OpcodeList2 carries a MapPolynomial per plane, and its colours depend on -/// it. Each plane's samples are mapped through its polynomial, on the linear reference values. +/// it. craft-raw leaves the samples as stored and hands the polynomials on; development maps each +/// plane through its own, on the linear reference values. #[test] fn map_polynomial_maps_each_plane_of_floating_point_data() { let (w, h) = (24, 16); @@ -827,13 +834,20 @@ fn map_polynomial_maps_each_plane_of_floating_point_data() { let want: Vec = data.iter().enumerate().map(|(i, &v)| poly(&planes[i % 3], f64::from(f32::from(v) / 65535.)) as f32).collect(); assert!(near(floats(&s), &unit(&data)), "stored float values stay unprocessed until development"); assert_polynomial_development(&s, want); + assert_eq!(s.polynomials.len(), planes.len()); + for (p, c) in s.polynomials.iter().zip(&planes) { + assert_eq!(&p.coefficients, c); + for x in [0.0, 0.2, 0.5, 1.0] { + assert!((p.eval(x) - poly(c, x)).abs() < 1e-12); + } + } assert!(s.warnings.iter().all(|w| !w.contains("MapPolynomial")), "{:?}", s.warnings); let d = develop(&bytes, &DevelopOptions::default()).unwrap(); assert!(d.warnings.iter().all(|w| !w.contains("MapPolynomial")), "{:?}", d.warnings); } -/// With a LinearizationTable, MapPolynomial maps the linearized values: the samples are -/// linearized first and the table is then done with. +/// With a LinearizationTable, the samples are linearized at decode, and the MapPolynomial is +/// handed on for development to apply to the linearized values. #[test] fn map_polynomial_follows_the_linearization_table() { let (w, h) = (16, 8); @@ -849,6 +863,7 @@ fn map_polynomial_follows_the_linearization_table() { assert_eq!(s.data, data.iter().map(|&value| table[usize::from(value)]).collect::>()); let want: Vec = data.iter().map(|&v| poly(&[0.0, 0.0, 1.0], f64::from(f32::from(table[usize::from(v)]) / 8190.)) as f32).collect(); assert_polynomial_development(&s, want); + assert_eq!(s.polynomials.len(), 1); } /// A LinearizationTable maps integer samples: floating-point data ignores one. @@ -979,11 +994,29 @@ fn jpeg_xl_mismatches_are_errors() { #[test] fn profile_gain_table_map_is_reported() { - let gain_table = |s: &Sensor| s.warnings.iter().any(|w| w.contains("ProfileGainTableMap")); + let gain_table = |s: &Sensor| s.warnings.iter().any(|w| w.contains("gain table map")); let mut spec = DngSpec::cfa(8, 8, vec![500; 64]); assert!(!gain_table(&sensor(&spec.build()))); - spec.profile_gain_table_map = Some(vec![0; 64]); - assert!(gain_table(&sensor(&spec.build()))); + // A well-formed ProfileGainTableMap (version 1, little-endian): one table of one gain. craft-raw + // reads the tag; a malformed optional map is omitted with a separate notice. + let mut map = Vec::new(); + map.extend_from_slice(&[1, 0, 0, 0, 1, 0, 0, 0]); // points V, H + for v in [1.0f64, 1.0, 0.0, 0.0] { + map.extend_from_slice(&v.to_le_bytes()); // spacing V, H; origin V, H + } + map.extend_from_slice(&1u32.to_le_bytes()); // points N + for v in [0.3f32, 0.6, 0.1, 0.0, 0.0] { + map.extend_from_slice(&v.to_le_bytes()); // weights + } + map.extend_from_slice(&1.0f32.to_le_bytes()); // the gain + spec.profile_gain_table_map = Some(map); + let s = sensor(&spec.build()); + assert!(gain_table(&s)); + let d = develop_sensor(&s, &DevelopOptions::default()).unwrap(); + for warnings in [&s.warnings, &d.warnings] { + assert!(warnings.iter().any(|w| w.contains("gain table map") && w.contains("not applied")), "{warnings:?}"); + assert!(!warnings.iter().any(|w| w.contains("gain table map") && w.contains("omitted")), "{warnings:?}"); + } } // ---------------------------------------------------------------- lossy DNG (compression 34892) @@ -1153,7 +1186,7 @@ fn lossy_jpeg_tile_dimension_mismatch_errors() { assert_eq!((s.width, s.height, s.data.len()), (w, h, w * h)); assert!(s.data.iter().all(|&v| v.abs_diff(100) <= 2), "{tw}x{th}: visible source pixels survive padding"); } - for (tw, th) in [(16, 11), (15, 16), (12, 16), (16, 33), (33, 16)] { + for (tw, th) in [(16, 11), (15, 16), (12, 16), (16, 10), (10, 10), (16, 33), (33, 16)] { spec.lossy_segments = vec![baseline_jpeg(&vec![100u8; tw * th], tw, th, 1)]; assert!(matches!(decode(&spec.build(), &Limits::default()), Err(RawError::Malformed(_))), "{tw}x{th}"); } @@ -1203,8 +1236,9 @@ fn lossy_jpeg_oversized_frame_header_errors() { assert!(decode(&big, &tight).is_err()); } -/// DNG 1.4 stores lossy JPEG at 8 bits per sample; other depths and sample counts are reported -/// as unsupported, not decoded as something else. +/// DNG 1.4 stores lossy JPEG at 8 bits per sample; other depths are reported as unsupported, not +/// decoded as something else. (craft-raw takes a JPEG's components as they come: a mismatch with the +/// IFD's sample count is no longer an error.) #[test] fn lossy_jpeg_rejects_other_depths_and_sample_counts() { let (w, h) = (16, 16); @@ -1216,13 +1250,33 @@ fn lossy_jpeg_rejects_other_depths_and_sample_counts() { let err = decode(&spec.build(), &Limits::default()).unwrap_err(); assert!(matches!(&err, RawError::Unsupported(m) if m.contains(&format!("{bits}-bit"))), "{err}"); } - // Four samples per pixel (the IFD's claim; the JPEG itself is three-component). - let mut spec = lossy_spec(w, h, vec![90; w * h * 3], DngStorage::LossyJpegTiles { width: 16, height: 16 }); - spec.samples = 3; - let mut bytes = spec.build(); - let samples_tag = 277u16.to_le_bytes(); - let at = bytes.windows(4).position(|e| e[..2] == samples_tag && e[2..] == 3u16.to_le_bytes()).expect("SamplesPerPixel entry"); - bytes[at + 8] = 4; - let err = decode(&bytes, &Limits::default()).unwrap_err(); - assert!(matches!(&err, RawError::Unsupported(m) if m.contains("4 samples")), "{err}"); +} + +/// Decoder fallback notices must survive both the adapter and development. +#[test] +fn adjusted_crop_and_omitted_gain_table_notices_survive_development() { + let mut spec = DngSpec::cfa(16, 12, vec![1000; 16 * 12]); + spec.active_area = Some([2, 3, 10, 14]); + let check = |spec: &DngSpec, crop: Rect, crop_warning: bool, gain_warning: bool| { + let s = sensor(&spec.build()); + assert_eq!(s.crop, crop); + let d = develop_sensor(&s, &DevelopOptions { orient: false, ..Default::default() }).unwrap(); + assert_eq!((d.width as usize, d.height as usize), (crop.width, crop.height)); + for warnings in [&s.warnings, &d.warnings] { + assert_eq!(warnings.iter().any(|w| w.contains("default crop")), crop_warning, "{warnings:?}"); + assert_eq!(warnings.iter().any(|w| w.contains("gain table map") && w.contains("omitted")), gain_warning, "{warnings:?}"); + } + }; + check(&spec, Rect::new(3, 2, 11, 8), false, false); + spec.default_crop = Some(([1, 1], [4, 4])); + check(&spec, Rect::new(4, 3, 4, 4), false, false); + spec.default_crop = Some(([8, 1], [5, 4])); + check(&spec, Rect::new(11, 3, 3, 4), true, false); + spec.default_crop_origin_double = Some([1e300, 0.0]); + check(&spec, Rect::new(3, 2, 11, 8), true, false); + spec.profile_gain_table_map = Some(vec![0; 16]); + check(&spec, Rect::new(3, 2, 11, 8), true, true); + spec.default_crop = None; + spec.default_crop_origin_double = None; + check(&spec, Rect::new(3, 2, 11, 8), false, true); } diff --git a/crates/raw/tests/it/hasselblad.rs b/crates/raw/tests/it/hasselblad.rs index 4eeefa7a36..0c96dff7df 100644 --- a/crates/raw/tests/it/hasselblad.rs +++ b/crates/raw/tests/it/hasselblad.rs @@ -45,10 +45,10 @@ fn metadata() { assert_eq!(sensor.active, Rect::new(0, 0, 16, 12)); assert_eq!(sensor.black, BlackLevels::uniform(4096.0)); assert_eq!(sensor.white, [64763.0; 3]); - let wb = sensor.camera_wb.unwrap(); - assert!((wb[0] - 1.0 / 0.375).abs() < 1e-9, "{wb:?}"); - assert!((wb[2] - 1.0 / 0.617).abs() < 1e-9, "{wb:?}"); - assert_eq!((sensor.make.as_deref(), sensor.model.as_deref()), (Some("Hasselblad"), Some("X2D II 100C"))); + // craft-raw reads AsShotNeutral as the DNG colour tag; development turns it into multipliers. + let neutral = sensor.color.as_shot_neutral.unwrap(); + assert!((neutral[0] - 0.375).abs() < 1e-9 && (neutral[2] - 0.617).abs() < 1e-9, "{neutral:?}"); + assert_eq!((sensor.make.as_deref(), sensor.model.as_deref()), (Some("Hasselblad"), Some("Hasselblad X2D II 100C"))); assert_eq!(sensor.orientation, 1); // This real-layout fixture deliberately has no CFAPattern tag. All source // metadata is retained, while the decoder discloses its assumed RGGB phase. @@ -67,14 +67,6 @@ fn develops() { } } -#[test] -fn unknown_body_warns_about_the_assumed_phase() { - let mut s = spec(); - s.model = "X2D 100C".into(); - let sensor = decode(&s.build(), &Limits::default()).unwrap(); - assert!(sensor.warnings.iter().any(|w| w.contains("Bayer phase")), "{:?}", sensor.warnings); -} - #[test] fn compressed_3fr_is_reported_unsupported() { let mut s = spec(); @@ -133,12 +125,13 @@ fn an_active_area_outside_the_plane_is_ignored() { assert_eq!((sensor.active, sensor.crop), (Rect::new(0, 0, 16, 12), Rect::new(0, 0, 16, 12))); } +/// Refuse truncated sensor data rather than silently inventing black pixels. #[test] -fn truncated_strip_is_malformed() { +fn truncated_strip_is_refused() { let mut b = spec().build(); // The preview blob sits past the strip; cutting 60 bytes eats into the strip. b.truncate(b.len() - 60); - assert!(matches!(decode(&b, &Limits::default()), Err(RawError::Malformed(_)))); + assert!(matches!(decode(&b, &Limits::default()), Err(photocraft_raw::RawError::Malformed(_)))); } #[test] @@ -147,3 +140,11 @@ fn zero_dimensions_are_malformed() { s.width = 0; assert!(matches!(decode(&s.build(), &Limits::default()), Err(RawError::Malformed(_)))); } + +#[test] +fn unknown_body_warns_about_the_assumed_phase() { + let mut s = spec(); + s.model = "X2D 100C".into(); + let sensor = decode(&s.build(), &Limits::default()).unwrap(); + assert!(sensor.warnings.iter().any(|w| w.contains("Bayer phase")), "{:?}", sensor.warnings); +} diff --git a/crates/raw/tests/it/raf.rs b/crates/raw/tests/it/raf.rs index 7ffcb349e2..7ef82b8704 100644 --- a/crates/raw/tests/it/raf.rs +++ b/crates/raw/tests/it/raf.rs @@ -6,7 +6,7 @@ use photocraft_raw::*; const RGGB: [u8; 4] = [0, 1, 1, 2]; -/// A 30×18 X-Trans RAF with a 2-pixel masked border. +/// A 30×18 X-Trans RAF with a 2-pixel masked border, exercising padded rows. fn xtrans(packing: RafPacking, bits: u32) -> RafSpec { let (w, h) = (30, 18); let white = ((1u32 << bits) - 1) as u16; diff --git a/crates/raw/tests/it/vendor_codecs.rs b/crates/raw/tests/it/vendor_codecs.rs index 1b1f6cee77..f8a441477a 100644 --- a/crates/raw/tests/it/vendor_codecs.rs +++ b/crates/raw/tests/it/vendor_codecs.rs @@ -155,7 +155,8 @@ fn rw2_round_trip_12_and_14_bit() { assert_eq!(s.data, data, "{bits}-bit"); assert_eq!(s.cfa.as_ref().unwrap().phase(0, 0), [0, 1, 1, 2]); assert_eq!(s.black.values, vec![128.0, 129.0, 129.0, 130.0]); - assert_eq!(s.white, [f32::from(max); 3]); + // craft-raw takes the white level from the data: the saturation plateau of the scene, else the full range. + assert!(s.white[0] > 0.0 && s.white[0] <= f32::from(max), "{:?}", s.white); assert_eq!(s.camera_wb, Some([2.0, 1.0, 1.5])); assert_eq!(s.crop, Rect::new(2, 2, w - 4, h - 4)); let d = develop_sensor(&s, &DevelopOptions::default()).unwrap(); @@ -221,6 +222,7 @@ fn rw2_format4_crosses_pages() { assert_eq!(s.data, data); } +/// A width that is not whole 14-pixel blocks never panics (craft-raw decodes the partial last block). #[test] fn rw2_format4_preserves_samples_with_a_partial_final_block() { let (w, h) = (42, 2); @@ -237,6 +239,9 @@ fn rw2_undecoded_formats_fall_back() { let data = vec![200u16; 20 * 4]; let mut b = rw2(20, 4, &data, 12); assert!(decode(&b, &Limits::default()).is_ok()); + // Format 6 is supported by the shared reader. + patch_ifd0_short(&mut b, 0x002D, 6); + assert!(decode(&b, &Limits::default()).is_ok()); patch_ifd0_short(&mut b, 0x002D, 9); match decode(&b, &Limits::default()) { Err(RawError::Unsupported(m)) => assert!(m.contains("raw format 9"), "{m}"), @@ -294,9 +299,20 @@ fn orf_truncated_in_ifd0_is_malformed_not_the_compressed_variant() { // Cut right before the StripByteCounts entry: width, height and compression survive. let cut = at(279); assert!(cut > at(259), "compression precedes the byte counts"); + assert!(decode(&b[..cut], &Limits::default()).is_err()); +} + +/// The shared decoder must preserve damage classification for every truncated prefix. +#[test] +fn orf_truncated_in_ifd0_is_malformed_not_the_compressed_variant_in_craft_raw() { + let (w, h) = (40, 24); + let data = mosaic(&scene(w, h), w, [1, 0, 2, 1], 64, 4095); + let b = orf(w, h, &data); + let ifd = u32::from_le_bytes(b[4..8].try_into().unwrap()) as usize; + let n = u16::from_le_bytes([b[ifd], b[ifd + 1]]) as usize; + let entries: Vec = (0..n).map(|i| u16::from_le_bytes([b[ifd + 2 + 12 * i], b[ifd + 3 + 12 * i]])).collect(); + let cut = ifd + 2 + 12 * entries.iter().position(|&t| t == 279).unwrap(); assert!(matches!(decode(&b[..cut], &Limits::default()), Err(RawError::Malformed(_))), "{:?}", decode(&b[..cut], &Limits::default()).err()); - // No prefix of the file reads as the compressed variant: the compression declaration is - // intact or gone, never "compressed". for cut in 0..b.len() { if let Err(RawError::Unsupported(m)) = decode(&b[..cut], &Limits::default()) { assert!(!m.contains("compressed"), "prefix {cut}: {m}"); diff --git a/crates/raw/tests/it/vendors.rs b/crates/raw/tests/it/vendors.rs index 8b5248dac0..0167322b53 100644 --- a/crates/raw/tests/it/vendors.rs +++ b/crates/raw/tests/it/vendors.rs @@ -132,21 +132,19 @@ fn embedded_preview_is_found() { assert!(embedded_preview(&cr2_spec(32, 8, 2, vec![]).build()).is_none()); } -/// #193: a CR2 whose sensor data is mosaicked with `cfa` (row-major 2×2 colours) anchored at -/// data (0, 0), image area from (`l`, `t`). Left half: a colourful scene; right half: a neutral -/// grey patch. Raw values are scene / white-balance gain, as a camera records them. -fn cr2_phase_spec(cfa: [u8; 4], l: usize, t: usize, model_id: Option) -> Cr2Spec { - let (w, h) = (192usize, 96usize); - let wb = [2.0f32, 1.0, 1.5]; - let colourful = scene(w, h); - let rgb: Vec<[f32; 3]> = (0..w * h) - .map(|i| { - let p = if i % w >= w / 2 { [0.4; 3] } else { colourful[i] }; - [p[0] / wb[0], p[1] / wb[1], p[2] / wb[2]] +/// A neutral scene recorded through per-channel WB gains, with a black masked border. +/// Phase is anchored at the sensor origin, not the cropped image origin. +fn cr2_neutral_spec(cfa: [u8; 4], l: usize, t: usize, model_id: Option) -> Cr2Spec { + let (w, h) = (96, 64); + let rgb: Vec<_> = scene(w, h) + .into_iter() + .enumerate() + .map(|(i, p)| { + let p = if i % w >= w / 2 { [0.4; 3] } else { p }; + [p[0] / 2.0, p[1], p[2] / 1.5] }) .collect(); let mut data = mosaic(&rgb, w, cfa, 512, 13000); - // Masked border: black. for y in 0..h { for x in 0..w { if x < l || y < t { @@ -160,7 +158,7 @@ fn cr2_phase_spec(cfa: [u8; 4], l: usize, t: usize, model_id: Option) -> Cr data, precision: 14, components: 2, - slices: vec![96, 96], + slices: vec![48, 48], borders: Some([l as u16, t as u16, w as u16 - 1, h as u16 - 1]), wb_rggb: Some([2048, 1024, 1024, 1536]), orientation: 1, @@ -168,20 +166,20 @@ fn cr2_phase_spec(cfa: [u8; 4], l: usize, t: usize, model_id: Option) -> Cr } } -/// Mean developed RGB over the interior of the grey patch (from column `x0` of the image area). -fn grey_patch(d: &Developed, x0: usize) -> [f64; 3] { +fn assert_cr2_neutral(sensor: &Sensor) -> Developed { + let d = develop_sensor(sensor, &DevelopOptions { orient: false, ..Default::default() }).unwrap(); let (w, h) = (d.width as usize, d.height as usize); - let mut sum = [0f64; 3]; - let mut n = 0.0; + let mut sum = [0.0f64; 3]; for y in 8..h - 8 { - for x in x0 + 8..w - 8 { - for (c, s) in sum.iter_mut().enumerate() { - *s += f64::from(d.rgb[(y * w + x) * 3 + c]); + for x in 48 - sensor.crop.x + 8..w - 8 { + for (c, channel) in sum.iter_mut().enumerate() { + *channel += f64::from(d.rgb[(y * w + x) * 3 + c]); } - n += 1.0; } } - sum.map(|s| s / n) + assert!(sum[1] > 0.0); + assert!((sum[0] / sum[1] - 1.0).abs() < 0.02 && (sum[2] / sum[1] - 1.0).abs() < 0.02, "{sum:?}"); + d } #[test] @@ -249,3 +247,81 @@ fn cr2_cfa_phase_falls_back_to_the_model_table() { assert_eq!(s.cfa.as_ref().unwrap().phase(0, 0), [0, 1, 1, 2]); assert!(s.warnings.iter().any(|w| w.contains("colour filter phase")), "{:?}", s.warnings); } + +#[test] +fn cr2_explicit_cfa_keeps_neutral_colour_across_phases_and_border_parity() { + for (code, cfa) in [(1, [0, 1, 1, 2]), (2, [2, 1, 1, 0]), (3, [1, 2, 0, 1]), (4, [1, 0, 2, 1])] { + for (l, t) in [(16, 4), (17, 4), (16, 5), (17, 5)] { + // A conflicting model fallback must not override explicit file metadata. + let spec = cr2_neutral_spec(cfa, l, t, Some(0x8000_0250)); + let sensor = decode(&spec.build_with_cfa_tag(Some(code)), &Limits::default()).unwrap(); + assert_eq!(sensor.cfa.as_ref().unwrap().phase(0, 0), cfa, "code {code}, border {l},{t}"); + assert!(!sensor.warnings.iter().any(|w| w.contains("colour filter phase"))); + let d = assert_cr2_neutral(&sensor); + assert_eq!((d.width as usize, d.height as usize), (96 - l, 64 - t)); + assert!(!d.warnings.iter().any(|w| w.contains("colour filter phase"))); + } + } +} + +#[test] +fn cr2_missing_or_unknown_cfa_discloses_model_and_default_fallback_through_develop() { + for (model, cfa) in [(Some(0x8000_0250), [1, 2, 0, 1]), (Some(0x8000_0001), [0, 1, 1, 2]), (None, [0, 1, 1, 2])] { + for tag in [None, Some(99)] { + let spec = cr2_neutral_spec(cfa, 17, 5, model); + let sensor = decode(&spec.build_with_cfa_tag(tag), &Limits::default()).unwrap(); + assert_eq!(sensor.cfa.as_ref().unwrap().phase(0, 0), cfa); + assert!(sensor.warnings.iter().any(|w| w.contains("colour filter phase"))); + let d = assert_cr2_neutral(&sensor); + assert!(d.warnings.iter().any(|w| w.contains("colour filter phase"))); + } + } +} + +fn cr2_phase_spec(cfa: [u8; 4], l: usize, t: usize, model_id: Option) -> Cr2Spec { + let (w, h) = (192usize, 96usize); + let wb = [2.0f32, 1.0, 1.5]; + let colourful = scene(w, h); + let rgb: Vec<[f32; 3]> = (0..w * h) + .map(|i| { + let p = if i % w >= w / 2 { [0.4; 3] } else { colourful[i] }; + [p[0] / wb[0], p[1] / wb[1], p[2] / wb[2]] + }) + .collect(); + let mut data = mosaic(&rgb, w, cfa, 512, 13000); + // Masked border: black. + for y in 0..h { + for x in 0..w { + if x < l || y < t { + data[y * w + x] = 512; + } + } + } + Cr2Spec { + width: w, + height: h, + data, + precision: 14, + components: 2, + slices: vec![96, 96], + borders: Some([l as u16, t as u16, w as u16 - 1, h as u16 - 1]), + wb_rggb: Some([2048, 1024, 1024, 1536]), + orientation: 1, + model_id, + } +} + +fn grey_patch(d: &Developed, x0: usize) -> [f64; 3] { + let (w, h) = (d.width as usize, d.height as usize); + let mut sum = [0f64; 3]; + let mut n = 0.0; + for y in 8..h - 8 { + for x in x0 + 8..w - 8 { + for (c, s) in sum.iter_mut().enumerate() { + *s += f64::from(d.rgb[(y * w + x) * 3 + c]); + } + n += 1.0; + } + } + sum.map(|s| s / n) +} diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index 89f996bbea..0fbb1fe34a 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -15,3 +15,7 @@ serde_json = { workspace = true } # on Linux read /proc/self/statm, not /proc/self/smaps, which walks every mapping under the mmap # lock and made the 2 ms sampler thread a fifth of a large bench's CPU time. memory-stats = { version = "1.2", features = ["always_use_statm"] } + +[target.'cfg(target_os = "linux")'.dependencies] +# One Vulkan instance kept for the whole test process (`gpu_lock`). +wgpu = { version = "30", default-features = false, features = ["std", "vulkan"] } diff --git a/crates/testkit/src/gpu.rs b/crates/testkit/src/gpu.rs index 3bb5df1ed8..9fb7f918bb 100644 --- a/crates/testkit/src/gpu.rs +++ b/crates/testkit/src/gpu.rs @@ -21,6 +21,10 @@ //! So every test that builds a GPU harness (or its own wgpu device) holds [`gpu_lock`] for its //! whole run, harness included. Under nextest each test is its own process and the lock costs //! nothing; `.config/nextest.toml` caps how many of those run at once instead. +//! +//! The lock alone left a segfault in libvulkan about once in 20 runs of a large test binary: the +//! last wgpu instance going away tears Vulkan down, and the next one can find it half gone. +//! [`gpu_lock`] keeps one instance for the rest of the process, so that never happens. use std::sync::{Mutex, MutexGuard, PoisonError}; @@ -30,13 +34,70 @@ static GPU_LOCK: Mutex<()> = Mutex::new(()); /// line (`let _gpu = gpu_lock();`) so it is released last. A test that failed while holding it /// doesn't block the rest. pub fn gpu_lock() -> MutexGuard<'static, ()> { - GPU_LOCK.lock().unwrap_or_else(PoisonError::into_inner) + let guard = GPU_LOCK.lock().unwrap_or_else(PoisonError::into_inner); + #[cfg(target_os = "linux")] + keep_vulkan(); + guard +} + +/// Creates the Vulkan instance that stays for the rest of the process, unless `WGPU_BACKEND` +/// leaves Vulkan out (to keep a broken Vulkan driver out of the tests). +#[cfg(target_os = "linux")] +fn keep_vulkan() { + use wgpu::{Backends, Instance, InstanceDescriptor}; + static KEPT: std::sync::OnceLock> = std::sync::OnceLock::new(); + KEPT.get_or_init(|| { + kept_backends(Backends::from_env()).map(|backends| Instance::new(InstanceDescriptor { backends, ..InstanceDescriptor::new_without_display_handle() })) + }); +} + +/// The backends of the kept instance for a `WGPU_BACKEND` of `env`: Vulkan, if it allows it. +#[cfg(target_os = "linux")] +fn kept_backends(env: Option) -> Option { + let vulkan = env.unwrap_or(wgpu::Backends::VULKAN) & wgpu::Backends::VULKAN; + (!vulkan.is_empty()).then_some(vulkan) } #[cfg(test)] mod tests { use super::*; + /// Without the kept instance, creating and dropping instances on several threads segfaults in + /// libvulkan within a second, an abort no test can catch. Skipped when `WGPU_BACKEND` leaves + /// Vulkan out: nothing is kept then, and that is how a broken driver is kept out of the tests. + #[cfg(target_os = "linux")] + #[test] + fn instances_can_come_and_go_on_several_threads() { + use wgpu::{Backends, Instance, InstanceDescriptor}; + if kept_backends(Backends::from_env()).is_none() { + eprintln!("skipping: WGPU_BACKEND leaves Vulkan out"); + return; + } + drop(gpu_lock()); + let threads: Vec<_> = (0..8) + .map(|_| { + std::thread::spawn(|| { + for _ in 0..10 { + drop(Instance::new(InstanceDescriptor { backends: Backends::VULKAN, ..InstanceDescriptor::new_without_display_handle() })); + } + }) + }) + .collect(); + for t in threads { + assert!(t.join().is_ok()); + } + } + + /// `WGPU_BACKEND=gl` keeps Vulkan out of the tests: no Vulkan instance is kept then. + #[cfg(target_os = "linux")] + #[test] + fn the_kept_instance_follows_wgpu_backend() { + use wgpu::Backends; + assert_eq!(kept_backends(None), Some(Backends::VULKAN)); + assert_eq!(kept_backends(Some(Backends::GL)), None); + assert_eq!(kept_backends(Some(Backends::GL | Backends::VULKAN)), Some(Backends::VULKAN)); + } + #[test] fn a_panicked_holder_does_not_block_the_next_test() { let _ = std::thread::spawn(|| { diff --git a/crates/ui-egui/src/canvas/cpu_background_tests.rs b/crates/ui-egui/src/canvas/cpu_background_tests.rs index dfd7ea77e2..b5bf41fcd0 100644 --- a/crates/ui-egui/src/canvas/cpu_background_tests.rs +++ b/crates/ui-egui/src/canvas/cpu_background_tests.rs @@ -113,12 +113,14 @@ fn reference_frame(h: &mut Harness) { #[test] #[should_panic(expected = "called `Result::unwrap()` on an `Err` value")] fn fixture_failures_are_not_skipped_as_a_missing_adapter() { + let _gpu = photocraft_testkit::gpu_lock(); // An invalid fixture document must fail on any machine, with or without a graphics adapter. let _ = harness([0, 0], "white"); } #[test] fn omitting_an_occluded_checker_preserves_cpu_canvas_pixels() { + let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness([320, 240], "white") else { eprintln!("skipping: no offscreen graphics adapter"); return; @@ -159,6 +161,7 @@ fn omitting_an_occluded_checker_preserves_cpu_canvas_pixels() { #[test] fn pattern_preview_keeps_the_legacy_checker_for_every_copy() { + let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness([320, 240], "white") else { eprintln!("skipping: no offscreen graphics adapter"); return; @@ -198,6 +201,7 @@ fn pattern_preview_keeps_the_legacy_checker_for_every_copy() { #[test] #[ignore = "manual release benchmark: 24 MP CPU canvas on the offscreen software adapter"] fn cpu_canvas_background_benchmark() { + let _gpu = photocraft_testkit::gpu_lock(); use std::time::Instant; let mut results = Vec::new(); let output = std::env::var_os("PHOTOCRAFT_CPU_BENCH_OUTPUT").map(std::path::PathBuf::from); diff --git a/crates/ui-egui/src/menus/native_menu/tests.rs b/crates/ui-egui/src/menus/native_menu/tests.rs index a20761f50f..ab683f5feb 100644 --- a/crates/ui-egui/src/menus/native_menu/tests.rs +++ b/crates/ui-egui/src/menus/native_menu/tests.rs @@ -288,6 +288,7 @@ fn menu_rows_show_the_shortcut_that_runs_them() { /// documents gains a row, which rebuilds only the Window menu. #[test] fn opening_a_document_changes_state_not_structure() { + let _registry = crate::menus::plugin_ui::registry_guard(); let (a, b) = (crate::menus::menu_items(&app(false)), crate::menus::menu_items(&app(true))); let kind = |items: &[MenuItem]| items.iter().map(|i| (i.id.clone(), i.checked.is_some())).collect::>(); let (ka, kb) = (kind(&a), kind(&b)); @@ -302,6 +303,7 @@ fn opening_a_document_changes_state_not_structure() { /// the active one checked. Switching documents moves the check without a rebuild. #[test] fn the_documents_follow_bring_all_to_front() { + let _registry = crate::menus::plugin_ui::registry_guard(); let none = ids(&layout(false).bar.menu(MenuRole::Window).unwrap().children); assert_eq!(none.last().map(String::as_str), Some("")); @@ -320,6 +322,28 @@ fn the_documents_follow_bring_all_to_front() { assert_eq!((structure_key(&switched), window_key(&switched)), (structure_key(&bar), window_key(&bar)), "a check moves in place"); } +/// The guard those two tests hold keeps a plug-in install out from between their menu builds: +/// an install on another thread doesn't finish until the guard is dropped, whatever is already +/// installed (a reinstall of the same plug-in leaves the menus as they were). +#[test] +fn a_plugin_install_waits_for_a_test_comparing_menu_builds() { + use std::time::Duration; + let guard = crate::menus::plugin_ui::registry_guard(); + assert!(matches!(crate::menus::plugin_ui::REGISTRY.try_lock(), Err(std::sync::TryLockError::WouldBlock)), "the guard holds the registry mutex"); + let before = structure_key(&layout(false).bar); + let (installed, done) = std::sync::mpsc::channel(); + let installer = std::thread::spawn(move || { + let _registry = crate::menus::plugin_ui::registry_guard(); + photocraft_plugins::registry::install_bytes(include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../plugins/tests/fixtures/invert.wasm"))).unwrap(); + installed.send(()).unwrap(); + }); + assert!(done.recv_timeout(Duration::from_millis(200)).is_err(), "the install waits for the guard"); + assert_eq!(structure_key(&layout(false).bar), before, "no plug-in row appeared between the builds"); + drop(guard); + done.recv_timeout(Duration::from_secs(30)).expect("the install goes ahead once the guard is dropped"); + installer.join().unwrap(); +} + #[test] fn native_key_equivalents_are_command_and_function_keys_only() { assert!(Chord::parse("Cmd+B").unwrap().native_ok()); diff --git a/crates/ui-egui/src/menus/plugin_ui.rs b/crates/ui-egui/src/menus/plugin_ui.rs index 0faa71bd6e..3e919c5939 100644 --- a/crates/ui-egui/src/menus/plugin_ui.rs +++ b/crates/ui-egui/src/menus/plugin_ui.rs @@ -9,6 +9,18 @@ use crate::menus::MenuItem; /// Menu ids of installed plug-ins: `plugin.filter.`. const PREFIX: &str = "plugin.filter."; +/// Held by tests that install a plug-in and by tests that compare two builds of the menus. The +/// plug-in registry is shared by the whole test process, so an install between two builds adds a +/// Filter › Plug-ins row to the second one only. +#[cfg(test)] +pub(crate) fn registry_guard() -> std::sync::MutexGuard<'static, ()> { + REGISTRY.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// The mutex [`registry_guard`] holds. +#[cfg(test)] +pub(crate) static REGISTRY: std::sync::Mutex<()> = std::sync::Mutex::new(()); + /// Inserts the installed plug-ins into Filter › Plug-ins, above "Install Plug-in…". pub fn insert_menu_items(app: &PhotocraftApp, items: &mut Vec) { let plugins = photocraft_plugins::registry::list(); @@ -76,6 +88,7 @@ mod tests { #[test] fn installed_plugins_appear_under_filter_plugins_and_run() { + let _registry = registry_guard(); let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); let ctx = egui::Context::default(); let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../plugins/tests/fixtures/invert.wasm"); @@ -105,6 +118,7 @@ mod tests { if !crate::i18n::needs_catalogs() { return; } + let _registry = registry_guard(); let ja = crate::i18n::Lang::from_code("ja").expect("registered language"); let _lang = crate::i18n::language_scope(ja); let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index b8eb48bd4f..da886de81d 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -2026,6 +2026,7 @@ mod layer_click_type_commit_tests { #[test] #[ignore = "offscreen visual evidence for #5584"] fn layer_click_synthetic_visual_evidence() { + let _gpu = photocraft_testkit::gpu_lock(); let (h, text, _) = harness(theme::ThemeKind::ProMedium); let mut app = h.into_state(); app.ui.tool = Tool::Type; diff --git a/crates/ui-egui/src/panels/clipping_indicator_tests.rs b/crates/ui-egui/src/panels/clipping_indicator_tests.rs index 99c22ecf10..0d2e1a5a16 100644 --- a/crates/ui-egui/src/panels/clipping_indicator_tests.rs +++ b/crates/ui-egui/src/panels/clipping_indicator_tests.rs @@ -200,6 +200,7 @@ fn panel_adjustment_clips_to_selected_layer_and_scope_undoes_at_all_depths() { #[test] #[ignore = "writes synthetic compact adjustment-panel screenshots to log/adjustment-scope"] fn write_adjustment_scope_preview() { + let _gpu = photocraft_testkit::gpu_lock(); let phase = std::env::var("PHOTOCRAFT_EVIDENCE_PHASE").unwrap_or_else(|_| "after".into()); let output = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../log/adjustment-scope"); std::fs::create_dir_all(&output).unwrap(); diff --git a/crates/ui-egui/src/pen_path_visual_tests.rs b/crates/ui-egui/src/pen_path_visual_tests.rs index 6fc23e8ade..b3829085fc 100644 --- a/crates/ui-egui/src/pen_path_visual_tests.rs +++ b/crates/ui-egui/src/pen_path_visual_tests.rs @@ -33,6 +33,7 @@ fn button(pos: Pos2, pressed: bool) -> Event { #[test] #[ignore = "manual offscreen visual fixture; writes synthetic screenshots"] fn saved_path_drag_visual_fixture() { + let _gpu = photocraft_testkit::gpu_lock(); let baseline = std::env::var("PHOTOCRAFT_PEN_VISUAL_BASELINE").is_ok_and(|v| v == "1"); let output = std::env::var_os("PHOTOCRAFT_PEN_VISUAL_DIR").map(std::path::PathBuf::from).unwrap_or_else(|| "log/pen-path-visual".into()); std::fs::create_dir_all(&output).expect("create synthetic screenshot directory"); diff --git a/crates/ui-egui/src/smart_svg_ui/tests.rs b/crates/ui-egui/src/smart_svg_ui/tests.rs index 91f480d4c3..5bced96c17 100644 --- a/crates/ui-egui/src/smart_svg_ui/tests.rs +++ b/crates/ui-egui/src/smart_svg_ui/tests.rs @@ -564,6 +564,7 @@ fn bounded_sessions_require_reuse_or_closing_a_document() { #[test] fn capture_smart_svg_visual_fixtures() { + let _gpu = photocraft_testkit::gpu_lock(); let Some(directory) = std::env::var_os("CRAFT_SMART_SVG_FIXTURES").map(std::path::PathBuf::from) else { return }; std::fs::create_dir_all(&directory).unwrap(); for theme in [crate::theme::ThemeKind::Pro, crate::theme::ThemeKind::StudioLight] { @@ -632,6 +633,7 @@ fn embedded_ai_link_table_handoff_preserves_source_until_saved_and_undo_restores /// Optional screenshot uses authored bytes and mock services, never private artwork or an editor. #[test] fn capture_embedded_vector_conversion_prompt() { + let _gpu = photocraft_testkit::gpu_lock(); let Some(directory) = std::env::var_os("CRAFT_SMART_SVG_FIXTURES").map(std::path::PathBuf::from) else { return }; std::fs::create_dir_all(&directory).unwrap(); let (mut app, _, _) = fixture(); diff --git a/crates/ui-egui/src/text/served_fonts.rs b/crates/ui-egui/src/text/served_fonts.rs index e61d66e0c6..001b361fba 100644 --- a/crates/ui-egui/src/text/served_fonts.rs +++ b/crates/ui-egui/src/text/served_fonts.rs @@ -18,6 +18,25 @@ use crate::PhotocraftApp; /// Layers whose document was busy with a background job when their font arrived. static PENDING: Mutex> = Mutex::new(Vec::new()); +/// The served catalog is process-wide, and every family added while a font menu is open adds a +/// row that egui styles on its next pass, so `Harness::run` takes one more pass per family. Tests +/// that add families hold this for writing ([`changing_catalog`]), and tests that wait for an +/// open font menu to settle hold it for reading ([`steady_catalog`]). +#[cfg(test)] +static CATALOG: std::sync::RwLock<()> = std::sync::RwLock::new(()); + +/// Held by a test while it adds families to the served catalog. +#[cfg(test)] +pub(crate) fn changing_catalog() -> std::sync::RwLockWriteGuard<'static, ()> { + CATALOG.write().unwrap_or_else(PoisonError::into_inner) +} + +/// Held by a test while it waits for an open font menu to settle: no family is added meanwhile. +#[cfg(test)] +pub(crate) fn steady_catalog() -> std::sync::RwLockReadGuard<'static, ()> { + CATALOG.read().unwrap_or_else(PoisonError::into_inner) +} + /// Served script fallbacks in the UI's font stack, by egui font name, unscaled: kept so the stack /// `theme::install_fonts` rebuilds on a language change includes them again. static UI_FACES: Mutex)>> = Mutex::new(Vec::new()); @@ -204,7 +223,10 @@ mod tests { fn a_layer_in_a_script_redraws_when_that_scripts_fallback_arrives() { // Thai: other tests use other scripts (the served catalog is process-wide). let thai = "Served Test Thai"; - photocraft_text::served::add_fonts(&parse_manifest(&format!("{thai} | Regular | fonts/t/T.ttf | Thai\n")).0); + { + let _catalog = changing_catalog(); + photocraft_text::served::add_fonts(&parse_manifest(&format!("{thai} | Regular | fonts/t/T.ttf | Thai\n")).0); + } let layer = |text: &str| TextLayer { text: text.into(), font_family: "Inter".into(), ..Default::default() }; assert!(redraws_for(&layer("สวัสดี"), &[thai.into()]), "Thai text set in Inter falls back to it"); assert!(!redraws_for(&layer("hello"), &[thai.into()])); @@ -276,7 +298,12 @@ mod tests { return; } let (jpan, hans) = ("Served Test Jpan", "Served Test Hans"); - photocraft_text::served::add_fonts(&parse_manifest(&format!("{jpan} | Regular | fonts/j/J.ttf | Jpan\n{hans} | Regular | fonts/h/H.ttf | Hans\n")).0); + { + let _catalog = changing_catalog(); + photocraft_text::served::add_fonts( + &parse_manifest(&format!("{jpan} | Regular | fonts/j/J.ttf | Jpan\n{hans} | Regular | fonts/h/H.ttf | Hans\n")).0, + ); + } crate::i18n::set_current(crate::i18n::Lang::from_code("zh-hans").expect("Simplified Chinese")); let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); diff --git a/crates/ui-egui/src/tools/type_font_preview.rs b/crates/ui-egui/src/tools/type_font_preview.rs index a334642c99..7f7c4ccfbb 100644 --- a/crates/ui-egui/src/tools/type_font_preview.rs +++ b/crates/ui-egui/src/tools/type_font_preview.rs @@ -198,7 +198,10 @@ mod tests { // Families the host serves but hasn't sent (own names: the served catalog is process-wide). let (a, b) = ("Served Hover Rest A", "Served Hover Rest B"); let (fonts, _) = photocraft_text::served::parse_manifest(&format!("{a} | Regular | fonts/a/A.ttf\n{b} | Regular | fonts/b/B.ttf\n")); - photocraft_text::served::add_fonts(&fonts); + { + let _catalog = crate::served_fonts::changing_catalog(); + photocraft_text::served::add_fonts(&fonts); + } let mut app = app_with_type_layer(); let ctx = egui::Context::default(); diff --git a/crates/ui-egui/src/tools/type_tool/canvas_tests.rs b/crates/ui-egui/src/tools/type_tool/canvas_tests.rs index 96c0551955..d6f9ac41f4 100644 --- a/crates/ui-egui/src/tools/type_tool/canvas_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/canvas_tests.rs @@ -1905,7 +1905,10 @@ fn variable_font_axes_become_sliders_with_the_drawn_value() { /// Families the host serves are in the font menu before they are fetched. #[test] fn the_font_menu_lists_served_families() { - photocraft_text::served::add_families(["Served Menu Test Serif".to_string()]); + { + let _catalog = crate::served_fonts::changing_catalog(); + photocraft_text::served::add_families(["Served Menu Test Serif".to_string()]); + } assert!(super::families().iter().any(|f| f == "Served Menu Test Serif")); } @@ -2186,6 +2189,7 @@ mod multi_layer_formatting { #[test] fn options_font_family_preserves_peer_faces_and_batches_layer_flags() { + let _catalog = crate::served_fonts::steady_catalog(); let (app, ids) = fixture(); let before = ids.map(|id| style(&app, id, 0)); let mut h = controls(app, false); @@ -2284,6 +2288,7 @@ mod multi_layer_formatting { /// Here both happen on every pass. #[test] fn the_font_menu_settles_while_other_engines_register_fonts() { + let _catalog = crate::served_fonts::changing_catalog(); let (app, _) = fixture(); let mut pass = 0u32; let mut h = Harness::builder().with_size(vec2(1100.0, 800.0)).build_ui_state( @@ -2310,6 +2315,7 @@ mod multi_layer_formatting { /// layers selected, sets them and is kept for new type, as the options bar's menu does. #[test] fn a_style_picked_in_the_character_sections_font_menu_is_kept_for_new_type() { + let _catalog = crate::served_fonts::steady_catalog(); let (app, ids) = fixture(); // The first style row under the family (so it is in view), other than the defaults'. let pick = super::super::styles("Inter").into_iter().find(|s| s != "Regular" && s != "Bold Italic").expect("Inter has several styles"); diff --git a/crates/ui-egui/src/tools/type_tool/fonts.rs b/crates/ui-egui/src/tools/type_tool/fonts.rs index 2b1091ffa7..985e96ab02 100644 --- a/crates/ui-egui/src/tools/type_tool/fonts.rs +++ b/crates/ui-egui/src/tools/type_tool/fonts.rs @@ -251,7 +251,10 @@ pub fn warm_fonts() { /// disabled "Loading fonts…" box `width` wide instead of blocking the UI, and a repaint picks the /// menus up once the scan is done. pub(crate) fn fonts_ready(ui: &mut egui::Ui, width: f32) -> bool { - if photocraft_text::try_shared().is_some() { + let loaded = photocraft_text::try_shared().is_some(); + #[cfg(test)] + let loaded = loaded && !TEST_FONTS_LOADING.get(); + if loaded { return true; } let label = tl!("Loading fonts…").to_string(); @@ -260,6 +263,31 @@ pub(crate) fn fonts_ready(ui: &mut egui::Ui, width: f32) -> bool { false } +#[cfg(test)] +thread_local! { + // Tests draw the font menus as still loading while a `FontsLoading` is alive, whether or not + // the font database has finished its scan. + static TEST_FONTS_LOADING: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// While alive, [`fonts_ready`] draws the "Loading fonts…" box on this thread (tests). +#[cfg(test)] +pub(crate) struct FontsLoading(bool); + +#[cfg(test)] +impl FontsLoading { + pub(crate) fn start() -> Self { + Self(TEST_FONTS_LOADING.replace(true)) + } +} + +#[cfg(test)] +impl Drop for FontsLoading { + fn drop(&mut self) { + TEST_FONTS_LOADING.set(self.0); + } +} + /// The font menu's local library (`photocraft_engine::font_library_cmds`): the recent fonts it /// lists first and the favourites it stars, read before the menu is drawn, plus the font whose /// star was clicked, starred or un-starred by [`FontLibrary::finish`] afterwards, and the style diff --git a/crates/ui-egui/src/tools/type_tool/fonts_loading_tests.rs b/crates/ui-egui/src/tools/type_tool/fonts_loading_tests.rs new file mode 100644 index 0000000000..2fd400d6cf --- /dev/null +++ b/crates/ui-egui/src/tools/type_tool/fonts_loading_tests.rs @@ -0,0 +1,46 @@ +//! A click on a Type options bar button after the font menus lands when the fonts finish loading +//! between the press and the release: the buttons keep their place and ids when the "Loading +//! fonts…" box gives way to the menus. + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; + +use super::super::fonts::FontsLoading; +use super::super::vertical_align_buttons_tests::new_app; +use crate::PhotocraftApp; +use crate::state::Tool; + +/// The options bar with the fonts loading until the first pass that sees a pointer press ends. +fn bar_loading_until_a_press(tool: Tool) -> Harness<'static, PhotocraftApp> { + let mut loading = Some(FontsLoading::start()); + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 60.0)).build_ui_state( + move |ui, app: &mut PhotocraftApp| { + ui.horizontal(|ui| super::options_bar(app, ui)); + if ui.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::PointerButton { pressed: true, .. }))) { + drop(loading.take()); + } + }, + new_app(tool), + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(3); + h +} + +#[test] +fn a_click_lands_when_the_fonts_finish_loading_between_the_press_and_the_release() { + let _ = photocraft_text::shared(); + for (tool, label) in [(Tool::Type, "Right align text"), (Tool::VerticalTypeMask, "Bottom align text")] { + let mut h = bar_loading_until_a_press(tool); + assert!(h.query_by_label("Style").is_none(), "{label}: no style menu while the fonts load"); + let button = h.get_by_role_and_label(Role::Button, label); + let (rect, id) = (button.rect(), button.accesskit_node().id()); + button.click(); + h.run_steps(2); + assert!(h.query_by_label("Style").is_some(), "{label}: the style menu once the fonts are loaded"); + assert_eq!(h.state().ui.tool_options.type_align, "right", "{label}: the click lands"); + let button = h.get_by_role_and_label(Role::Button, label); + assert_eq!((button.rect(), button.accesskit_node().id()), (rect, id), "{label}: the button keeps its place and id"); + } +} diff --git a/crates/ui-egui/src/tools/type_tool/options_bar.rs b/crates/ui-egui/src/tools/type_tool/options_bar.rs index 56b54b5c27..2865fb7ba6 100644 --- a/crates/ui-egui/src/tools/type_tool/options_bar.rs +++ b/crates/ui-egui/src/tools/type_tool/options_bar.rs @@ -25,38 +25,43 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { app.ui.status_error = true; } } - // Font family and style menus (one placeholder in their place while the fonts load). - if fonts_ready(ui, 170.0 + ui.spacing().item_spacing.x + 110.0) { - if let Some(picked) = font_picker(app, ui, &mut fam, 170.0) { - app.ui.tool_options.type_font = fam.clone(); - let st = styles(&fam); - let picked = picked.filter(|s| st.contains(s)); - style = match &picked { - Some(s) => s.clone(), - None if st.contains(&style) => style, - None => st.first().cloned().unwrap_or_else(|| "Regular".into()), - }; - app.ui.tool_options.type_style = style.clone(); - // Only a style picked under the family's ">" is set: otherwise each selected layer - // keeps its own face in the new family (#3556). - match picked { - Some(s) => apply(app, ui.ctx(), json!({"font": fam, "fontStyle": s})), - None => apply(app, ui.ctx(), json!({"font": fam})), + // Font family and style menus (one placeholder in their place while the fonts load), in one + // scope so the controls after them keep their ids when the fonts finish loading: a click + // pressed before and released after still lands. The salt keeps the menus' ids apart from the + // Character panel's font menus. + ui.push_id("type-options-fonts", |ui| { + if fonts_ready(ui, 170.0 + ui.spacing().item_spacing.x + 110.0) { + if let Some(picked) = font_picker(app, ui, &mut fam, 170.0) { + app.ui.tool_options.type_font = fam.clone(); + let st = styles(&fam); + let picked = picked.filter(|s| st.contains(s)); + style = match &picked { + Some(s) => s.clone(), + None if st.contains(&style) => style.clone(), + None => st.first().cloned().unwrap_or_else(|| "Regular".into()), + }; + app.ui.tool_options.type_style = style.clone(); + // Only a style picked under the family's ">" is set: otherwise each selected layer + // keeps its own face in the new family (#3556). + match picked { + Some(s) => apply(app, ui.ctx(), json!({"font": fam, "fontStyle": s})), + None => apply(app, ui.ctx(), json!({"font": fam})), + } + } + font_picker_tip(ui, tl!("Search and select fonts")); + let style_family = if fam.is_empty() { styles_at(app).map(|(c, _)| c.font_family).unwrap_or_default() } else { fam.clone() }; + let opts: Vec<(String, String)> = styles(&style_family).into_iter().map(|s| (s.clone(), style_label(&s))).collect(); + let opts_ref: Vec<(String, &str)> = opts.iter().map(|(a, b)| (a.clone(), b.as_str())).collect(); + if crate::widgets::dropdown(ui, "type-style", tl!("Style"), &mut style, &opts_ref, 110.0) { + app.ui.tool_options.type_style = style.clone(); + apply(app, ui.ctx(), json!({"fontStyle": style})); + } + // The menu's button, by the id its combo box takes from "type-style"; "Style" stays its name. + if let Some(menu) = ui.ctx().read_response(ui.make_persistent_id(egui::IdSalt::new("type-style"))) { + menu.on_hover_text(tl!("Set font style")); } } - font_picker_tip(ui, tl!("Search and select fonts")); - let style_family = if fam.is_empty() { styles_at(app).map(|(c, _)| c.font_family).unwrap_or_default() } else { fam.clone() }; - let opts: Vec<(String, String)> = styles(&style_family).into_iter().map(|s| (s.clone(), style_label(&s))).collect(); - let opts_ref: Vec<(String, &str)> = opts.iter().map(|(a, b)| (a.clone(), b.as_str())).collect(); - if crate::widgets::dropdown(ui, "type-style", tl!("Style"), &mut style, &opts_ref, 110.0) { - app.ui.tool_options.type_style = style.clone(); - apply(app, ui.ctx(), json!({"fontStyle": style})); - } - // The menu's button, by the id its combo box takes from "type-style"; "Style" stays its name. - if let Some(menu) = ui.ctx().read_response(ui.make_persistent_id(egui::IdSalt::new("type-style"))) { - menu.on_hover_text(tl!("Set font style")); - } - } + }); let (r, icon) = ui.allocate_exact_size(egui::vec2(18.0, 22.0), egui::Sense::hover()); crate::icons::paint(ui, r, "type", 13.0, t.icon); icon.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, tl!("Font size"))); @@ -500,6 +505,10 @@ fn size_field(ui: &mut egui::Ui, display: &mut f32, unit: f32, label: &str) -> O preset.or(typed.then_some(MetricChoice::Typed(*display))) } +#[cfg(test)] +#[path = "fonts_loading_tests.rs"] +mod fonts_loading_tests; + #[cfg(test)] #[path = "size_presets_tests.rs"] mod size_presets_tests; diff --git a/crates/ui-egui/src/tools/type_tool/options_tooltips_tests.rs b/crates/ui-egui/src/tools/type_tool/options_tooltips_tests.rs index a41a0e2f2c..700d00a073 100644 --- a/crates/ui-egui/src/tools/type_tool/options_tooltips_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/options_tooltips_tests.rs @@ -22,6 +22,8 @@ fn app() -> PhotocraftApp { /// `draw` in a row, once the app's fonts are set up (the first pass has none). fn harness(draw: fn(&mut PhotocraftApp, &mut egui::Ui)) -> Harness<'static, PhotocraftApp> { + // Load the fonts first: if they finish mid-test the bar swaps "Loading fonts…" for its menus and a click is lost (#13408). + let _ = photocraft_text::shared(); let mut h = Harness::builder().with_size(vec2(1400.0, 600.0)).build_ui_state( move |ui, app| { if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { diff --git a/crates/ui-egui/src/tools/type_tool/panels_toggle_tests.rs b/crates/ui-egui/src/tools/type_tool/panels_toggle_tests.rs index 893a5a90ba..f1d3fd34a1 100644 --- a/crates/ui-egui/src/tools/type_tool/panels_toggle_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/panels_toggle_tests.rs @@ -47,6 +47,8 @@ fn editing(mut app: PhotocraftApp, id: LayerId) -> PhotocraftApp { /// The options bar in a row, once the app's fonts are set up (the first pass has none). fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + // Load the fonts first: if they finish mid-test the bar swaps "Loading fonts…" for its menus and a click is lost (#13408). + let _ = photocraft_text::shared(); let mut h = Harness::builder().with_size(vec2(1400.0, 200.0)).with_max_steps(16).build_ui_state( |ui, app| { if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { diff --git a/crates/ui-egui/src/tools/type_tool/size_presets_tests.rs b/crates/ui-egui/src/tools/type_tool/size_presets_tests.rs index f39294be5a..eb1e623d9e 100644 --- a/crates/ui-egui/src/tools/type_tool/size_presets_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/size_presets_tests.rs @@ -39,6 +39,8 @@ fn app_with_layer(size: f32) -> (PhotocraftApp, LayerId) { /// `draw` in a window tall enough for the list, once the app's fonts are set up. Up to 16 passes, /// because the font list arrives in batches (see `canvas_tests::controls`). fn harness(app: PhotocraftApp, draw: fn(&mut PhotocraftApp, &mut egui::Ui)) -> Harness<'static, PhotocraftApp> { + // Load the fonts first: if they finish mid-test the bar swaps "Loading fonts…" for its menus and a click is lost (#13408). + let _ = photocraft_text::shared(); let mut h = Harness::builder().with_size(vec2(1400.0, 800.0)).with_max_steps(16).build_ui_state( move |ui, app| { if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { diff --git a/crates/ui-egui/src/tools/type_tool/vertical_align_buttons_tests.rs b/crates/ui-egui/src/tools/type_tool/vertical_align_buttons_tests.rs index 25b9993943..45ac0c9ae4 100644 --- a/crates/ui-egui/src/tools/type_tool/vertical_align_buttons_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/vertical_align_buttons_tests.rs @@ -31,6 +31,8 @@ fn text_layer(app: &mut PhotocraftApp, orientation: &str) -> LayerId { } pub(super) fn bar(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + // Load the fonts first: if they finish mid-test the bar swaps "Loading fonts…" for its menus and a click is lost (#13408). + let _ = photocraft_text::shared(); let mut h = Harness::builder().with_size(egui::vec2(1200.0, 60.0)).build_ui_state( |ui, app: &mut PhotocraftApp| { ui.horizontal(|ui| super::options_bar(app, ui)); diff --git a/crates/ui-egui/src/tools/zoom_tool/tests.rs b/crates/ui-egui/src/tools/zoom_tool/tests.rs index e2b557ac42..022576fbb3 100644 --- a/crates/ui-egui/src/tools/zoom_tool/tests.rs +++ b/crates/ui-egui/src/tools/zoom_tool/tests.rs @@ -203,6 +203,7 @@ fn discrete_zoom_animates_and_keeps_its_document_anchor_fixed() { #[test] fn gpu_zoom_animation_reuses_the_document_composite() { + let _gpu = photocraft_testkit::gpu_lock(); let Ok(rs) = std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default())) else { eprintln!("skipping: no GPU adapter"); return; diff --git a/docs/releasing.md b/docs/releasing.md index b1c030a02b..f39898724c 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -242,7 +242,15 @@ Why these formats: `~/.local/share/applications/ai.storyteller.photocraft.desktop` with `Exec` rewritten to the AppImage's path (`TryExec` dropped, the binary isn't on the host PATH) and the hicolor icons beside it, rewriting only when the content changed, and any failure leaves - the launch untouched. `PHOTOCRAFT_NO_DESKTOP_INTEGRATION=1` opts out; to uninstall, `rm + the launch untouched. Launcher refresh uses a hidden generated snapshot to preserve + user edits, comments and deleted keys while updating untouched packaged metadata and + known executable paths. Missing or damaged snapshots use a conservative fallback. + External integration removes a duplicate only when a regular launcher exactly matches + a valid regular snapshot. Symlinked launchers or snapshots (including dangling links) + and special files are left alone during both refresh and deduplication; icons still + install. These checks do not synchronize concurrent changes by other processes. + This overlaps the deduplication protection proposed in #5168 without depending on it. + `PHOTOCRAFT_NO_DESKTOP_INTEGRATION=1` opts out; to uninstall, `rm ~/.local/share/applications/ai.storyteller.photocraft.desktop` and `find ~/.local/share/icons/hicolor -name 'ai.storyteller.photocraft*' -delete`. The script is covered by `packaging/linux/apprun-test.sh` in the packaging-lint workflow. diff --git a/packaging/linux/AppRun b/packaging/linux/AppRun index 3414c5acc7..75632e32ce 100755 --- a/packaging/linux/AppRun +++ b/packaging/linux/AppRun @@ -25,6 +25,29 @@ case "${ARGV0:-}" in photocraft-cli | */photocraft-cli) exec "$APPDIR/usr/bin/photocraft-cli" "$@" ;; esac +# A damaged snapshot is not evidence that an absent user key was newly added. +# Treat it like a legacy installation and preserve the existing launcher. +valid_baseline() { + [ -f "$1" ] && [ ! -L "$1" ] && [ -s "$1" ] || return 1 + awk ' + /^\[/ { group = $0; if (group == "[Desktop Entry]") sections++; next } + /^[ \t]*($|#)/ { next } + /^[^= \t][^=]*=/ { + name = $0; sub(/=.*/, "", name) + k = group SUBSEP name + if (seen[k]++) bad = 1 + if (group == "[Desktop Entry]") { + if ($0 == "Type=Application") type = 1 + if ($0 ~ /^Name=.+$/) title = 1 + if ($0 ~ /^Exec=".+" %F$/) executable = 1 + } + next + } + { bad = 1 } + END { exit !(sections == 1 && type && title && executable && !bad) } + ' "$1" +} + integrate() { case "${PHOTOCRAFT_NO_DESKTOP_INTEGRATION:-}" in 1 | true | yes) return 0 ;; @@ -54,6 +77,8 @@ integrate() { # "already integrated" left the menu with no entry (#5534). apps="$data/applications" mkdir -p "$apps" 2>/dev/null || return 0 + desktop="$apps/$DESK_ID.desktop" + baseline="$apps/.$DESK_ID.generated" external=0 for f in "$apps"/*.desktop; do if [ ! -f "$f" ] || [ "$f" = "$apps/$DESK_ID.desktop" ]; then @@ -74,10 +99,19 @@ integrate() { break fi done - if [ "$external" = 1 ]; then - if [ -f "$apps/$DESK_ID.desktop" ]; then - rm -f "$apps/$DESK_ID.desktop" 2>/dev/null || true - command -v update-desktop-database >/dev/null 2>&1 && update-desktop-database "$apps" >/dev/null 2>&1 + if [ -L "$desktop" ] || [ -L "$baseline" ] || + { [ -e "$desktop" ] && [ ! -f "$desktop" ]; } || + { [ -e "$baseline" ] && [ ! -f "$baseline" ]; }; then + # A link (including a dangling one) or special file is not our installation. + # Leave both launcher and snapshot alone; icons may still be installed below. + : + elif [ "$external" = 1 ]; then + # Only a byte-identical, valid generated snapshot proves this is ours to + # remove. A customized or legacy launcher belongs to the user. + if [ -f "$desktop" ] && valid_baseline "$baseline" && cmp -s "$baseline" "$desktop" && [ ! -L "$desktop" ]; then + if rm -f "$desktop" 2>/dev/null; then + command -v update-desktop-database >/dev/null 2>&1 && update-desktop-database "$apps" >/dev/null 2>&1 + fi fi else # Rewrite Exec to this AppImage (the binary is not on the host PATH) and drop @@ -85,19 +119,93 @@ integrate() { tmp="$apps/.$DESK_ID.tmp.$$" esc="$(printf '%s' "$appimage" | sed 's/[\\&|]/\\&/g')" if sed -e "s|^Exec=.*|Exec=\"$esc\" %F|" -e '/^TryExec=/d' "$src_desktop" 2>/dev/null >"$tmp"; then - if cmp -s "$tmp" "$apps/$DESK_ID.desktop"; then + generated="$tmp.generated" + cp "$tmp" "$generated" 2>/dev/null || { rm -f "$tmp"; return 0; } + if [ -f "$desktop" ]; then + # Three-way merge: update shipped keys only if the user has not changed + # them. Keep custom keys, comments and deletions. The snapshot is hidden + # and has no .desktop suffix, so desktop menus do not discover it. + # For older installs without a snapshot, the current template is the + # conservative baseline. An unknown previous executable is left alone. + previous="$baseline" + bootstrap=0 + if ! valid_baseline "$previous"; then + previous="$tmp.previous" + cp "$generated" "$previous" 2>/dev/null || { rm -f "$tmp" "$generated"; return 0; } + bootstrap=1 + fi + if ! awk -v bootstrap="$bootstrap" ' + function key(line) { + if (line ~ /^\[/) { group = line; return "" } + if (line ~ /^[^#= \t][^=]*=/) { + name = line; sub(/=.*/, "", name); return group SUBSEP name + } + return "" + } + FNR == 1 { group = "" } + FILENAME == ARGV[1] { + k = key($0); if (k != "") old[k] = $0 + if (group == "[Desktop Entry]" && $0 ~ /^Exec=".*" %F$/) + old_exec = substr($0, 6, length($0) - 8) + next + } + FILENAME == ARGV[2] { + k = key($0); if (k != "") { fresh[k] = $0; order[++n] = k } + if (group == "[Desktop Entry]" && $0 ~ /^Exec=/) + new_exec = substr($0, 6, length($0) - 8) + next + } + function additions( i, k) { + for (i = 1; i <= n; i++) { + k = order[i] + if (index(k, "[Desktop Entry]" SUBSEP) == 1 && !(k in old) && !(k in seen)) + print fresh[k] + } + } + { + if ($0 ~ /^\[/ && group == "[Desktop Entry]") additions() + k = key($0) + if (k != "") { + seen[k] = 1 + if (k in old && $0 == old[k]) { + if (k in fresh) print fresh[k] + next + } + if (group == "[Desktop Entry]" && name == "Exec") { + # Literal substitution, never a regex or shell evaluation: keep + # environment wrappers and arguments around the managed path. + pos = index($0, old_exec) + prefix = substr($0, 1, pos - 1) + if (old_exec != "" && pos > 0 && prefix ~ /^Exec=(env[ \t]+([^ \t=]+=[^ \t]*[ \t]+)*)?$/) + $0 = substr($0, 1, pos - 1) new_exec substr($0, pos + length(old_exec)) + } + } + print + } + END { if (group == "[Desktop Entry]") additions() } + ' "$previous" "$generated" "$desktop" >"$tmp"; then + rm -f "$tmp" "$generated" + [ "$bootstrap" = 0 ] || rm -f "$previous" + return 0 + fi + [ "$bootstrap" = 0 ] || rm -f "$previous" + fi + if cmp -s "$tmp" "$desktop"; then rm -f "$tmp" else - if mv -f "$tmp" "$apps/$DESK_ID.desktop" 2>/dev/null; then + if mv -f "$tmp" "$desktop" 2>/dev/null; then command -v update-desktop-database >/dev/null 2>&1 && update-desktop-database "$apps" >/dev/null 2>&1 else - rm -f "$tmp" + rm -f "$tmp" "$generated" + return 0 fi fi + mv -f "$generated" "$baseline" 2>/dev/null || rm -f "$generated" else rm -f "$tmp" return 0 fi + fi # Icons: per-file compare so an unchanged install costs a handful of cmp calls. diff --git a/packaging/linux/apprun-test.sh b/packaging/linux/apprun-test.sh index 473872ebfe..f25dd007eb 100755 --- a/packaging/linux/apprun-test.sh +++ b/packaging/linux/apprun-test.sh @@ -30,6 +30,7 @@ APPIMAGE="$TMP/photocraft test.AppImage" # spaces on purpose: Exec must stay quo export APPIMAGE export HOME="$TMP/home" export XDG_DATA_HOME="$HOME/.local/share" +unset DESKTOPINTEGRATION PHOTOCRAFT_NO_DESKTOP_INTEGRATION mkdir -p "$HOME" fail() { @@ -74,6 +75,128 @@ export APPIMAGE="$TMP/moved.AppImage" "$APPDIR/AppRun" >/dev/null || fail "launch after move exited non-zero" grep -Fxq "Exec=\"$(readlink -f "$APPIMAGE")\" %F" "$DESKTOP" || fail "Exec not refreshed after move" +# Customized launch options and metadata survive launches and relocation (#2905). +old_path="$(readlink -f "$APPIMAGE")" +sed -i "s|^Exec=.*|Exec=env WAYLAND_DISPLAY= \"$old_path\" --custom %F|; s|^Name=.*|Name=My PhotoCraft|" "$DESKTOP" +printf '\nX-User-Setting=keep me\n' >>"$DESKTOP" +cp "$DESKTOP" "$TMP/custom.desktop" +before="$(stat -c %i "$DESKTOP")" +"$APPDIR/AppRun" >/dev/null +cmp -s "$DESKTOP" "$TMP/custom.desktop" || fail "customized launcher overwritten" +[ "$before" = "$(stat -c %i "$DESKTOP")" ] || fail "custom launcher rewritten although unchanged" +mv "$APPIMAGE" "$TMP/new version.AppImage" +export APPIMAGE="$TMP/new version.AppImage" +"$APPDIR/AppRun" >/dev/null +grep -Fxq "Exec=env WAYLAND_DISPLAY= \"$APPIMAGE\" --custom %F" "$DESKTOP" || fail "custom Exec not relocated" +grep -Fxq 'Name=My PhotoCraft' "$DESKTOP" || fail "custom Name lost" +grep -Fxq 'X-User-Setting=keep me' "$DESKTOP" || fail "custom key lost" + +# Packaged updates apply only to untouched keys; user deletions stay deleted. +sed -i '/^Comment=/d' "$DESKTOP" +sed -i 's/^Name=.*/Name=Packaged update/; s/^Categories=.*/Categories=Graphics;/; s/^Comment=.*/Comment=Updated description/' "$APPDIR/usr/share/applications/$APP_ID.desktop" +printf '\nX-New-Packaged-Key=added\n' >>"$APPDIR/usr/share/applications/$APP_ID.desktop" +"$APPDIR/AppRun" >/dev/null +grep -Fxq 'Name=My PhotoCraft' "$DESKTOP" || fail "packaged update erased custom Name" +grep -Fxq 'Categories=Graphics;' "$DESKTOP" || fail "untouched metadata not updated" +grep -q '^Comment=' "$DESKTOP" && fail "user deletion undone" +grep -Fxq 'X-New-Packaged-Key=added' "$DESKTOP" || fail "new packaged key missing" +if command -v desktop-file-validate >/dev/null; then + desktop-file-validate "$DESKTOP" || fail "customized entry is invalid" +fi + +# A replaced executable may mention the old AppImage as an argument: leave it. +sed -i "s|^Exec=.*|Exec=\"/custom/wrapper\" \"$APPIMAGE\" %F|" "$DESKTOP" +expected_wrapper="$(grep '^Exec=' "$DESKTOP")" +mv "$APPIMAGE" "$TMP/another version.AppImage" +export APPIMAGE="$TMP/another version.AppImage" +"$APPDIR/AppRun" >/dev/null +grep -Fxq "$expected_wrapper" "$DESKTOP" || fail "wrapper argument mistaken for managed executable" + +# Existing launchers from before snapshots: bootstrap without losing edits. +rm -f "$XDG_DATA_HOME/applications/.$APP_ID.generated" +cp "$DESKTOP" "$TMP/legacy.desktop" +"$APPDIR/AppRun" >/dev/null +cmp -s "$DESKTOP" "$TMP/legacy.desktop" || fail "legacy custom launcher overwritten" +rm -f "$XDG_DATA_HOME/applications/.$APP_ID.generated" +sed -i 's|^Exec=.*|Exec="/custom/wrapper" %F|' "$DESKTOP" +"$APPDIR/AppRun" >/dev/null +grep -Fxq 'Exec="/custom/wrapper" %F' "$DESKTOP" || fail "legacy executable customization overwritten" + + +# Empty or malformed snapshots must never resurrect user-deleted keys. +for invalid in empty garbage missing-exec; do + baseline="$XDG_DATA_HOME/applications/.$APP_ID.generated" + case "$invalid" in + empty) : >"$baseline" ;; + garbage) printf 'not a desktop entry\n' >"$baseline" ;; + missing-exec) printf '[Desktop Entry]\nType=Application\nName=PhotoCraft\n' >"$baseline" ;; + esac + sed -i '/^Comment=/d; /^StartupNotify=/d' "$DESKTOP" + cp "$DESKTOP" "$TMP/before-invalid.desktop" + "$APPDIR/AppRun" >/dev/null || fail "invalid baseline blocked launch" + cmp -s "$DESKTOP" "$TMP/before-invalid.desktop" || fail "$invalid baseline changed user launcher" +done + +# External integration must preserve customized and unknown legacy entries. +for baseline_kind in valid missing empty; do + baseline="$XDG_DATA_HOME/applications/.$APP_ID.generated" + case "$baseline_kind" in + missing) rm -f "$baseline" ;; + empty) : >"$baseline" ;; + esac + cp "$DESKTOP" "$TMP/before-external.desktop" + DESKTOPINTEGRATION=AppImageLauncher "$APPDIR/AppRun" >/dev/null + cmp -s "$DESKTOP" "$TMP/before-external.desktop" || fail "DESKTOPINTEGRATION changed $baseline_kind custom entry" + ext="$XDG_DATA_HOME/applications/external.desktop" + printf '[Desktop Entry]\nType=Application\nName=External\nExec="%s" %%F\n' "$APPIMAGE" >"$ext" + "$APPDIR/AppRun" >/dev/null + cmp -s "$DESKTOP" "$TMP/before-external.desktop" || fail "external desktop removed $baseline_kind custom entry" + rm -f "$ext" +done + +# Linked launchers and snapshots are externally owned, even when their bytes +# match a generated entry. Check both normal refresh and external deduplication. +for integration in normal external; do + for linked in launcher dangling-launcher baseline dangling-baseline; do + rm -rf "$XDG_DATA_HOME" + "$APPDIR/AppRun" >/dev/null + baseline="$XDG_DATA_HOME/applications/.$APP_ID.generated" + target="$TMP/linked-target" + cp "$DESKTOP" "$target" + case "$linked" in + launcher|dangling-launcher) link="$DESKTOP" ;; + baseline|dangling-baseline) link="$baseline" ;; + esac + rm -f "$link" + case "$linked" in dangling-*) rm -f "$target" ;; esac + ln -s "$target" "$link" + [ ! -f "$target" ] || cp "$target" "$TMP/linked-target-before" + # A packaged metadata change would otherwise cause a symlink to be replaced. + template="$APPDIR/usr/share/applications/$APP_ID.desktop" + cp "$template" "$TMP/link-template-before" + printf '\nX-Link-Refresh=changed\n' >>"$template" + if [ "$integration" = external ]; then + ext="$XDG_DATA_HOME/applications/external.desktop" + printf '[Desktop Entry]\nType=Application\nName=External\nExec="%s" %%F\n' "$APPIMAGE" >"$ext" + DESKTOPINTEGRATION=AppImageLauncher "$APPDIR/AppRun" >/dev/null + else + "$APPDIR/AppRun" >/dev/null + fi + [ -L "$link" ] || fail "$integration replaced or removed $linked" + [ "$(readlink "$link")" = "$target" ] || fail "$integration retargeted $linked" + case "$linked" in + dangling-*) [ ! -e "$target" ] || fail "$integration created dangling target" ;; + *) cmp -s "$target" "$TMP/linked-target-before" || fail "$integration changed linked target" ;; + esac + [ -f "$XDG_DATA_HOME/icons/hicolor/256x256/apps/$APP_ID.png" ] || fail "link preservation skipped icons" + cp "$TMP/link-template-before" "$template" + done +done + +# Reset the stub fixture so the duplicate-removal test starts with an untouched entry. +rm -rf "$XDG_DATA_HOME" +"$APPDIR/AppRun" >/dev/null + # 6. External AppImage integrator (#3623): if another .desktop file in $XDG_DATA_HOME/applications # already launches this AppImage (e.g. AppImageLauncher's appimagekit-*.desktop), AppRun removes # its own duplicate .desktop entry while keeping the hicolor icons installed.